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.GITHUB_ACTIONS == 'true') {
96 return 'github';
97 } else if (this._env.CI) {
98 // this should always be the last branch
99 return 'CI/unknown';
100 }
101
102 return null;
103 }
104 }, {
105 key: 'ciVersion',
106 get: function get() {
107 switch (this.ci) {
108 case 'gitlab':
109 return 'gitlab/' + this._env.CI_SERVER_VERSION;
110 case 'github':
111 return 'github/' + (this._env.PERCY_GITHUB_ACTION || 'unkown');
112 }
113 return this.ci;
114 }
115 }, {
116 key: 'commitData',
117 get: function get() {
118 // Read the result from environment data
119 var result = {
120 branch: this.branch,
121 sha: this.commitSha,
122
123 // These GIT_ environment vars are from the Jenkins Git Plugin, but could be
124 // used generically. This behavior may change in the future.
125 authorName: this._env['GIT_AUTHOR_NAME'],
126 authorEmail: this._env['GIT_AUTHOR_EMAIL'],
127 committerName: this._env['GIT_COMMITTER_NAME'],
128 committerEmail: this._env['GIT_COMMITTER_EMAIL']
129 };
130
131 // Try and get more meta-data from git
132 var formattedCommitData = '';
133 if (this.commitSha) {
134 formattedCommitData = this.rawCommitData(this.commitSha);
135 }
136 if (!formattedCommitData) {
137 formattedCommitData = this.rawCommitData('HEAD');
138 }
139 if (!formattedCommitData) {
140 return result;
141 }
142
143 // If this.commitSha didn't provide a sha, use the one from the commit
144 if (!result.sha) {
145 result.sha = this.parse(formattedCommitData, /COMMIT_SHA:(.*)/);
146 }
147
148 result.message = this.parse(formattedCommitData, /COMMIT_MESSAGE:(.*)/m);
149 result.committedAt = this.parse(formattedCommitData, /COMMITTED_DATE:(.*)/);
150 result.authorName = this.parse(formattedCommitData, /AUTHOR_NAME:(.*)/);
151 result.authorEmail = this.parse(formattedCommitData, /AUTHOR_EMAIL:(.*)/);
152 result.committerName = this.parse(formattedCommitData, /COMMITTER_NAME:(.*)/);
153 result.committerEmail = this.parse(formattedCommitData, /COMMITTER_EMAIL:(.*)/);
154
155 return result;
156 }
157 }, {
158 key: 'jenkinsMergeCommitBuild',
159 get: function get() {
160 var formattedCommitData = this.rawCommitData('HEAD');
161
162 if (!formattedCommitData) {
163 return false;
164 }
165
166 var authorName = this.parse(formattedCommitData, /AUTHOR_NAME:(.*)/);
167 var authorEmail = this.parse(formattedCommitData, /AUTHOR_EMAIL:(.*)/);
168 var message = this.parse(formattedCommitData, /COMMIT_MESSAGE:(.*)/m);
169
170 if (authorName === 'Jenkins' && authorEmail === 'nobody@nowhere') {
171 // Example merge message: Merge commit 'ec4d24c3d22f3c95e34af95c1fda2d462396d885' into HEAD
172 if (message.substring(0, 13) === 'Merge commit ' && message.substring(55) === ' into HEAD') {
173 return true;
174 }
175 }
176
177 return false;
178 }
179 }, {
180 key: 'secondToLastCommitSHA',
181 get: function get() {
182 var formattedCommitData = this.rawCommitData('HEAD^');
183
184 if (!formattedCommitData) {
185 return null;
186 }
187
188 return this.parse(formattedCommitData, /COMMIT_SHA:(.*)/);
189 }
190 }, {
191 key: 'commitSha',
192 get: function get() {
193 if (this._env.PERCY_COMMIT) {
194 return this._env.PERCY_COMMIT;
195 }
196 switch (this.ci) {
197 case 'travis':
198 return this._env.TRAVIS_COMMIT;
199 case 'jenkins-prb':
200 // Pull Request Builder Plugin OR Git Plugin.
201 return this._env.ghprbActualCommit || this._env.GIT_COMMIT;
202 case 'jenkins':
203 if (this.jenkinsMergeCommitBuild) {
204 return this.secondToLastCommitSHA;
205 }
206 return this._env.GIT_COMMIT;
207 case 'circle':
208 return this._env.CIRCLE_SHA1;
209 case 'codeship':
210 return this._env.CI_COMMIT_ID;
211 case 'drone':
212 return this._env.DRONE_COMMIT;
213 case 'semaphore':
214 return this._env.REVISION;
215 case 'buildkite':
216 {
217 var commitSha = this._env.BUILDKITE_COMMIT;
218 // Buildkite mixes SHAs and non-SHAs in BUILDKITE_COMMIT, so we return null if non-SHA.
219 return commitSha !== 'HEAD' ? this._env.BUILDKITE_COMMIT : null;
220 }
221 case 'heroku':
222 return this._env.HEROKU_TEST_RUN_COMMIT_VERSION;
223 case 'gitlab':
224 return this._env.CI_COMMIT_SHA;
225 case 'azure':
226 return this._env.SYSTEM_PULLREQUEST_SOURCECOMMITID || this._env.BUILD_SOURCEVERSION;
227 case 'appveyor':
228 return this._env.APPVEYOR_PULL_REQUEST_HEAD_COMMIT || this._env.APPVEYOR_REPO_COMMIT;
229 case 'probo':
230 return this._env.COMMIT_REF;
231 case 'bitbucket':
232 return this._env.BITBUCKET_COMMIT;
233 case 'github':
234 return this._env.GITHUB_SHA;
235 }
236
237 return null;
238 }
239 }, {
240 key: 'targetCommitSha',
241 get: function get() {
242 return this._env.PERCY_TARGET_COMMIT || null;
243 }
244 }, {
245 key: 'partialBuild',
246 get: function get() {
247 var partial = this._env.PERCY_PARTIAL_BUILD;
248 return !!partial && partial !== '0';
249 }
250 }, {
251 key: 'branch',
252 get: function get() {
253 if (this._env.PERCY_BRANCH) {
254 return this._env.PERCY_BRANCH;
255 }
256 var result = '';
257 switch (this.ci) {
258 case 'travis':
259 if (this.pullRequestNumber && this._env.TRAVIS_PULL_REQUEST_BRANCH) {
260 result = this._env.TRAVIS_PULL_REQUEST_BRANCH;
261 } else {
262 result = this._env.TRAVIS_BRANCH;
263 }
264 break;
265 case 'jenkins-prb':
266 result = this._env.ghprbSourceBranch;
267 break;
268 case 'jenkins':
269 result = this._env.CHANGE_BRANCH || this._env.GIT_BRANCH;
270 break;
271 case 'circle':
272 result = this._env.CIRCLE_BRANCH;
273 break;
274 case 'codeship':
275 result = this._env.CI_BRANCH;
276 break;
277 case 'drone':
278 result = this._env.DRONE_BRANCH;
279 break;
280 case 'semaphore':
281 result = this._env.BRANCH_NAME;
282 break;
283 case 'buildkite':
284 result = this._env.BUILDKITE_BRANCH;
285 break;
286 case 'heroku':
287 result = this._env.HEROKU_TEST_RUN_BRANCH;
288 break;
289 case 'gitlab':
290 result = this._env.CI_COMMIT_REF_NAME;
291 break;
292 case 'azure':
293 result = this._env.SYSTEM_PULLREQUEST_SOURCEBRANCH || this._env.BUILD_SOURCEBRANCHNAME;
294 break;
295 case 'appveyor':
296 result = this._env.APPVEYOR_PULL_REQUEST_HEAD_REPO_BRANCH || this._env.APPVEYOR_REPO_BRANCH;
297 break;
298 case 'probo':
299 result = this._env.BRANCH_NAME;
300 break;
301 case 'bitbucket':
302 result = this._env.BITBUCKET_BRANCH;
303 break;
304 case 'github':
305 if (this._env.GITHUB_REF && this._env.GITHUB_REF.match(/^refs\//)) {
306 result = this._env.GITHUB_REF.replace(/^refs\/\w+?\//, '');
307 } else {
308 result = this._env.GITHUB_REF;
309 }
310 break;
311 }
312
313 if (result == '') {
314 result = this.rawBranch();
315 }
316
317 if (result == '') {
318 // Branch not specified
319 result = null;
320 }
321
322 return result;
323 }
324 }, {
325 key: 'targetBranch',
326 get: function get() {
327 return this._env.PERCY_TARGET_BRANCH || null;
328 }
329 }, {
330 key: 'pullRequestNumber',
331 get: function get() {
332 if (this._env.PERCY_PULL_REQUEST) {
333 return this._env.PERCY_PULL_REQUEST;
334 }
335 switch (this.ci) {
336 case 'travis':
337 return this._env.TRAVIS_PULL_REQUEST !== 'false' ? this._env.TRAVIS_PULL_REQUEST : null;
338 case 'jenkins-prb':
339 return this._env.ghprbPullId;
340 case 'jenkins':
341 return this._env.CHANGE_ID || null;
342 case 'circle':
343 if (this._env.CI_PULL_REQUESTS && this._env.CI_PULL_REQUESTS !== '') {
344 return this._env.CI_PULL_REQUESTS.split('/').slice(-1)[0];
345 }
346 break;
347 case 'codeship':
348 // Unfortunately, codeship always returns 'false' for CI_PULL_REQUEST. For now, return null.
349 break;
350 case 'drone':
351 return this._env.CI_PULL_REQUEST;
352 case 'semaphore':
353 return this._env.PULL_REQUEST_NUMBER;
354 case 'buildkite':
355 return this._env.BUILDKITE_PULL_REQUEST !== 'false' ? this._env.BUILDKITE_PULL_REQUEST : null;
356 case 'gitlab':
357 return this._env.CI_MERGE_REQUEST_IID || null;
358 case 'azure':
359 return this._env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER || null;
360 case 'appveyor':
361 return this._env.APPVEYOR_PULL_REQUEST_NUMBER || null;
362 case 'probo':
363 if (this._env.PULL_REQUEST_LINK && this._env.PULL_REQUEST_LINK !== '') {
364 return this._env.PULL_REQUEST_LINK.split('/').slice(-1)[0];
365 }
366 break;
367 case 'bitbucket':
368 return this._env.BITBUCKET_PR_ID || null;
369 }
370 return null;
371 }
372
373 // A nonce which will be the same for all nodes of a parallel build, used to identify shards
374 // of the same CI build. This is usually just the CI environment build ID.
375
376 }, {
377 key: 'parallelNonce',
378 get: function get() {
379 if (this._env.PERCY_PARALLEL_NONCE) {
380 return this._env.PERCY_PARALLEL_NONCE;
381 }
382 switch (this.ci) {
383 case 'travis':
384 return this._env.TRAVIS_BUILD_NUMBER;
385 case 'jenkins-prb':
386 return this._env.BUILD_NUMBER;
387 case 'jenkins':
388 if (this._env.BUILD_TAG) {
389 return utils.reverseString(this._env.BUILD_TAG).substring(0, 60);
390 }
391 break;
392 case 'circle':
393 return this._env.CIRCLE_WORKFLOW_ID || this._env.CIRCLE_BUILD_NUM;
394 case 'codeship':
395 return this._env.CI_BUILD_NUMBER || this._env.CI_BUILD_ID;
396 case 'drone':
397 return this._env.DRONE_BUILD_NUMBER;
398 case 'semaphore':
399 return this._env.SEMAPHORE_BRANCH_ID + '/' + this._env.SEMAPHORE_BUILD_NUMBER;
400 case 'buildkite':
401 return this._env.BUILDKITE_BUILD_ID;
402 case 'heroku':
403 return this._env.HEROKU_TEST_RUN_ID;
404 case 'gitlab':
405 return this._env.CI_PIPELINE_ID;
406 case 'azure':
407 return this._env.BUILD_BUILDID;
408 case 'appveyor':
409 return this._env.APPVEYOR_BUILD_ID;
410 case 'probo':
411 return this._env.BUILD_ID;
412 case 'bitbucket':
413 return this._env.BITBUCKET_BUILD_NUMBER;
414 }
415 return null;
416 }
417 }, {
418 key: 'parallelTotalShards',
419 get: function get() {
420 if (this._env.PERCY_PARALLEL_TOTAL) {
421 return parseInt(this._env.PERCY_PARALLEL_TOTAL);
422 }
423 switch (this.ci) {
424 case 'travis':
425 // Support for https://github.com/ArturT/knapsack
426 if (this._env.CI_NODE_TOTAL) {
427 return parseInt(this._env.CI_NODE_TOTAL);
428 }
429 break;
430 case 'jenkins-prb':
431 break;
432 case 'jenkins':
433 break;
434 case 'circle':
435 if (this._env.CIRCLE_NODE_TOTAL) {
436 return parseInt(this._env.CIRCLE_NODE_TOTAL);
437 }
438 break;
439 case 'codeship':
440 if (this._env.CI_NODE_TOTAL) {
441 return parseInt(this._env.CI_NODE_TOTAL);
442 }
443 break;
444 case 'drone':
445 break;
446 case 'semaphore':
447 if (this._env.SEMAPHORE_THREAD_COUNT) {
448 return parseInt(this._env.SEMAPHORE_THREAD_COUNT);
449 }
450 break;
451 case 'buildkite':
452 if (this._env.BUILDKITE_PARALLEL_JOB_COUNT) {
453 return parseInt(this._env.BUILDKITE_PARALLEL_JOB_COUNT);
454 }
455 break;
456 case 'heroku':
457 if (this._env.CI_NODE_TOTAL) {
458 return parseInt(this._env.CI_NODE_TOTAL);
459 }
460 break;
461 case 'azure':
462 // SYSTEM_TOTALJOBSINPHASE is set for parallel builds and non-parallel matrix builds, so
463 // check build strategy is parallel by ensuring SYSTEM_PARALLELEXECUTIONTYPE == MultiMachine
464 if (this._env.SYSTEM_PARALLELEXECUTIONTYPE == 'MultiMachine' && this._env.SYSTEM_TOTALJOBSINPHASE) {
465 return parseInt(this._env.SYSTEM_TOTALJOBSINPHASE);
466 }
467 break;
468 }
469 return null;
470 }
471 }]);
472
473 return Environment;
474}();
475
476module.exports = Environment;
477},{"./utils":4,"child_process":112}],2:[function(require,module,exports){
478(function (process){
479'use strict';
480
481var _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; };
482
483var _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; }; }();
484
485function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
486
487var http = require('http');
488var https = require('https');
489var utils = require('./utils');
490var Environment = require('./environment');
491var UserAgent = require('./user-agent');
492var retry = require('bluebird-retry');
493var requestPromise = require('request-promise');
494var PromisePool = require('es6-promise-pool');
495var regeneratorRuntime = require('regenerator-runtime'); // eslint-disable-line no-unused-vars
496var fs = require('fs');
497
498require('dotenv').config();
499
500var JSON_API_CONTENT_TYPE = 'application/vnd.api+json';
501var CONCURRENCY = 2;
502
503var Resource = function () {
504 function Resource(options) {
505 _classCallCheck(this, Resource);
506
507 if (!options.resourceUrl) {
508 throw new Error('"resourceUrl" arg is required to create a Resource.');
509 }
510 if (!options.sha && !options.content) {
511 throw new Error('Either "sha" or "content" is required to create a Resource.');
512 }
513 if (/\s/.test(options.resourceUrl)) {
514 throw new Error('"resourceUrl" arg includes whitespace. It needs to be encoded.');
515 }
516 this.resourceUrl = options.resourceUrl;
517 this.content = options.content;
518 this.sha = options.sha || utils.sha256hash(options.content);
519 this.mimetype = options.mimetype;
520 this.isRoot = options.isRoot;
521
522 // Temporary convenience attributes, will not be serialized. These are used, for example,
523 // to hold the local path so reading file contents can be deferred.
524 this.localPath = options.localPath;
525 }
526
527 _createClass(Resource, [{
528 key: 'serialize',
529 value: function serialize() {
530 return {
531 type: 'resources',
532 id: this.sha,
533 attributes: {
534 'resource-url': this.resourceUrl,
535 mimetype: this.mimetype || null,
536 'is-root': this.isRoot || null
537 }
538 };
539 }
540 }]);
541
542 return Resource;
543}();
544
545var PercyClient = function () {
546 function PercyClient(options) {
547 _classCallCheck(this, PercyClient);
548
549 options = options || {};
550 this.token = options.token;
551 this.apiUrl = options.apiUrl || 'https://percy.io/api/v1';
552 this.environment = options.environment || new Environment(process.env);
553 this._httpClient = requestPromise;
554 this._httpModule = this.apiUrl.indexOf('http://') === 0 ? http : https;
555 // A custom HttpAgent with pooling and keepalive.
556 this._httpAgent = new this._httpModule.Agent({
557 maxSockets: 5,
558 keepAlive: true
559 });
560 this._clientInfo = options.clientInfo;
561 this._environmentInfo = options.environmentInfo;
562 this._sdkClientInfo = null;
563 this._sdkEnvironmentInfo = null;
564 }
565
566 _createClass(PercyClient, [{
567 key: '_headers',
568 value: function _headers(headers) {
569 return _extends({
570 Authorization: 'Token token=' + this.token,
571 'User-Agent': new UserAgent(this).toString()
572 }, headers);
573 }
574 }, {
575 key: '_httpGet',
576 value: function _httpGet(uri) {
577 var requestOptions = {
578 method: 'GET',
579 uri: uri,
580 headers: this._headers(),
581 json: true,
582 resolveWithFullResponse: true,
583 agent: this._httpAgent
584 };
585
586 return retry(this._httpClient, {
587 context: this,
588 args: [uri, requestOptions],
589 interval: 50,
590 max_tries: 5,
591 throw_original: true,
592 predicate: function predicate(err) {
593 return err.statusCode >= 500 && err.statusCode < 600;
594 }
595 });
596 }
597 }, {
598 key: '_httpPost',
599 value: function _httpPost(uri, data) {
600 var requestOptions = {
601 method: 'POST',
602 uri: uri,
603 body: data,
604 headers: this._headers({ 'Content-Type': JSON_API_CONTENT_TYPE }),
605 json: true,
606 resolveWithFullResponse: true,
607 agent: this._httpAgent
608 };
609
610 return retry(this._httpClient, {
611 context: this,
612 args: [uri, requestOptions],
613 interval: 50,
614 max_tries: 5,
615 throw_original: true,
616 predicate: function predicate(err) {
617 return err.statusCode >= 500 && err.statusCode < 600;
618 }
619 });
620 }
621 }, {
622 key: 'createBuild',
623 value: function createBuild(options) {
624 var parallelNonce = this.environment.parallelNonce;
625 var parallelTotalShards = this.environment.parallelTotalShards;
626
627 // Only pass parallelism data if it all exists.
628 if (!parallelNonce || !parallelTotalShards) {
629 parallelNonce = null;
630 parallelTotalShards = null;
631 }
632
633 options = options || {};
634
635 var commitData = options['commitData'] || this.environment.commitData;
636
637 var data = {
638 data: {
639 type: 'builds',
640 attributes: {
641 branch: commitData.branch,
642 'target-branch': this.environment.targetBranch,
643 'target-commit-sha': this.environment.targetCommitSha,
644 'commit-sha': commitData.sha,
645 'commit-committed-at': commitData.committedAt,
646 'commit-author-name': commitData.authorName,
647 'commit-author-email': commitData.authorEmail,
648 'commit-committer-name': commitData.committerName,
649 'commit-committer-email': commitData.committerEmail,
650 'commit-message': commitData.message,
651 'pull-request-number': this.environment.pullRequestNumber,
652 'parallel-nonce': parallelNonce,
653 'parallel-total-shards': parallelTotalShards,
654 partial: this.environment.partialBuild
655 }
656 }
657 };
658
659 if (options.resources) {
660 data['data']['relationships'] = {
661 resources: {
662 data: options.resources.map(function (resource) {
663 return resource.serialize();
664 })
665 }
666 };
667 }
668
669 return this._httpPost(this.apiUrl + '/builds/', data);
670 }
671
672 // This method is unavailable to normal write-only project tokens.
673
674 }, {
675 key: 'getBuild',
676 value: function getBuild(buildId) {
677 return this._httpGet(this.apiUrl + '/builds/' + buildId);
678 }
679
680 // This method is unavailable to normal write-only project tokens.
681
682 }, {
683 key: 'getBuilds',
684 value: function getBuilds(project, filter) {
685 filter = filter || {};
686 var queryString = Object.keys(filter).map(function (key) {
687 if (Array.isArray(filter[key])) {
688 // If filter value is an array, match Percy API's format expectations of:
689 // filter[key][]=value1&filter[key][]=value2
690 return filter[key].map(function (array_value) {
691 return 'filter[' + key + '][]=' + array_value;
692 }).join('&');
693 } else {
694 return 'filter[' + key + ']=' + filter[key];
695 }
696 }).join('&');
697
698 if (queryString.length > 0) {
699 queryString = '?' + queryString;
700 }
701
702 return this._httpGet(this.apiUrl + '/projects/' + project + '/builds' + queryString);
703 }
704 }, {
705 key: 'makeResource',
706 value: function makeResource(options) {
707 return new Resource(options);
708 }
709
710 // Synchronously walks a directory of compiled assets and returns an array of Resource objects.
711
712 }, {
713 key: 'gatherBuildResources',
714 value: function gatherBuildResources(rootDir, options) {
715 return utils.gatherBuildResources(this, rootDir, options);
716 }
717 }, {
718 key: 'uploadResource',
719 value: function uploadResource(buildId, content) {
720 var sha = utils.sha256hash(content);
721 var data = {
722 data: {
723 type: 'resources',
724 id: sha,
725 attributes: {
726 'base64-content': utils.base64encode(content)
727 }
728 }
729 };
730
731 return this._httpPost(this.apiUrl + '/builds/' + buildId + '/resources/', data);
732 }
733 }, {
734 key: 'uploadResources',
735 value: function uploadResources(buildId, resources) {
736 var _marked = /*#__PURE__*/regeneratorRuntime.mark(generatePromises);
737
738 var _this = this;
739 function generatePromises() {
740 var _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, resource, content;
741
742 return regeneratorRuntime.wrap(function generatePromises$(_context) {
743 while (1) {
744 switch (_context.prev = _context.next) {
745 case 0:
746 _iteratorNormalCompletion = true;
747 _didIteratorError = false;
748 _iteratorError = undefined;
749 _context.prev = 3;
750 _iterator = resources[Symbol.iterator]();
751
752 case 5:
753 if (_iteratorNormalCompletion = (_step = _iterator.next()).done) {
754 _context.next = 13;
755 break;
756 }
757
758 resource = _step.value;
759 content = resource.localPath ? fs.readFileSync(resource.localPath) : resource.content;
760 _context.next = 10;
761 return _this.uploadResource(buildId, content);
762
763 case 10:
764 _iteratorNormalCompletion = true;
765 _context.next = 5;
766 break;
767
768 case 13:
769 _context.next = 19;
770 break;
771
772 case 15:
773 _context.prev = 15;
774 _context.t0 = _context['catch'](3);
775 _didIteratorError = true;
776 _iteratorError = _context.t0;
777
778 case 19:
779 _context.prev = 19;
780 _context.prev = 20;
781
782 if (!_iteratorNormalCompletion && _iterator.return) {
783 _iterator.return();
784 }
785
786 case 22:
787 _context.prev = 22;
788
789 if (!_didIteratorError) {
790 _context.next = 25;
791 break;
792 }
793
794 throw _iteratorError;
795
796 case 25:
797 return _context.finish(22);
798
799 case 26:
800 return _context.finish(19);
801
802 case 27:
803 case 'end':
804 return _context.stop();
805 }
806 }
807 }, _marked, this, [[3, 15, 19, 27], [20,, 22, 26]]);
808 }
809
810 var pool = new PromisePool(generatePromises(), CONCURRENCY);
811 return pool.start();
812 }
813 }, {
814 key: 'uploadMissingResources',
815 value: function uploadMissingResources(buildId, response, resources) {
816 var missingResourceShas = utils.getMissingResources(response);
817 if (!missingResourceShas.length) {
818 return Promise.resolve();
819 }
820
821 var resourcesBySha = resources.reduce(function (map, resource) {
822 map[resource.sha] = resource;
823 return map;
824 }, {});
825 var missingResources = missingResourceShas.map(function (resource) {
826 return resourcesBySha[resource.id];
827 });
828
829 return this.uploadResources(buildId, missingResources);
830 }
831 }, {
832 key: 'createSnapshot',
833 value: function createSnapshot(buildId, resources, options) {
834 options = options || {};
835 resources = resources || [];
836
837 var data = {
838 data: {
839 type: 'snapshots',
840 attributes: {
841 name: options.name || null,
842 'enable-javascript': options.enableJavaScript || null,
843 widths: options.widths || null,
844 'minimum-height': options.minimumHeight || null
845 },
846 relationships: {
847 resources: {
848 data: resources.map(function (resource) {
849 return resource.serialize();
850 })
851 }
852 }
853 }
854 };
855
856 this._sdkClientInfo = options.clientInfo;
857 this._sdkEnvironmentInfo = options.environmentInfo;
858 return this._httpPost(this.apiUrl + '/builds/' + buildId + '/snapshots/', data);
859 }
860 }, {
861 key: 'finalizeSnapshot',
862 value: function finalizeSnapshot(snapshotId) {
863 return this._httpPost(this.apiUrl + '/snapshots/' + snapshotId + '/finalize', {});
864 }
865 }, {
866 key: 'finalizeBuild',
867 value: function finalizeBuild(buildId, options) {
868 options = options || {};
869 var allShards = options.allShards || false;
870 var query = allShards ? '?all-shards=true' : '';
871 return this._httpPost(this.apiUrl + '/builds/' + buildId + '/finalize' + query, {});
872 }
873 }]);
874
875 return PercyClient;
876}();
877
878module.exports = PercyClient;
879}).call(this,require('_process'))
880},{"./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){
881(function (process){
882'use strict';
883
884var _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; }; }();
885
886var _package = require('../package.json');
887
888function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
889
890var UserAgent = function () {
891 function UserAgent(client) {
892 _classCallCheck(this, UserAgent);
893
894 if (!client) {
895 throw new Error('"client" arg is required to create a UserAgent.');
896 }
897 this._client = client;
898 }
899
900 _createClass(UserAgent, [{
901 key: 'toString',
902 value: function toString() {
903 var client = ['Percy/' + this._apiVersion(), this._client._sdkClientInfo, this._client._clientInfo, 'percy-js/' + _package.version].filter(function (el) {
904 return el != null;
905 }).join(' ');
906
907 var environment = [this._client._sdkEnvironmentInfo, this._client._environmentInfo, 'node/' + this._nodeVersion(), this._client.environment.ciVersion].filter(function (el) {
908 return el != null;
909 }).join('; ');
910
911 return client + ' (' + environment + ')';
912 }
913 }, {
914 key: '_nodeVersion',
915 value: function _nodeVersion() {
916 return process.version;
917 }
918 }, {
919 key: '_apiVersion',
920 value: function _apiVersion() {
921 return (/\w+$/.exec(this._client.apiUrl)
922 );
923 }
924 }]);
925
926 return UserAgent;
927}();
928
929module.exports = UserAgent;
930}).call(this,require('_process'))
931},{"../package.json":407,"_process":265}],4:[function(require,module,exports){
932(function (Buffer){
933'use strict';
934
935var crypto = require('crypto');
936var fs = require('fs');
937var path = require('path');
938var walk = require('walk');
939
940var MAX_FILE_SIZE_BYTES = 15728640; // 15MB.
941
942module.exports = {
943 sha256hash: function sha256hash(content) {
944 return crypto.createHash('sha256').update(content, 'utf8').digest('hex');
945 },
946 base64encode: function base64encode(content) {
947 return Buffer.from(content).toString('base64');
948 },
949 getMissingResources: function getMissingResources(response) {
950 return response && response.body && response.body.data && response.body.data.relationships && response.body.data.relationships['missing-resources'] && response.body.data.relationships['missing-resources'].data || [];
951 },
952
953
954 // Synchronously walk a directory of compiled assets, read each file and calculate its SHA 256
955 // hash, and create an array of Resource objects.
956 gatherBuildResources: function gatherBuildResources(percyClient, rootDir) {
957 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
958
959 // The base of the URL that will be prepended to every resource URL, such as "/assets".
960 options.baseUrlPath = options.baseUrlPath || '';
961 options.skippedPathRegexes = options.skippedPathRegexes || [];
962 options.followLinks = options.followLinks || true;
963
964 var resources = [];
965
966 var fileWalker = function fileWalker(root, fileStats, next) {
967 var absolutePath = path.join(root, fileStats.name);
968 var resourceUrl = absolutePath.replace(rootDir, '');
969
970 if (path.sep == '\\') {
971 // Windows support: transform filesystem backslashes into forward-slashes for the URL.
972 resourceUrl = resourceUrl.replace(/\\/g, '/');
973 }
974
975 // Prepend the baseUrlPath if it is given. We normalize it to make sure it does not have
976 // a trailing slash, or it's a blank string.
977 var normalizedBaseUrlPath = (options.baseUrlPath || '/').replace(/\/$/, '');
978 resourceUrl = normalizedBaseUrlPath + resourceUrl;
979
980 // Skip excluded paths.
981 for (var i in options.skippedPathRegexes) {
982 if (resourceUrl.match(options.skippedPathRegexes[i])) {
983 next();
984 return;
985 }
986 }
987
988 // Skip large files.
989 if (fs.statSync(absolutePath)['size'] > MAX_FILE_SIZE_BYTES) {
990 // eslint-disable-next-line no-console
991 console.warn('\n[percy][WARNING] Skipping large build resource: ', resourceUrl);
992 return;
993 }
994
995 // Note: this is synchronous and potentially memory intensive, but we don't keep a
996 // reference to the content around so each should be garbage collected. Reevaluate?
997 var content = fs.readFileSync(absolutePath);
998 var sha = crypto.createHash('sha256').update(content).digest('hex');
999
1000 var resource = percyClient.makeResource({
1001 resourceUrl: encodeURI(resourceUrl),
1002 sha: sha,
1003 localPath: absolutePath
1004 });
1005
1006 resources.push(resource);
1007 next();
1008 };
1009
1010 var walkOptions = {
1011 // Follow symlinks because assets may be just symlinks.
1012 followLinks: options.followLinks,
1013 listeners: {
1014 file: fileWalker
1015 }
1016 };
1017 walk.walkSync(rootDir, walkOptions);
1018
1019 return resources;
1020 },
1021 reverseString: function reverseString(str) {
1022 return str.split('').reverse().join('');
1023 }
1024};
1025}).call(this,require("buffer").Buffer)
1026},{"buffer":114,"crypto":126,"fs":112,"path":257,"walk":405}],5:[function(require,module,exports){
1027'use strict';
1028
1029var compileSchema = require('./compile')
1030 , resolve = require('./compile/resolve')
1031 , Cache = require('./cache')
1032 , SchemaObject = require('./compile/schema_obj')
1033 , stableStringify = require('fast-json-stable-stringify')
1034 , formats = require('./compile/formats')
1035 , rules = require('./compile/rules')
1036 , $dataMetaSchema = require('./data')
1037 , util = require('./compile/util');
1038
1039module.exports = Ajv;
1040
1041Ajv.prototype.validate = validate;
1042Ajv.prototype.compile = compile;
1043Ajv.prototype.addSchema = addSchema;
1044Ajv.prototype.addMetaSchema = addMetaSchema;
1045Ajv.prototype.validateSchema = validateSchema;
1046Ajv.prototype.getSchema = getSchema;
1047Ajv.prototype.removeSchema = removeSchema;
1048Ajv.prototype.addFormat = addFormat;
1049Ajv.prototype.errorsText = errorsText;
1050
1051Ajv.prototype._addSchema = _addSchema;
1052Ajv.prototype._compile = _compile;
1053
1054Ajv.prototype.compileAsync = require('./compile/async');
1055var customKeyword = require('./keyword');
1056Ajv.prototype.addKeyword = customKeyword.add;
1057Ajv.prototype.getKeyword = customKeyword.get;
1058Ajv.prototype.removeKeyword = customKeyword.remove;
1059Ajv.prototype.validateKeyword = customKeyword.validate;
1060
1061var errorClasses = require('./compile/error_classes');
1062Ajv.ValidationError = errorClasses.Validation;
1063Ajv.MissingRefError = errorClasses.MissingRef;
1064Ajv.$dataMetaSchema = $dataMetaSchema;
1065
1066var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
1067
1068var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
1069var META_SUPPORT_DATA = ['/properties'];
1070
1071/**
1072 * Creates validator instance.
1073 * Usage: `Ajv(opts)`
1074 * @param {Object} opts optional options
1075 * @return {Object} ajv instance
1076 */
1077function Ajv(opts) {
1078 if (!(this instanceof Ajv)) return new Ajv(opts);
1079 opts = this._opts = util.copy(opts) || {};
1080 setLogger(this);
1081 this._schemas = {};
1082 this._refs = {};
1083 this._fragments = {};
1084 this._formats = formats(opts.format);
1085
1086 this._cache = opts.cache || new Cache;
1087 this._loadingSchemas = {};
1088 this._compilations = [];
1089 this.RULES = rules();
1090 this._getId = chooseGetId(opts);
1091
1092 opts.loopRequired = opts.loopRequired || Infinity;
1093 if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
1094 if (opts.serialize === undefined) opts.serialize = stableStringify;
1095 this._metaOpts = getMetaSchemaOptions(this);
1096
1097 if (opts.formats) addInitialFormats(this);
1098 addDefaultMetaSchema(this);
1099 if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
1100 if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
1101 addInitialSchemas(this);
1102}
1103
1104
1105
1106/**
1107 * Validate data using schema
1108 * 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.
1109 * @this Ajv
1110 * @param {String|Object} schemaKeyRef key, ref or schema object
1111 * @param {Any} data to be validated
1112 * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
1113 */
1114function validate(schemaKeyRef, data) {
1115 var v;
1116 if (typeof schemaKeyRef == 'string') {
1117 v = this.getSchema(schemaKeyRef);
1118 if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
1119 } else {
1120 var schemaObj = this._addSchema(schemaKeyRef);
1121 v = schemaObj.validate || this._compile(schemaObj);
1122 }
1123
1124 var valid = v(data);
1125 if (v.$async !== true) this.errors = v.errors;
1126 return valid;
1127}
1128
1129
1130/**
1131 * Create validating function for passed schema.
1132 * @this Ajv
1133 * @param {Object} schema schema object
1134 * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
1135 * @return {Function} validating function
1136 */
1137function compile(schema, _meta) {
1138 var schemaObj = this._addSchema(schema, undefined, _meta);
1139 return schemaObj.validate || this._compile(schemaObj);
1140}
1141
1142
1143/**
1144 * Adds schema to the instance.
1145 * @this Ajv
1146 * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
1147 * @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`.
1148 * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
1149 * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
1150 * @return {Ajv} this for method chaining
1151 */
1152function addSchema(schema, key, _skipValidation, _meta) {
1153 if (Array.isArray(schema)){
1154 for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta);
1155 return this;
1156 }
1157 var id = this._getId(schema);
1158 if (id !== undefined && typeof id != 'string')
1159 throw new Error('schema id must be string');
1160 key = resolve.normalizeId(key || id);
1161 checkUnique(this, key);
1162 this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
1163 return this;
1164}
1165
1166
1167/**
1168 * Add schema that will be used to validate other schemas
1169 * options in META_IGNORE_OPTIONS are alway set to false
1170 * @this Ajv
1171 * @param {Object} schema schema object
1172 * @param {String} key optional schema key
1173 * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema
1174 * @return {Ajv} this for method chaining
1175 */
1176function addMetaSchema(schema, key, skipValidation) {
1177 this.addSchema(schema, key, skipValidation, true);
1178 return this;
1179}
1180
1181
1182/**
1183 * Validate schema
1184 * @this Ajv
1185 * @param {Object} schema schema to validate
1186 * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid
1187 * @return {Boolean} true if schema is valid
1188 */
1189function validateSchema(schema, throwOrLogError) {
1190 var $schema = schema.$schema;
1191 if ($schema !== undefined && typeof $schema != 'string')
1192 throw new Error('$schema must be a string');
1193 $schema = $schema || this._opts.defaultMeta || defaultMeta(this);
1194 if (!$schema) {
1195 this.logger.warn('meta-schema not available');
1196 this.errors = null;
1197 return true;
1198 }
1199 var valid = this.validate($schema, schema);
1200 if (!valid && throwOrLogError) {
1201 var message = 'schema is invalid: ' + this.errorsText();
1202 if (this._opts.validateSchema == 'log') this.logger.error(message);
1203 else throw new Error(message);
1204 }
1205 return valid;
1206}
1207
1208
1209function defaultMeta(self) {
1210 var meta = self._opts.meta;
1211 self._opts.defaultMeta = typeof meta == 'object'
1212 ? self._getId(meta) || meta
1213 : self.getSchema(META_SCHEMA_ID)
1214 ? META_SCHEMA_ID
1215 : undefined;
1216 return self._opts.defaultMeta;
1217}
1218
1219
1220/**
1221 * Get compiled schema from the instance by `key` or `ref`.
1222 * @this Ajv
1223 * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id).
1224 * @return {Function} schema validating function (with property `schema`).
1225 */
1226function getSchema(keyRef) {
1227 var schemaObj = _getSchemaObj(this, keyRef);
1228 switch (typeof schemaObj) {
1229 case 'object': return schemaObj.validate || this._compile(schemaObj);
1230 case 'string': return this.getSchema(schemaObj);
1231 case 'undefined': return _getSchemaFragment(this, keyRef);
1232 }
1233}
1234
1235
1236function _getSchemaFragment(self, ref) {
1237 var res = resolve.schema.call(self, { schema: {} }, ref);
1238 if (res) {
1239 var schema = res.schema
1240 , root = res.root
1241 , baseId = res.baseId;
1242 var v = compileSchema.call(self, schema, root, undefined, baseId);
1243 self._fragments[ref] = new SchemaObject({
1244 ref: ref,
1245 fragment: true,
1246 schema: schema,
1247 root: root,
1248 baseId: baseId,
1249 validate: v
1250 });
1251 return v;
1252 }
1253}
1254
1255
1256function _getSchemaObj(self, keyRef) {
1257 keyRef = resolve.normalizeId(keyRef);
1258 return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
1259}
1260
1261
1262/**
1263 * Remove cached schema(s).
1264 * If no parameter is passed all schemas but meta-schemas are removed.
1265 * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
1266 * Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
1267 * @this Ajv
1268 * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object
1269 * @return {Ajv} this for method chaining
1270 */
1271function removeSchema(schemaKeyRef) {
1272 if (schemaKeyRef instanceof RegExp) {
1273 _removeAllSchemas(this, this._schemas, schemaKeyRef);
1274 _removeAllSchemas(this, this._refs, schemaKeyRef);
1275 return this;
1276 }
1277 switch (typeof schemaKeyRef) {
1278 case 'undefined':
1279 _removeAllSchemas(this, this._schemas);
1280 _removeAllSchemas(this, this._refs);
1281 this._cache.clear();
1282 return this;
1283 case 'string':
1284 var schemaObj = _getSchemaObj(this, schemaKeyRef);
1285 if (schemaObj) this._cache.del(schemaObj.cacheKey);
1286 delete this._schemas[schemaKeyRef];
1287 delete this._refs[schemaKeyRef];
1288 return this;
1289 case 'object':
1290 var serialize = this._opts.serialize;
1291 var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
1292 this._cache.del(cacheKey);
1293 var id = this._getId(schemaKeyRef);
1294 if (id) {
1295 id = resolve.normalizeId(id);
1296 delete this._schemas[id];
1297 delete this._refs[id];
1298 }
1299 }
1300 return this;
1301}
1302
1303
1304function _removeAllSchemas(self, schemas, regex) {
1305 for (var keyRef in schemas) {
1306 var schemaObj = schemas[keyRef];
1307 if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
1308 self._cache.del(schemaObj.cacheKey);
1309 delete schemas[keyRef];
1310 }
1311 }
1312}
1313
1314
1315/* @this Ajv */
1316function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
1317 if (typeof schema != 'object' && typeof schema != 'boolean')
1318 throw new Error('schema should be object or boolean');
1319 var serialize = this._opts.serialize;
1320 var cacheKey = serialize ? serialize(schema) : schema;
1321 var cached = this._cache.get(cacheKey);
1322 if (cached) return cached;
1323
1324 shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false;
1325
1326 var id = resolve.normalizeId(this._getId(schema));
1327 if (id && shouldAddSchema) checkUnique(this, id);
1328
1329 var willValidate = this._opts.validateSchema !== false && !skipValidation;
1330 var recursiveMeta;
1331 if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema)))
1332 this.validateSchema(schema, true);
1333
1334 var localRefs = resolve.ids.call(this, schema);
1335
1336 var schemaObj = new SchemaObject({
1337 id: id,
1338 schema: schema,
1339 localRefs: localRefs,
1340 cacheKey: cacheKey,
1341 meta: meta
1342 });
1343
1344 if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj;
1345 this._cache.put(cacheKey, schemaObj);
1346
1347 if (willValidate && recursiveMeta) this.validateSchema(schema, true);
1348
1349 return schemaObj;
1350}
1351
1352
1353/* @this Ajv */
1354function _compile(schemaObj, root) {
1355 if (schemaObj.compiling) {
1356 schemaObj.validate = callValidate;
1357 callValidate.schema = schemaObj.schema;
1358 callValidate.errors = null;
1359 callValidate.root = root ? root : callValidate;
1360 if (schemaObj.schema.$async === true)
1361 callValidate.$async = true;
1362 return callValidate;
1363 }
1364 schemaObj.compiling = true;
1365
1366 var currentOpts;
1367 if (schemaObj.meta) {
1368 currentOpts = this._opts;
1369 this._opts = this._metaOpts;
1370 }
1371
1372 var v;
1373 try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); }
1374 catch(e) {
1375 delete schemaObj.validate;
1376 throw e;
1377 }
1378 finally {
1379 schemaObj.compiling = false;
1380 if (schemaObj.meta) this._opts = currentOpts;
1381 }
1382
1383 schemaObj.validate = v;
1384 schemaObj.refs = v.refs;
1385 schemaObj.refVal = v.refVal;
1386 schemaObj.root = v.root;
1387 return v;
1388
1389
1390 /* @this {*} - custom context, see passContext option */
1391 function callValidate() {
1392 /* jshint validthis: true */
1393 var _validate = schemaObj.validate;
1394 var result = _validate.apply(this, arguments);
1395 callValidate.errors = _validate.errors;
1396 return result;
1397 }
1398}
1399
1400
1401function chooseGetId(opts) {
1402 switch (opts.schemaId) {
1403 case 'auto': return _get$IdOrId;
1404 case 'id': return _getId;
1405 default: return _get$Id;
1406 }
1407}
1408
1409/* @this Ajv */
1410function _getId(schema) {
1411 if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
1412 return schema.id;
1413}
1414
1415/* @this Ajv */
1416function _get$Id(schema) {
1417 if (schema.id) this.logger.warn('schema id ignored', schema.id);
1418 return schema.$id;
1419}
1420
1421
1422function _get$IdOrId(schema) {
1423 if (schema.$id && schema.id && schema.$id != schema.id)
1424 throw new Error('schema $id is different from id');
1425 return schema.$id || schema.id;
1426}
1427
1428
1429/**
1430 * Convert array of error message objects to string
1431 * @this Ajv
1432 * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used.
1433 * @param {Object} options optional options with properties `separator` and `dataVar`.
1434 * @return {String} human readable string with all errors descriptions
1435 */
1436function errorsText(errors, options) {
1437 errors = errors || this.errors;
1438 if (!errors) return 'No errors';
1439 options = options || {};
1440 var separator = options.separator === undefined ? ', ' : options.separator;
1441 var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
1442
1443 var text = '';
1444 for (var i=0; i<errors.length; i++) {
1445 var e = errors[i];
1446 if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
1447 }
1448 return text.slice(0, -separator.length);
1449}
1450
1451
1452/**
1453 * Add custom format
1454 * @this Ajv
1455 * @param {String} name format name
1456 * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid)
1457 * @return {Ajv} this for method chaining
1458 */
1459function addFormat(name, format) {
1460 if (typeof format == 'string') format = new RegExp(format);
1461 this._formats[name] = format;
1462 return this;
1463}
1464
1465
1466function addDefaultMetaSchema(self) {
1467 var $dataSchema;
1468 if (self._opts.$data) {
1469 $dataSchema = require('./refs/data.json');
1470 self.addMetaSchema($dataSchema, $dataSchema.$id, true);
1471 }
1472 if (self._opts.meta === false) return;
1473 var metaSchema = require('./refs/json-schema-draft-07.json');
1474 if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
1475 self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
1476 self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
1477}
1478
1479
1480function addInitialSchemas(self) {
1481 var optsSchemas = self._opts.schemas;
1482 if (!optsSchemas) return;
1483 if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
1484 else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key);
1485}
1486
1487
1488function addInitialFormats(self) {
1489 for (var name in self._opts.formats) {
1490 var format = self._opts.formats[name];
1491 self.addFormat(name, format);
1492 }
1493}
1494
1495
1496function checkUnique(self, id) {
1497 if (self._schemas[id] || self._refs[id])
1498 throw new Error('schema with key or id "' + id + '" already exists');
1499}
1500
1501
1502function getMetaSchemaOptions(self) {
1503 var metaOpts = util.copy(self._opts);
1504 for (var i=0; i<META_IGNORE_OPTIONS.length; i++)
1505 delete metaOpts[META_IGNORE_OPTIONS[i]];
1506 return metaOpts;
1507}
1508
1509
1510function setLogger(self) {
1511 var logger = self._opts.logger;
1512 if (logger === false) {
1513 self.logger = {log: noop, warn: noop, error: noop};
1514 } else {
1515 if (logger === undefined) logger = console;
1516 if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error))
1517 throw new Error('logger must implement log, warn and error methods');
1518 self.logger = logger;
1519 }
1520}
1521
1522
1523function noop() {}
1524
1525},{"./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){
1526'use strict';
1527
1528
1529var Cache = module.exports = function Cache() {
1530 this._cache = {};
1531};
1532
1533
1534Cache.prototype.put = function Cache_put(key, value) {
1535 this._cache[key] = value;
1536};
1537
1538
1539Cache.prototype.get = function Cache_get(key) {
1540 return this._cache[key];
1541};
1542
1543
1544Cache.prototype.del = function Cache_del(key) {
1545 delete this._cache[key];
1546};
1547
1548
1549Cache.prototype.clear = function Cache_clear() {
1550 this._cache = {};
1551};
1552
1553},{}],7:[function(require,module,exports){
1554'use strict';
1555
1556var MissingRefError = require('./error_classes').MissingRef;
1557
1558module.exports = compileAsync;
1559
1560
1561/**
1562 * Creates validating function for passed schema with asynchronous loading of missing schemas.
1563 * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
1564 * @this Ajv
1565 * @param {Object} schema schema object
1566 * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped
1567 * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function.
1568 * @return {Promise} promise that resolves with a validating function.
1569 */
1570function compileAsync(schema, meta, callback) {
1571 /* eslint no-shadow: 0 */
1572 /* global Promise */
1573 /* jshint validthis: true */
1574 var self = this;
1575 if (typeof this._opts.loadSchema != 'function')
1576 throw new Error('options.loadSchema should be a function');
1577
1578 if (typeof meta == 'function') {
1579 callback = meta;
1580 meta = undefined;
1581 }
1582
1583 var p = loadMetaSchemaOf(schema).then(function () {
1584 var schemaObj = self._addSchema(schema, undefined, meta);
1585 return schemaObj.validate || _compileAsync(schemaObj);
1586 });
1587
1588 if (callback) {
1589 p.then(
1590 function(v) { callback(null, v); },
1591 callback
1592 );
1593 }
1594
1595 return p;
1596
1597
1598 function loadMetaSchemaOf(sch) {
1599 var $schema = sch.$schema;
1600 return $schema && !self.getSchema($schema)
1601 ? compileAsync.call(self, { $ref: $schema }, true)
1602 : Promise.resolve();
1603 }
1604
1605
1606 function _compileAsync(schemaObj) {
1607 try { return self._compile(schemaObj); }
1608 catch(e) {
1609 if (e instanceof MissingRefError) return loadMissingSchema(e);
1610 throw e;
1611 }
1612
1613
1614 function loadMissingSchema(e) {
1615 var ref = e.missingSchema;
1616 if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
1617
1618 var schemaPromise = self._loadingSchemas[ref];
1619 if (!schemaPromise) {
1620 schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
1621 schemaPromise.then(removePromise, removePromise);
1622 }
1623
1624 return schemaPromise.then(function (sch) {
1625 if (!added(ref)) {
1626 return loadMetaSchemaOf(sch).then(function () {
1627 if (!added(ref)) self.addSchema(sch, ref, undefined, meta);
1628 });
1629 }
1630 }).then(function() {
1631 return _compileAsync(schemaObj);
1632 });
1633
1634 function removePromise() {
1635 delete self._loadingSchemas[ref];
1636 }
1637
1638 function added(ref) {
1639 return self._refs[ref] || self._schemas[ref];
1640 }
1641 }
1642 }
1643}
1644
1645},{"./error_classes":8}],8:[function(require,module,exports){
1646'use strict';
1647
1648var resolve = require('./resolve');
1649
1650module.exports = {
1651 Validation: errorSubclass(ValidationError),
1652 MissingRef: errorSubclass(MissingRefError)
1653};
1654
1655
1656function ValidationError(errors) {
1657 this.message = 'validation failed';
1658 this.errors = errors;
1659 this.ajv = this.validation = true;
1660}
1661
1662
1663MissingRefError.message = function (baseId, ref) {
1664 return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
1665};
1666
1667
1668function MissingRefError(baseId, ref, message) {
1669 this.message = message || MissingRefError.message(baseId, ref);
1670 this.missingRef = resolve.url(baseId, ref);
1671 this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
1672}
1673
1674
1675function errorSubclass(Subclass) {
1676 Subclass.prototype = Object.create(Error.prototype);
1677 Subclass.prototype.constructor = Subclass;
1678 return Subclass;
1679}
1680
1681},{"./resolve":11}],9:[function(require,module,exports){
1682'use strict';
1683
1684var util = require('./util');
1685
1686var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
1687var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31];
1688var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d:\d\d)?$/i;
1689var HOSTNAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i;
1690var 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;
1691var 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;
1692// uri-template: https://tools.ietf.org/html/rfc6570
1693var 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;
1694// For the source: https://gist.github.com/dperini/729294
1695// For test cases: https://mathiasbynens.be/demo/url-regex
1696// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
1697// 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;
1698var 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;
1699var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
1700var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
1701var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
1702var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
1703
1704
1705module.exports = formats;
1706
1707function formats(mode) {
1708 mode = mode == 'full' ? 'full' : 'fast';
1709 return util.copy(formats[mode]);
1710}
1711
1712
1713formats.fast = {
1714 // date: http://tools.ietf.org/html/rfc3339#section-5.6
1715 date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
1716 // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
1717 time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
1718 '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,
1719 // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
1720 uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i,
1721 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
1722 'uri-template': URITEMPLATE,
1723 url: URL,
1724 // email (sources from jsen validator):
1725 // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
1726 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
1727 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,
1728 hostname: HOSTNAME,
1729 // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
1730 ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
1731 // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
1732 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,
1733 regex: regex,
1734 // uuid: http://tools.ietf.org/html/rfc4122
1735 uuid: UUID,
1736 // JSON-pointer: https://tools.ietf.org/html/rfc6901
1737 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
1738 'json-pointer': JSON_POINTER,
1739 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
1740 // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
1741 'relative-json-pointer': RELATIVE_JSON_POINTER
1742};
1743
1744
1745formats.full = {
1746 date: date,
1747 time: time,
1748 'date-time': date_time,
1749 uri: uri,
1750 'uri-reference': URIREF,
1751 'uri-template': URITEMPLATE,
1752 url: URL,
1753 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,
1754 hostname: hostname,
1755 ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
1756 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,
1757 regex: regex,
1758 uuid: UUID,
1759 'json-pointer': JSON_POINTER,
1760 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
1761 'relative-json-pointer': RELATIVE_JSON_POINTER
1762};
1763
1764
1765function isLeapYear(year) {
1766 // https://tools.ietf.org/html/rfc3339#appendix-C
1767 return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1768}
1769
1770
1771function date(str) {
1772 // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
1773 var matches = str.match(DATE);
1774 if (!matches) return false;
1775
1776 var year = +matches[1];
1777 var month = +matches[2];
1778 var day = +matches[3];
1779
1780 return month >= 1 && month <= 12 && day >= 1 &&
1781 day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
1782}
1783
1784
1785function time(str, full) {
1786 var matches = str.match(TIME);
1787 if (!matches) return false;
1788
1789 var hour = matches[1];
1790 var minute = matches[2];
1791 var second = matches[3];
1792 var timeZone = matches[5];
1793 return ((hour <= 23 && minute <= 59 && second <= 59) ||
1794 (hour == 23 && minute == 59 && second == 60)) &&
1795 (!full || timeZone);
1796}
1797
1798
1799var DATE_TIME_SEPARATOR = /t|\s/i;
1800function date_time(str) {
1801 // http://tools.ietf.org/html/rfc3339#section-5.6
1802 var dateTime = str.split(DATE_TIME_SEPARATOR);
1803 return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
1804}
1805
1806
1807function hostname(str) {
1808 // https://tools.ietf.org/html/rfc1034#section-3.5
1809 // https://tools.ietf.org/html/rfc1123#section-2
1810 return str.length <= 255 && HOSTNAME.test(str);
1811}
1812
1813
1814var NOT_URI_FRAGMENT = /\/|:/;
1815function uri(str) {
1816 // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
1817 return NOT_URI_FRAGMENT.test(str) && URI.test(str);
1818}
1819
1820
1821var Z_ANCHOR = /[^\\]\\Z/;
1822function regex(str) {
1823 if (Z_ANCHOR.test(str)) return false;
1824 try {
1825 new RegExp(str);
1826 return true;
1827 } catch(e) {
1828 return false;
1829 }
1830}
1831
1832},{"./util":15}],10:[function(require,module,exports){
1833'use strict';
1834
1835var resolve = require('./resolve')
1836 , util = require('./util')
1837 , errorClasses = require('./error_classes')
1838 , stableStringify = require('fast-json-stable-stringify');
1839
1840var validateGenerator = require('../dotjs/validate');
1841
1842/**
1843 * Functions below are used inside compiled validations function
1844 */
1845
1846var ucs2length = util.ucs2length;
1847var equal = require('fast-deep-equal');
1848
1849// this error is thrown by async schemas to return validation errors via exception
1850var ValidationError = errorClasses.Validation;
1851
1852module.exports = compile;
1853
1854
1855/**
1856 * Compiles schema to validation function
1857 * @this Ajv
1858 * @param {Object} schema schema object
1859 * @param {Object} root object with information about the root schema for this schema
1860 * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
1861 * @param {String} baseId base ID for IDs in the schema
1862 * @return {Function} validation function
1863 */
1864function compile(schema, root, localRefs, baseId) {
1865 /* jshint validthis: true, evil: true */
1866 /* eslint no-shadow: 0 */
1867 var self = this
1868 , opts = this._opts
1869 , refVal = [ undefined ]
1870 , refs = {}
1871 , patterns = []
1872 , patternsHash = {}
1873 , defaults = []
1874 , defaultsHash = {}
1875 , customRules = [];
1876
1877 root = root || { schema: schema, refVal: refVal, refs: refs };
1878
1879 var c = checkCompiling.call(this, schema, root, baseId);
1880 var compilation = this._compilations[c.index];
1881 if (c.compiling) return (compilation.callValidate = callValidate);
1882
1883 var formats = this._formats;
1884 var RULES = this.RULES;
1885
1886 try {
1887 var v = localCompile(schema, root, localRefs, baseId);
1888 compilation.validate = v;
1889 var cv = compilation.callValidate;
1890 if (cv) {
1891 cv.schema = v.schema;
1892 cv.errors = null;
1893 cv.refs = v.refs;
1894 cv.refVal = v.refVal;
1895 cv.root = v.root;
1896 cv.$async = v.$async;
1897 if (opts.sourceCode) cv.source = v.source;
1898 }
1899 return v;
1900 } finally {
1901 endCompiling.call(this, schema, root, baseId);
1902 }
1903
1904 /* @this {*} - custom context, see passContext option */
1905 function callValidate() {
1906 /* jshint validthis: true */
1907 var validate = compilation.validate;
1908 var result = validate.apply(this, arguments);
1909 callValidate.errors = validate.errors;
1910 return result;
1911 }
1912
1913 function localCompile(_schema, _root, localRefs, baseId) {
1914 var isRoot = !_root || (_root && _root.schema == _schema);
1915 if (_root.schema != root.schema)
1916 return compile.call(self, _schema, _root, localRefs, baseId);
1917
1918 var $async = _schema.$async === true;
1919
1920 var sourceCode = validateGenerator({
1921 isTop: true,
1922 schema: _schema,
1923 isRoot: isRoot,
1924 baseId: baseId,
1925 root: _root,
1926 schemaPath: '',
1927 errSchemaPath: '#',
1928 errorPath: '""',
1929 MissingRefError: errorClasses.MissingRef,
1930 RULES: RULES,
1931 validate: validateGenerator,
1932 util: util,
1933 resolve: resolve,
1934 resolveRef: resolveRef,
1935 usePattern: usePattern,
1936 useDefault: useDefault,
1937 useCustomRule: useCustomRule,
1938 opts: opts,
1939 formats: formats,
1940 logger: self.logger,
1941 self: self
1942 });
1943
1944 sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
1945 + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
1946 + sourceCode;
1947
1948 if (opts.processCode) sourceCode = opts.processCode(sourceCode);
1949 // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
1950 var validate;
1951 try {
1952 var makeValidate = new Function(
1953 'self',
1954 'RULES',
1955 'formats',
1956 'root',
1957 'refVal',
1958 'defaults',
1959 'customRules',
1960 'equal',
1961 'ucs2length',
1962 'ValidationError',
1963 sourceCode
1964 );
1965
1966 validate = makeValidate(
1967 self,
1968 RULES,
1969 formats,
1970 root,
1971 refVal,
1972 defaults,
1973 customRules,
1974 equal,
1975 ucs2length,
1976 ValidationError
1977 );
1978
1979 refVal[0] = validate;
1980 } catch(e) {
1981 self.logger.error('Error compiling schema, function code:', sourceCode);
1982 throw e;
1983 }
1984
1985 validate.schema = _schema;
1986 validate.errors = null;
1987 validate.refs = refs;
1988 validate.refVal = refVal;
1989 validate.root = isRoot ? validate : _root;
1990 if ($async) validate.$async = true;
1991 if (opts.sourceCode === true) {
1992 validate.source = {
1993 code: sourceCode,
1994 patterns: patterns,
1995 defaults: defaults
1996 };
1997 }
1998
1999 return validate;
2000 }
2001
2002 function resolveRef(baseId, ref, isRoot) {
2003 ref = resolve.url(baseId, ref);
2004 var refIndex = refs[ref];
2005 var _refVal, refCode;
2006 if (refIndex !== undefined) {
2007 _refVal = refVal[refIndex];
2008 refCode = 'refVal[' + refIndex + ']';
2009 return resolvedRef(_refVal, refCode);
2010 }
2011 if (!isRoot && root.refs) {
2012 var rootRefId = root.refs[ref];
2013 if (rootRefId !== undefined) {
2014 _refVal = root.refVal[rootRefId];
2015 refCode = addLocalRef(ref, _refVal);
2016 return resolvedRef(_refVal, refCode);
2017 }
2018 }
2019
2020 refCode = addLocalRef(ref);
2021 var v = resolve.call(self, localCompile, root, ref);
2022 if (v === undefined) {
2023 var localSchema = localRefs && localRefs[ref];
2024 if (localSchema) {
2025 v = resolve.inlineRef(localSchema, opts.inlineRefs)
2026 ? localSchema
2027 : compile.call(self, localSchema, root, localRefs, baseId);
2028 }
2029 }
2030
2031 if (v === undefined) {
2032 removeLocalRef(ref);
2033 } else {
2034 replaceLocalRef(ref, v);
2035 return resolvedRef(v, refCode);
2036 }
2037 }
2038
2039 function addLocalRef(ref, v) {
2040 var refId = refVal.length;
2041 refVal[refId] = v;
2042 refs[ref] = refId;
2043 return 'refVal' + refId;
2044 }
2045
2046 function removeLocalRef(ref) {
2047 delete refs[ref];
2048 }
2049
2050 function replaceLocalRef(ref, v) {
2051 var refId = refs[ref];
2052 refVal[refId] = v;
2053 }
2054
2055 function resolvedRef(refVal, code) {
2056 return typeof refVal == 'object' || typeof refVal == 'boolean'
2057 ? { code: code, schema: refVal, inline: true }
2058 : { code: code, $async: refVal && !!refVal.$async };
2059 }
2060
2061 function usePattern(regexStr) {
2062 var index = patternsHash[regexStr];
2063 if (index === undefined) {
2064 index = patternsHash[regexStr] = patterns.length;
2065 patterns[index] = regexStr;
2066 }
2067 return 'pattern' + index;
2068 }
2069
2070 function useDefault(value) {
2071 switch (typeof value) {
2072 case 'boolean':
2073 case 'number':
2074 return '' + value;
2075 case 'string':
2076 return util.toQuotedString(value);
2077 case 'object':
2078 if (value === null) return 'null';
2079 var valueStr = stableStringify(value);
2080 var index = defaultsHash[valueStr];
2081 if (index === undefined) {
2082 index = defaultsHash[valueStr] = defaults.length;
2083 defaults[index] = value;
2084 }
2085 return 'default' + index;
2086 }
2087 }
2088
2089 function useCustomRule(rule, schema, parentSchema, it) {
2090 if (self._opts.validateSchema !== false) {
2091 var deps = rule.definition.dependencies;
2092 if (deps && !deps.every(function(keyword) {
2093 return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
2094 }))
2095 throw new Error('parent schema must have all required keywords: ' + deps.join(','));
2096
2097 var validateSchema = rule.definition.validateSchema;
2098 if (validateSchema) {
2099 var valid = validateSchema(schema);
2100 if (!valid) {
2101 var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
2102 if (self._opts.validateSchema == 'log') self.logger.error(message);
2103 else throw new Error(message);
2104 }
2105 }
2106 }
2107
2108 var compile = rule.definition.compile
2109 , inline = rule.definition.inline
2110 , macro = rule.definition.macro;
2111
2112 var validate;
2113 if (compile) {
2114 validate = compile.call(self, schema, parentSchema, it);
2115 } else if (macro) {
2116 validate = macro.call(self, schema, parentSchema, it);
2117 if (opts.validateSchema !== false) self.validateSchema(validate, true);
2118 } else if (inline) {
2119 validate = inline.call(self, it, rule.keyword, schema, parentSchema);
2120 } else {
2121 validate = rule.definition.validate;
2122 if (!validate) return;
2123 }
2124
2125 if (validate === undefined)
2126 throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
2127
2128 var index = customRules.length;
2129 customRules[index] = validate;
2130
2131 return {
2132 code: 'customRule' + index,
2133 validate: validate
2134 };
2135 }
2136}
2137
2138
2139/**
2140 * Checks if the schema is currently compiled
2141 * @this Ajv
2142 * @param {Object} schema schema to compile
2143 * @param {Object} root root object
2144 * @param {String} baseId base schema ID
2145 * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
2146 */
2147function checkCompiling(schema, root, baseId) {
2148 /* jshint validthis: true */
2149 var index = compIndex.call(this, schema, root, baseId);
2150 if (index >= 0) return { index: index, compiling: true };
2151 index = this._compilations.length;
2152 this._compilations[index] = {
2153 schema: schema,
2154 root: root,
2155 baseId: baseId
2156 };
2157 return { index: index, compiling: false };
2158}
2159
2160
2161/**
2162 * Removes the schema from the currently compiled list
2163 * @this Ajv
2164 * @param {Object} schema schema to compile
2165 * @param {Object} root root object
2166 * @param {String} baseId base schema ID
2167 */
2168function endCompiling(schema, root, baseId) {
2169 /* jshint validthis: true */
2170 var i = compIndex.call(this, schema, root, baseId);
2171 if (i >= 0) this._compilations.splice(i, 1);
2172}
2173
2174
2175/**
2176 * Index of schema compilation in the currently compiled list
2177 * @this Ajv
2178 * @param {Object} schema schema to compile
2179 * @param {Object} root root object
2180 * @param {String} baseId base schema ID
2181 * @return {Integer} compilation index
2182 */
2183function compIndex(schema, root, baseId) {
2184 /* jshint validthis: true */
2185 for (var i=0; i<this._compilations.length; i++) {
2186 var c = this._compilations[i];
2187 if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
2188 }
2189 return -1;
2190}
2191
2192
2193function patternCode(i, patterns) {
2194 return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
2195}
2196
2197
2198function defaultCode(i) {
2199 return 'var default' + i + ' = defaults[' + i + '];';
2200}
2201
2202
2203function refValCode(i, refVal) {
2204 return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
2205}
2206
2207
2208function customRuleCode(i) {
2209 return 'var customRule' + i + ' = customRules[' + i + '];';
2210}
2211
2212
2213function vars(arr, statement) {
2214 if (!arr.length) return '';
2215 var code = '';
2216 for (var i=0; i<arr.length; i++)
2217 code += statement(i, arr);
2218 return code;
2219}
2220
2221},{"../dotjs/validate":42,"./error_classes":8,"./resolve":11,"./util":15,"fast-deep-equal":163,"fast-json-stable-stringify":164}],11:[function(require,module,exports){
2222'use strict';
2223
2224var URI = require('uri-js')
2225 , equal = require('fast-deep-equal')
2226 , util = require('./util')
2227 , SchemaObject = require('./schema_obj')
2228 , traverse = require('json-schema-traverse');
2229
2230module.exports = resolve;
2231
2232resolve.normalizeId = normalizeId;
2233resolve.fullPath = getFullPath;
2234resolve.url = resolveUrl;
2235resolve.ids = resolveIds;
2236resolve.inlineRef = inlineRef;
2237resolve.schema = resolveSchema;
2238
2239/**
2240 * [resolve and compile the references ($ref)]
2241 * @this Ajv
2242 * @param {Function} compile reference to schema compilation funciton (localCompile)
2243 * @param {Object} root object with information about the root schema for the current schema
2244 * @param {String} ref reference to resolve
2245 * @return {Object|Function} schema object (if the schema can be inlined) or validation function
2246 */
2247function resolve(compile, root, ref) {
2248 /* jshint validthis: true */
2249 var refVal = this._refs[ref];
2250 if (typeof refVal == 'string') {
2251 if (this._refs[refVal]) refVal = this._refs[refVal];
2252 else return resolve.call(this, compile, root, refVal);
2253 }
2254
2255 refVal = refVal || this._schemas[ref];
2256 if (refVal instanceof SchemaObject) {
2257 return inlineRef(refVal.schema, this._opts.inlineRefs)
2258 ? refVal.schema
2259 : refVal.validate || this._compile(refVal);
2260 }
2261
2262 var res = resolveSchema.call(this, root, ref);
2263 var schema, v, baseId;
2264 if (res) {
2265 schema = res.schema;
2266 root = res.root;
2267 baseId = res.baseId;
2268 }
2269
2270 if (schema instanceof SchemaObject) {
2271 v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId);
2272 } else if (schema !== undefined) {
2273 v = inlineRef(schema, this._opts.inlineRefs)
2274 ? schema
2275 : compile.call(this, schema, root, undefined, baseId);
2276 }
2277
2278 return v;
2279}
2280
2281
2282/**
2283 * Resolve schema, its root and baseId
2284 * @this Ajv
2285 * @param {Object} root root object with properties schema, refVal, refs
2286 * @param {String} ref reference to resolve
2287 * @return {Object} object with properties schema, root, baseId
2288 */
2289function resolveSchema(root, ref) {
2290 /* jshint validthis: true */
2291 var p = URI.parse(ref)
2292 , refPath = _getFullPath(p)
2293 , baseId = getFullPath(this._getId(root.schema));
2294 if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
2295 var id = normalizeId(refPath);
2296 var refVal = this._refs[id];
2297 if (typeof refVal == 'string') {
2298 return resolveRecursive.call(this, root, refVal, p);
2299 } else if (refVal instanceof SchemaObject) {
2300 if (!refVal.validate) this._compile(refVal);
2301 root = refVal;
2302 } else {
2303 refVal = this._schemas[id];
2304 if (refVal instanceof SchemaObject) {
2305 if (!refVal.validate) this._compile(refVal);
2306 if (id == normalizeId(ref))
2307 return { schema: refVal, root: root, baseId: baseId };
2308 root = refVal;
2309 } else {
2310 return;
2311 }
2312 }
2313 if (!root.schema) return;
2314 baseId = getFullPath(this._getId(root.schema));
2315 }
2316 return getJsonPointer.call(this, p, baseId, root.schema, root);
2317}
2318
2319
2320/* @this Ajv */
2321function resolveRecursive(root, ref, parsedRef) {
2322 /* jshint validthis: true */
2323 var res = resolveSchema.call(this, root, ref);
2324 if (res) {
2325 var schema = res.schema;
2326 var baseId = res.baseId;
2327 root = res.root;
2328 var id = this._getId(schema);
2329 if (id) baseId = resolveUrl(baseId, id);
2330 return getJsonPointer.call(this, parsedRef, baseId, schema, root);
2331 }
2332}
2333
2334
2335var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']);
2336/* @this Ajv */
2337function getJsonPointer(parsedRef, baseId, schema, root) {
2338 /* jshint validthis: true */
2339 parsedRef.fragment = parsedRef.fragment || '';
2340 if (parsedRef.fragment.slice(0,1) != '/') return;
2341 var parts = parsedRef.fragment.split('/');
2342
2343 for (var i = 1; i < parts.length; i++) {
2344 var part = parts[i];
2345 if (part) {
2346 part = util.unescapeFragment(part);
2347 schema = schema[part];
2348 if (schema === undefined) break;
2349 var id;
2350 if (!PREVENT_SCOPE_CHANGE[part]) {
2351 id = this._getId(schema);
2352 if (id) baseId = resolveUrl(baseId, id);
2353 if (schema.$ref) {
2354 var $ref = resolveUrl(baseId, schema.$ref);
2355 var res = resolveSchema.call(this, root, $ref);
2356 if (res) {
2357 schema = res.schema;
2358 root = res.root;
2359 baseId = res.baseId;
2360 }
2361 }
2362 }
2363 }
2364 }
2365 if (schema !== undefined && schema !== root.schema)
2366 return { schema: schema, root: root, baseId: baseId };
2367}
2368
2369
2370var SIMPLE_INLINED = util.toHash([
2371 'type', 'format', 'pattern',
2372 'maxLength', 'minLength',
2373 'maxProperties', 'minProperties',
2374 'maxItems', 'minItems',
2375 'maximum', 'minimum',
2376 'uniqueItems', 'multipleOf',
2377 'required', 'enum'
2378]);
2379function inlineRef(schema, limit) {
2380 if (limit === false) return false;
2381 if (limit === undefined || limit === true) return checkNoRef(schema);
2382 else if (limit) return countKeys(schema) <= limit;
2383}
2384
2385
2386function checkNoRef(schema) {
2387 var item;
2388 if (Array.isArray(schema)) {
2389 for (var i=0; i<schema.length; i++) {
2390 item = schema[i];
2391 if (typeof item == 'object' && !checkNoRef(item)) return false;
2392 }
2393 } else {
2394 for (var key in schema) {
2395 if (key == '$ref') return false;
2396 item = schema[key];
2397 if (typeof item == 'object' && !checkNoRef(item)) return false;
2398 }
2399 }
2400 return true;
2401}
2402
2403
2404function countKeys(schema) {
2405 var count = 0, item;
2406 if (Array.isArray(schema)) {
2407 for (var i=0; i<schema.length; i++) {
2408 item = schema[i];
2409 if (typeof item == 'object') count += countKeys(item);
2410 if (count == Infinity) return Infinity;
2411 }
2412 } else {
2413 for (var key in schema) {
2414 if (key == '$ref') return Infinity;
2415 if (SIMPLE_INLINED[key]) {
2416 count++;
2417 } else {
2418 item = schema[key];
2419 if (typeof item == 'object') count += countKeys(item) + 1;
2420 if (count == Infinity) return Infinity;
2421 }
2422 }
2423 }
2424 return count;
2425}
2426
2427
2428function getFullPath(id, normalize) {
2429 if (normalize !== false) id = normalizeId(id);
2430 var p = URI.parse(id);
2431 return _getFullPath(p);
2432}
2433
2434
2435function _getFullPath(p) {
2436 return URI.serialize(p).split('#')[0] + '#';
2437}
2438
2439
2440var TRAILING_SLASH_HASH = /#\/?$/;
2441function normalizeId(id) {
2442 return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
2443}
2444
2445
2446function resolveUrl(baseId, id) {
2447 id = normalizeId(id);
2448 return URI.resolve(baseId, id);
2449}
2450
2451
2452/* @this Ajv */
2453function resolveIds(schema) {
2454 var schemaId = normalizeId(this._getId(schema));
2455 var baseIds = {'': schemaId};
2456 var fullPaths = {'': getFullPath(schemaId, false)};
2457 var localRefs = {};
2458 var self = this;
2459
2460 traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
2461 if (jsonPtr === '') return;
2462 var id = self._getId(sch);
2463 var baseId = baseIds[parentJsonPtr];
2464 var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
2465 if (keyIndex !== undefined)
2466 fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex));
2467
2468 if (typeof id == 'string') {
2469 id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
2470
2471 var refVal = self._refs[id];
2472 if (typeof refVal == 'string') refVal = self._refs[refVal];
2473 if (refVal && refVal.schema) {
2474 if (!equal(sch, refVal.schema))
2475 throw new Error('id "' + id + '" resolves to more than one schema');
2476 } else if (id != normalizeId(fullPath)) {
2477 if (id[0] == '#') {
2478 if (localRefs[id] && !equal(sch, localRefs[id]))
2479 throw new Error('id "' + id + '" resolves to more than one schema');
2480 localRefs[id] = sch;
2481 } else {
2482 self._refs[id] = fullPath;
2483 }
2484 }
2485 }
2486 baseIds[jsonPtr] = baseId;
2487 fullPaths[jsonPtr] = fullPath;
2488 });
2489
2490 return localRefs;
2491}
2492
2493},{"./schema_obj":13,"./util":15,"fast-deep-equal":163,"json-schema-traverse":216,"uri-js":392}],12:[function(require,module,exports){
2494'use strict';
2495
2496var ruleModules = require('../dotjs')
2497 , toHash = require('./util').toHash;
2498
2499module.exports = function rules() {
2500 var RULES = [
2501 { type: 'number',
2502 rules: [ { 'maximum': ['exclusiveMaximum'] },
2503 { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
2504 { type: 'string',
2505 rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
2506 { type: 'array',
2507 rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] },
2508 { type: 'object',
2509 rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
2510 { 'properties': ['additionalProperties', 'patternProperties'] } ] },
2511 { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] }
2512 ];
2513
2514 var ALL = [ 'type', '$comment' ];
2515 var KEYWORDS = [
2516 '$schema', '$id', 'id', '$data', '$async', 'title',
2517 'description', 'default', 'definitions',
2518 'examples', 'readOnly', 'writeOnly',
2519 'contentMediaType', 'contentEncoding',
2520 'additionalItems', 'then', 'else'
2521 ];
2522 var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
2523 RULES.all = toHash(ALL);
2524 RULES.types = toHash(TYPES);
2525
2526 RULES.forEach(function (group) {
2527 group.rules = group.rules.map(function (keyword) {
2528 var implKeywords;
2529 if (typeof keyword == 'object') {
2530 var key = Object.keys(keyword)[0];
2531 implKeywords = keyword[key];
2532 keyword = key;
2533 implKeywords.forEach(function (k) {
2534 ALL.push(k);
2535 RULES.all[k] = true;
2536 });
2537 }
2538 ALL.push(keyword);
2539 var rule = RULES.all[keyword] = {
2540 keyword: keyword,
2541 code: ruleModules[keyword],
2542 implements: implKeywords
2543 };
2544 return rule;
2545 });
2546
2547 RULES.all.$comment = {
2548 keyword: '$comment',
2549 code: ruleModules.$comment
2550 };
2551
2552 if (group.type) RULES.types[group.type] = group;
2553 });
2554
2555 RULES.keywords = toHash(ALL.concat(KEYWORDS));
2556 RULES.custom = {};
2557
2558 return RULES;
2559};
2560
2561},{"../dotjs":31,"./util":15}],13:[function(require,module,exports){
2562'use strict';
2563
2564var util = require('./util');
2565
2566module.exports = SchemaObject;
2567
2568function SchemaObject(obj) {
2569 util.copy(obj, this);
2570}
2571
2572},{"./util":15}],14:[function(require,module,exports){
2573'use strict';
2574
2575// https://mathiasbynens.be/notes/javascript-encoding
2576// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
2577module.exports = function ucs2length(str) {
2578 var length = 0
2579 , len = str.length
2580 , pos = 0
2581 , value;
2582 while (pos < len) {
2583 length++;
2584 value = str.charCodeAt(pos++);
2585 if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
2586 // high surrogate, and there is a next character
2587 value = str.charCodeAt(pos);
2588 if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
2589 }
2590 }
2591 return length;
2592};
2593
2594},{}],15:[function(require,module,exports){
2595'use strict';
2596
2597
2598module.exports = {
2599 copy: copy,
2600 checkDataType: checkDataType,
2601 checkDataTypes: checkDataTypes,
2602 coerceToTypes: coerceToTypes,
2603 toHash: toHash,
2604 getProperty: getProperty,
2605 escapeQuotes: escapeQuotes,
2606 equal: require('fast-deep-equal'),
2607 ucs2length: require('./ucs2length'),
2608 varOccurences: varOccurences,
2609 varReplace: varReplace,
2610 cleanUpCode: cleanUpCode,
2611 finalCleanUpCode: finalCleanUpCode,
2612 schemaHasRules: schemaHasRules,
2613 schemaHasRulesExcept: schemaHasRulesExcept,
2614 schemaUnknownRules: schemaUnknownRules,
2615 toQuotedString: toQuotedString,
2616 getPathExpr: getPathExpr,
2617 getPath: getPath,
2618 getData: getData,
2619 unescapeFragment: unescapeFragment,
2620 unescapeJsonPointer: unescapeJsonPointer,
2621 escapeFragment: escapeFragment,
2622 escapeJsonPointer: escapeJsonPointer
2623};
2624
2625
2626function copy(o, to) {
2627 to = to || {};
2628 for (var key in o) to[key] = o[key];
2629 return to;
2630}
2631
2632
2633function checkDataType(dataType, data, negate) {
2634 var EQUAL = negate ? ' !== ' : ' === '
2635 , AND = negate ? ' || ' : ' && '
2636 , OK = negate ? '!' : ''
2637 , NOT = negate ? '' : '!';
2638 switch (dataType) {
2639 case 'null': return data + EQUAL + 'null';
2640 case 'array': return OK + 'Array.isArray(' + data + ')';
2641 case 'object': return '(' + OK + data + AND +
2642 'typeof ' + data + EQUAL + '"object"' + AND +
2643 NOT + 'Array.isArray(' + data + '))';
2644 case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
2645 NOT + '(' + data + ' % 1)' +
2646 AND + data + EQUAL + data + ')';
2647 default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
2648 }
2649}
2650
2651
2652function checkDataTypes(dataTypes, data) {
2653 switch (dataTypes.length) {
2654 case 1: return checkDataType(dataTypes[0], data, true);
2655 default:
2656 var code = '';
2657 var types = toHash(dataTypes);
2658 if (types.array && types.object) {
2659 code = types.null ? '(': '(!' + data + ' || ';
2660 code += 'typeof ' + data + ' !== "object")';
2661 delete types.null;
2662 delete types.array;
2663 delete types.object;
2664 }
2665 if (types.number) delete types.integer;
2666 for (var t in types)
2667 code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
2668
2669 return code;
2670 }
2671}
2672
2673
2674var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
2675function coerceToTypes(optionCoerceTypes, dataTypes) {
2676 if (Array.isArray(dataTypes)) {
2677 var types = [];
2678 for (var i=0; i<dataTypes.length; i++) {
2679 var t = dataTypes[i];
2680 if (COERCE_TO_TYPES[t]) types[types.length] = t;
2681 else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t;
2682 }
2683 if (types.length) return types;
2684 } else if (COERCE_TO_TYPES[dataTypes]) {
2685 return [dataTypes];
2686 } else if (optionCoerceTypes === 'array' && dataTypes === 'array') {
2687 return ['array'];
2688 }
2689}
2690
2691
2692function toHash(arr) {
2693 var hash = {};
2694 for (var i=0; i<arr.length; i++) hash[arr[i]] = true;
2695 return hash;
2696}
2697
2698
2699var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
2700var SINGLE_QUOTE = /'|\\/g;
2701function getProperty(key) {
2702 return typeof key == 'number'
2703 ? '[' + key + ']'
2704 : IDENTIFIER.test(key)
2705 ? '.' + key
2706 : "['" + escapeQuotes(key) + "']";
2707}
2708
2709
2710function escapeQuotes(str) {
2711 return str.replace(SINGLE_QUOTE, '\\$&')
2712 .replace(/\n/g, '\\n')
2713 .replace(/\r/g, '\\r')
2714 .replace(/\f/g, '\\f')
2715 .replace(/\t/g, '\\t');
2716}
2717
2718
2719function varOccurences(str, dataVar) {
2720 dataVar += '[^0-9]';
2721 var matches = str.match(new RegExp(dataVar, 'g'));
2722 return matches ? matches.length : 0;
2723}
2724
2725
2726function varReplace(str, dataVar, expr) {
2727 dataVar += '([^0-9])';
2728 expr = expr.replace(/\$/g, '$$$$');
2729 return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
2730}
2731
2732
2733var EMPTY_ELSE = /else\s*{\s*}/g
2734 , EMPTY_IF_NO_ELSE = /if\s*\([^)]+\)\s*\{\s*\}(?!\s*else)/g
2735 , EMPTY_IF_WITH_ELSE = /if\s*\(([^)]+)\)\s*\{\s*\}\s*else(?!\s*if)/g;
2736function cleanUpCode(out) {
2737 return out.replace(EMPTY_ELSE, '')
2738 .replace(EMPTY_IF_NO_ELSE, '')
2739 .replace(EMPTY_IF_WITH_ELSE, 'if (!($1))');
2740}
2741
2742
2743var ERRORS_REGEXP = /[^v.]errors/g
2744 , REMOVE_ERRORS = /var errors = 0;|var vErrors = null;|validate.errors = vErrors;/g
2745 , REMOVE_ERRORS_ASYNC = /var errors = 0;|var vErrors = null;/g
2746 , RETURN_VALID = 'return errors === 0;'
2747 , RETURN_TRUE = 'validate.errors = null; return true;'
2748 , RETURN_ASYNC = /if \(errors === 0\) return data;\s*else throw new ValidationError\(vErrors\);/
2749 , RETURN_DATA_ASYNC = 'return data;'
2750 , ROOTDATA_REGEXP = /[^A-Za-z_$]rootData[^A-Za-z0-9_$]/g
2751 , REMOVE_ROOTDATA = /if \(rootData === undefined\) rootData = data;/;
2752
2753function finalCleanUpCode(out, async) {
2754 var matches = out.match(ERRORS_REGEXP);
2755 if (matches && matches.length == 2) {
2756 out = async
2757 ? out.replace(REMOVE_ERRORS_ASYNC, '')
2758 .replace(RETURN_ASYNC, RETURN_DATA_ASYNC)
2759 : out.replace(REMOVE_ERRORS, '')
2760 .replace(RETURN_VALID, RETURN_TRUE);
2761 }
2762
2763 matches = out.match(ROOTDATA_REGEXP);
2764 if (!matches || matches.length !== 3) return out;
2765 return out.replace(REMOVE_ROOTDATA, '');
2766}
2767
2768
2769function schemaHasRules(schema, rules) {
2770 if (typeof schema == 'boolean') return !schema;
2771 for (var key in schema) if (rules[key]) return true;
2772}
2773
2774
2775function schemaHasRulesExcept(schema, rules, exceptKeyword) {
2776 if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not';
2777 for (var key in schema) if (key != exceptKeyword && rules[key]) return true;
2778}
2779
2780
2781function schemaUnknownRules(schema, rules) {
2782 if (typeof schema == 'boolean') return;
2783 for (var key in schema) if (!rules[key]) return key;
2784}
2785
2786
2787function toQuotedString(str) {
2788 return '\'' + escapeQuotes(str) + '\'';
2789}
2790
2791
2792function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
2793 var path = jsonPointers // false by default
2794 ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')')
2795 : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'');
2796 return joinPaths(currentPath, path);
2797}
2798
2799
2800function getPath(currentPath, prop, jsonPointers) {
2801 var path = jsonPointers // false by default
2802 ? toQuotedString('/' + escapeJsonPointer(prop))
2803 : toQuotedString(getProperty(prop));
2804 return joinPaths(currentPath, path);
2805}
2806
2807
2808var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
2809var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
2810function getData($data, lvl, paths) {
2811 var up, jsonPointer, data, matches;
2812 if ($data === '') return 'rootData';
2813 if ($data[0] == '/') {
2814 if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
2815 jsonPointer = $data;
2816 data = 'rootData';
2817 } else {
2818 matches = $data.match(RELATIVE_JSON_POINTER);
2819 if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
2820 up = +matches[1];
2821 jsonPointer = matches[2];
2822 if (jsonPointer == '#') {
2823 if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
2824 return paths[lvl - up];
2825 }
2826
2827 if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
2828 data = 'data' + ((lvl - up) || '');
2829 if (!jsonPointer) return data;
2830 }
2831
2832 var expr = data;
2833 var segments = jsonPointer.split('/');
2834 for (var i=0; i<segments.length; i++) {
2835 var segment = segments[i];
2836 if (segment) {
2837 data += getProperty(unescapeJsonPointer(segment));
2838 expr += ' && ' + data;
2839 }
2840 }
2841 return expr;
2842}
2843
2844
2845function joinPaths (a, b) {
2846 if (a == '""') return b;
2847 return (a + ' + ' + b).replace(/' \+ '/g, '');
2848}
2849
2850
2851function unescapeFragment(str) {
2852 return unescapeJsonPointer(decodeURIComponent(str));
2853}
2854
2855
2856function escapeFragment(str) {
2857 return encodeURIComponent(escapeJsonPointer(str));
2858}
2859
2860
2861function escapeJsonPointer(str) {
2862 return str.replace(/~/g, '~0').replace(/\//g, '~1');
2863}
2864
2865
2866function unescapeJsonPointer(str) {
2867 return str.replace(/~1/g, '/').replace(/~0/g, '~');
2868}
2869
2870},{"./ucs2length":14,"fast-deep-equal":163}],16:[function(require,module,exports){
2871'use strict';
2872
2873var KEYWORDS = [
2874 'multipleOf',
2875 'maximum',
2876 'exclusiveMaximum',
2877 'minimum',
2878 'exclusiveMinimum',
2879 'maxLength',
2880 'minLength',
2881 'pattern',
2882 'additionalItems',
2883 'maxItems',
2884 'minItems',
2885 'uniqueItems',
2886 'maxProperties',
2887 'minProperties',
2888 'required',
2889 'additionalProperties',
2890 'enum',
2891 'format',
2892 'const'
2893];
2894
2895module.exports = function (metaSchema, keywordsJsonPointers) {
2896 for (var i=0; i<keywordsJsonPointers.length; i++) {
2897 metaSchema = JSON.parse(JSON.stringify(metaSchema));
2898 var segments = keywordsJsonPointers[i].split('/');
2899 var keywords = metaSchema;
2900 var j;
2901 for (j=1; j<segments.length; j++)
2902 keywords = keywords[segments[j]];
2903
2904 for (j=0; j<KEYWORDS.length; j++) {
2905 var key = KEYWORDS[j];
2906 var schema = keywords[key];
2907 if (schema) {
2908 keywords[key] = {
2909 anyOf: [
2910 schema,
2911 { $ref: 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
2912 ]
2913 };
2914 }
2915 }
2916 }
2917
2918 return metaSchema;
2919};
2920
2921},{}],17:[function(require,module,exports){
2922'use strict';
2923module.exports = function generate__limit(it, $keyword, $ruleType) {
2924 var out = ' ';
2925 var $lvl = it.level;
2926 var $dataLvl = it.dataLevel;
2927 var $schema = it.schema[$keyword];
2928 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
2929 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
2930 var $breakOnError = !it.opts.allErrors;
2931 var $errorKeyword;
2932 var $data = 'data' + ($dataLvl || '');
2933 var $isData = it.opts.$data && $schema && $schema.$data,
2934 $schemaValue;
2935 if ($isData) {
2936 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
2937 $schemaValue = 'schema' + $lvl;
2938 } else {
2939 $schemaValue = $schema;
2940 }
2941 var $isMax = $keyword == 'maximum',
2942 $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum',
2943 $schemaExcl = it.schema[$exclusiveKeyword],
2944 $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data,
2945 $op = $isMax ? '<' : '>',
2946 $notOp = $isMax ? '>' : '<',
2947 $errorKeyword = undefined;
2948 if ($isDataExcl) {
2949 var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
2950 $exclusive = 'exclusive' + $lvl,
2951 $exclType = 'exclType' + $lvl,
2952 $exclIsNumber = 'exclIsNumber' + $lvl,
2953 $opExpr = 'op' + $lvl,
2954 $opStr = '\' + ' + $opExpr + ' + \'';
2955 out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
2956 $schemaValueExcl = 'schemaExcl' + $lvl;
2957 out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
2958 var $errorKeyword = $exclusiveKeyword;
2959 var $$outStack = $$outStack || [];
2960 $$outStack.push(out);
2961 out = ''; /* istanbul ignore else */
2962 if (it.createErrors !== false) {
2963 out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
2964 if (it.opts.messages !== false) {
2965 out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
2966 }
2967 if (it.opts.verbose) {
2968 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
2969 }
2970 out += ' } ';
2971 } else {
2972 out += ' {} ';
2973 }
2974 var __err = out;
2975 out = $$outStack.pop();
2976 if (!it.compositeRule && $breakOnError) {
2977 /* istanbul ignore if */
2978 if (it.async) {
2979 out += ' throw new ValidationError([' + (__err) + ']); ';
2980 } else {
2981 out += ' validate.errors = [' + (__err) + ']; return false; ';
2982 }
2983 } else {
2984 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
2985 }
2986 out += ' } else if ( ';
2987 if ($isData) {
2988 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
2989 }
2990 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) + '=\'; ';
2991 if ($schema === undefined) {
2992 $errorKeyword = $exclusiveKeyword;
2993 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
2994 $schemaValue = $schemaValueExcl;
2995 $isData = $isDataExcl;
2996 }
2997 } else {
2998 var $exclIsNumber = typeof $schemaExcl == 'number',
2999 $opStr = $op;
3000 if ($exclIsNumber && $isData) {
3001 var $opExpr = '\'' + $opStr + '\'';
3002 out += ' if ( ';
3003 if ($isData) {
3004 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3005 }
3006 out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
3007 } else {
3008 if ($exclIsNumber && $schema === undefined) {
3009 $exclusive = true;
3010 $errorKeyword = $exclusiveKeyword;
3011 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
3012 $schemaValue = $schemaExcl;
3013 $notOp += '=';
3014 } else {
3015 if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
3016 if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
3017 $exclusive = true;
3018 $errorKeyword = $exclusiveKeyword;
3019 $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
3020 $notOp += '=';
3021 } else {
3022 $exclusive = false;
3023 $opStr += '=';
3024 }
3025 }
3026 var $opExpr = '\'' + $opStr + '\'';
3027 out += ' if ( ';
3028 if ($isData) {
3029 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3030 }
3031 out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
3032 }
3033 }
3034 $errorKeyword = $errorKeyword || $keyword;
3035 var $$outStack = $$outStack || [];
3036 $$outStack.push(out);
3037 out = ''; /* istanbul ignore else */
3038 if (it.createErrors !== false) {
3039 out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
3040 if (it.opts.messages !== false) {
3041 out += ' , message: \'should be ' + ($opStr) + ' ';
3042 if ($isData) {
3043 out += '\' + ' + ($schemaValue);
3044 } else {
3045 out += '' + ($schemaValue) + '\'';
3046 }
3047 }
3048 if (it.opts.verbose) {
3049 out += ' , schema: ';
3050 if ($isData) {
3051 out += 'validate.schema' + ($schemaPath);
3052 } else {
3053 out += '' + ($schema);
3054 }
3055 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3056 }
3057 out += ' } ';
3058 } else {
3059 out += ' {} ';
3060 }
3061 var __err = out;
3062 out = $$outStack.pop();
3063 if (!it.compositeRule && $breakOnError) {
3064 /* istanbul ignore if */
3065 if (it.async) {
3066 out += ' throw new ValidationError([' + (__err) + ']); ';
3067 } else {
3068 out += ' validate.errors = [' + (__err) + ']; return false; ';
3069 }
3070 } else {
3071 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3072 }
3073 out += ' } ';
3074 if ($breakOnError) {
3075 out += ' else { ';
3076 }
3077 return out;
3078}
3079
3080},{}],18:[function(require,module,exports){
3081'use strict';
3082module.exports = function generate__limitItems(it, $keyword, $ruleType) {
3083 var out = ' ';
3084 var $lvl = it.level;
3085 var $dataLvl = it.dataLevel;
3086 var $schema = it.schema[$keyword];
3087 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3088 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3089 var $breakOnError = !it.opts.allErrors;
3090 var $errorKeyword;
3091 var $data = 'data' + ($dataLvl || '');
3092 var $isData = it.opts.$data && $schema && $schema.$data,
3093 $schemaValue;
3094 if ($isData) {
3095 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3096 $schemaValue = 'schema' + $lvl;
3097 } else {
3098 $schemaValue = $schema;
3099 }
3100 var $op = $keyword == 'maxItems' ? '>' : '<';
3101 out += 'if ( ';
3102 if ($isData) {
3103 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3104 }
3105 out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
3106 var $errorKeyword = $keyword;
3107 var $$outStack = $$outStack || [];
3108 $$outStack.push(out);
3109 out = ''; /* istanbul ignore else */
3110 if (it.createErrors !== false) {
3111 out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
3112 if (it.opts.messages !== false) {
3113 out += ' , message: \'should NOT have ';
3114 if ($keyword == 'maxItems') {
3115 out += 'more';
3116 } else {
3117 out += 'fewer';
3118 }
3119 out += ' than ';
3120 if ($isData) {
3121 out += '\' + ' + ($schemaValue) + ' + \'';
3122 } else {
3123 out += '' + ($schema);
3124 }
3125 out += ' items\' ';
3126 }
3127 if (it.opts.verbose) {
3128 out += ' , schema: ';
3129 if ($isData) {
3130 out += 'validate.schema' + ($schemaPath);
3131 } else {
3132 out += '' + ($schema);
3133 }
3134 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3135 }
3136 out += ' } ';
3137 } else {
3138 out += ' {} ';
3139 }
3140 var __err = out;
3141 out = $$outStack.pop();
3142 if (!it.compositeRule && $breakOnError) {
3143 /* istanbul ignore if */
3144 if (it.async) {
3145 out += ' throw new ValidationError([' + (__err) + ']); ';
3146 } else {
3147 out += ' validate.errors = [' + (__err) + ']; return false; ';
3148 }
3149 } else {
3150 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3151 }
3152 out += '} ';
3153 if ($breakOnError) {
3154 out += ' else { ';
3155 }
3156 return out;
3157}
3158
3159},{}],19:[function(require,module,exports){
3160'use strict';
3161module.exports = function generate__limitLength(it, $keyword, $ruleType) {
3162 var out = ' ';
3163 var $lvl = it.level;
3164 var $dataLvl = it.dataLevel;
3165 var $schema = it.schema[$keyword];
3166 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3167 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3168 var $breakOnError = !it.opts.allErrors;
3169 var $errorKeyword;
3170 var $data = 'data' + ($dataLvl || '');
3171 var $isData = it.opts.$data && $schema && $schema.$data,
3172 $schemaValue;
3173 if ($isData) {
3174 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3175 $schemaValue = 'schema' + $lvl;
3176 } else {
3177 $schemaValue = $schema;
3178 }
3179 var $op = $keyword == 'maxLength' ? '>' : '<';
3180 out += 'if ( ';
3181 if ($isData) {
3182 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3183 }
3184 if (it.opts.unicode === false) {
3185 out += ' ' + ($data) + '.length ';
3186 } else {
3187 out += ' ucs2length(' + ($data) + ') ';
3188 }
3189 out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
3190 var $errorKeyword = $keyword;
3191 var $$outStack = $$outStack || [];
3192 $$outStack.push(out);
3193 out = ''; /* istanbul ignore else */
3194 if (it.createErrors !== false) {
3195 out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
3196 if (it.opts.messages !== false) {
3197 out += ' , message: \'should NOT be ';
3198 if ($keyword == 'maxLength') {
3199 out += 'longer';
3200 } else {
3201 out += 'shorter';
3202 }
3203 out += ' than ';
3204 if ($isData) {
3205 out += '\' + ' + ($schemaValue) + ' + \'';
3206 } else {
3207 out += '' + ($schema);
3208 }
3209 out += ' characters\' ';
3210 }
3211 if (it.opts.verbose) {
3212 out += ' , schema: ';
3213 if ($isData) {
3214 out += 'validate.schema' + ($schemaPath);
3215 } else {
3216 out += '' + ($schema);
3217 }
3218 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3219 }
3220 out += ' } ';
3221 } else {
3222 out += ' {} ';
3223 }
3224 var __err = out;
3225 out = $$outStack.pop();
3226 if (!it.compositeRule && $breakOnError) {
3227 /* istanbul ignore if */
3228 if (it.async) {
3229 out += ' throw new ValidationError([' + (__err) + ']); ';
3230 } else {
3231 out += ' validate.errors = [' + (__err) + ']; return false; ';
3232 }
3233 } else {
3234 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3235 }
3236 out += '} ';
3237 if ($breakOnError) {
3238 out += ' else { ';
3239 }
3240 return out;
3241}
3242
3243},{}],20:[function(require,module,exports){
3244'use strict';
3245module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
3246 var out = ' ';
3247 var $lvl = it.level;
3248 var $dataLvl = it.dataLevel;
3249 var $schema = it.schema[$keyword];
3250 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3251 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3252 var $breakOnError = !it.opts.allErrors;
3253 var $errorKeyword;
3254 var $data = 'data' + ($dataLvl || '');
3255 var $isData = it.opts.$data && $schema && $schema.$data,
3256 $schemaValue;
3257 if ($isData) {
3258 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3259 $schemaValue = 'schema' + $lvl;
3260 } else {
3261 $schemaValue = $schema;
3262 }
3263 var $op = $keyword == 'maxProperties' ? '>' : '<';
3264 out += 'if ( ';
3265 if ($isData) {
3266 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
3267 }
3268 out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
3269 var $errorKeyword = $keyword;
3270 var $$outStack = $$outStack || [];
3271 $$outStack.push(out);
3272 out = ''; /* istanbul ignore else */
3273 if (it.createErrors !== false) {
3274 out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
3275 if (it.opts.messages !== false) {
3276 out += ' , message: \'should NOT have ';
3277 if ($keyword == 'maxProperties') {
3278 out += 'more';
3279 } else {
3280 out += 'fewer';
3281 }
3282 out += ' than ';
3283 if ($isData) {
3284 out += '\' + ' + ($schemaValue) + ' + \'';
3285 } else {
3286 out += '' + ($schema);
3287 }
3288 out += ' properties\' ';
3289 }
3290 if (it.opts.verbose) {
3291 out += ' , schema: ';
3292 if ($isData) {
3293 out += 'validate.schema' + ($schemaPath);
3294 } else {
3295 out += '' + ($schema);
3296 }
3297 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3298 }
3299 out += ' } ';
3300 } else {
3301 out += ' {} ';
3302 }
3303 var __err = out;
3304 out = $$outStack.pop();
3305 if (!it.compositeRule && $breakOnError) {
3306 /* istanbul ignore if */
3307 if (it.async) {
3308 out += ' throw new ValidationError([' + (__err) + ']); ';
3309 } else {
3310 out += ' validate.errors = [' + (__err) + ']; return false; ';
3311 }
3312 } else {
3313 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3314 }
3315 out += '} ';
3316 if ($breakOnError) {
3317 out += ' else { ';
3318 }
3319 return out;
3320}
3321
3322},{}],21:[function(require,module,exports){
3323'use strict';
3324module.exports = function generate_allOf(it, $keyword, $ruleType) {
3325 var out = ' ';
3326 var $schema = it.schema[$keyword];
3327 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3328 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3329 var $breakOnError = !it.opts.allErrors;
3330 var $it = it.util.copy(it);
3331 var $closingBraces = '';
3332 $it.level++;
3333 var $nextValid = 'valid' + $it.level;
3334 var $currentBaseId = $it.baseId,
3335 $allSchemasEmpty = true;
3336 var arr1 = $schema;
3337 if (arr1) {
3338 var $sch, $i = -1,
3339 l1 = arr1.length - 1;
3340 while ($i < l1) {
3341 $sch = arr1[$i += 1];
3342 if (it.util.schemaHasRules($sch, it.RULES.all)) {
3343 $allSchemasEmpty = false;
3344 $it.schema = $sch;
3345 $it.schemaPath = $schemaPath + '[' + $i + ']';
3346 $it.errSchemaPath = $errSchemaPath + '/' + $i;
3347 out += ' ' + (it.validate($it)) + ' ';
3348 $it.baseId = $currentBaseId;
3349 if ($breakOnError) {
3350 out += ' if (' + ($nextValid) + ') { ';
3351 $closingBraces += '}';
3352 }
3353 }
3354 }
3355 }
3356 if ($breakOnError) {
3357 if ($allSchemasEmpty) {
3358 out += ' if (true) { ';
3359 } else {
3360 out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
3361 }
3362 }
3363 out = it.util.cleanUpCode(out);
3364 return out;
3365}
3366
3367},{}],22:[function(require,module,exports){
3368'use strict';
3369module.exports = function generate_anyOf(it, $keyword, $ruleType) {
3370 var out = ' ';
3371 var $lvl = it.level;
3372 var $dataLvl = it.dataLevel;
3373 var $schema = it.schema[$keyword];
3374 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3375 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3376 var $breakOnError = !it.opts.allErrors;
3377 var $data = 'data' + ($dataLvl || '');
3378 var $valid = 'valid' + $lvl;
3379 var $errs = 'errs__' + $lvl;
3380 var $it = it.util.copy(it);
3381 var $closingBraces = '';
3382 $it.level++;
3383 var $nextValid = 'valid' + $it.level;
3384 var $noEmptySchema = $schema.every(function($sch) {
3385 return it.util.schemaHasRules($sch, it.RULES.all);
3386 });
3387 if ($noEmptySchema) {
3388 var $currentBaseId = $it.baseId;
3389 out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; ';
3390 var $wasComposite = it.compositeRule;
3391 it.compositeRule = $it.compositeRule = true;
3392 var arr1 = $schema;
3393 if (arr1) {
3394 var $sch, $i = -1,
3395 l1 = arr1.length - 1;
3396 while ($i < l1) {
3397 $sch = arr1[$i += 1];
3398 $it.schema = $sch;
3399 $it.schemaPath = $schemaPath + '[' + $i + ']';
3400 $it.errSchemaPath = $errSchemaPath + '/' + $i;
3401 out += ' ' + (it.validate($it)) + ' ';
3402 $it.baseId = $currentBaseId;
3403 out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
3404 $closingBraces += '}';
3405 }
3406 }
3407 it.compositeRule = $it.compositeRule = $wasComposite;
3408 out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
3409 if (it.createErrors !== false) {
3410 out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
3411 if (it.opts.messages !== false) {
3412 out += ' , message: \'should match some schema in anyOf\' ';
3413 }
3414 if (it.opts.verbose) {
3415 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3416 }
3417 out += ' } ';
3418 } else {
3419 out += ' {} ';
3420 }
3421 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3422 if (!it.compositeRule && $breakOnError) {
3423 /* istanbul ignore if */
3424 if (it.async) {
3425 out += ' throw new ValidationError(vErrors); ';
3426 } else {
3427 out += ' validate.errors = vErrors; return false; ';
3428 }
3429 }
3430 out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
3431 if (it.opts.allErrors) {
3432 out += ' } ';
3433 }
3434 out = it.util.cleanUpCode(out);
3435 } else {
3436 if ($breakOnError) {
3437 out += ' if (true) { ';
3438 }
3439 }
3440 return out;
3441}
3442
3443},{}],23:[function(require,module,exports){
3444'use strict';
3445module.exports = function generate_comment(it, $keyword, $ruleType) {
3446 var out = ' ';
3447 var $schema = it.schema[$keyword];
3448 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3449 var $breakOnError = !it.opts.allErrors;
3450 var $comment = it.util.toQuotedString($schema);
3451 if (it.opts.$comment === true) {
3452 out += ' console.log(' + ($comment) + ');';
3453 } else if (typeof it.opts.$comment == 'function') {
3454 out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
3455 }
3456 return out;
3457}
3458
3459},{}],24:[function(require,module,exports){
3460'use strict';
3461module.exports = function generate_const(it, $keyword, $ruleType) {
3462 var out = ' ';
3463 var $lvl = it.level;
3464 var $dataLvl = it.dataLevel;
3465 var $schema = it.schema[$keyword];
3466 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3467 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3468 var $breakOnError = !it.opts.allErrors;
3469 var $data = 'data' + ($dataLvl || '');
3470 var $valid = 'valid' + $lvl;
3471 var $isData = it.opts.$data && $schema && $schema.$data,
3472 $schemaValue;
3473 if ($isData) {
3474 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3475 $schemaValue = 'schema' + $lvl;
3476 } else {
3477 $schemaValue = $schema;
3478 }
3479 if (!$isData) {
3480 out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
3481 }
3482 out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { ';
3483 var $$outStack = $$outStack || [];
3484 $$outStack.push(out);
3485 out = ''; /* istanbul ignore else */
3486 if (it.createErrors !== false) {
3487 out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
3488 if (it.opts.messages !== false) {
3489 out += ' , message: \'should be equal to constant\' ';
3490 }
3491 if (it.opts.verbose) {
3492 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3493 }
3494 out += ' } ';
3495 } else {
3496 out += ' {} ';
3497 }
3498 var __err = out;
3499 out = $$outStack.pop();
3500 if (!it.compositeRule && $breakOnError) {
3501 /* istanbul ignore if */
3502 if (it.async) {
3503 out += ' throw new ValidationError([' + (__err) + ']); ';
3504 } else {
3505 out += ' validate.errors = [' + (__err) + ']; return false; ';
3506 }
3507 } else {
3508 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3509 }
3510 out += ' }';
3511 if ($breakOnError) {
3512 out += ' else { ';
3513 }
3514 return out;
3515}
3516
3517},{}],25:[function(require,module,exports){
3518'use strict';
3519module.exports = function generate_contains(it, $keyword, $ruleType) {
3520 var out = ' ';
3521 var $lvl = it.level;
3522 var $dataLvl = it.dataLevel;
3523 var $schema = it.schema[$keyword];
3524 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3525 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3526 var $breakOnError = !it.opts.allErrors;
3527 var $data = 'data' + ($dataLvl || '');
3528 var $valid = 'valid' + $lvl;
3529 var $errs = 'errs__' + $lvl;
3530 var $it = it.util.copy(it);
3531 var $closingBraces = '';
3532 $it.level++;
3533 var $nextValid = 'valid' + $it.level;
3534 var $idx = 'i' + $lvl,
3535 $dataNxt = $it.dataLevel = it.dataLevel + 1,
3536 $nextData = 'data' + $dataNxt,
3537 $currentBaseId = it.baseId,
3538 $nonEmptySchema = it.util.schemaHasRules($schema, it.RULES.all);
3539 out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
3540 if ($nonEmptySchema) {
3541 var $wasComposite = it.compositeRule;
3542 it.compositeRule = $it.compositeRule = true;
3543 $it.schema = $schema;
3544 $it.schemaPath = $schemaPath;
3545 $it.errSchemaPath = $errSchemaPath;
3546 out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
3547 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
3548 var $passData = $data + '[' + $idx + ']';
3549 $it.dataPathArr[$dataNxt] = $idx;
3550 var $code = it.validate($it);
3551 $it.baseId = $currentBaseId;
3552 if (it.util.varOccurences($code, $nextData) < 2) {
3553 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
3554 } else {
3555 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
3556 }
3557 out += ' if (' + ($nextValid) + ') break; } ';
3558 it.compositeRule = $it.compositeRule = $wasComposite;
3559 out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
3560 } else {
3561 out += ' if (' + ($data) + '.length == 0) {';
3562 }
3563 var $$outStack = $$outStack || [];
3564 $$outStack.push(out);
3565 out = ''; /* istanbul ignore else */
3566 if (it.createErrors !== false) {
3567 out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
3568 if (it.opts.messages !== false) {
3569 out += ' , message: \'should contain a valid item\' ';
3570 }
3571 if (it.opts.verbose) {
3572 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3573 }
3574 out += ' } ';
3575 } else {
3576 out += ' {} ';
3577 }
3578 var __err = out;
3579 out = $$outStack.pop();
3580 if (!it.compositeRule && $breakOnError) {
3581 /* istanbul ignore if */
3582 if (it.async) {
3583 out += ' throw new ValidationError([' + (__err) + ']); ';
3584 } else {
3585 out += ' validate.errors = [' + (__err) + ']; return false; ';
3586 }
3587 } else {
3588 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3589 }
3590 out += ' } else { ';
3591 if ($nonEmptySchema) {
3592 out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
3593 }
3594 if (it.opts.allErrors) {
3595 out += ' } ';
3596 }
3597 out = it.util.cleanUpCode(out);
3598 return out;
3599}
3600
3601},{}],26:[function(require,module,exports){
3602'use strict';
3603module.exports = function generate_custom(it, $keyword, $ruleType) {
3604 var out = ' ';
3605 var $lvl = it.level;
3606 var $dataLvl = it.dataLevel;
3607 var $schema = it.schema[$keyword];
3608 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3609 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3610 var $breakOnError = !it.opts.allErrors;
3611 var $errorKeyword;
3612 var $data = 'data' + ($dataLvl || '');
3613 var $valid = 'valid' + $lvl;
3614 var $errs = 'errs__' + $lvl;
3615 var $isData = it.opts.$data && $schema && $schema.$data,
3616 $schemaValue;
3617 if ($isData) {
3618 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
3619 $schemaValue = 'schema' + $lvl;
3620 } else {
3621 $schemaValue = $schema;
3622 }
3623 var $rule = this,
3624 $definition = 'definition' + $lvl,
3625 $rDef = $rule.definition,
3626 $closingBraces = '';
3627 var $compile, $inline, $macro, $ruleValidate, $validateCode;
3628 if ($isData && $rDef.$data) {
3629 $validateCode = 'keywordValidate' + $lvl;
3630 var $validateSchema = $rDef.validateSchema;
3631 out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
3632 } else {
3633 $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
3634 if (!$ruleValidate) return;
3635 $schemaValue = 'validate.schema' + $schemaPath;
3636 $validateCode = $ruleValidate.code;
3637 $compile = $rDef.compile;
3638 $inline = $rDef.inline;
3639 $macro = $rDef.macro;
3640 }
3641 var $ruleErrs = $validateCode + '.errors',
3642 $i = 'i' + $lvl,
3643 $ruleErr = 'ruleErr' + $lvl,
3644 $asyncKeyword = $rDef.async;
3645 if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
3646 if (!($inline || $macro)) {
3647 out += '' + ($ruleErrs) + ' = null;';
3648 }
3649 out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
3650 if ($isData && $rDef.$data) {
3651 $closingBraces += '}';
3652 out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
3653 if ($validateSchema) {
3654 $closingBraces += '}';
3655 out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
3656 }
3657 }
3658 if ($inline) {
3659 if ($rDef.statements) {
3660 out += ' ' + ($ruleValidate.validate) + ' ';
3661 } else {
3662 out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
3663 }
3664 } else if ($macro) {
3665 var $it = it.util.copy(it);
3666 var $closingBraces = '';
3667 $it.level++;
3668 var $nextValid = 'valid' + $it.level;
3669 $it.schema = $ruleValidate.validate;
3670 $it.schemaPath = '';
3671 var $wasComposite = it.compositeRule;
3672 it.compositeRule = $it.compositeRule = true;
3673 var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
3674 it.compositeRule = $it.compositeRule = $wasComposite;
3675 out += ' ' + ($code);
3676 } else {
3677 var $$outStack = $$outStack || [];
3678 $$outStack.push(out);
3679 out = '';
3680 out += ' ' + ($validateCode) + '.call( ';
3681 if (it.opts.passContext) {
3682 out += 'this';
3683 } else {
3684 out += 'self';
3685 }
3686 if ($compile || $rDef.schema === false) {
3687 out += ' , ' + ($data) + ' ';
3688 } else {
3689 out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
3690 }
3691 out += ' , (dataPath || \'\')';
3692 if (it.errorPath != '""') {
3693 out += ' + ' + (it.errorPath);
3694 }
3695 var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
3696 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
3697 out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) ';
3698 var def_callRuleValidate = out;
3699 out = $$outStack.pop();
3700 if ($rDef.errors === false) {
3701 out += ' ' + ($valid) + ' = ';
3702 if ($asyncKeyword) {
3703 out += 'await ';
3704 }
3705 out += '' + (def_callRuleValidate) + '; ';
3706 } else {
3707 if ($asyncKeyword) {
3708 $ruleErrs = 'customErrors' + $lvl;
3709 out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
3710 } else {
3711 out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
3712 }
3713 }
3714 }
3715 if ($rDef.modifying) {
3716 out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
3717 }
3718 out += '' + ($closingBraces);
3719 if ($rDef.valid) {
3720 if ($breakOnError) {
3721 out += ' if (true) { ';
3722 }
3723 } else {
3724 out += ' if ( ';
3725 if ($rDef.valid === undefined) {
3726 out += ' !';
3727 if ($macro) {
3728 out += '' + ($nextValid);
3729 } else {
3730 out += '' + ($valid);
3731 }
3732 } else {
3733 out += ' ' + (!$rDef.valid) + ' ';
3734 }
3735 out += ') { ';
3736 $errorKeyword = $rule.keyword;
3737 var $$outStack = $$outStack || [];
3738 $$outStack.push(out);
3739 out = '';
3740 var $$outStack = $$outStack || [];
3741 $$outStack.push(out);
3742 out = ''; /* istanbul ignore else */
3743 if (it.createErrors !== false) {
3744 out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
3745 if (it.opts.messages !== false) {
3746 out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
3747 }
3748 if (it.opts.verbose) {
3749 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3750 }
3751 out += ' } ';
3752 } else {
3753 out += ' {} ';
3754 }
3755 var __err = out;
3756 out = $$outStack.pop();
3757 if (!it.compositeRule && $breakOnError) {
3758 /* istanbul ignore if */
3759 if (it.async) {
3760 out += ' throw new ValidationError([' + (__err) + ']); ';
3761 } else {
3762 out += ' validate.errors = [' + (__err) + ']; return false; ';
3763 }
3764 } else {
3765 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3766 }
3767 var def_customError = out;
3768 out = $$outStack.pop();
3769 if ($inline) {
3770 if ($rDef.errors) {
3771 if ($rDef.errors != 'full') {
3772 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) + '"; } ';
3773 if (it.opts.verbose) {
3774 out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
3775 }
3776 out += ' } ';
3777 }
3778 } else {
3779 if ($rDef.errors === false) {
3780 out += ' ' + (def_customError) + ' ';
3781 } else {
3782 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) + '"; } ';
3783 if (it.opts.verbose) {
3784 out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
3785 }
3786 out += ' } } ';
3787 }
3788 }
3789 } else if ($macro) {
3790 out += ' var err = '; /* istanbul ignore else */
3791 if (it.createErrors !== false) {
3792 out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
3793 if (it.opts.messages !== false) {
3794 out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
3795 }
3796 if (it.opts.verbose) {
3797 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3798 }
3799 out += ' } ';
3800 } else {
3801 out += ' {} ';
3802 }
3803 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3804 if (!it.compositeRule && $breakOnError) {
3805 /* istanbul ignore if */
3806 if (it.async) {
3807 out += ' throw new ValidationError(vErrors); ';
3808 } else {
3809 out += ' validate.errors = vErrors; return false; ';
3810 }
3811 }
3812 } else {
3813 if ($rDef.errors === false) {
3814 out += ' ' + (def_customError) + ' ';
3815 } else {
3816 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) + '"; ';
3817 if (it.opts.verbose) {
3818 out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; ';
3819 }
3820 out += ' } } else { ' + (def_customError) + ' } ';
3821 }
3822 }
3823 out += ' } ';
3824 if ($breakOnError) {
3825 out += ' else { ';
3826 }
3827 }
3828 return out;
3829}
3830
3831},{}],27:[function(require,module,exports){
3832'use strict';
3833module.exports = function generate_dependencies(it, $keyword, $ruleType) {
3834 var out = ' ';
3835 var $lvl = it.level;
3836 var $dataLvl = it.dataLevel;
3837 var $schema = it.schema[$keyword];
3838 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
3839 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
3840 var $breakOnError = !it.opts.allErrors;
3841 var $data = 'data' + ($dataLvl || '');
3842 var $errs = 'errs__' + $lvl;
3843 var $it = it.util.copy(it);
3844 var $closingBraces = '';
3845 $it.level++;
3846 var $nextValid = 'valid' + $it.level;
3847 var $schemaDeps = {},
3848 $propertyDeps = {},
3849 $ownProperties = it.opts.ownProperties;
3850 for ($property in $schema) {
3851 var $sch = $schema[$property];
3852 var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
3853 $deps[$property] = $sch;
3854 }
3855 out += 'var ' + ($errs) + ' = errors;';
3856 var $currentErrorPath = it.errorPath;
3857 out += 'var missing' + ($lvl) + ';';
3858 for (var $property in $propertyDeps) {
3859 $deps = $propertyDeps[$property];
3860 if ($deps.length) {
3861 out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
3862 if ($ownProperties) {
3863 out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
3864 }
3865 if ($breakOnError) {
3866 out += ' && ( ';
3867 var arr1 = $deps;
3868 if (arr1) {
3869 var $propertyKey, $i = -1,
3870 l1 = arr1.length - 1;
3871 while ($i < l1) {
3872 $propertyKey = arr1[$i += 1];
3873 if ($i) {
3874 out += ' || ';
3875 }
3876 var $prop = it.util.getProperty($propertyKey),
3877 $useData = $data + $prop;
3878 out += ' ( ( ' + ($useData) + ' === undefined ';
3879 if ($ownProperties) {
3880 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
3881 }
3882 out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
3883 }
3884 }
3885 out += ')) { ';
3886 var $propertyPath = 'missing' + $lvl,
3887 $missingProperty = '\' + ' + $propertyPath + ' + \'';
3888 if (it.opts._errorDataPathProperty) {
3889 it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
3890 }
3891 var $$outStack = $$outStack || [];
3892 $$outStack.push(out);
3893 out = ''; /* istanbul ignore else */
3894 if (it.createErrors !== false) {
3895 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(", "))) + '\' } ';
3896 if (it.opts.messages !== false) {
3897 out += ' , message: \'should have ';
3898 if ($deps.length == 1) {
3899 out += 'property ' + (it.util.escapeQuotes($deps[0]));
3900 } else {
3901 out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
3902 }
3903 out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
3904 }
3905 if (it.opts.verbose) {
3906 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3907 }
3908 out += ' } ';
3909 } else {
3910 out += ' {} ';
3911 }
3912 var __err = out;
3913 out = $$outStack.pop();
3914 if (!it.compositeRule && $breakOnError) {
3915 /* istanbul ignore if */
3916 if (it.async) {
3917 out += ' throw new ValidationError([' + (__err) + ']); ';
3918 } else {
3919 out += ' validate.errors = [' + (__err) + ']; return false; ';
3920 }
3921 } else {
3922 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
3923 }
3924 } else {
3925 out += ' ) { ';
3926 var arr2 = $deps;
3927 if (arr2) {
3928 var $propertyKey, i2 = -1,
3929 l2 = arr2.length - 1;
3930 while (i2 < l2) {
3931 $propertyKey = arr2[i2 += 1];
3932 var $prop = it.util.getProperty($propertyKey),
3933 $missingProperty = it.util.escapeQuotes($propertyKey),
3934 $useData = $data + $prop;
3935 if (it.opts._errorDataPathProperty) {
3936 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
3937 }
3938 out += ' if ( ' + ($useData) + ' === undefined ';
3939 if ($ownProperties) {
3940 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
3941 }
3942 out += ') { var err = '; /* istanbul ignore else */
3943 if (it.createErrors !== false) {
3944 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(", "))) + '\' } ';
3945 if (it.opts.messages !== false) {
3946 out += ' , message: \'should have ';
3947 if ($deps.length == 1) {
3948 out += 'property ' + (it.util.escapeQuotes($deps[0]));
3949 } else {
3950 out += 'properties ' + (it.util.escapeQuotes($deps.join(", ")));
3951 }
3952 out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' ';
3953 }
3954 if (it.opts.verbose) {
3955 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
3956 }
3957 out += ' } ';
3958 } else {
3959 out += ' {} ';
3960 }
3961 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
3962 }
3963 }
3964 }
3965 out += ' } ';
3966 if ($breakOnError) {
3967 $closingBraces += '}';
3968 out += ' else { ';
3969 }
3970 }
3971 }
3972 it.errorPath = $currentErrorPath;
3973 var $currentBaseId = $it.baseId;
3974 for (var $property in $schemaDeps) {
3975 var $sch = $schemaDeps[$property];
3976 if (it.util.schemaHasRules($sch, it.RULES.all)) {
3977 out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
3978 if ($ownProperties) {
3979 out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
3980 }
3981 out += ') { ';
3982 $it.schema = $sch;
3983 $it.schemaPath = $schemaPath + it.util.getProperty($property);
3984 $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
3985 out += ' ' + (it.validate($it)) + ' ';
3986 $it.baseId = $currentBaseId;
3987 out += ' } ';
3988 if ($breakOnError) {
3989 out += ' if (' + ($nextValid) + ') { ';
3990 $closingBraces += '}';
3991 }
3992 }
3993 }
3994 if ($breakOnError) {
3995 out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
3996 }
3997 out = it.util.cleanUpCode(out);
3998 return out;
3999}
4000
4001},{}],28:[function(require,module,exports){
4002'use strict';
4003module.exports = function generate_enum(it, $keyword, $ruleType) {
4004 var out = ' ';
4005 var $lvl = it.level;
4006 var $dataLvl = it.dataLevel;
4007 var $schema = it.schema[$keyword];
4008 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4009 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4010 var $breakOnError = !it.opts.allErrors;
4011 var $data = 'data' + ($dataLvl || '');
4012 var $valid = 'valid' + $lvl;
4013 var $isData = it.opts.$data && $schema && $schema.$data,
4014 $schemaValue;
4015 if ($isData) {
4016 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4017 $schemaValue = 'schema' + $lvl;
4018 } else {
4019 $schemaValue = $schema;
4020 }
4021 var $i = 'i' + $lvl,
4022 $vSchema = 'schema' + $lvl;
4023 if (!$isData) {
4024 out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
4025 }
4026 out += 'var ' + ($valid) + ';';
4027 if ($isData) {
4028 out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
4029 }
4030 out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
4031 if ($isData) {
4032 out += ' } ';
4033 }
4034 out += ' if (!' + ($valid) + ') { ';
4035 var $$outStack = $$outStack || [];
4036 $$outStack.push(out);
4037 out = ''; /* istanbul ignore else */
4038 if (it.createErrors !== false) {
4039 out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
4040 if (it.opts.messages !== false) {
4041 out += ' , message: \'should be equal to one of the allowed values\' ';
4042 }
4043 if (it.opts.verbose) {
4044 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4045 }
4046 out += ' } ';
4047 } else {
4048 out += ' {} ';
4049 }
4050 var __err = out;
4051 out = $$outStack.pop();
4052 if (!it.compositeRule && $breakOnError) {
4053 /* istanbul ignore if */
4054 if (it.async) {
4055 out += ' throw new ValidationError([' + (__err) + ']); ';
4056 } else {
4057 out += ' validate.errors = [' + (__err) + ']; return false; ';
4058 }
4059 } else {
4060 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4061 }
4062 out += ' }';
4063 if ($breakOnError) {
4064 out += ' else { ';
4065 }
4066 return out;
4067}
4068
4069},{}],29:[function(require,module,exports){
4070'use strict';
4071module.exports = function generate_format(it, $keyword, $ruleType) {
4072 var out = ' ';
4073 var $lvl = it.level;
4074 var $dataLvl = it.dataLevel;
4075 var $schema = it.schema[$keyword];
4076 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4077 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4078 var $breakOnError = !it.opts.allErrors;
4079 var $data = 'data' + ($dataLvl || '');
4080 if (it.opts.format === false) {
4081 if ($breakOnError) {
4082 out += ' if (true) { ';
4083 }
4084 return out;
4085 }
4086 var $isData = it.opts.$data && $schema && $schema.$data,
4087 $schemaValue;
4088 if ($isData) {
4089 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4090 $schemaValue = 'schema' + $lvl;
4091 } else {
4092 $schemaValue = $schema;
4093 }
4094 var $unknownFormats = it.opts.unknownFormats,
4095 $allowUnknown = Array.isArray($unknownFormats);
4096 if ($isData) {
4097 var $format = 'format' + $lvl,
4098 $isObject = 'isObject' + $lvl,
4099 $formatType = 'formatType' + $lvl;
4100 out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
4101 if (it.async) {
4102 out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
4103 }
4104 out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';
4105 if ($isData) {
4106 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
4107 }
4108 out += ' (';
4109 if ($unknownFormats != 'ignore') {
4110 out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
4111 if ($allowUnknown) {
4112 out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
4113 }
4114 out += ') || ';
4115 }
4116 out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
4117 if (it.async) {
4118 out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
4119 } else {
4120 out += ' ' + ($format) + '(' + ($data) + ') ';
4121 }
4122 out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
4123 } else {
4124 var $format = it.formats[$schema];
4125 if (!$format) {
4126 if ($unknownFormats == 'ignore') {
4127 it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
4128 if ($breakOnError) {
4129 out += ' if (true) { ';
4130 }
4131 return out;
4132 } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
4133 if ($breakOnError) {
4134 out += ' if (true) { ';
4135 }
4136 return out;
4137 } else {
4138 throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
4139 }
4140 }
4141 var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
4142 var $formatType = $isObject && $format.type || 'string';
4143 if ($isObject) {
4144 var $async = $format.async === true;
4145 $format = $format.validate;
4146 }
4147 if ($formatType != $ruleType) {
4148 if ($breakOnError) {
4149 out += ' if (true) { ';
4150 }
4151 return out;
4152 }
4153 if ($async) {
4154 if (!it.async) throw new Error('async format in sync schema');
4155 var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
4156 out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
4157 } else {
4158 out += ' if (! ';
4159 var $formatRef = 'formats' + it.util.getProperty($schema);
4160 if ($isObject) $formatRef += '.validate';
4161 if (typeof $format == 'function') {
4162 out += ' ' + ($formatRef) + '(' + ($data) + ') ';
4163 } else {
4164 out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
4165 }
4166 out += ') { ';
4167 }
4168 }
4169 var $$outStack = $$outStack || [];
4170 $$outStack.push(out);
4171 out = ''; /* istanbul ignore else */
4172 if (it.createErrors !== false) {
4173 out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';
4174 if ($isData) {
4175 out += '' + ($schemaValue);
4176 } else {
4177 out += '' + (it.util.toQuotedString($schema));
4178 }
4179 out += ' } ';
4180 if (it.opts.messages !== false) {
4181 out += ' , message: \'should match format "';
4182 if ($isData) {
4183 out += '\' + ' + ($schemaValue) + ' + \'';
4184 } else {
4185 out += '' + (it.util.escapeQuotes($schema));
4186 }
4187 out += '"\' ';
4188 }
4189 if (it.opts.verbose) {
4190 out += ' , schema: ';
4191 if ($isData) {
4192 out += 'validate.schema' + ($schemaPath);
4193 } else {
4194 out += '' + (it.util.toQuotedString($schema));
4195 }
4196 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4197 }
4198 out += ' } ';
4199 } else {
4200 out += ' {} ';
4201 }
4202 var __err = out;
4203 out = $$outStack.pop();
4204 if (!it.compositeRule && $breakOnError) {
4205 /* istanbul ignore if */
4206 if (it.async) {
4207 out += ' throw new ValidationError([' + (__err) + ']); ';
4208 } else {
4209 out += ' validate.errors = [' + (__err) + ']; return false; ';
4210 }
4211 } else {
4212 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4213 }
4214 out += ' } ';
4215 if ($breakOnError) {
4216 out += ' else { ';
4217 }
4218 return out;
4219}
4220
4221},{}],30:[function(require,module,exports){
4222'use strict';
4223module.exports = function generate_if(it, $keyword, $ruleType) {
4224 var out = ' ';
4225 var $lvl = it.level;
4226 var $dataLvl = it.dataLevel;
4227 var $schema = it.schema[$keyword];
4228 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4229 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4230 var $breakOnError = !it.opts.allErrors;
4231 var $data = 'data' + ($dataLvl || '');
4232 var $valid = 'valid' + $lvl;
4233 var $errs = 'errs__' + $lvl;
4234 var $it = it.util.copy(it);
4235 $it.level++;
4236 var $nextValid = 'valid' + $it.level;
4237 var $thenSch = it.schema['then'],
4238 $elseSch = it.schema['else'],
4239 $thenPresent = $thenSch !== undefined && it.util.schemaHasRules($thenSch, it.RULES.all),
4240 $elsePresent = $elseSch !== undefined && it.util.schemaHasRules($elseSch, it.RULES.all),
4241 $currentBaseId = $it.baseId;
4242 if ($thenPresent || $elsePresent) {
4243 var $ifClause;
4244 $it.createErrors = false;
4245 $it.schema = $schema;
4246 $it.schemaPath = $schemaPath;
4247 $it.errSchemaPath = $errSchemaPath;
4248 out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; ';
4249 var $wasComposite = it.compositeRule;
4250 it.compositeRule = $it.compositeRule = true;
4251 out += ' ' + (it.validate($it)) + ' ';
4252 $it.baseId = $currentBaseId;
4253 $it.createErrors = true;
4254 out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
4255 it.compositeRule = $it.compositeRule = $wasComposite;
4256 if ($thenPresent) {
4257 out += ' if (' + ($nextValid) + ') { ';
4258 $it.schema = it.schema['then'];
4259 $it.schemaPath = it.schemaPath + '.then';
4260 $it.errSchemaPath = it.errSchemaPath + '/then';
4261 out += ' ' + (it.validate($it)) + ' ';
4262 $it.baseId = $currentBaseId;
4263 out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
4264 if ($thenPresent && $elsePresent) {
4265 $ifClause = 'ifClause' + $lvl;
4266 out += ' var ' + ($ifClause) + ' = \'then\'; ';
4267 } else {
4268 $ifClause = '\'then\'';
4269 }
4270 out += ' } ';
4271 if ($elsePresent) {
4272 out += ' else { ';
4273 }
4274 } else {
4275 out += ' if (!' + ($nextValid) + ') { ';
4276 }
4277 if ($elsePresent) {
4278 $it.schema = it.schema['else'];
4279 $it.schemaPath = it.schemaPath + '.else';
4280 $it.errSchemaPath = it.errSchemaPath + '/else';
4281 out += ' ' + (it.validate($it)) + ' ';
4282 $it.baseId = $currentBaseId;
4283 out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
4284 if ($thenPresent && $elsePresent) {
4285 $ifClause = 'ifClause' + $lvl;
4286 out += ' var ' + ($ifClause) + ' = \'else\'; ';
4287 } else {
4288 $ifClause = '\'else\'';
4289 }
4290 out += ' } ';
4291 }
4292 out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
4293 if (it.createErrors !== false) {
4294 out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
4295 if (it.opts.messages !== false) {
4296 out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
4297 }
4298 if (it.opts.verbose) {
4299 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4300 }
4301 out += ' } ';
4302 } else {
4303 out += ' {} ';
4304 }
4305 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4306 if (!it.compositeRule && $breakOnError) {
4307 /* istanbul ignore if */
4308 if (it.async) {
4309 out += ' throw new ValidationError(vErrors); ';
4310 } else {
4311 out += ' validate.errors = vErrors; return false; ';
4312 }
4313 }
4314 out += ' } ';
4315 if ($breakOnError) {
4316 out += ' else { ';
4317 }
4318 out = it.util.cleanUpCode(out);
4319 } else {
4320 if ($breakOnError) {
4321 out += ' if (true) { ';
4322 }
4323 }
4324 return out;
4325}
4326
4327},{}],31:[function(require,module,exports){
4328'use strict';
4329
4330//all requires must be explicit because browserify won't work with dynamic requires
4331module.exports = {
4332 '$ref': require('./ref'),
4333 allOf: require('./allOf'),
4334 anyOf: require('./anyOf'),
4335 '$comment': require('./comment'),
4336 const: require('./const'),
4337 contains: require('./contains'),
4338 dependencies: require('./dependencies'),
4339 'enum': require('./enum'),
4340 format: require('./format'),
4341 'if': require('./if'),
4342 items: require('./items'),
4343 maximum: require('./_limit'),
4344 minimum: require('./_limit'),
4345 maxItems: require('./_limitItems'),
4346 minItems: require('./_limitItems'),
4347 maxLength: require('./_limitLength'),
4348 minLength: require('./_limitLength'),
4349 maxProperties: require('./_limitProperties'),
4350 minProperties: require('./_limitProperties'),
4351 multipleOf: require('./multipleOf'),
4352 not: require('./not'),
4353 oneOf: require('./oneOf'),
4354 pattern: require('./pattern'),
4355 properties: require('./properties'),
4356 propertyNames: require('./propertyNames'),
4357 required: require('./required'),
4358 uniqueItems: require('./uniqueItems'),
4359 validate: require('./validate')
4360};
4361
4362},{"./_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){
4363'use strict';
4364module.exports = function generate_items(it, $keyword, $ruleType) {
4365 var out = ' ';
4366 var $lvl = it.level;
4367 var $dataLvl = it.dataLevel;
4368 var $schema = it.schema[$keyword];
4369 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4370 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4371 var $breakOnError = !it.opts.allErrors;
4372 var $data = 'data' + ($dataLvl || '');
4373 var $valid = 'valid' + $lvl;
4374 var $errs = 'errs__' + $lvl;
4375 var $it = it.util.copy(it);
4376 var $closingBraces = '';
4377 $it.level++;
4378 var $nextValid = 'valid' + $it.level;
4379 var $idx = 'i' + $lvl,
4380 $dataNxt = $it.dataLevel = it.dataLevel + 1,
4381 $nextData = 'data' + $dataNxt,
4382 $currentBaseId = it.baseId;
4383 out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
4384 if (Array.isArray($schema)) {
4385 var $additionalItems = it.schema.additionalItems;
4386 if ($additionalItems === false) {
4387 out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
4388 var $currErrSchemaPath = $errSchemaPath;
4389 $errSchemaPath = it.errSchemaPath + '/additionalItems';
4390 out += ' if (!' + ($valid) + ') { ';
4391 var $$outStack = $$outStack || [];
4392 $$outStack.push(out);
4393 out = ''; /* istanbul ignore else */
4394 if (it.createErrors !== false) {
4395 out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
4396 if (it.opts.messages !== false) {
4397 out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
4398 }
4399 if (it.opts.verbose) {
4400 out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4401 }
4402 out += ' } ';
4403 } else {
4404 out += ' {} ';
4405 }
4406 var __err = out;
4407 out = $$outStack.pop();
4408 if (!it.compositeRule && $breakOnError) {
4409 /* istanbul ignore if */
4410 if (it.async) {
4411 out += ' throw new ValidationError([' + (__err) + ']); ';
4412 } else {
4413 out += ' validate.errors = [' + (__err) + ']; return false; ';
4414 }
4415 } else {
4416 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4417 }
4418 out += ' } ';
4419 $errSchemaPath = $currErrSchemaPath;
4420 if ($breakOnError) {
4421 $closingBraces += '}';
4422 out += ' else { ';
4423 }
4424 }
4425 var arr1 = $schema;
4426 if (arr1) {
4427 var $sch, $i = -1,
4428 l1 = arr1.length - 1;
4429 while ($i < l1) {
4430 $sch = arr1[$i += 1];
4431 if (it.util.schemaHasRules($sch, it.RULES.all)) {
4432 out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
4433 var $passData = $data + '[' + $i + ']';
4434 $it.schema = $sch;
4435 $it.schemaPath = $schemaPath + '[' + $i + ']';
4436 $it.errSchemaPath = $errSchemaPath + '/' + $i;
4437 $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
4438 $it.dataPathArr[$dataNxt] = $i;
4439 var $code = it.validate($it);
4440 $it.baseId = $currentBaseId;
4441 if (it.util.varOccurences($code, $nextData) < 2) {
4442 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4443 } else {
4444 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4445 }
4446 out += ' } ';
4447 if ($breakOnError) {
4448 out += ' if (' + ($nextValid) + ') { ';
4449 $closingBraces += '}';
4450 }
4451 }
4452 }
4453 }
4454 if (typeof $additionalItems == 'object' && it.util.schemaHasRules($additionalItems, it.RULES.all)) {
4455 $it.schema = $additionalItems;
4456 $it.schemaPath = it.schemaPath + '.additionalItems';
4457 $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
4458 out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
4459 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
4460 var $passData = $data + '[' + $idx + ']';
4461 $it.dataPathArr[$dataNxt] = $idx;
4462 var $code = it.validate($it);
4463 $it.baseId = $currentBaseId;
4464 if (it.util.varOccurences($code, $nextData) < 2) {
4465 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4466 } else {
4467 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4468 }
4469 if ($breakOnError) {
4470 out += ' if (!' + ($nextValid) + ') break; ';
4471 }
4472 out += ' } } ';
4473 if ($breakOnError) {
4474 out += ' if (' + ($nextValid) + ') { ';
4475 $closingBraces += '}';
4476 }
4477 }
4478 } else if (it.util.schemaHasRules($schema, it.RULES.all)) {
4479 $it.schema = $schema;
4480 $it.schemaPath = $schemaPath;
4481 $it.errSchemaPath = $errSchemaPath;
4482 out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
4483 $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
4484 var $passData = $data + '[' + $idx + ']';
4485 $it.dataPathArr[$dataNxt] = $idx;
4486 var $code = it.validate($it);
4487 $it.baseId = $currentBaseId;
4488 if (it.util.varOccurences($code, $nextData) < 2) {
4489 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4490 } else {
4491 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4492 }
4493 if ($breakOnError) {
4494 out += ' if (!' + ($nextValid) + ') break; ';
4495 }
4496 out += ' }';
4497 }
4498 if ($breakOnError) {
4499 out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
4500 }
4501 out = it.util.cleanUpCode(out);
4502 return out;
4503}
4504
4505},{}],33:[function(require,module,exports){
4506'use strict';
4507module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
4508 var out = ' ';
4509 var $lvl = it.level;
4510 var $dataLvl = it.dataLevel;
4511 var $schema = it.schema[$keyword];
4512 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4513 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4514 var $breakOnError = !it.opts.allErrors;
4515 var $data = 'data' + ($dataLvl || '');
4516 var $isData = it.opts.$data && $schema && $schema.$data,
4517 $schemaValue;
4518 if ($isData) {
4519 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4520 $schemaValue = 'schema' + $lvl;
4521 } else {
4522 $schemaValue = $schema;
4523 }
4524 out += 'var division' + ($lvl) + ';if (';
4525 if ($isData) {
4526 out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
4527 }
4528 out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
4529 if (it.opts.multipleOfPrecision) {
4530 out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
4531 } else {
4532 out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
4533 }
4534 out += ' ) ';
4535 if ($isData) {
4536 out += ' ) ';
4537 }
4538 out += ' ) { ';
4539 var $$outStack = $$outStack || [];
4540 $$outStack.push(out);
4541 out = ''; /* istanbul ignore else */
4542 if (it.createErrors !== false) {
4543 out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
4544 if (it.opts.messages !== false) {
4545 out += ' , message: \'should be multiple of ';
4546 if ($isData) {
4547 out += '\' + ' + ($schemaValue);
4548 } else {
4549 out += '' + ($schemaValue) + '\'';
4550 }
4551 }
4552 if (it.opts.verbose) {
4553 out += ' , schema: ';
4554 if ($isData) {
4555 out += 'validate.schema' + ($schemaPath);
4556 } else {
4557 out += '' + ($schema);
4558 }
4559 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4560 }
4561 out += ' } ';
4562 } else {
4563 out += ' {} ';
4564 }
4565 var __err = out;
4566 out = $$outStack.pop();
4567 if (!it.compositeRule && $breakOnError) {
4568 /* istanbul ignore if */
4569 if (it.async) {
4570 out += ' throw new ValidationError([' + (__err) + ']); ';
4571 } else {
4572 out += ' validate.errors = [' + (__err) + ']; return false; ';
4573 }
4574 } else {
4575 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4576 }
4577 out += '} ';
4578 if ($breakOnError) {
4579 out += ' else { ';
4580 }
4581 return out;
4582}
4583
4584},{}],34:[function(require,module,exports){
4585'use strict';
4586module.exports = function generate_not(it, $keyword, $ruleType) {
4587 var out = ' ';
4588 var $lvl = it.level;
4589 var $dataLvl = it.dataLevel;
4590 var $schema = it.schema[$keyword];
4591 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4592 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4593 var $breakOnError = !it.opts.allErrors;
4594 var $data = 'data' + ($dataLvl || '');
4595 var $errs = 'errs__' + $lvl;
4596 var $it = it.util.copy(it);
4597 $it.level++;
4598 var $nextValid = 'valid' + $it.level;
4599 if (it.util.schemaHasRules($schema, it.RULES.all)) {
4600 $it.schema = $schema;
4601 $it.schemaPath = $schemaPath;
4602 $it.errSchemaPath = $errSchemaPath;
4603 out += ' var ' + ($errs) + ' = errors; ';
4604 var $wasComposite = it.compositeRule;
4605 it.compositeRule = $it.compositeRule = true;
4606 $it.createErrors = false;
4607 var $allErrorsOption;
4608 if ($it.opts.allErrors) {
4609 $allErrorsOption = $it.opts.allErrors;
4610 $it.opts.allErrors = false;
4611 }
4612 out += ' ' + (it.validate($it)) + ' ';
4613 $it.createErrors = true;
4614 if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
4615 it.compositeRule = $it.compositeRule = $wasComposite;
4616 out += ' if (' + ($nextValid) + ') { ';
4617 var $$outStack = $$outStack || [];
4618 $$outStack.push(out);
4619 out = ''; /* istanbul ignore else */
4620 if (it.createErrors !== false) {
4621 out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
4622 if (it.opts.messages !== false) {
4623 out += ' , message: \'should NOT be valid\' ';
4624 }
4625 if (it.opts.verbose) {
4626 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4627 }
4628 out += ' } ';
4629 } else {
4630 out += ' {} ';
4631 }
4632 var __err = out;
4633 out = $$outStack.pop();
4634 if (!it.compositeRule && $breakOnError) {
4635 /* istanbul ignore if */
4636 if (it.async) {
4637 out += ' throw new ValidationError([' + (__err) + ']); ';
4638 } else {
4639 out += ' validate.errors = [' + (__err) + ']; return false; ';
4640 }
4641 } else {
4642 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4643 }
4644 out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
4645 if (it.opts.allErrors) {
4646 out += ' } ';
4647 }
4648 } else {
4649 out += ' var err = '; /* istanbul ignore else */
4650 if (it.createErrors !== false) {
4651 out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
4652 if (it.opts.messages !== false) {
4653 out += ' , message: \'should NOT be valid\' ';
4654 }
4655 if (it.opts.verbose) {
4656 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4657 }
4658 out += ' } ';
4659 } else {
4660 out += ' {} ';
4661 }
4662 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4663 if ($breakOnError) {
4664 out += ' if (false) { ';
4665 }
4666 }
4667 return out;
4668}
4669
4670},{}],35:[function(require,module,exports){
4671'use strict';
4672module.exports = function generate_oneOf(it, $keyword, $ruleType) {
4673 var out = ' ';
4674 var $lvl = it.level;
4675 var $dataLvl = it.dataLevel;
4676 var $schema = it.schema[$keyword];
4677 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4678 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4679 var $breakOnError = !it.opts.allErrors;
4680 var $data = 'data' + ($dataLvl || '');
4681 var $valid = 'valid' + $lvl;
4682 var $errs = 'errs__' + $lvl;
4683 var $it = it.util.copy(it);
4684 var $closingBraces = '';
4685 $it.level++;
4686 var $nextValid = 'valid' + $it.level;
4687 var $currentBaseId = $it.baseId,
4688 $prevValid = 'prevValid' + $lvl,
4689 $passingSchemas = 'passingSchemas' + $lvl;
4690 out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
4691 var $wasComposite = it.compositeRule;
4692 it.compositeRule = $it.compositeRule = true;
4693 var arr1 = $schema;
4694 if (arr1) {
4695 var $sch, $i = -1,
4696 l1 = arr1.length - 1;
4697 while ($i < l1) {
4698 $sch = arr1[$i += 1];
4699 if (it.util.schemaHasRules($sch, it.RULES.all)) {
4700 $it.schema = $sch;
4701 $it.schemaPath = $schemaPath + '[' + $i + ']';
4702 $it.errSchemaPath = $errSchemaPath + '/' + $i;
4703 out += ' ' + (it.validate($it)) + ' ';
4704 $it.baseId = $currentBaseId;
4705 } else {
4706 out += ' var ' + ($nextValid) + ' = true; ';
4707 }
4708 if ($i) {
4709 out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
4710 $closingBraces += '}';
4711 }
4712 out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
4713 }
4714 }
4715 it.compositeRule = $it.compositeRule = $wasComposite;
4716 out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
4717 if (it.createErrors !== false) {
4718 out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
4719 if (it.opts.messages !== false) {
4720 out += ' , message: \'should match exactly one schema in oneOf\' ';
4721 }
4722 if (it.opts.verbose) {
4723 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4724 }
4725 out += ' } ';
4726 } else {
4727 out += ' {} ';
4728 }
4729 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4730 if (!it.compositeRule && $breakOnError) {
4731 /* istanbul ignore if */
4732 if (it.async) {
4733 out += ' throw new ValidationError(vErrors); ';
4734 } else {
4735 out += ' validate.errors = vErrors; return false; ';
4736 }
4737 }
4738 out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
4739 if (it.opts.allErrors) {
4740 out += ' } ';
4741 }
4742 return out;
4743}
4744
4745},{}],36:[function(require,module,exports){
4746'use strict';
4747module.exports = function generate_pattern(it, $keyword, $ruleType) {
4748 var out = ' ';
4749 var $lvl = it.level;
4750 var $dataLvl = it.dataLevel;
4751 var $schema = it.schema[$keyword];
4752 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4753 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4754 var $breakOnError = !it.opts.allErrors;
4755 var $data = 'data' + ($dataLvl || '');
4756 var $isData = it.opts.$data && $schema && $schema.$data,
4757 $schemaValue;
4758 if ($isData) {
4759 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
4760 $schemaValue = 'schema' + $lvl;
4761 } else {
4762 $schemaValue = $schema;
4763 }
4764 var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
4765 out += 'if ( ';
4766 if ($isData) {
4767 out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
4768 }
4769 out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { ';
4770 var $$outStack = $$outStack || [];
4771 $$outStack.push(out);
4772 out = ''; /* istanbul ignore else */
4773 if (it.createErrors !== false) {
4774 out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: ';
4775 if ($isData) {
4776 out += '' + ($schemaValue);
4777 } else {
4778 out += '' + (it.util.toQuotedString($schema));
4779 }
4780 out += ' } ';
4781 if (it.opts.messages !== false) {
4782 out += ' , message: \'should match pattern "';
4783 if ($isData) {
4784 out += '\' + ' + ($schemaValue) + ' + \'';
4785 } else {
4786 out += '' + (it.util.escapeQuotes($schema));
4787 }
4788 out += '"\' ';
4789 }
4790 if (it.opts.verbose) {
4791 out += ' , schema: ';
4792 if ($isData) {
4793 out += 'validate.schema' + ($schemaPath);
4794 } else {
4795 out += '' + (it.util.toQuotedString($schema));
4796 }
4797 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4798 }
4799 out += ' } ';
4800 } else {
4801 out += ' {} ';
4802 }
4803 var __err = out;
4804 out = $$outStack.pop();
4805 if (!it.compositeRule && $breakOnError) {
4806 /* istanbul ignore if */
4807 if (it.async) {
4808 out += ' throw new ValidationError([' + (__err) + ']); ';
4809 } else {
4810 out += ' validate.errors = [' + (__err) + ']; return false; ';
4811 }
4812 } else {
4813 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4814 }
4815 out += '} ';
4816 if ($breakOnError) {
4817 out += ' else { ';
4818 }
4819 return out;
4820}
4821
4822},{}],37:[function(require,module,exports){
4823'use strict';
4824module.exports = function generate_properties(it, $keyword, $ruleType) {
4825 var out = ' ';
4826 var $lvl = it.level;
4827 var $dataLvl = it.dataLevel;
4828 var $schema = it.schema[$keyword];
4829 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
4830 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
4831 var $breakOnError = !it.opts.allErrors;
4832 var $data = 'data' + ($dataLvl || '');
4833 var $errs = 'errs__' + $lvl;
4834 var $it = it.util.copy(it);
4835 var $closingBraces = '';
4836 $it.level++;
4837 var $nextValid = 'valid' + $it.level;
4838 var $key = 'key' + $lvl,
4839 $idx = 'idx' + $lvl,
4840 $dataNxt = $it.dataLevel = it.dataLevel + 1,
4841 $nextData = 'data' + $dataNxt,
4842 $dataProperties = 'dataProperties' + $lvl;
4843 var $schemaKeys = Object.keys($schema || {}),
4844 $pProperties = it.schema.patternProperties || {},
4845 $pPropertyKeys = Object.keys($pProperties),
4846 $aProperties = it.schema.additionalProperties,
4847 $someProperties = $schemaKeys.length || $pPropertyKeys.length,
4848 $noAdditional = $aProperties === false,
4849 $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
4850 $removeAdditional = it.opts.removeAdditional,
4851 $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
4852 $ownProperties = it.opts.ownProperties,
4853 $currentBaseId = it.baseId;
4854 var $required = it.schema.required;
4855 if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
4856 out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
4857 if ($ownProperties) {
4858 out += ' var ' + ($dataProperties) + ' = undefined;';
4859 }
4860 if ($checkAdditional) {
4861 if ($ownProperties) {
4862 out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
4863 } else {
4864 out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
4865 }
4866 if ($someProperties) {
4867 out += ' var isAdditional' + ($lvl) + ' = !(false ';
4868 if ($schemaKeys.length) {
4869 if ($schemaKeys.length > 8) {
4870 out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
4871 } else {
4872 var arr1 = $schemaKeys;
4873 if (arr1) {
4874 var $propertyKey, i1 = -1,
4875 l1 = arr1.length - 1;
4876 while (i1 < l1) {
4877 $propertyKey = arr1[i1 += 1];
4878 out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
4879 }
4880 }
4881 }
4882 }
4883 if ($pPropertyKeys.length) {
4884 var arr2 = $pPropertyKeys;
4885 if (arr2) {
4886 var $pProperty, $i = -1,
4887 l2 = arr2.length - 1;
4888 while ($i < l2) {
4889 $pProperty = arr2[$i += 1];
4890 out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
4891 }
4892 }
4893 }
4894 out += ' ); if (isAdditional' + ($lvl) + ') { ';
4895 }
4896 if ($removeAdditional == 'all') {
4897 out += ' delete ' + ($data) + '[' + ($key) + ']; ';
4898 } else {
4899 var $currentErrorPath = it.errorPath;
4900 var $additionalProperty = '\' + ' + $key + ' + \'';
4901 if (it.opts._errorDataPathProperty) {
4902 it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
4903 }
4904 if ($noAdditional) {
4905 if ($removeAdditional) {
4906 out += ' delete ' + ($data) + '[' + ($key) + ']; ';
4907 } else {
4908 out += ' ' + ($nextValid) + ' = false; ';
4909 var $currErrSchemaPath = $errSchemaPath;
4910 $errSchemaPath = it.errSchemaPath + '/additionalProperties';
4911 var $$outStack = $$outStack || [];
4912 $$outStack.push(out);
4913 out = ''; /* istanbul ignore else */
4914 if (it.createErrors !== false) {
4915 out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
4916 if (it.opts.messages !== false) {
4917 out += ' , message: \'';
4918 if (it.opts._errorDataPathProperty) {
4919 out += 'is an invalid additional property';
4920 } else {
4921 out += 'should NOT have additional properties';
4922 }
4923 out += '\' ';
4924 }
4925 if (it.opts.verbose) {
4926 out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
4927 }
4928 out += ' } ';
4929 } else {
4930 out += ' {} ';
4931 }
4932 var __err = out;
4933 out = $$outStack.pop();
4934 if (!it.compositeRule && $breakOnError) {
4935 /* istanbul ignore if */
4936 if (it.async) {
4937 out += ' throw new ValidationError([' + (__err) + ']); ';
4938 } else {
4939 out += ' validate.errors = [' + (__err) + ']; return false; ';
4940 }
4941 } else {
4942 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
4943 }
4944 $errSchemaPath = $currErrSchemaPath;
4945 if ($breakOnError) {
4946 out += ' break; ';
4947 }
4948 }
4949 } else if ($additionalIsSchema) {
4950 if ($removeAdditional == 'failing') {
4951 out += ' var ' + ($errs) + ' = errors; ';
4952 var $wasComposite = it.compositeRule;
4953 it.compositeRule = $it.compositeRule = true;
4954 $it.schema = $aProperties;
4955 $it.schemaPath = it.schemaPath + '.additionalProperties';
4956 $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
4957 $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
4958 var $passData = $data + '[' + $key + ']';
4959 $it.dataPathArr[$dataNxt] = $key;
4960 var $code = it.validate($it);
4961 $it.baseId = $currentBaseId;
4962 if (it.util.varOccurences($code, $nextData) < 2) {
4963 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4964 } else {
4965 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4966 }
4967 out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } ';
4968 it.compositeRule = $it.compositeRule = $wasComposite;
4969 } else {
4970 $it.schema = $aProperties;
4971 $it.schemaPath = it.schemaPath + '.additionalProperties';
4972 $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
4973 $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
4974 var $passData = $data + '[' + $key + ']';
4975 $it.dataPathArr[$dataNxt] = $key;
4976 var $code = it.validate($it);
4977 $it.baseId = $currentBaseId;
4978 if (it.util.varOccurences($code, $nextData) < 2) {
4979 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
4980 } else {
4981 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
4982 }
4983 if ($breakOnError) {
4984 out += ' if (!' + ($nextValid) + ') break; ';
4985 }
4986 }
4987 }
4988 it.errorPath = $currentErrorPath;
4989 }
4990 if ($someProperties) {
4991 out += ' } ';
4992 }
4993 out += ' } ';
4994 if ($breakOnError) {
4995 out += ' if (' + ($nextValid) + ') { ';
4996 $closingBraces += '}';
4997 }
4998 }
4999 var $useDefaults = it.opts.useDefaults && !it.compositeRule;
5000 if ($schemaKeys.length) {
5001 var arr3 = $schemaKeys;
5002 if (arr3) {
5003 var $propertyKey, i3 = -1,
5004 l3 = arr3.length - 1;
5005 while (i3 < l3) {
5006 $propertyKey = arr3[i3 += 1];
5007 var $sch = $schema[$propertyKey];
5008 if (it.util.schemaHasRules($sch, it.RULES.all)) {
5009 var $prop = it.util.getProperty($propertyKey),
5010 $passData = $data + $prop,
5011 $hasDefault = $useDefaults && $sch.default !== undefined;
5012 $it.schema = $sch;
5013 $it.schemaPath = $schemaPath + $prop;
5014 $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
5015 $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
5016 $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
5017 var $code = it.validate($it);
5018 $it.baseId = $currentBaseId;
5019 if (it.util.varOccurences($code, $nextData) < 2) {
5020 $code = it.util.varReplace($code, $nextData, $passData);
5021 var $useData = $passData;
5022 } else {
5023 var $useData = $nextData;
5024 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
5025 }
5026 if ($hasDefault) {
5027 out += ' ' + ($code) + ' ';
5028 } else {
5029 if ($requiredHash && $requiredHash[$propertyKey]) {
5030 out += ' if ( ' + ($useData) + ' === undefined ';
5031 if ($ownProperties) {
5032 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5033 }
5034 out += ') { ' + ($nextValid) + ' = false; ';
5035 var $currentErrorPath = it.errorPath,
5036 $currErrSchemaPath = $errSchemaPath,
5037 $missingProperty = it.util.escapeQuotes($propertyKey);
5038 if (it.opts._errorDataPathProperty) {
5039 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
5040 }
5041 $errSchemaPath = it.errSchemaPath + '/required';
5042 var $$outStack = $$outStack || [];
5043 $$outStack.push(out);
5044 out = ''; /* istanbul ignore else */
5045 if (it.createErrors !== false) {
5046 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5047 if (it.opts.messages !== false) {
5048 out += ' , message: \'';
5049 if (it.opts._errorDataPathProperty) {
5050 out += 'is a required property';
5051 } else {
5052 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5053 }
5054 out += '\' ';
5055 }
5056 if (it.opts.verbose) {
5057 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5058 }
5059 out += ' } ';
5060 } else {
5061 out += ' {} ';
5062 }
5063 var __err = out;
5064 out = $$outStack.pop();
5065 if (!it.compositeRule && $breakOnError) {
5066 /* istanbul ignore if */
5067 if (it.async) {
5068 out += ' throw new ValidationError([' + (__err) + ']); ';
5069 } else {
5070 out += ' validate.errors = [' + (__err) + ']; return false; ';
5071 }
5072 } else {
5073 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5074 }
5075 $errSchemaPath = $currErrSchemaPath;
5076 it.errorPath = $currentErrorPath;
5077 out += ' } else { ';
5078 } else {
5079 if ($breakOnError) {
5080 out += ' if ( ' + ($useData) + ' === undefined ';
5081 if ($ownProperties) {
5082 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5083 }
5084 out += ') { ' + ($nextValid) + ' = true; } else { ';
5085 } else {
5086 out += ' if (' + ($useData) + ' !== undefined ';
5087 if ($ownProperties) {
5088 out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5089 }
5090 out += ' ) { ';
5091 }
5092 }
5093 out += ' ' + ($code) + ' } ';
5094 }
5095 }
5096 if ($breakOnError) {
5097 out += ' if (' + ($nextValid) + ') { ';
5098 $closingBraces += '}';
5099 }
5100 }
5101 }
5102 }
5103 if ($pPropertyKeys.length) {
5104 var arr4 = $pPropertyKeys;
5105 if (arr4) {
5106 var $pProperty, i4 = -1,
5107 l4 = arr4.length - 1;
5108 while (i4 < l4) {
5109 $pProperty = arr4[i4 += 1];
5110 var $sch = $pProperties[$pProperty];
5111 if (it.util.schemaHasRules($sch, it.RULES.all)) {
5112 $it.schema = $sch;
5113 $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
5114 $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
5115 if ($ownProperties) {
5116 out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
5117 } else {
5118 out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
5119 }
5120 out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
5121 $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
5122 var $passData = $data + '[' + $key + ']';
5123 $it.dataPathArr[$dataNxt] = $key;
5124 var $code = it.validate($it);
5125 $it.baseId = $currentBaseId;
5126 if (it.util.varOccurences($code, $nextData) < 2) {
5127 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
5128 } else {
5129 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
5130 }
5131 if ($breakOnError) {
5132 out += ' if (!' + ($nextValid) + ') break; ';
5133 }
5134 out += ' } ';
5135 if ($breakOnError) {
5136 out += ' else ' + ($nextValid) + ' = true; ';
5137 }
5138 out += ' } ';
5139 if ($breakOnError) {
5140 out += ' if (' + ($nextValid) + ') { ';
5141 $closingBraces += '}';
5142 }
5143 }
5144 }
5145 }
5146 }
5147 if ($breakOnError) {
5148 out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
5149 }
5150 out = it.util.cleanUpCode(out);
5151 return out;
5152}
5153
5154},{}],38:[function(require,module,exports){
5155'use strict';
5156module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
5157 var out = ' ';
5158 var $lvl = it.level;
5159 var $dataLvl = it.dataLevel;
5160 var $schema = it.schema[$keyword];
5161 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
5162 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5163 var $breakOnError = !it.opts.allErrors;
5164 var $data = 'data' + ($dataLvl || '');
5165 var $errs = 'errs__' + $lvl;
5166 var $it = it.util.copy(it);
5167 var $closingBraces = '';
5168 $it.level++;
5169 var $nextValid = 'valid' + $it.level;
5170 out += 'var ' + ($errs) + ' = errors;';
5171 if (it.util.schemaHasRules($schema, it.RULES.all)) {
5172 $it.schema = $schema;
5173 $it.schemaPath = $schemaPath;
5174 $it.errSchemaPath = $errSchemaPath;
5175 var $key = 'key' + $lvl,
5176 $idx = 'idx' + $lvl,
5177 $i = 'i' + $lvl,
5178 $invalidName = '\' + ' + $key + ' + \'',
5179 $dataNxt = $it.dataLevel = it.dataLevel + 1,
5180 $nextData = 'data' + $dataNxt,
5181 $dataProperties = 'dataProperties' + $lvl,
5182 $ownProperties = it.opts.ownProperties,
5183 $currentBaseId = it.baseId;
5184 if ($ownProperties) {
5185 out += ' var ' + ($dataProperties) + ' = undefined; ';
5186 }
5187 if ($ownProperties) {
5188 out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
5189 } else {
5190 out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
5191 }
5192 out += ' var startErrs' + ($lvl) + ' = errors; ';
5193 var $passData = $key;
5194 var $wasComposite = it.compositeRule;
5195 it.compositeRule = $it.compositeRule = true;
5196 var $code = it.validate($it);
5197 $it.baseId = $currentBaseId;
5198 if (it.util.varOccurences($code, $nextData) < 2) {
5199 out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
5200 } else {
5201 out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
5202 }
5203 it.compositeRule = $it.compositeRule = $wasComposite;
5204 out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; } var err = '; /* istanbul ignore else */
5205 if (it.createErrors !== false) {
5206 out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } ';
5207 if (it.opts.messages !== false) {
5208 out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' ';
5209 }
5210 if (it.opts.verbose) {
5211 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5212 }
5213 out += ' } ';
5214 } else {
5215 out += ' {} ';
5216 }
5217 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5218 if (!it.compositeRule && $breakOnError) {
5219 /* istanbul ignore if */
5220 if (it.async) {
5221 out += ' throw new ValidationError(vErrors); ';
5222 } else {
5223 out += ' validate.errors = vErrors; return false; ';
5224 }
5225 }
5226 if ($breakOnError) {
5227 out += ' break; ';
5228 }
5229 out += ' } }';
5230 }
5231 if ($breakOnError) {
5232 out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
5233 }
5234 out = it.util.cleanUpCode(out);
5235 return out;
5236}
5237
5238},{}],39:[function(require,module,exports){
5239'use strict';
5240module.exports = function generate_ref(it, $keyword, $ruleType) {
5241 var out = ' ';
5242 var $lvl = it.level;
5243 var $dataLvl = it.dataLevel;
5244 var $schema = it.schema[$keyword];
5245 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5246 var $breakOnError = !it.opts.allErrors;
5247 var $data = 'data' + ($dataLvl || '');
5248 var $valid = 'valid' + $lvl;
5249 var $async, $refCode;
5250 if ($schema == '#' || $schema == '#/') {
5251 if (it.isRoot) {
5252 $async = it.async;
5253 $refCode = 'validate';
5254 } else {
5255 $async = it.root.schema.$async === true;
5256 $refCode = 'root.refVal[0]';
5257 }
5258 } else {
5259 var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
5260 if ($refVal === undefined) {
5261 var $message = it.MissingRefError.message(it.baseId, $schema);
5262 if (it.opts.missingRefs == 'fail') {
5263 it.logger.error($message);
5264 var $$outStack = $$outStack || [];
5265 $$outStack.push(out);
5266 out = ''; /* istanbul ignore else */
5267 if (it.createErrors !== false) {
5268 out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } ';
5269 if (it.opts.messages !== false) {
5270 out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' ';
5271 }
5272 if (it.opts.verbose) {
5273 out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5274 }
5275 out += ' } ';
5276 } else {
5277 out += ' {} ';
5278 }
5279 var __err = out;
5280 out = $$outStack.pop();
5281 if (!it.compositeRule && $breakOnError) {
5282 /* istanbul ignore if */
5283 if (it.async) {
5284 out += ' throw new ValidationError([' + (__err) + ']); ';
5285 } else {
5286 out += ' validate.errors = [' + (__err) + ']; return false; ';
5287 }
5288 } else {
5289 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5290 }
5291 if ($breakOnError) {
5292 out += ' if (false) { ';
5293 }
5294 } else if (it.opts.missingRefs == 'ignore') {
5295 it.logger.warn($message);
5296 if ($breakOnError) {
5297 out += ' if (true) { ';
5298 }
5299 } else {
5300 throw new it.MissingRefError(it.baseId, $schema, $message);
5301 }
5302 } else if ($refVal.inline) {
5303 var $it = it.util.copy(it);
5304 $it.level++;
5305 var $nextValid = 'valid' + $it.level;
5306 $it.schema = $refVal.schema;
5307 $it.schemaPath = '';
5308 $it.errSchemaPath = $schema;
5309 var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
5310 out += ' ' + ($code) + ' ';
5311 if ($breakOnError) {
5312 out += ' if (' + ($nextValid) + ') { ';
5313 }
5314 } else {
5315 $async = $refVal.$async === true || (it.async && $refVal.$async !== false);
5316 $refCode = $refVal.code;
5317 }
5318 }
5319 if ($refCode) {
5320 var $$outStack = $$outStack || [];
5321 $$outStack.push(out);
5322 out = '';
5323 if (it.opts.passContext) {
5324 out += ' ' + ($refCode) + '.call(this, ';
5325 } else {
5326 out += ' ' + ($refCode) + '( ';
5327 }
5328 out += ' ' + ($data) + ', (dataPath || \'\')';
5329 if (it.errorPath != '""') {
5330 out += ' + ' + (it.errorPath);
5331 }
5332 var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
5333 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
5334 out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) ';
5335 var __callValidate = out;
5336 out = $$outStack.pop();
5337 if ($async) {
5338 if (!it.async) throw new Error('async schema referenced by sync schema');
5339 if ($breakOnError) {
5340 out += ' var ' + ($valid) + '; ';
5341 }
5342 out += ' try { await ' + (__callValidate) + '; ';
5343 if ($breakOnError) {
5344 out += ' ' + ($valid) + ' = true; ';
5345 }
5346 out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
5347 if ($breakOnError) {
5348 out += ' ' + ($valid) + ' = false; ';
5349 }
5350 out += ' } ';
5351 if ($breakOnError) {
5352 out += ' if (' + ($valid) + ') { ';
5353 }
5354 } else {
5355 out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } ';
5356 if ($breakOnError) {
5357 out += ' else { ';
5358 }
5359 }
5360 }
5361 return out;
5362}
5363
5364},{}],40:[function(require,module,exports){
5365'use strict';
5366module.exports = function generate_required(it, $keyword, $ruleType) {
5367 var out = ' ';
5368 var $lvl = it.level;
5369 var $dataLvl = it.dataLevel;
5370 var $schema = it.schema[$keyword];
5371 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
5372 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5373 var $breakOnError = !it.opts.allErrors;
5374 var $data = 'data' + ($dataLvl || '');
5375 var $valid = 'valid' + $lvl;
5376 var $isData = it.opts.$data && $schema && $schema.$data,
5377 $schemaValue;
5378 if ($isData) {
5379 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
5380 $schemaValue = 'schema' + $lvl;
5381 } else {
5382 $schemaValue = $schema;
5383 }
5384 var $vSchema = 'schema' + $lvl;
5385 if (!$isData) {
5386 if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
5387 var $required = [];
5388 var arr1 = $schema;
5389 if (arr1) {
5390 var $property, i1 = -1,
5391 l1 = arr1.length - 1;
5392 while (i1 < l1) {
5393 $property = arr1[i1 += 1];
5394 var $propertySch = it.schema.properties[$property];
5395 if (!($propertySch && it.util.schemaHasRules($propertySch, it.RULES.all))) {
5396 $required[$required.length] = $property;
5397 }
5398 }
5399 }
5400 } else {
5401 var $required = $schema;
5402 }
5403 }
5404 if ($isData || $required.length) {
5405 var $currentErrorPath = it.errorPath,
5406 $loopRequired = $isData || $required.length >= it.opts.loopRequired,
5407 $ownProperties = it.opts.ownProperties;
5408 if ($breakOnError) {
5409 out += ' var missing' + ($lvl) + '; ';
5410 if ($loopRequired) {
5411 if (!$isData) {
5412 out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
5413 }
5414 var $i = 'i' + $lvl,
5415 $propertyPath = 'schema' + $lvl + '[' + $i + ']',
5416 $missingProperty = '\' + ' + $propertyPath + ' + \'';
5417 if (it.opts._errorDataPathProperty) {
5418 it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
5419 }
5420 out += ' var ' + ($valid) + ' = true; ';
5421 if ($isData) {
5422 out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
5423 }
5424 out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
5425 if ($ownProperties) {
5426 out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
5427 }
5428 out += '; if (!' + ($valid) + ') break; } ';
5429 if ($isData) {
5430 out += ' } ';
5431 }
5432 out += ' if (!' + ($valid) + ') { ';
5433 var $$outStack = $$outStack || [];
5434 $$outStack.push(out);
5435 out = ''; /* istanbul ignore else */
5436 if (it.createErrors !== false) {
5437 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5438 if (it.opts.messages !== false) {
5439 out += ' , message: \'';
5440 if (it.opts._errorDataPathProperty) {
5441 out += 'is a required property';
5442 } else {
5443 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5444 }
5445 out += '\' ';
5446 }
5447 if (it.opts.verbose) {
5448 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5449 }
5450 out += ' } ';
5451 } else {
5452 out += ' {} ';
5453 }
5454 var __err = out;
5455 out = $$outStack.pop();
5456 if (!it.compositeRule && $breakOnError) {
5457 /* istanbul ignore if */
5458 if (it.async) {
5459 out += ' throw new ValidationError([' + (__err) + ']); ';
5460 } else {
5461 out += ' validate.errors = [' + (__err) + ']; return false; ';
5462 }
5463 } else {
5464 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5465 }
5466 out += ' } else { ';
5467 } else {
5468 out += ' if ( ';
5469 var arr2 = $required;
5470 if (arr2) {
5471 var $propertyKey, $i = -1,
5472 l2 = arr2.length - 1;
5473 while ($i < l2) {
5474 $propertyKey = arr2[$i += 1];
5475 if ($i) {
5476 out += ' || ';
5477 }
5478 var $prop = it.util.getProperty($propertyKey),
5479 $useData = $data + $prop;
5480 out += ' ( ( ' + ($useData) + ' === undefined ';
5481 if ($ownProperties) {
5482 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5483 }
5484 out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
5485 }
5486 }
5487 out += ') { ';
5488 var $propertyPath = 'missing' + $lvl,
5489 $missingProperty = '\' + ' + $propertyPath + ' + \'';
5490 if (it.opts._errorDataPathProperty) {
5491 it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
5492 }
5493 var $$outStack = $$outStack || [];
5494 $$outStack.push(out);
5495 out = ''; /* istanbul ignore else */
5496 if (it.createErrors !== false) {
5497 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5498 if (it.opts.messages !== false) {
5499 out += ' , message: \'';
5500 if (it.opts._errorDataPathProperty) {
5501 out += 'is a required property';
5502 } else {
5503 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5504 }
5505 out += '\' ';
5506 }
5507 if (it.opts.verbose) {
5508 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5509 }
5510 out += ' } ';
5511 } else {
5512 out += ' {} ';
5513 }
5514 var __err = out;
5515 out = $$outStack.pop();
5516 if (!it.compositeRule && $breakOnError) {
5517 /* istanbul ignore if */
5518 if (it.async) {
5519 out += ' throw new ValidationError([' + (__err) + ']); ';
5520 } else {
5521 out += ' validate.errors = [' + (__err) + ']; return false; ';
5522 }
5523 } else {
5524 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5525 }
5526 out += ' } else { ';
5527 }
5528 } else {
5529 if ($loopRequired) {
5530 if (!$isData) {
5531 out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
5532 }
5533 var $i = 'i' + $lvl,
5534 $propertyPath = 'schema' + $lvl + '[' + $i + ']',
5535 $missingProperty = '\' + ' + $propertyPath + ' + \'';
5536 if (it.opts._errorDataPathProperty) {
5537 it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
5538 }
5539 if ($isData) {
5540 out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */
5541 if (it.createErrors !== false) {
5542 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5543 if (it.opts.messages !== false) {
5544 out += ' , message: \'';
5545 if (it.opts._errorDataPathProperty) {
5546 out += 'is a required property';
5547 } else {
5548 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5549 }
5550 out += '\' ';
5551 }
5552 if (it.opts.verbose) {
5553 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5554 }
5555 out += ' } ';
5556 } else {
5557 out += ' {} ';
5558 }
5559 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
5560 }
5561 out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
5562 if ($ownProperties) {
5563 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
5564 }
5565 out += ') { var err = '; /* istanbul ignore else */
5566 if (it.createErrors !== false) {
5567 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5568 if (it.opts.messages !== false) {
5569 out += ' , message: \'';
5570 if (it.opts._errorDataPathProperty) {
5571 out += 'is a required property';
5572 } else {
5573 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5574 }
5575 out += '\' ';
5576 }
5577 if (it.opts.verbose) {
5578 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5579 }
5580 out += ' } ';
5581 } else {
5582 out += ' {} ';
5583 }
5584 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
5585 if ($isData) {
5586 out += ' } ';
5587 }
5588 } else {
5589 var arr3 = $required;
5590 if (arr3) {
5591 var $propertyKey, i3 = -1,
5592 l3 = arr3.length - 1;
5593 while (i3 < l3) {
5594 $propertyKey = arr3[i3 += 1];
5595 var $prop = it.util.getProperty($propertyKey),
5596 $missingProperty = it.util.escapeQuotes($propertyKey),
5597 $useData = $data + $prop;
5598 if (it.opts._errorDataPathProperty) {
5599 it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
5600 }
5601 out += ' if ( ' + ($useData) + ' === undefined ';
5602 if ($ownProperties) {
5603 out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
5604 }
5605 out += ') { var err = '; /* istanbul ignore else */
5606 if (it.createErrors !== false) {
5607 out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
5608 if (it.opts.messages !== false) {
5609 out += ' , message: \'';
5610 if (it.opts._errorDataPathProperty) {
5611 out += 'is a required property';
5612 } else {
5613 out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
5614 }
5615 out += '\' ';
5616 }
5617 if (it.opts.verbose) {
5618 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5619 }
5620 out += ' } ';
5621 } else {
5622 out += ' {} ';
5623 }
5624 out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
5625 }
5626 }
5627 }
5628 }
5629 it.errorPath = $currentErrorPath;
5630 } else if ($breakOnError) {
5631 out += ' if (true) {';
5632 }
5633 return out;
5634}
5635
5636},{}],41:[function(require,module,exports){
5637'use strict';
5638module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
5639 var out = ' ';
5640 var $lvl = it.level;
5641 var $dataLvl = it.dataLevel;
5642 var $schema = it.schema[$keyword];
5643 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
5644 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5645 var $breakOnError = !it.opts.allErrors;
5646 var $data = 'data' + ($dataLvl || '');
5647 var $valid = 'valid' + $lvl;
5648 var $isData = it.opts.$data && $schema && $schema.$data,
5649 $schemaValue;
5650 if ($isData) {
5651 out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
5652 $schemaValue = 'schema' + $lvl;
5653 } else {
5654 $schemaValue = $schema;
5655 }
5656 if (($schema || $isData) && it.opts.uniqueItems !== false) {
5657 if ($isData) {
5658 out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
5659 }
5660 out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
5661 var $itemType = it.schema.items && it.schema.items.type,
5662 $typeIsArray = Array.isArray($itemType);
5663 if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
5664 out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
5665 } else {
5666 out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
5667 var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
5668 out += ' if (' + (it.util[$method]($itemType, 'item', true)) + ') continue; ';
5669 if ($typeIsArray) {
5670 out += ' if (typeof item == \'string\') item = \'"\' + item; ';
5671 }
5672 out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
5673 }
5674 out += ' } ';
5675 if ($isData) {
5676 out += ' } ';
5677 }
5678 out += ' if (!' + ($valid) + ') { ';
5679 var $$outStack = $$outStack || [];
5680 $$outStack.push(out);
5681 out = ''; /* istanbul ignore else */
5682 if (it.createErrors !== false) {
5683 out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
5684 if (it.opts.messages !== false) {
5685 out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
5686 }
5687 if (it.opts.verbose) {
5688 out += ' , schema: ';
5689 if ($isData) {
5690 out += 'validate.schema' + ($schemaPath);
5691 } else {
5692 out += '' + ($schema);
5693 }
5694 out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5695 }
5696 out += ' } ';
5697 } else {
5698 out += ' {} ';
5699 }
5700 var __err = out;
5701 out = $$outStack.pop();
5702 if (!it.compositeRule && $breakOnError) {
5703 /* istanbul ignore if */
5704 if (it.async) {
5705 out += ' throw new ValidationError([' + (__err) + ']); ';
5706 } else {
5707 out += ' validate.errors = [' + (__err) + ']; return false; ';
5708 }
5709 } else {
5710 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5711 }
5712 out += ' } ';
5713 if ($breakOnError) {
5714 out += ' else { ';
5715 }
5716 } else {
5717 if ($breakOnError) {
5718 out += ' if (true) { ';
5719 }
5720 }
5721 return out;
5722}
5723
5724},{}],42:[function(require,module,exports){
5725'use strict';
5726module.exports = function generate_validate(it, $keyword, $ruleType) {
5727 var out = '';
5728 var $async = it.schema.$async === true,
5729 $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
5730 $id = it.self._getId(it.schema);
5731 if (it.opts.strictKeywords) {
5732 var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
5733 if ($unknownKwd) {
5734 var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
5735 if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
5736 else throw new Error($keywordsMsg);
5737 }
5738 }
5739 if (it.isTop) {
5740 out += ' var validate = ';
5741 if ($async) {
5742 it.async = true;
5743 out += 'async ';
5744 }
5745 out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
5746 if ($id && (it.opts.sourceCode || it.opts.processCode)) {
5747 out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
5748 }
5749 }
5750 if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
5751 var $keyword = 'false schema';
5752 var $lvl = it.level;
5753 var $dataLvl = it.dataLevel;
5754 var $schema = it.schema[$keyword];
5755 var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
5756 var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
5757 var $breakOnError = !it.opts.allErrors;
5758 var $errorKeyword;
5759 var $data = 'data' + ($dataLvl || '');
5760 var $valid = 'valid' + $lvl;
5761 if (it.schema === false) {
5762 if (it.isTop) {
5763 $breakOnError = true;
5764 } else {
5765 out += ' var ' + ($valid) + ' = false; ';
5766 }
5767 var $$outStack = $$outStack || [];
5768 $$outStack.push(out);
5769 out = ''; /* istanbul ignore else */
5770 if (it.createErrors !== false) {
5771 out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
5772 if (it.opts.messages !== false) {
5773 out += ' , message: \'boolean schema is false\' ';
5774 }
5775 if (it.opts.verbose) {
5776 out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5777 }
5778 out += ' } ';
5779 } else {
5780 out += ' {} ';
5781 }
5782 var __err = out;
5783 out = $$outStack.pop();
5784 if (!it.compositeRule && $breakOnError) {
5785 /* istanbul ignore if */
5786 if (it.async) {
5787 out += ' throw new ValidationError([' + (__err) + ']); ';
5788 } else {
5789 out += ' validate.errors = [' + (__err) + ']; return false; ';
5790 }
5791 } else {
5792 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5793 }
5794 } else {
5795 if (it.isTop) {
5796 if ($async) {
5797 out += ' return data; ';
5798 } else {
5799 out += ' validate.errors = null; return true; ';
5800 }
5801 } else {
5802 out += ' var ' + ($valid) + ' = true; ';
5803 }
5804 }
5805 if (it.isTop) {
5806 out += ' }; return validate; ';
5807 }
5808 return out;
5809 }
5810 if (it.isTop) {
5811 var $top = it.isTop,
5812 $lvl = it.level = 0,
5813 $dataLvl = it.dataLevel = 0,
5814 $data = 'data';
5815 it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
5816 it.baseId = it.baseId || it.rootId;
5817 delete it.isTop;
5818 it.dataPathArr = [undefined];
5819 if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
5820 var $defaultMsg = 'default is ignored in the schema root';
5821 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
5822 else throw new Error($defaultMsg);
5823 }
5824 out += ' var vErrors = null; ';
5825 out += ' var errors = 0; ';
5826 out += ' if (rootData === undefined) rootData = data; ';
5827 } else {
5828 var $lvl = it.level,
5829 $dataLvl = it.dataLevel,
5830 $data = 'data' + ($dataLvl || '');
5831 if ($id) it.baseId = it.resolve.url(it.baseId, $id);
5832 if ($async && !it.async) throw new Error('async schema in sync schema');
5833 out += ' var errs_' + ($lvl) + ' = errors;';
5834 }
5835 var $valid = 'valid' + $lvl,
5836 $breakOnError = !it.opts.allErrors,
5837 $closingBraces1 = '',
5838 $closingBraces2 = '';
5839 var $errorKeyword;
5840 var $typeSchema = it.schema.type,
5841 $typeIsArray = Array.isArray($typeSchema);
5842 if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
5843 if ($typeIsArray) {
5844 if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
5845 } else if ($typeSchema != 'null') {
5846 $typeSchema = [$typeSchema, 'null'];
5847 $typeIsArray = true;
5848 }
5849 }
5850 if ($typeIsArray && $typeSchema.length == 1) {
5851 $typeSchema = $typeSchema[0];
5852 $typeIsArray = false;
5853 }
5854 if (it.schema.$ref && $refKeywords) {
5855 if (it.opts.extendRefs == 'fail') {
5856 throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
5857 } else if (it.opts.extendRefs !== true) {
5858 $refKeywords = false;
5859 it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
5860 }
5861 }
5862 if (it.schema.$comment && it.opts.$comment) {
5863 out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
5864 }
5865 if ($typeSchema) {
5866 if (it.opts.coerceTypes) {
5867 var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
5868 }
5869 var $rulesGroup = it.RULES.types[$typeSchema];
5870 if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
5871 var $schemaPath = it.schemaPath + '.type',
5872 $errSchemaPath = it.errSchemaPath + '/type';
5873 var $schemaPath = it.schemaPath + '.type',
5874 $errSchemaPath = it.errSchemaPath + '/type',
5875 $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
5876 out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
5877 if ($coerceToTypes) {
5878 var $dataType = 'dataType' + $lvl,
5879 $coerced = 'coerced' + $lvl;
5880 out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
5881 if (it.opts.coerceTypes == 'array') {
5882 out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
5883 }
5884 out += ' var ' + ($coerced) + ' = undefined; ';
5885 var $bracesCoercion = '';
5886 var arr1 = $coerceToTypes;
5887 if (arr1) {
5888 var $type, $i = -1,
5889 l1 = arr1.length - 1;
5890 while ($i < l1) {
5891 $type = arr1[$i += 1];
5892 if ($i) {
5893 out += ' if (' + ($coerced) + ' === undefined) { ';
5894 $bracesCoercion += '}';
5895 }
5896 if (it.opts.coerceTypes == 'array' && $type != 'array') {
5897 out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } ';
5898 }
5899 if ($type == 'string') {
5900 out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
5901 } else if ($type == 'number' || $type == 'integer') {
5902 out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
5903 if ($type == 'integer') {
5904 out += ' && !(' + ($data) + ' % 1)';
5905 }
5906 out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
5907 } else if ($type == 'boolean') {
5908 out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
5909 } else if ($type == 'null') {
5910 out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
5911 } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
5912 out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
5913 }
5914 }
5915 }
5916 out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { ';
5917 var $$outStack = $$outStack || [];
5918 $$outStack.push(out);
5919 out = ''; /* istanbul ignore else */
5920 if (it.createErrors !== false) {
5921 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
5922 if ($typeIsArray) {
5923 out += '' + ($typeSchema.join(","));
5924 } else {
5925 out += '' + ($typeSchema);
5926 }
5927 out += '\' } ';
5928 if (it.opts.messages !== false) {
5929 out += ' , message: \'should be ';
5930 if ($typeIsArray) {
5931 out += '' + ($typeSchema.join(","));
5932 } else {
5933 out += '' + ($typeSchema);
5934 }
5935 out += '\' ';
5936 }
5937 if (it.opts.verbose) {
5938 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5939 }
5940 out += ' } ';
5941 } else {
5942 out += ' {} ';
5943 }
5944 var __err = out;
5945 out = $$outStack.pop();
5946 if (!it.compositeRule && $breakOnError) {
5947 /* istanbul ignore if */
5948 if (it.async) {
5949 out += ' throw new ValidationError([' + (__err) + ']); ';
5950 } else {
5951 out += ' validate.errors = [' + (__err) + ']; return false; ';
5952 }
5953 } else {
5954 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
5955 }
5956 out += ' } else { ';
5957 var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
5958 $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
5959 out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
5960 if (!$dataLvl) {
5961 out += 'if (' + ($parentData) + ' !== undefined)';
5962 }
5963 out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
5964 } else {
5965 var $$outStack = $$outStack || [];
5966 $$outStack.push(out);
5967 out = ''; /* istanbul ignore else */
5968 if (it.createErrors !== false) {
5969 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
5970 if ($typeIsArray) {
5971 out += '' + ($typeSchema.join(","));
5972 } else {
5973 out += '' + ($typeSchema);
5974 }
5975 out += '\' } ';
5976 if (it.opts.messages !== false) {
5977 out += ' , message: \'should be ';
5978 if ($typeIsArray) {
5979 out += '' + ($typeSchema.join(","));
5980 } else {
5981 out += '' + ($typeSchema);
5982 }
5983 out += '\' ';
5984 }
5985 if (it.opts.verbose) {
5986 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
5987 }
5988 out += ' } ';
5989 } else {
5990 out += ' {} ';
5991 }
5992 var __err = out;
5993 out = $$outStack.pop();
5994 if (!it.compositeRule && $breakOnError) {
5995 /* istanbul ignore if */
5996 if (it.async) {
5997 out += ' throw new ValidationError([' + (__err) + ']); ';
5998 } else {
5999 out += ' validate.errors = [' + (__err) + ']; return false; ';
6000 }
6001 } else {
6002 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
6003 }
6004 }
6005 out += ' } ';
6006 }
6007 }
6008 if (it.schema.$ref && !$refKeywords) {
6009 out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
6010 if ($breakOnError) {
6011 out += ' } if (errors === ';
6012 if ($top) {
6013 out += '0';
6014 } else {
6015 out += 'errs_' + ($lvl);
6016 }
6017 out += ') { ';
6018 $closingBraces2 += '}';
6019 }
6020 } else {
6021 var arr2 = it.RULES;
6022 if (arr2) {
6023 var $rulesGroup, i2 = -1,
6024 l2 = arr2.length - 1;
6025 while (i2 < l2) {
6026 $rulesGroup = arr2[i2 += 1];
6027 if ($shouldUseGroup($rulesGroup)) {
6028 if ($rulesGroup.type) {
6029 out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
6030 }
6031 if (it.opts.useDefaults) {
6032 if ($rulesGroup.type == 'object' && it.schema.properties) {
6033 var $schema = it.schema.properties,
6034 $schemaKeys = Object.keys($schema);
6035 var arr3 = $schemaKeys;
6036 if (arr3) {
6037 var $propertyKey, i3 = -1,
6038 l3 = arr3.length - 1;
6039 while (i3 < l3) {
6040 $propertyKey = arr3[i3 += 1];
6041 var $sch = $schema[$propertyKey];
6042 if ($sch.default !== undefined) {
6043 var $passData = $data + it.util.getProperty($propertyKey);
6044 if (it.compositeRule) {
6045 if (it.opts.strictDefaults) {
6046 var $defaultMsg = 'default is ignored for: ' + $passData;
6047 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
6048 else throw new Error($defaultMsg);
6049 }
6050 } else {
6051 out += ' if (' + ($passData) + ' === undefined ';
6052 if (it.opts.useDefaults == 'empty') {
6053 out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
6054 }
6055 out += ' ) ' + ($passData) + ' = ';
6056 if (it.opts.useDefaults == 'shared') {
6057 out += ' ' + (it.useDefault($sch.default)) + ' ';
6058 } else {
6059 out += ' ' + (JSON.stringify($sch.default)) + ' ';
6060 }
6061 out += '; ';
6062 }
6063 }
6064 }
6065 }
6066 } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
6067 var arr4 = it.schema.items;
6068 if (arr4) {
6069 var $sch, $i = -1,
6070 l4 = arr4.length - 1;
6071 while ($i < l4) {
6072 $sch = arr4[$i += 1];
6073 if ($sch.default !== undefined) {
6074 var $passData = $data + '[' + $i + ']';
6075 if (it.compositeRule) {
6076 if (it.opts.strictDefaults) {
6077 var $defaultMsg = 'default is ignored for: ' + $passData;
6078 if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
6079 else throw new Error($defaultMsg);
6080 }
6081 } else {
6082 out += ' if (' + ($passData) + ' === undefined ';
6083 if (it.opts.useDefaults == 'empty') {
6084 out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
6085 }
6086 out += ' ) ' + ($passData) + ' = ';
6087 if (it.opts.useDefaults == 'shared') {
6088 out += ' ' + (it.useDefault($sch.default)) + ' ';
6089 } else {
6090 out += ' ' + (JSON.stringify($sch.default)) + ' ';
6091 }
6092 out += '; ';
6093 }
6094 }
6095 }
6096 }
6097 }
6098 }
6099 var arr5 = $rulesGroup.rules;
6100 if (arr5) {
6101 var $rule, i5 = -1,
6102 l5 = arr5.length - 1;
6103 while (i5 < l5) {
6104 $rule = arr5[i5 += 1];
6105 if ($shouldUseRule($rule)) {
6106 var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
6107 if ($code) {
6108 out += ' ' + ($code) + ' ';
6109 if ($breakOnError) {
6110 $closingBraces1 += '}';
6111 }
6112 }
6113 }
6114 }
6115 }
6116 if ($breakOnError) {
6117 out += ' ' + ($closingBraces1) + ' ';
6118 $closingBraces1 = '';
6119 }
6120 if ($rulesGroup.type) {
6121 out += ' } ';
6122 if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
6123 out += ' else { ';
6124 var $schemaPath = it.schemaPath + '.type',
6125 $errSchemaPath = it.errSchemaPath + '/type';
6126 var $$outStack = $$outStack || [];
6127 $$outStack.push(out);
6128 out = ''; /* istanbul ignore else */
6129 if (it.createErrors !== false) {
6130 out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
6131 if ($typeIsArray) {
6132 out += '' + ($typeSchema.join(","));
6133 } else {
6134 out += '' + ($typeSchema);
6135 }
6136 out += '\' } ';
6137 if (it.opts.messages !== false) {
6138 out += ' , message: \'should be ';
6139 if ($typeIsArray) {
6140 out += '' + ($typeSchema.join(","));
6141 } else {
6142 out += '' + ($typeSchema);
6143 }
6144 out += '\' ';
6145 }
6146 if (it.opts.verbose) {
6147 out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
6148 }
6149 out += ' } ';
6150 } else {
6151 out += ' {} ';
6152 }
6153 var __err = out;
6154 out = $$outStack.pop();
6155 if (!it.compositeRule && $breakOnError) {
6156 /* istanbul ignore if */
6157 if (it.async) {
6158 out += ' throw new ValidationError([' + (__err) + ']); ';
6159 } else {
6160 out += ' validate.errors = [' + (__err) + ']; return false; ';
6161 }
6162 } else {
6163 out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
6164 }
6165 out += ' } ';
6166 }
6167 }
6168 if ($breakOnError) {
6169 out += ' if (errors === ';
6170 if ($top) {
6171 out += '0';
6172 } else {
6173 out += 'errs_' + ($lvl);
6174 }
6175 out += ') { ';
6176 $closingBraces2 += '}';
6177 }
6178 }
6179 }
6180 }
6181 }
6182 if ($breakOnError) {
6183 out += ' ' + ($closingBraces2) + ' ';
6184 }
6185 if ($top) {
6186 if ($async) {
6187 out += ' if (errors === 0) return data; ';
6188 out += ' else throw new ValidationError(vErrors); ';
6189 } else {
6190 out += ' validate.errors = vErrors; ';
6191 out += ' return errors === 0; ';
6192 }
6193 out += ' }; return validate;';
6194 } else {
6195 out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
6196 }
6197 out = it.util.cleanUpCode(out);
6198 if ($top) {
6199 out = it.util.finalCleanUpCode(out, $async);
6200 }
6201
6202 function $shouldUseGroup($rulesGroup) {
6203 var rules = $rulesGroup.rules;
6204 for (var i = 0; i < rules.length; i++)
6205 if ($shouldUseRule(rules[i])) return true;
6206 }
6207
6208 function $shouldUseRule($rule) {
6209 return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
6210 }
6211
6212 function $ruleImplementsSomeKeyword($rule) {
6213 var impl = $rule.implements;
6214 for (var i = 0; i < impl.length; i++)
6215 if (it.schema[impl[i]] !== undefined) return true;
6216 }
6217 return out;
6218}
6219
6220},{}],43:[function(require,module,exports){
6221'use strict';
6222
6223var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
6224var customRuleCode = require('./dotjs/custom');
6225var metaSchema = require('./refs/json-schema-draft-07.json');
6226
6227module.exports = {
6228 add: addKeyword,
6229 get: getKeyword,
6230 remove: removeKeyword,
6231 validate: validateKeyword
6232};
6233
6234var definitionSchema = {
6235 definitions: {
6236 simpleTypes: metaSchema.definitions.simpleTypes
6237 },
6238 type: 'object',
6239 dependencies: {
6240 schema: ['validate'],
6241 $data: ['validate'],
6242 statements: ['inline'],
6243 valid: {not: {required: ['macro']}}
6244 },
6245 properties: {
6246 type: metaSchema.properties.type,
6247 schema: {type: 'boolean'},
6248 statements: {type: 'boolean'},
6249 dependencies: {
6250 type: 'array',
6251 items: {type: 'string'}
6252 },
6253 metaSchema: {type: 'object'},
6254 modifying: {type: 'boolean'},
6255 valid: {type: 'boolean'},
6256 $data: {type: 'boolean'},
6257 async: {type: 'boolean'},
6258 errors: {
6259 anyOf: [
6260 {type: 'boolean'},
6261 {const: 'full'}
6262 ]
6263 }
6264 }
6265};
6266
6267/**
6268 * Define custom keyword
6269 * @this Ajv
6270 * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
6271 * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
6272 * @return {Ajv} this for method chaining
6273 */
6274function addKeyword(keyword, definition) {
6275 /* jshint validthis: true */
6276 /* eslint no-shadow: 0 */
6277 var RULES = this.RULES;
6278 if (RULES.keywords[keyword])
6279 throw new Error('Keyword ' + keyword + ' is already defined');
6280
6281 if (!IDENTIFIER.test(keyword))
6282 throw new Error('Keyword ' + keyword + ' is not a valid identifier');
6283
6284 if (definition) {
6285 this.validateKeyword(definition, true);
6286
6287 var dataType = definition.type;
6288 if (Array.isArray(dataType)) {
6289 for (var i=0; i<dataType.length; i++)
6290 _addRule(keyword, dataType[i], definition);
6291 } else {
6292 _addRule(keyword, dataType, definition);
6293 }
6294
6295 var metaSchema = definition.metaSchema;
6296 if (metaSchema) {
6297 if (definition.$data && this._opts.$data) {
6298 metaSchema = {
6299 anyOf: [
6300 metaSchema,
6301 { '$ref': 'https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#' }
6302 ]
6303 };
6304 }
6305 definition.validateSchema = this.compile(metaSchema, true);
6306 }
6307 }
6308
6309 RULES.keywords[keyword] = RULES.all[keyword] = true;
6310
6311
6312 function _addRule(keyword, dataType, definition) {
6313 var ruleGroup;
6314 for (var i=0; i<RULES.length; i++) {
6315 var rg = RULES[i];
6316 if (rg.type == dataType) {
6317 ruleGroup = rg;
6318 break;
6319 }
6320 }
6321
6322 if (!ruleGroup) {
6323 ruleGroup = { type: dataType, rules: [] };
6324 RULES.push(ruleGroup);
6325 }
6326
6327 var rule = {
6328 keyword: keyword,
6329 definition: definition,
6330 custom: true,
6331 code: customRuleCode,
6332 implements: definition.implements
6333 };
6334 ruleGroup.rules.push(rule);
6335 RULES.custom[keyword] = rule;
6336 }
6337
6338 return this;
6339}
6340
6341
6342/**
6343 * Get keyword
6344 * @this Ajv
6345 * @param {String} keyword pre-defined or custom keyword.
6346 * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise.
6347 */
6348function getKeyword(keyword) {
6349 /* jshint validthis: true */
6350 var rule = this.RULES.custom[keyword];
6351 return rule ? rule.definition : this.RULES.keywords[keyword] || false;
6352}
6353
6354
6355/**
6356 * Remove keyword
6357 * @this Ajv
6358 * @param {String} keyword pre-defined or custom keyword.
6359 * @return {Ajv} this for method chaining
6360 */
6361function removeKeyword(keyword) {
6362 /* jshint validthis: true */
6363 var RULES = this.RULES;
6364 delete RULES.keywords[keyword];
6365 delete RULES.all[keyword];
6366 delete RULES.custom[keyword];
6367 for (var i=0; i<RULES.length; i++) {
6368 var rules = RULES[i].rules;
6369 for (var j=0; j<rules.length; j++) {
6370 if (rules[j].keyword == keyword) {
6371 rules.splice(j, 1);
6372 break;
6373 }
6374 }
6375 }
6376 return this;
6377}
6378
6379
6380/**
6381 * Validate keyword definition
6382 * @this Ajv
6383 * @param {Object} definition keyword definition object.
6384 * @param {Boolean} throwError true to throw exception if definition is invalid
6385 * @return {boolean} validation result
6386 */
6387function validateKeyword(definition, throwError) {
6388 validateKeyword.errors = null;
6389 var v = this._validateKeyword = this._validateKeyword
6390 || this.compile(definitionSchema, true);
6391
6392 if (v(definition)) return true;
6393 validateKeyword.errors = v.errors;
6394 if (throwError)
6395 throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));
6396 else
6397 return false;
6398}
6399
6400},{"./dotjs/custom":26,"./refs/json-schema-draft-07.json":46}],44:[function(require,module,exports){
6401module.exports={
6402 "$schema": "http://json-schema.org/draft-07/schema#",
6403 "$id": "https://raw.githubusercontent.com/epoberezkin/ajv/master/lib/refs/data.json#",
6404 "description": "Meta-schema for $data reference (JSON Schema extension proposal)",
6405 "type": "object",
6406 "required": [ "$data" ],
6407 "properties": {
6408 "$data": {
6409 "type": "string",
6410 "anyOf": [
6411 { "format": "relative-json-pointer" },
6412 { "format": "json-pointer" }
6413 ]
6414 }
6415 },
6416 "additionalProperties": false
6417}
6418
6419},{}],45:[function(require,module,exports){
6420module.exports={
6421 "$schema": "http://json-schema.org/draft-06/schema#",
6422 "$id": "http://json-schema.org/draft-06/schema#",
6423 "title": "Core schema meta-schema",
6424 "definitions": {
6425 "schemaArray": {
6426 "type": "array",
6427 "minItems": 1,
6428 "items": { "$ref": "#" }
6429 },
6430 "nonNegativeInteger": {
6431 "type": "integer",
6432 "minimum": 0
6433 },
6434 "nonNegativeIntegerDefault0": {
6435 "allOf": [
6436 { "$ref": "#/definitions/nonNegativeInteger" },
6437 { "default": 0 }
6438 ]
6439 },
6440 "simpleTypes": {
6441 "enum": [
6442 "array",
6443 "boolean",
6444 "integer",
6445 "null",
6446 "number",
6447 "object",
6448 "string"
6449 ]
6450 },
6451 "stringArray": {
6452 "type": "array",
6453 "items": { "type": "string" },
6454 "uniqueItems": true,
6455 "default": []
6456 }
6457 },
6458 "type": ["object", "boolean"],
6459 "properties": {
6460 "$id": {
6461 "type": "string",
6462 "format": "uri-reference"
6463 },
6464 "$schema": {
6465 "type": "string",
6466 "format": "uri"
6467 },
6468 "$ref": {
6469 "type": "string",
6470 "format": "uri-reference"
6471 },
6472 "title": {
6473 "type": "string"
6474 },
6475 "description": {
6476 "type": "string"
6477 },
6478 "default": {},
6479 "examples": {
6480 "type": "array",
6481 "items": {}
6482 },
6483 "multipleOf": {
6484 "type": "number",
6485 "exclusiveMinimum": 0
6486 },
6487 "maximum": {
6488 "type": "number"
6489 },
6490 "exclusiveMaximum": {
6491 "type": "number"
6492 },
6493 "minimum": {
6494 "type": "number"
6495 },
6496 "exclusiveMinimum": {
6497 "type": "number"
6498 },
6499 "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
6500 "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6501 "pattern": {
6502 "type": "string",
6503 "format": "regex"
6504 },
6505 "additionalItems": { "$ref": "#" },
6506 "items": {
6507 "anyOf": [
6508 { "$ref": "#" },
6509 { "$ref": "#/definitions/schemaArray" }
6510 ],
6511 "default": {}
6512 },
6513 "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
6514 "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6515 "uniqueItems": {
6516 "type": "boolean",
6517 "default": false
6518 },
6519 "contains": { "$ref": "#" },
6520 "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
6521 "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6522 "required": { "$ref": "#/definitions/stringArray" },
6523 "additionalProperties": { "$ref": "#" },
6524 "definitions": {
6525 "type": "object",
6526 "additionalProperties": { "$ref": "#" },
6527 "default": {}
6528 },
6529 "properties": {
6530 "type": "object",
6531 "additionalProperties": { "$ref": "#" },
6532 "default": {}
6533 },
6534 "patternProperties": {
6535 "type": "object",
6536 "additionalProperties": { "$ref": "#" },
6537 "default": {}
6538 },
6539 "dependencies": {
6540 "type": "object",
6541 "additionalProperties": {
6542 "anyOf": [
6543 { "$ref": "#" },
6544 { "$ref": "#/definitions/stringArray" }
6545 ]
6546 }
6547 },
6548 "propertyNames": { "$ref": "#" },
6549 "const": {},
6550 "enum": {
6551 "type": "array",
6552 "minItems": 1,
6553 "uniqueItems": true
6554 },
6555 "type": {
6556 "anyOf": [
6557 { "$ref": "#/definitions/simpleTypes" },
6558 {
6559 "type": "array",
6560 "items": { "$ref": "#/definitions/simpleTypes" },
6561 "minItems": 1,
6562 "uniqueItems": true
6563 }
6564 ]
6565 },
6566 "format": { "type": "string" },
6567 "allOf": { "$ref": "#/definitions/schemaArray" },
6568 "anyOf": { "$ref": "#/definitions/schemaArray" },
6569 "oneOf": { "$ref": "#/definitions/schemaArray" },
6570 "not": { "$ref": "#" }
6571 },
6572 "default": {}
6573}
6574
6575},{}],46:[function(require,module,exports){
6576module.exports={
6577 "$schema": "http://json-schema.org/draft-07/schema#",
6578 "$id": "http://json-schema.org/draft-07/schema#",
6579 "title": "Core schema meta-schema",
6580 "definitions": {
6581 "schemaArray": {
6582 "type": "array",
6583 "minItems": 1,
6584 "items": { "$ref": "#" }
6585 },
6586 "nonNegativeInteger": {
6587 "type": "integer",
6588 "minimum": 0
6589 },
6590 "nonNegativeIntegerDefault0": {
6591 "allOf": [
6592 { "$ref": "#/definitions/nonNegativeInteger" },
6593 { "default": 0 }
6594 ]
6595 },
6596 "simpleTypes": {
6597 "enum": [
6598 "array",
6599 "boolean",
6600 "integer",
6601 "null",
6602 "number",
6603 "object",
6604 "string"
6605 ]
6606 },
6607 "stringArray": {
6608 "type": "array",
6609 "items": { "type": "string" },
6610 "uniqueItems": true,
6611 "default": []
6612 }
6613 },
6614 "type": ["object", "boolean"],
6615 "properties": {
6616 "$id": {
6617 "type": "string",
6618 "format": "uri-reference"
6619 },
6620 "$schema": {
6621 "type": "string",
6622 "format": "uri"
6623 },
6624 "$ref": {
6625 "type": "string",
6626 "format": "uri-reference"
6627 },
6628 "$comment": {
6629 "type": "string"
6630 },
6631 "title": {
6632 "type": "string"
6633 },
6634 "description": {
6635 "type": "string"
6636 },
6637 "default": true,
6638 "readOnly": {
6639 "type": "boolean",
6640 "default": false
6641 },
6642 "examples": {
6643 "type": "array",
6644 "items": true
6645 },
6646 "multipleOf": {
6647 "type": "number",
6648 "exclusiveMinimum": 0
6649 },
6650 "maximum": {
6651 "type": "number"
6652 },
6653 "exclusiveMaximum": {
6654 "type": "number"
6655 },
6656 "minimum": {
6657 "type": "number"
6658 },
6659 "exclusiveMinimum": {
6660 "type": "number"
6661 },
6662 "maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
6663 "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6664 "pattern": {
6665 "type": "string",
6666 "format": "regex"
6667 },
6668 "additionalItems": { "$ref": "#" },
6669 "items": {
6670 "anyOf": [
6671 { "$ref": "#" },
6672 { "$ref": "#/definitions/schemaArray" }
6673 ],
6674 "default": true
6675 },
6676 "maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
6677 "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6678 "uniqueItems": {
6679 "type": "boolean",
6680 "default": false
6681 },
6682 "contains": { "$ref": "#" },
6683 "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
6684 "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
6685 "required": { "$ref": "#/definitions/stringArray" },
6686 "additionalProperties": { "$ref": "#" },
6687 "definitions": {
6688 "type": "object",
6689 "additionalProperties": { "$ref": "#" },
6690 "default": {}
6691 },
6692 "properties": {
6693 "type": "object",
6694 "additionalProperties": { "$ref": "#" },
6695 "default": {}
6696 },
6697 "patternProperties": {
6698 "type": "object",
6699 "additionalProperties": { "$ref": "#" },
6700 "propertyNames": { "format": "regex" },
6701 "default": {}
6702 },
6703 "dependencies": {
6704 "type": "object",
6705 "additionalProperties": {
6706 "anyOf": [
6707 { "$ref": "#" },
6708 { "$ref": "#/definitions/stringArray" }
6709 ]
6710 }
6711 },
6712 "propertyNames": { "$ref": "#" },
6713 "const": true,
6714 "enum": {
6715 "type": "array",
6716 "items": true,
6717 "minItems": 1,
6718 "uniqueItems": true
6719 },
6720 "type": {
6721 "anyOf": [
6722 { "$ref": "#/definitions/simpleTypes" },
6723 {
6724 "type": "array",
6725 "items": { "$ref": "#/definitions/simpleTypes" },
6726 "minItems": 1,
6727 "uniqueItems": true
6728 }
6729 ]
6730 },
6731 "format": { "type": "string" },
6732 "contentMediaType": { "type": "string" },
6733 "contentEncoding": { "type": "string" },
6734 "if": {"$ref": "#"},
6735 "then": {"$ref": "#"},
6736 "else": {"$ref": "#"},
6737 "allOf": { "$ref": "#/definitions/schemaArray" },
6738 "anyOf": { "$ref": "#/definitions/schemaArray" },
6739 "oneOf": { "$ref": "#/definitions/schemaArray" },
6740 "not": { "$ref": "#" }
6741 },
6742 "default": true
6743}
6744
6745},{}],47:[function(require,module,exports){
6746var asn1 = exports;
6747
6748asn1.bignum = require('bn.js');
6749
6750asn1.define = require('./asn1/api').define;
6751asn1.base = require('./asn1/base');
6752asn1.constants = require('./asn1/constants');
6753asn1.decoders = require('./asn1/decoders');
6754asn1.encoders = require('./asn1/encoders');
6755
6756},{"./asn1/api":48,"./asn1/base":50,"./asn1/constants":54,"./asn1/decoders":56,"./asn1/encoders":59,"bn.js":80}],48:[function(require,module,exports){
6757var asn1 = require('../asn1');
6758var inherits = require('inherits');
6759
6760var api = exports;
6761
6762api.define = function define(name, body) {
6763 return new Entity(name, body);
6764};
6765
6766function Entity(name, body) {
6767 this.name = name;
6768 this.body = body;
6769
6770 this.decoders = {};
6771 this.encoders = {};
6772};
6773
6774Entity.prototype._createNamed = function createNamed(base) {
6775 var named;
6776 try {
6777 named = require('vm').runInThisContext(
6778 '(function ' + this.name + '(entity) {\n' +
6779 ' this._initNamed(entity);\n' +
6780 '})'
6781 );
6782 } catch (e) {
6783 named = function (entity) {
6784 this._initNamed(entity);
6785 };
6786 }
6787 inherits(named, base);
6788 named.prototype._initNamed = function initnamed(entity) {
6789 base.call(this, entity);
6790 };
6791
6792 return new named(this);
6793};
6794
6795Entity.prototype._getDecoder = function _getDecoder(enc) {
6796 enc = enc || 'der';
6797 // Lazily create decoder
6798 if (!this.decoders.hasOwnProperty(enc))
6799 this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
6800 return this.decoders[enc];
6801};
6802
6803Entity.prototype.decode = function decode(data, enc, options) {
6804 return this._getDecoder(enc).decode(data, options);
6805};
6806
6807Entity.prototype._getEncoder = function _getEncoder(enc) {
6808 enc = enc || 'der';
6809 // Lazily create encoder
6810 if (!this.encoders.hasOwnProperty(enc))
6811 this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
6812 return this.encoders[enc];
6813};
6814
6815Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
6816 return this._getEncoder(enc).encode(data, reporter);
6817};
6818
6819},{"../asn1":47,"inherits":210,"vm":403}],49:[function(require,module,exports){
6820var inherits = require('inherits');
6821var Reporter = require('../base').Reporter;
6822var Buffer = require('buffer').Buffer;
6823
6824function DecoderBuffer(base, options) {
6825 Reporter.call(this, options);
6826 if (!Buffer.isBuffer(base)) {
6827 this.error('Input not Buffer');
6828 return;
6829 }
6830
6831 this.base = base;
6832 this.offset = 0;
6833 this.length = base.length;
6834}
6835inherits(DecoderBuffer, Reporter);
6836exports.DecoderBuffer = DecoderBuffer;
6837
6838DecoderBuffer.prototype.save = function save() {
6839 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
6840};
6841
6842DecoderBuffer.prototype.restore = function restore(save) {
6843 // Return skipped data
6844 var res = new DecoderBuffer(this.base);
6845 res.offset = save.offset;
6846 res.length = this.offset;
6847
6848 this.offset = save.offset;
6849 Reporter.prototype.restore.call(this, save.reporter);
6850
6851 return res;
6852};
6853
6854DecoderBuffer.prototype.isEmpty = function isEmpty() {
6855 return this.offset === this.length;
6856};
6857
6858DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
6859 if (this.offset + 1 <= this.length)
6860 return this.base.readUInt8(this.offset++, true);
6861 else
6862 return this.error(fail || 'DecoderBuffer overrun');
6863}
6864
6865DecoderBuffer.prototype.skip = function skip(bytes, fail) {
6866 if (!(this.offset + bytes <= this.length))
6867 return this.error(fail || 'DecoderBuffer overrun');
6868
6869 var res = new DecoderBuffer(this.base);
6870
6871 // Share reporter state
6872 res._reporterState = this._reporterState;
6873
6874 res.offset = this.offset;
6875 res.length = this.offset + bytes;
6876 this.offset += bytes;
6877 return res;
6878}
6879
6880DecoderBuffer.prototype.raw = function raw(save) {
6881 return this.base.slice(save ? save.offset : this.offset, this.length);
6882}
6883
6884function EncoderBuffer(value, reporter) {
6885 if (Array.isArray(value)) {
6886 this.length = 0;
6887 this.value = value.map(function(item) {
6888 if (!(item instanceof EncoderBuffer))
6889 item = new EncoderBuffer(item, reporter);
6890 this.length += item.length;
6891 return item;
6892 }, this);
6893 } else if (typeof value === 'number') {
6894 if (!(0 <= value && value <= 0xff))
6895 return reporter.error('non-byte EncoderBuffer value');
6896 this.value = value;
6897 this.length = 1;
6898 } else if (typeof value === 'string') {
6899 this.value = value;
6900 this.length = Buffer.byteLength(value);
6901 } else if (Buffer.isBuffer(value)) {
6902 this.value = value;
6903 this.length = value.length;
6904 } else {
6905 return reporter.error('Unsupported type: ' + typeof value);
6906 }
6907}
6908exports.EncoderBuffer = EncoderBuffer;
6909
6910EncoderBuffer.prototype.join = function join(out, offset) {
6911 if (!out)
6912 out = new Buffer(this.length);
6913 if (!offset)
6914 offset = 0;
6915
6916 if (this.length === 0)
6917 return out;
6918
6919 if (Array.isArray(this.value)) {
6920 this.value.forEach(function(item) {
6921 item.join(out, offset);
6922 offset += item.length;
6923 });
6924 } else {
6925 if (typeof this.value === 'number')
6926 out[offset] = this.value;
6927 else if (typeof this.value === 'string')
6928 out.write(this.value, offset);
6929 else if (Buffer.isBuffer(this.value))
6930 this.value.copy(out, offset);
6931 offset += this.length;
6932 }
6933
6934 return out;
6935};
6936
6937},{"../base":50,"buffer":114,"inherits":210}],50:[function(require,module,exports){
6938var base = exports;
6939
6940base.Reporter = require('./reporter').Reporter;
6941base.DecoderBuffer = require('./buffer').DecoderBuffer;
6942base.EncoderBuffer = require('./buffer').EncoderBuffer;
6943base.Node = require('./node');
6944
6945},{"./buffer":49,"./node":51,"./reporter":52}],51:[function(require,module,exports){
6946var Reporter = require('../base').Reporter;
6947var EncoderBuffer = require('../base').EncoderBuffer;
6948var DecoderBuffer = require('../base').DecoderBuffer;
6949var assert = require('minimalistic-assert');
6950
6951// Supported tags
6952var tags = [
6953 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
6954 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
6955 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
6956 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
6957];
6958
6959// Public methods list
6960var methods = [
6961 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
6962 'any', 'contains'
6963].concat(tags);
6964
6965// Overrided methods list
6966var overrided = [
6967 '_peekTag', '_decodeTag', '_use',
6968 '_decodeStr', '_decodeObjid', '_decodeTime',
6969 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
6970
6971 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
6972 '_encodeNull', '_encodeInt', '_encodeBool'
6973];
6974
6975function Node(enc, parent) {
6976 var state = {};
6977 this._baseState = state;
6978
6979 state.enc = enc;
6980
6981 state.parent = parent || null;
6982 state.children = null;
6983
6984 // State
6985 state.tag = null;
6986 state.args = null;
6987 state.reverseArgs = null;
6988 state.choice = null;
6989 state.optional = false;
6990 state.any = false;
6991 state.obj = false;
6992 state.use = null;
6993 state.useDecoder = null;
6994 state.key = null;
6995 state['default'] = null;
6996 state.explicit = null;
6997 state.implicit = null;
6998 state.contains = null;
6999
7000 // Should create new instance on each method
7001 if (!state.parent) {
7002 state.children = [];
7003 this._wrap();
7004 }
7005}
7006module.exports = Node;
7007
7008var stateProps = [
7009 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
7010 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
7011 'implicit', 'contains'
7012];
7013
7014Node.prototype.clone = function clone() {
7015 var state = this._baseState;
7016 var cstate = {};
7017 stateProps.forEach(function(prop) {
7018 cstate[prop] = state[prop];
7019 });
7020 var res = new this.constructor(cstate.parent);
7021 res._baseState = cstate;
7022 return res;
7023};
7024
7025Node.prototype._wrap = function wrap() {
7026 var state = this._baseState;
7027 methods.forEach(function(method) {
7028 this[method] = function _wrappedMethod() {
7029 var clone = new this.constructor(this);
7030 state.children.push(clone);
7031 return clone[method].apply(clone, arguments);
7032 };
7033 }, this);
7034};
7035
7036Node.prototype._init = function init(body) {
7037 var state = this._baseState;
7038
7039 assert(state.parent === null);
7040 body.call(this);
7041
7042 // Filter children
7043 state.children = state.children.filter(function(child) {
7044 return child._baseState.parent === this;
7045 }, this);
7046 assert.equal(state.children.length, 1, 'Root node can have only one child');
7047};
7048
7049Node.prototype._useArgs = function useArgs(args) {
7050 var state = this._baseState;
7051
7052 // Filter children and args
7053 var children = args.filter(function(arg) {
7054 return arg instanceof this.constructor;
7055 }, this);
7056 args = args.filter(function(arg) {
7057 return !(arg instanceof this.constructor);
7058 }, this);
7059
7060 if (children.length !== 0) {
7061 assert(state.children === null);
7062 state.children = children;
7063
7064 // Replace parent to maintain backward link
7065 children.forEach(function(child) {
7066 child._baseState.parent = this;
7067 }, this);
7068 }
7069 if (args.length !== 0) {
7070 assert(state.args === null);
7071 state.args = args;
7072 state.reverseArgs = args.map(function(arg) {
7073 if (typeof arg !== 'object' || arg.constructor !== Object)
7074 return arg;
7075
7076 var res = {};
7077 Object.keys(arg).forEach(function(key) {
7078 if (key == (key | 0))
7079 key |= 0;
7080 var value = arg[key];
7081 res[value] = key;
7082 });
7083 return res;
7084 });
7085 }
7086};
7087
7088//
7089// Overrided methods
7090//
7091
7092overrided.forEach(function(method) {
7093 Node.prototype[method] = function _overrided() {
7094 var state = this._baseState;
7095 throw new Error(method + ' not implemented for encoding: ' + state.enc);
7096 };
7097});
7098
7099//
7100// Public methods
7101//
7102
7103tags.forEach(function(tag) {
7104 Node.prototype[tag] = function _tagMethod() {
7105 var state = this._baseState;
7106 var args = Array.prototype.slice.call(arguments);
7107
7108 assert(state.tag === null);
7109 state.tag = tag;
7110
7111 this._useArgs(args);
7112
7113 return this;
7114 };
7115});
7116
7117Node.prototype.use = function use(item) {
7118 assert(item);
7119 var state = this._baseState;
7120
7121 assert(state.use === null);
7122 state.use = item;
7123
7124 return this;
7125};
7126
7127Node.prototype.optional = function optional() {
7128 var state = this._baseState;
7129
7130 state.optional = true;
7131
7132 return this;
7133};
7134
7135Node.prototype.def = function def(val) {
7136 var state = this._baseState;
7137
7138 assert(state['default'] === null);
7139 state['default'] = val;
7140 state.optional = true;
7141
7142 return this;
7143};
7144
7145Node.prototype.explicit = function explicit(num) {
7146 var state = this._baseState;
7147
7148 assert(state.explicit === null && state.implicit === null);
7149 state.explicit = num;
7150
7151 return this;
7152};
7153
7154Node.prototype.implicit = function implicit(num) {
7155 var state = this._baseState;
7156
7157 assert(state.explicit === null && state.implicit === null);
7158 state.implicit = num;
7159
7160 return this;
7161};
7162
7163Node.prototype.obj = function obj() {
7164 var state = this._baseState;
7165 var args = Array.prototype.slice.call(arguments);
7166
7167 state.obj = true;
7168
7169 if (args.length !== 0)
7170 this._useArgs(args);
7171
7172 return this;
7173};
7174
7175Node.prototype.key = function key(newKey) {
7176 var state = this._baseState;
7177
7178 assert(state.key === null);
7179 state.key = newKey;
7180
7181 return this;
7182};
7183
7184Node.prototype.any = function any() {
7185 var state = this._baseState;
7186
7187 state.any = true;
7188
7189 return this;
7190};
7191
7192Node.prototype.choice = function choice(obj) {
7193 var state = this._baseState;
7194
7195 assert(state.choice === null);
7196 state.choice = obj;
7197 this._useArgs(Object.keys(obj).map(function(key) {
7198 return obj[key];
7199 }));
7200
7201 return this;
7202};
7203
7204Node.prototype.contains = function contains(item) {
7205 var state = this._baseState;
7206
7207 assert(state.use === null);
7208 state.contains = item;
7209
7210 return this;
7211};
7212
7213//
7214// Decoding
7215//
7216
7217Node.prototype._decode = function decode(input, options) {
7218 var state = this._baseState;
7219
7220 // Decode root node
7221 if (state.parent === null)
7222 return input.wrapResult(state.children[0]._decode(input, options));
7223
7224 var result = state['default'];
7225 var present = true;
7226
7227 var prevKey = null;
7228 if (state.key !== null)
7229 prevKey = input.enterKey(state.key);
7230
7231 // Check if tag is there
7232 if (state.optional) {
7233 var tag = null;
7234 if (state.explicit !== null)
7235 tag = state.explicit;
7236 else if (state.implicit !== null)
7237 tag = state.implicit;
7238 else if (state.tag !== null)
7239 tag = state.tag;
7240
7241 if (tag === null && !state.any) {
7242 // Trial and Error
7243 var save = input.save();
7244 try {
7245 if (state.choice === null)
7246 this._decodeGeneric(state.tag, input, options);
7247 else
7248 this._decodeChoice(input, options);
7249 present = true;
7250 } catch (e) {
7251 present = false;
7252 }
7253 input.restore(save);
7254 } else {
7255 present = this._peekTag(input, tag, state.any);
7256
7257 if (input.isError(present))
7258 return present;
7259 }
7260 }
7261
7262 // Push object on stack
7263 var prevObj;
7264 if (state.obj && present)
7265 prevObj = input.enterObject();
7266
7267 if (present) {
7268 // Unwrap explicit values
7269 if (state.explicit !== null) {
7270 var explicit = this._decodeTag(input, state.explicit);
7271 if (input.isError(explicit))
7272 return explicit;
7273 input = explicit;
7274 }
7275
7276 var start = input.offset;
7277
7278 // Unwrap implicit and normal values
7279 if (state.use === null && state.choice === null) {
7280 if (state.any)
7281 var save = input.save();
7282 var body = this._decodeTag(
7283 input,
7284 state.implicit !== null ? state.implicit : state.tag,
7285 state.any
7286 );
7287 if (input.isError(body))
7288 return body;
7289
7290 if (state.any)
7291 result = input.raw(save);
7292 else
7293 input = body;
7294 }
7295
7296 if (options && options.track && state.tag !== null)
7297 options.track(input.path(), start, input.length, 'tagged');
7298
7299 if (options && options.track && state.tag !== null)
7300 options.track(input.path(), input.offset, input.length, 'content');
7301
7302 // Select proper method for tag
7303 if (state.any)
7304 result = result;
7305 else if (state.choice === null)
7306 result = this._decodeGeneric(state.tag, input, options);
7307 else
7308 result = this._decodeChoice(input, options);
7309
7310 if (input.isError(result))
7311 return result;
7312
7313 // Decode children
7314 if (!state.any && state.choice === null && state.children !== null) {
7315 state.children.forEach(function decodeChildren(child) {
7316 // NOTE: We are ignoring errors here, to let parser continue with other
7317 // parts of encoded data
7318 child._decode(input, options);
7319 });
7320 }
7321
7322 // Decode contained/encoded by schema, only in bit or octet strings
7323 if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
7324 var data = new DecoderBuffer(result);
7325 result = this._getUse(state.contains, input._reporterState.obj)
7326 ._decode(data, options);
7327 }
7328 }
7329
7330 // Pop object
7331 if (state.obj && present)
7332 result = input.leaveObject(prevObj);
7333
7334 // Set key
7335 if (state.key !== null && (result !== null || present === true))
7336 input.leaveKey(prevKey, state.key, result);
7337 else if (prevKey !== null)
7338 input.exitKey(prevKey);
7339
7340 return result;
7341};
7342
7343Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
7344 var state = this._baseState;
7345
7346 if (tag === 'seq' || tag === 'set')
7347 return null;
7348 if (tag === 'seqof' || tag === 'setof')
7349 return this._decodeList(input, tag, state.args[0], options);
7350 else if (/str$/.test(tag))
7351 return this._decodeStr(input, tag, options);
7352 else if (tag === 'objid' && state.args)
7353 return this._decodeObjid(input, state.args[0], state.args[1], options);
7354 else if (tag === 'objid')
7355 return this._decodeObjid(input, null, null, options);
7356 else if (tag === 'gentime' || tag === 'utctime')
7357 return this._decodeTime(input, tag, options);
7358 else if (tag === 'null_')
7359 return this._decodeNull(input, options);
7360 else if (tag === 'bool')
7361 return this._decodeBool(input, options);
7362 else if (tag === 'objDesc')
7363 return this._decodeStr(input, tag, options);
7364 else if (tag === 'int' || tag === 'enum')
7365 return this._decodeInt(input, state.args && state.args[0], options);
7366
7367 if (state.use !== null) {
7368 return this._getUse(state.use, input._reporterState.obj)
7369 ._decode(input, options);
7370 } else {
7371 return input.error('unknown tag: ' + tag);
7372 }
7373};
7374
7375Node.prototype._getUse = function _getUse(entity, obj) {
7376
7377 var state = this._baseState;
7378 // Create altered use decoder if implicit is set
7379 state.useDecoder = this._use(entity, obj);
7380 assert(state.useDecoder._baseState.parent === null);
7381 state.useDecoder = state.useDecoder._baseState.children[0];
7382 if (state.implicit !== state.useDecoder._baseState.implicit) {
7383 state.useDecoder = state.useDecoder.clone();
7384 state.useDecoder._baseState.implicit = state.implicit;
7385 }
7386 return state.useDecoder;
7387};
7388
7389Node.prototype._decodeChoice = function decodeChoice(input, options) {
7390 var state = this._baseState;
7391 var result = null;
7392 var match = false;
7393
7394 Object.keys(state.choice).some(function(key) {
7395 var save = input.save();
7396 var node = state.choice[key];
7397 try {
7398 var value = node._decode(input, options);
7399 if (input.isError(value))
7400 return false;
7401
7402 result = { type: key, value: value };
7403 match = true;
7404 } catch (e) {
7405 input.restore(save);
7406 return false;
7407 }
7408 return true;
7409 }, this);
7410
7411 if (!match)
7412 return input.error('Choice not matched');
7413
7414 return result;
7415};
7416
7417//
7418// Encoding
7419//
7420
7421Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
7422 return new EncoderBuffer(data, this.reporter);
7423};
7424
7425Node.prototype._encode = function encode(data, reporter, parent) {
7426 var state = this._baseState;
7427 if (state['default'] !== null && state['default'] === data)
7428 return;
7429
7430 var result = this._encodeValue(data, reporter, parent);
7431 if (result === undefined)
7432 return;
7433
7434 if (this._skipDefault(result, reporter, parent))
7435 return;
7436
7437 return result;
7438};
7439
7440Node.prototype._encodeValue = function encode(data, reporter, parent) {
7441 var state = this._baseState;
7442
7443 // Decode root node
7444 if (state.parent === null)
7445 return state.children[0]._encode(data, reporter || new Reporter());
7446
7447 var result = null;
7448
7449 // Set reporter to share it with a child class
7450 this.reporter = reporter;
7451
7452 // Check if data is there
7453 if (state.optional && data === undefined) {
7454 if (state['default'] !== null)
7455 data = state['default']
7456 else
7457 return;
7458 }
7459
7460 // Encode children first
7461 var content = null;
7462 var primitive = false;
7463 if (state.any) {
7464 // Anything that was given is translated to buffer
7465 result = this._createEncoderBuffer(data);
7466 } else if (state.choice) {
7467 result = this._encodeChoice(data, reporter);
7468 } else if (state.contains) {
7469 content = this._getUse(state.contains, parent)._encode(data, reporter);
7470 primitive = true;
7471 } else if (state.children) {
7472 content = state.children.map(function(child) {
7473 if (child._baseState.tag === 'null_')
7474 return child._encode(null, reporter, data);
7475
7476 if (child._baseState.key === null)
7477 return reporter.error('Child should have a key');
7478 var prevKey = reporter.enterKey(child._baseState.key);
7479
7480 if (typeof data !== 'object')
7481 return reporter.error('Child expected, but input is not object');
7482
7483 var res = child._encode(data[child._baseState.key], reporter, data);
7484 reporter.leaveKey(prevKey);
7485
7486 return res;
7487 }, this).filter(function(child) {
7488 return child;
7489 });
7490 content = this._createEncoderBuffer(content);
7491 } else {
7492 if (state.tag === 'seqof' || state.tag === 'setof') {
7493 // TODO(indutny): this should be thrown on DSL level
7494 if (!(state.args && state.args.length === 1))
7495 return reporter.error('Too many args for : ' + state.tag);
7496
7497 if (!Array.isArray(data))
7498 return reporter.error('seqof/setof, but data is not Array');
7499
7500 var child = this.clone();
7501 child._baseState.implicit = null;
7502 content = this._createEncoderBuffer(data.map(function(item) {
7503 var state = this._baseState;
7504
7505 return this._getUse(state.args[0], data)._encode(item, reporter);
7506 }, child));
7507 } else if (state.use !== null) {
7508 result = this._getUse(state.use, parent)._encode(data, reporter);
7509 } else {
7510 content = this._encodePrimitive(state.tag, data);
7511 primitive = true;
7512 }
7513 }
7514
7515 // Encode data itself
7516 var result;
7517 if (!state.any && state.choice === null) {
7518 var tag = state.implicit !== null ? state.implicit : state.tag;
7519 var cls = state.implicit === null ? 'universal' : 'context';
7520
7521 if (tag === null) {
7522 if (state.use === null)
7523 reporter.error('Tag could be omitted only for .use()');
7524 } else {
7525 if (state.use === null)
7526 result = this._encodeComposite(tag, primitive, cls, content);
7527 }
7528 }
7529
7530 // Wrap in explicit
7531 if (state.explicit !== null)
7532 result = this._encodeComposite(state.explicit, false, 'context', result);
7533
7534 return result;
7535};
7536
7537Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
7538 var state = this._baseState;
7539
7540 var node = state.choice[data.type];
7541 if (!node) {
7542 assert(
7543 false,
7544 data.type + ' not found in ' +
7545 JSON.stringify(Object.keys(state.choice)));
7546 }
7547 return node._encode(data.value, reporter);
7548};
7549
7550Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
7551 var state = this._baseState;
7552
7553 if (/str$/.test(tag))
7554 return this._encodeStr(data, tag);
7555 else if (tag === 'objid' && state.args)
7556 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
7557 else if (tag === 'objid')
7558 return this._encodeObjid(data, null, null);
7559 else if (tag === 'gentime' || tag === 'utctime')
7560 return this._encodeTime(data, tag);
7561 else if (tag === 'null_')
7562 return this._encodeNull();
7563 else if (tag === 'int' || tag === 'enum')
7564 return this._encodeInt(data, state.args && state.reverseArgs[0]);
7565 else if (tag === 'bool')
7566 return this._encodeBool(data);
7567 else if (tag === 'objDesc')
7568 return this._encodeStr(data, tag);
7569 else
7570 throw new Error('Unsupported tag: ' + tag);
7571};
7572
7573Node.prototype._isNumstr = function isNumstr(str) {
7574 return /^[0-9 ]*$/.test(str);
7575};
7576
7577Node.prototype._isPrintstr = function isPrintstr(str) {
7578 return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
7579};
7580
7581},{"../base":50,"minimalistic-assert":237}],52:[function(require,module,exports){
7582var inherits = require('inherits');
7583
7584function Reporter(options) {
7585 this._reporterState = {
7586 obj: null,
7587 path: [],
7588 options: options || {},
7589 errors: []
7590 };
7591}
7592exports.Reporter = Reporter;
7593
7594Reporter.prototype.isError = function isError(obj) {
7595 return obj instanceof ReporterError;
7596};
7597
7598Reporter.prototype.save = function save() {
7599 var state = this._reporterState;
7600
7601 return { obj: state.obj, pathLen: state.path.length };
7602};
7603
7604Reporter.prototype.restore = function restore(data) {
7605 var state = this._reporterState;
7606
7607 state.obj = data.obj;
7608 state.path = state.path.slice(0, data.pathLen);
7609};
7610
7611Reporter.prototype.enterKey = function enterKey(key) {
7612 return this._reporterState.path.push(key);
7613};
7614
7615Reporter.prototype.exitKey = function exitKey(index) {
7616 var state = this._reporterState;
7617
7618 state.path = state.path.slice(0, index - 1);
7619};
7620
7621Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
7622 var state = this._reporterState;
7623
7624 this.exitKey(index);
7625 if (state.obj !== null)
7626 state.obj[key] = value;
7627};
7628
7629Reporter.prototype.path = function path() {
7630 return this._reporterState.path.join('/');
7631};
7632
7633Reporter.prototype.enterObject = function enterObject() {
7634 var state = this._reporterState;
7635
7636 var prev = state.obj;
7637 state.obj = {};
7638 return prev;
7639};
7640
7641Reporter.prototype.leaveObject = function leaveObject(prev) {
7642 var state = this._reporterState;
7643
7644 var now = state.obj;
7645 state.obj = prev;
7646 return now;
7647};
7648
7649Reporter.prototype.error = function error(msg) {
7650 var err;
7651 var state = this._reporterState;
7652
7653 var inherited = msg instanceof ReporterError;
7654 if (inherited) {
7655 err = msg;
7656 } else {
7657 err = new ReporterError(state.path.map(function(elem) {
7658 return '[' + JSON.stringify(elem) + ']';
7659 }).join(''), msg.message || msg, msg.stack);
7660 }
7661
7662 if (!state.options.partial)
7663 throw err;
7664
7665 if (!inherited)
7666 state.errors.push(err);
7667
7668 return err;
7669};
7670
7671Reporter.prototype.wrapResult = function wrapResult(result) {
7672 var state = this._reporterState;
7673 if (!state.options.partial)
7674 return result;
7675
7676 return {
7677 result: this.isError(result) ? null : result,
7678 errors: state.errors
7679 };
7680};
7681
7682function ReporterError(path, msg) {
7683 this.path = path;
7684 this.rethrow(msg);
7685};
7686inherits(ReporterError, Error);
7687
7688ReporterError.prototype.rethrow = function rethrow(msg) {
7689 this.message = msg + ' at: ' + (this.path || '(shallow)');
7690 if (Error.captureStackTrace)
7691 Error.captureStackTrace(this, ReporterError);
7692
7693 if (!this.stack) {
7694 try {
7695 // IE only adds stack when thrown
7696 throw new Error(this.message);
7697 } catch (e) {
7698 this.stack = e.stack;
7699 }
7700 }
7701 return this;
7702};
7703
7704},{"inherits":210}],53:[function(require,module,exports){
7705var constants = require('../constants');
7706
7707exports.tagClass = {
7708 0: 'universal',
7709 1: 'application',
7710 2: 'context',
7711 3: 'private'
7712};
7713exports.tagClassByName = constants._reverse(exports.tagClass);
7714
7715exports.tag = {
7716 0x00: 'end',
7717 0x01: 'bool',
7718 0x02: 'int',
7719 0x03: 'bitstr',
7720 0x04: 'octstr',
7721 0x05: 'null_',
7722 0x06: 'objid',
7723 0x07: 'objDesc',
7724 0x08: 'external',
7725 0x09: 'real',
7726 0x0a: 'enum',
7727 0x0b: 'embed',
7728 0x0c: 'utf8str',
7729 0x0d: 'relativeOid',
7730 0x10: 'seq',
7731 0x11: 'set',
7732 0x12: 'numstr',
7733 0x13: 'printstr',
7734 0x14: 't61str',
7735 0x15: 'videostr',
7736 0x16: 'ia5str',
7737 0x17: 'utctime',
7738 0x18: 'gentime',
7739 0x19: 'graphstr',
7740 0x1a: 'iso646str',
7741 0x1b: 'genstr',
7742 0x1c: 'unistr',
7743 0x1d: 'charstr',
7744 0x1e: 'bmpstr'
7745};
7746exports.tagByName = constants._reverse(exports.tag);
7747
7748},{"../constants":54}],54:[function(require,module,exports){
7749var constants = exports;
7750
7751// Helper
7752constants._reverse = function reverse(map) {
7753 var res = {};
7754
7755 Object.keys(map).forEach(function(key) {
7756 // Convert key to integer if it is stringified
7757 if ((key | 0) == key)
7758 key = key | 0;
7759
7760 var value = map[key];
7761 res[value] = key;
7762 });
7763
7764 return res;
7765};
7766
7767constants.der = require('./der');
7768
7769},{"./der":53}],55:[function(require,module,exports){
7770var inherits = require('inherits');
7771
7772var asn1 = require('../../asn1');
7773var base = asn1.base;
7774var bignum = asn1.bignum;
7775
7776// Import DER constants
7777var der = asn1.constants.der;
7778
7779function DERDecoder(entity) {
7780 this.enc = 'der';
7781 this.name = entity.name;
7782 this.entity = entity;
7783
7784 // Construct base tree
7785 this.tree = new DERNode();
7786 this.tree._init(entity.body);
7787};
7788module.exports = DERDecoder;
7789
7790DERDecoder.prototype.decode = function decode(data, options) {
7791 if (!(data instanceof base.DecoderBuffer))
7792 data = new base.DecoderBuffer(data, options);
7793
7794 return this.tree._decode(data, options);
7795};
7796
7797// Tree methods
7798
7799function DERNode(parent) {
7800 base.Node.call(this, 'der', parent);
7801}
7802inherits(DERNode, base.Node);
7803
7804DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
7805 if (buffer.isEmpty())
7806 return false;
7807
7808 var state = buffer.save();
7809 var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
7810 if (buffer.isError(decodedTag))
7811 return decodedTag;
7812
7813 buffer.restore(state);
7814
7815 return decodedTag.tag === tag || decodedTag.tagStr === tag ||
7816 (decodedTag.tagStr + 'of') === tag || any;
7817};
7818
7819DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
7820 var decodedTag = derDecodeTag(buffer,
7821 'Failed to decode tag of "' + tag + '"');
7822 if (buffer.isError(decodedTag))
7823 return decodedTag;
7824
7825 var len = derDecodeLen(buffer,
7826 decodedTag.primitive,
7827 'Failed to get length of "' + tag + '"');
7828
7829 // Failure
7830 if (buffer.isError(len))
7831 return len;
7832
7833 if (!any &&
7834 decodedTag.tag !== tag &&
7835 decodedTag.tagStr !== tag &&
7836 decodedTag.tagStr + 'of' !== tag) {
7837 return buffer.error('Failed to match tag: "' + tag + '"');
7838 }
7839
7840 if (decodedTag.primitive || len !== null)
7841 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
7842
7843 // Indefinite length... find END tag
7844 var state = buffer.save();
7845 var res = this._skipUntilEnd(
7846 buffer,
7847 'Failed to skip indefinite length body: "' + this.tag + '"');
7848 if (buffer.isError(res))
7849 return res;
7850
7851 len = buffer.offset - state.offset;
7852 buffer.restore(state);
7853 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
7854};
7855
7856DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
7857 while (true) {
7858 var tag = derDecodeTag(buffer, fail);
7859 if (buffer.isError(tag))
7860 return tag;
7861 var len = derDecodeLen(buffer, tag.primitive, fail);
7862 if (buffer.isError(len))
7863 return len;
7864
7865 var res;
7866 if (tag.primitive || len !== null)
7867 res = buffer.skip(len)
7868 else
7869 res = this._skipUntilEnd(buffer, fail);
7870
7871 // Failure
7872 if (buffer.isError(res))
7873 return res;
7874
7875 if (tag.tagStr === 'end')
7876 break;
7877 }
7878};
7879
7880DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
7881 options) {
7882 var result = [];
7883 while (!buffer.isEmpty()) {
7884 var possibleEnd = this._peekTag(buffer, 'end');
7885 if (buffer.isError(possibleEnd))
7886 return possibleEnd;
7887
7888 var res = decoder.decode(buffer, 'der', options);
7889 if (buffer.isError(res) && possibleEnd)
7890 break;
7891 result.push(res);
7892 }
7893 return result;
7894};
7895
7896DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
7897 if (tag === 'bitstr') {
7898 var unused = buffer.readUInt8();
7899 if (buffer.isError(unused))
7900 return unused;
7901 return { unused: unused, data: buffer.raw() };
7902 } else if (tag === 'bmpstr') {
7903 var raw = buffer.raw();
7904 if (raw.length % 2 === 1)
7905 return buffer.error('Decoding of string type: bmpstr length mismatch');
7906
7907 var str = '';
7908 for (var i = 0; i < raw.length / 2; i++) {
7909 str += String.fromCharCode(raw.readUInt16BE(i * 2));
7910 }
7911 return str;
7912 } else if (tag === 'numstr') {
7913 var numstr = buffer.raw().toString('ascii');
7914 if (!this._isNumstr(numstr)) {
7915 return buffer.error('Decoding of string type: ' +
7916 'numstr unsupported characters');
7917 }
7918 return numstr;
7919 } else if (tag === 'octstr') {
7920 return buffer.raw();
7921 } else if (tag === 'objDesc') {
7922 return buffer.raw();
7923 } else if (tag === 'printstr') {
7924 var printstr = buffer.raw().toString('ascii');
7925 if (!this._isPrintstr(printstr)) {
7926 return buffer.error('Decoding of string type: ' +
7927 'printstr unsupported characters');
7928 }
7929 return printstr;
7930 } else if (/str$/.test(tag)) {
7931 return buffer.raw().toString();
7932 } else {
7933 return buffer.error('Decoding of string type: ' + tag + ' unsupported');
7934 }
7935};
7936
7937DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
7938 var result;
7939 var identifiers = [];
7940 var ident = 0;
7941 while (!buffer.isEmpty()) {
7942 var subident = buffer.readUInt8();
7943 ident <<= 7;
7944 ident |= subident & 0x7f;
7945 if ((subident & 0x80) === 0) {
7946 identifiers.push(ident);
7947 ident = 0;
7948 }
7949 }
7950 if (subident & 0x80)
7951 identifiers.push(ident);
7952
7953 var first = (identifiers[0] / 40) | 0;
7954 var second = identifiers[0] % 40;
7955
7956 if (relative)
7957 result = identifiers;
7958 else
7959 result = [first, second].concat(identifiers.slice(1));
7960
7961 if (values) {
7962 var tmp = values[result.join(' ')];
7963 if (tmp === undefined)
7964 tmp = values[result.join('.')];
7965 if (tmp !== undefined)
7966 result = tmp;
7967 }
7968
7969 return result;
7970};
7971
7972DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
7973 var str = buffer.raw().toString();
7974 if (tag === 'gentime') {
7975 var year = str.slice(0, 4) | 0;
7976 var mon = str.slice(4, 6) | 0;
7977 var day = str.slice(6, 8) | 0;
7978 var hour = str.slice(8, 10) | 0;
7979 var min = str.slice(10, 12) | 0;
7980 var sec = str.slice(12, 14) | 0;
7981 } else if (tag === 'utctime') {
7982 var year = str.slice(0, 2) | 0;
7983 var mon = str.slice(2, 4) | 0;
7984 var day = str.slice(4, 6) | 0;
7985 var hour = str.slice(6, 8) | 0;
7986 var min = str.slice(8, 10) | 0;
7987 var sec = str.slice(10, 12) | 0;
7988 if (year < 70)
7989 year = 2000 + year;
7990 else
7991 year = 1900 + year;
7992 } else {
7993 return buffer.error('Decoding ' + tag + ' time is not supported yet');
7994 }
7995
7996 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
7997};
7998
7999DERNode.prototype._decodeNull = function decodeNull(buffer) {
8000 return null;
8001};
8002
8003DERNode.prototype._decodeBool = function decodeBool(buffer) {
8004 var res = buffer.readUInt8();
8005 if (buffer.isError(res))
8006 return res;
8007 else
8008 return res !== 0;
8009};
8010
8011DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
8012 // Bigint, return as it is (assume big endian)
8013 var raw = buffer.raw();
8014 var res = new bignum(raw);
8015
8016 if (values)
8017 res = values[res.toString(10)] || res;
8018
8019 return res;
8020};
8021
8022DERNode.prototype._use = function use(entity, obj) {
8023 if (typeof entity === 'function')
8024 entity = entity(obj);
8025 return entity._getDecoder('der').tree;
8026};
8027
8028// Utility methods
8029
8030function derDecodeTag(buf, fail) {
8031 var tag = buf.readUInt8(fail);
8032 if (buf.isError(tag))
8033 return tag;
8034
8035 var cls = der.tagClass[tag >> 6];
8036 var primitive = (tag & 0x20) === 0;
8037
8038 // Multi-octet tag - load
8039 if ((tag & 0x1f) === 0x1f) {
8040 var oct = tag;
8041 tag = 0;
8042 while ((oct & 0x80) === 0x80) {
8043 oct = buf.readUInt8(fail);
8044 if (buf.isError(oct))
8045 return oct;
8046
8047 tag <<= 7;
8048 tag |= oct & 0x7f;
8049 }
8050 } else {
8051 tag &= 0x1f;
8052 }
8053 var tagStr = der.tag[tag];
8054
8055 return {
8056 cls: cls,
8057 primitive: primitive,
8058 tag: tag,
8059 tagStr: tagStr
8060 };
8061}
8062
8063function derDecodeLen(buf, primitive, fail) {
8064 var len = buf.readUInt8(fail);
8065 if (buf.isError(len))
8066 return len;
8067
8068 // Indefinite form
8069 if (!primitive && len === 0x80)
8070 return null;
8071
8072 // Definite form
8073 if ((len & 0x80) === 0) {
8074 // Short form
8075 return len;
8076 }
8077
8078 // Long form
8079 var num = len & 0x7f;
8080 if (num > 4)
8081 return buf.error('length octect is too long');
8082
8083 len = 0;
8084 for (var i = 0; i < num; i++) {
8085 len <<= 8;
8086 var j = buf.readUInt8(fail);
8087 if (buf.isError(j))
8088 return j;
8089 len |= j;
8090 }
8091
8092 return len;
8093}
8094
8095},{"../../asn1":47,"inherits":210}],56:[function(require,module,exports){
8096var decoders = exports;
8097
8098decoders.der = require('./der');
8099decoders.pem = require('./pem');
8100
8101},{"./der":55,"./pem":57}],57:[function(require,module,exports){
8102var inherits = require('inherits');
8103var Buffer = require('buffer').Buffer;
8104
8105var DERDecoder = require('./der');
8106
8107function PEMDecoder(entity) {
8108 DERDecoder.call(this, entity);
8109 this.enc = 'pem';
8110};
8111inherits(PEMDecoder, DERDecoder);
8112module.exports = PEMDecoder;
8113
8114PEMDecoder.prototype.decode = function decode(data, options) {
8115 var lines = data.toString().split(/[\r\n]+/g);
8116
8117 var label = options.label.toUpperCase();
8118
8119 var re = /^-----(BEGIN|END) ([^-]+)-----$/;
8120 var start = -1;
8121 var end = -1;
8122 for (var i = 0; i < lines.length; i++) {
8123 var match = lines[i].match(re);
8124 if (match === null)
8125 continue;
8126
8127 if (match[2] !== label)
8128 continue;
8129
8130 if (start === -1) {
8131 if (match[1] !== 'BEGIN')
8132 break;
8133 start = i;
8134 } else {
8135 if (match[1] !== 'END')
8136 break;
8137 end = i;
8138 break;
8139 }
8140 }
8141 if (start === -1 || end === -1)
8142 throw new Error('PEM section not found for: ' + label);
8143
8144 var base64 = lines.slice(start + 1, end).join('');
8145 // Remove excessive symbols
8146 base64.replace(/[^a-z0-9\+\/=]+/gi, '');
8147
8148 var input = new Buffer(base64, 'base64');
8149 return DERDecoder.prototype.decode.call(this, input, options);
8150};
8151
8152},{"./der":55,"buffer":114,"inherits":210}],58:[function(require,module,exports){
8153var inherits = require('inherits');
8154var Buffer = require('buffer').Buffer;
8155
8156var asn1 = require('../../asn1');
8157var base = asn1.base;
8158
8159// Import DER constants
8160var der = asn1.constants.der;
8161
8162function DEREncoder(entity) {
8163 this.enc = 'der';
8164 this.name = entity.name;
8165 this.entity = entity;
8166
8167 // Construct base tree
8168 this.tree = new DERNode();
8169 this.tree._init(entity.body);
8170};
8171module.exports = DEREncoder;
8172
8173DEREncoder.prototype.encode = function encode(data, reporter) {
8174 return this.tree._encode(data, reporter).join();
8175};
8176
8177// Tree methods
8178
8179function DERNode(parent) {
8180 base.Node.call(this, 'der', parent);
8181}
8182inherits(DERNode, base.Node);
8183
8184DERNode.prototype._encodeComposite = function encodeComposite(tag,
8185 primitive,
8186 cls,
8187 content) {
8188 var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
8189
8190 // Short form
8191 if (content.length < 0x80) {
8192 var header = new Buffer(2);
8193 header[0] = encodedTag;
8194 header[1] = content.length;
8195 return this._createEncoderBuffer([ header, content ]);
8196 }
8197
8198 // Long form
8199 // Count octets required to store length
8200 var lenOctets = 1;
8201 for (var i = content.length; i >= 0x100; i >>= 8)
8202 lenOctets++;
8203
8204 var header = new Buffer(1 + 1 + lenOctets);
8205 header[0] = encodedTag;
8206 header[1] = 0x80 | lenOctets;
8207
8208 for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
8209 header[i] = j & 0xff;
8210
8211 return this._createEncoderBuffer([ header, content ]);
8212};
8213
8214DERNode.prototype._encodeStr = function encodeStr(str, tag) {
8215 if (tag === 'bitstr') {
8216 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
8217 } else if (tag === 'bmpstr') {
8218 var buf = new Buffer(str.length * 2);
8219 for (var i = 0; i < str.length; i++) {
8220 buf.writeUInt16BE(str.charCodeAt(i), i * 2);
8221 }
8222 return this._createEncoderBuffer(buf);
8223 } else if (tag === 'numstr') {
8224 if (!this._isNumstr(str)) {
8225 return this.reporter.error('Encoding of string type: numstr supports ' +
8226 'only digits and space');
8227 }
8228 return this._createEncoderBuffer(str);
8229 } else if (tag === 'printstr') {
8230 if (!this._isPrintstr(str)) {
8231 return this.reporter.error('Encoding of string type: printstr supports ' +
8232 'only latin upper and lower case letters, ' +
8233 'digits, space, apostrophe, left and rigth ' +
8234 'parenthesis, plus sign, comma, hyphen, ' +
8235 'dot, slash, colon, equal sign, ' +
8236 'question mark');
8237 }
8238 return this._createEncoderBuffer(str);
8239 } else if (/str$/.test(tag)) {
8240 return this._createEncoderBuffer(str);
8241 } else if (tag === 'objDesc') {
8242 return this._createEncoderBuffer(str);
8243 } else {
8244 return this.reporter.error('Encoding of string type: ' + tag +
8245 ' unsupported');
8246 }
8247};
8248
8249DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
8250 if (typeof id === 'string') {
8251 if (!values)
8252 return this.reporter.error('string objid given, but no values map found');
8253 if (!values.hasOwnProperty(id))
8254 return this.reporter.error('objid not found in values map');
8255 id = values[id].split(/[\s\.]+/g);
8256 for (var i = 0; i < id.length; i++)
8257 id[i] |= 0;
8258 } else if (Array.isArray(id)) {
8259 id = id.slice();
8260 for (var i = 0; i < id.length; i++)
8261 id[i] |= 0;
8262 }
8263
8264 if (!Array.isArray(id)) {
8265 return this.reporter.error('objid() should be either array or string, ' +
8266 'got: ' + JSON.stringify(id));
8267 }
8268
8269 if (!relative) {
8270 if (id[1] >= 40)
8271 return this.reporter.error('Second objid identifier OOB');
8272 id.splice(0, 2, id[0] * 40 + id[1]);
8273 }
8274
8275 // Count number of octets
8276 var size = 0;
8277 for (var i = 0; i < id.length; i++) {
8278 var ident = id[i];
8279 for (size++; ident >= 0x80; ident >>= 7)
8280 size++;
8281 }
8282
8283 var objid = new Buffer(size);
8284 var offset = objid.length - 1;
8285 for (var i = id.length - 1; i >= 0; i--) {
8286 var ident = id[i];
8287 objid[offset--] = ident & 0x7f;
8288 while ((ident >>= 7) > 0)
8289 objid[offset--] = 0x80 | (ident & 0x7f);
8290 }
8291
8292 return this._createEncoderBuffer(objid);
8293};
8294
8295function two(num) {
8296 if (num < 10)
8297 return '0' + num;
8298 else
8299 return num;
8300}
8301
8302DERNode.prototype._encodeTime = function encodeTime(time, tag) {
8303 var str;
8304 var date = new Date(time);
8305
8306 if (tag === 'gentime') {
8307 str = [
8308 two(date.getFullYear()),
8309 two(date.getUTCMonth() + 1),
8310 two(date.getUTCDate()),
8311 two(date.getUTCHours()),
8312 two(date.getUTCMinutes()),
8313 two(date.getUTCSeconds()),
8314 'Z'
8315 ].join('');
8316 } else if (tag === 'utctime') {
8317 str = [
8318 two(date.getFullYear() % 100),
8319 two(date.getUTCMonth() + 1),
8320 two(date.getUTCDate()),
8321 two(date.getUTCHours()),
8322 two(date.getUTCMinutes()),
8323 two(date.getUTCSeconds()),
8324 'Z'
8325 ].join('');
8326 } else {
8327 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
8328 }
8329
8330 return this._encodeStr(str, 'octstr');
8331};
8332
8333DERNode.prototype._encodeNull = function encodeNull() {
8334 return this._createEncoderBuffer('');
8335};
8336
8337DERNode.prototype._encodeInt = function encodeInt(num, values) {
8338 if (typeof num === 'string') {
8339 if (!values)
8340 return this.reporter.error('String int or enum given, but no values map');
8341 if (!values.hasOwnProperty(num)) {
8342 return this.reporter.error('Values map doesn\'t contain: ' +
8343 JSON.stringify(num));
8344 }
8345 num = values[num];
8346 }
8347
8348 // Bignum, assume big endian
8349 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
8350 var numArray = num.toArray();
8351 if (!num.sign && numArray[0] & 0x80) {
8352 numArray.unshift(0);
8353 }
8354 num = new Buffer(numArray);
8355 }
8356
8357 if (Buffer.isBuffer(num)) {
8358 var size = num.length;
8359 if (num.length === 0)
8360 size++;
8361
8362 var out = new Buffer(size);
8363 num.copy(out);
8364 if (num.length === 0)
8365 out[0] = 0
8366 return this._createEncoderBuffer(out);
8367 }
8368
8369 if (num < 0x80)
8370 return this._createEncoderBuffer(num);
8371
8372 if (num < 0x100)
8373 return this._createEncoderBuffer([0, num]);
8374
8375 var size = 1;
8376 for (var i = num; i >= 0x100; i >>= 8)
8377 size++;
8378
8379 var out = new Array(size);
8380 for (var i = out.length - 1; i >= 0; i--) {
8381 out[i] = num & 0xff;
8382 num >>= 8;
8383 }
8384 if(out[0] & 0x80) {
8385 out.unshift(0);
8386 }
8387
8388 return this._createEncoderBuffer(new Buffer(out));
8389};
8390
8391DERNode.prototype._encodeBool = function encodeBool(value) {
8392 return this._createEncoderBuffer(value ? 0xff : 0);
8393};
8394
8395DERNode.prototype._use = function use(entity, obj) {
8396 if (typeof entity === 'function')
8397 entity = entity(obj);
8398 return entity._getEncoder('der').tree;
8399};
8400
8401DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
8402 var state = this._baseState;
8403 var i;
8404 if (state['default'] === null)
8405 return false;
8406
8407 var data = dataBuffer.join();
8408 if (state.defaultBuffer === undefined)
8409 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
8410
8411 if (data.length !== state.defaultBuffer.length)
8412 return false;
8413
8414 for (i=0; i < data.length; i++)
8415 if (data[i] !== state.defaultBuffer[i])
8416 return false;
8417
8418 return true;
8419};
8420
8421// Utility methods
8422
8423function encodeTag(tag, primitive, cls, reporter) {
8424 var res;
8425
8426 if (tag === 'seqof')
8427 tag = 'seq';
8428 else if (tag === 'setof')
8429 tag = 'set';
8430
8431 if (der.tagByName.hasOwnProperty(tag))
8432 res = der.tagByName[tag];
8433 else if (typeof tag === 'number' && (tag | 0) === tag)
8434 res = tag;
8435 else
8436 return reporter.error('Unknown tag: ' + tag);
8437
8438 if (res >= 0x1f)
8439 return reporter.error('Multi-octet tag encoding unsupported');
8440
8441 if (!primitive)
8442 res |= 0x20;
8443
8444 res |= (der.tagClassByName[cls || 'universal'] << 6);
8445
8446 return res;
8447}
8448
8449},{"../../asn1":47,"buffer":114,"inherits":210}],59:[function(require,module,exports){
8450var encoders = exports;
8451
8452encoders.der = require('./der');
8453encoders.pem = require('./pem');
8454
8455},{"./der":58,"./pem":60}],60:[function(require,module,exports){
8456var inherits = require('inherits');
8457
8458var DEREncoder = require('./der');
8459
8460function PEMEncoder(entity) {
8461 DEREncoder.call(this, entity);
8462 this.enc = 'pem';
8463};
8464inherits(PEMEncoder, DEREncoder);
8465module.exports = PEMEncoder;
8466
8467PEMEncoder.prototype.encode = function encode(data, options) {
8468 var buf = DEREncoder.prototype.encode.call(this, data);
8469
8470 var p = buf.toString('base64');
8471 var out = [ '-----BEGIN ' + options.label + '-----' ];
8472 for (var i = 0; i < p.length; i += 64)
8473 out.push(p.slice(i, i + 64));
8474 out.push('-----END ' + options.label + '-----');
8475 return out.join('\n');
8476};
8477
8478},{"./der":58,"inherits":210}],61:[function(require,module,exports){
8479// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8480
8481
8482module.exports = {
8483
8484 newInvalidAsn1Error: function (msg) {
8485 var e = new Error();
8486 e.name = 'InvalidAsn1Error';
8487 e.message = msg || '';
8488 return e;
8489 }
8490
8491};
8492
8493},{}],62:[function(require,module,exports){
8494// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8495
8496var errors = require('./errors');
8497var types = require('./types');
8498
8499var Reader = require('./reader');
8500var Writer = require('./writer');
8501
8502
8503// --- Exports
8504
8505module.exports = {
8506
8507 Reader: Reader,
8508
8509 Writer: Writer
8510
8511};
8512
8513for (var t in types) {
8514 if (types.hasOwnProperty(t))
8515 module.exports[t] = types[t];
8516}
8517for (var e in errors) {
8518 if (errors.hasOwnProperty(e))
8519 module.exports[e] = errors[e];
8520}
8521
8522},{"./errors":61,"./reader":63,"./types":64,"./writer":65}],63:[function(require,module,exports){
8523// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8524
8525var assert = require('assert');
8526var Buffer = require('safer-buffer').Buffer;
8527
8528var ASN1 = require('./types');
8529var errors = require('./errors');
8530
8531
8532// --- Globals
8533
8534var newInvalidAsn1Error = errors.newInvalidAsn1Error;
8535
8536
8537
8538// --- API
8539
8540function Reader(data) {
8541 if (!data || !Buffer.isBuffer(data))
8542 throw new TypeError('data must be a node Buffer');
8543
8544 this._buf = data;
8545 this._size = data.length;
8546
8547 // These hold the "current" state
8548 this._len = 0;
8549 this._offset = 0;
8550}
8551
8552Object.defineProperty(Reader.prototype, 'length', {
8553 enumerable: true,
8554 get: function () { return (this._len); }
8555});
8556
8557Object.defineProperty(Reader.prototype, 'offset', {
8558 enumerable: true,
8559 get: function () { return (this._offset); }
8560});
8561
8562Object.defineProperty(Reader.prototype, 'remain', {
8563 get: function () { return (this._size - this._offset); }
8564});
8565
8566Object.defineProperty(Reader.prototype, 'buffer', {
8567 get: function () { return (this._buf.slice(this._offset)); }
8568});
8569
8570
8571/**
8572 * Reads a single byte and advances offset; you can pass in `true` to make this
8573 * a "peek" operation (i.e., get the byte, but don't advance the offset).
8574 *
8575 * @param {Boolean} peek true means don't move offset.
8576 * @return {Number} the next byte, null if not enough data.
8577 */
8578Reader.prototype.readByte = function (peek) {
8579 if (this._size - this._offset < 1)
8580 return null;
8581
8582 var b = this._buf[this._offset] & 0xff;
8583
8584 if (!peek)
8585 this._offset += 1;
8586
8587 return b;
8588};
8589
8590
8591Reader.prototype.peek = function () {
8592 return this.readByte(true);
8593};
8594
8595
8596/**
8597 * Reads a (potentially) variable length off the BER buffer. This call is
8598 * not really meant to be called directly, as callers have to manipulate
8599 * the internal buffer afterwards.
8600 *
8601 * As a result of this call, you can call `Reader.length`, until the
8602 * next thing called that does a readLength.
8603 *
8604 * @return {Number} the amount of offset to advance the buffer.
8605 * @throws {InvalidAsn1Error} on bad ASN.1
8606 */
8607Reader.prototype.readLength = function (offset) {
8608 if (offset === undefined)
8609 offset = this._offset;
8610
8611 if (offset >= this._size)
8612 return null;
8613
8614 var lenB = this._buf[offset++] & 0xff;
8615 if (lenB === null)
8616 return null;
8617
8618 if ((lenB & 0x80) === 0x80) {
8619 lenB &= 0x7f;
8620
8621 if (lenB === 0)
8622 throw newInvalidAsn1Error('Indefinite length not supported');
8623
8624 if (lenB > 4)
8625 throw newInvalidAsn1Error('encoding too long');
8626
8627 if (this._size - offset < lenB)
8628 return null;
8629
8630 this._len = 0;
8631 for (var i = 0; i < lenB; i++)
8632 this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
8633
8634 } else {
8635 // Wasn't a variable length
8636 this._len = lenB;
8637 }
8638
8639 return offset;
8640};
8641
8642
8643/**
8644 * Parses the next sequence in this BER buffer.
8645 *
8646 * To get the length of the sequence, call `Reader.length`.
8647 *
8648 * @return {Number} the sequence's tag.
8649 */
8650Reader.prototype.readSequence = function (tag) {
8651 var seq = this.peek();
8652 if (seq === null)
8653 return null;
8654 if (tag !== undefined && tag !== seq)
8655 throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
8656 ': got 0x' + seq.toString(16));
8657
8658 var o = this.readLength(this._offset + 1); // stored in `length`
8659 if (o === null)
8660 return null;
8661
8662 this._offset = o;
8663 return seq;
8664};
8665
8666
8667Reader.prototype.readInt = function () {
8668 return this._readTag(ASN1.Integer);
8669};
8670
8671
8672Reader.prototype.readBoolean = function () {
8673 return (this._readTag(ASN1.Boolean) === 0 ? false : true);
8674};
8675
8676
8677Reader.prototype.readEnumeration = function () {
8678 return this._readTag(ASN1.Enumeration);
8679};
8680
8681
8682Reader.prototype.readString = function (tag, retbuf) {
8683 if (!tag)
8684 tag = ASN1.OctetString;
8685
8686 var b = this.peek();
8687 if (b === null)
8688 return null;
8689
8690 if (b !== tag)
8691 throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
8692 ': got 0x' + b.toString(16));
8693
8694 var o = this.readLength(this._offset + 1); // stored in `length`
8695
8696 if (o === null)
8697 return null;
8698
8699 if (this.length > this._size - o)
8700 return null;
8701
8702 this._offset = o;
8703
8704 if (this.length === 0)
8705 return retbuf ? Buffer.alloc(0) : '';
8706
8707 var str = this._buf.slice(this._offset, this._offset + this.length);
8708 this._offset += this.length;
8709
8710 return retbuf ? str : str.toString('utf8');
8711};
8712
8713Reader.prototype.readOID = function (tag) {
8714 if (!tag)
8715 tag = ASN1.OID;
8716
8717 var b = this.readString(tag, true);
8718 if (b === null)
8719 return null;
8720
8721 var values = [];
8722 var value = 0;
8723
8724 for (var i = 0; i < b.length; i++) {
8725 var byte = b[i] & 0xff;
8726
8727 value <<= 7;
8728 value += byte & 0x7f;
8729 if ((byte & 0x80) === 0) {
8730 values.push(value);
8731 value = 0;
8732 }
8733 }
8734
8735 value = values.shift();
8736 values.unshift(value % 40);
8737 values.unshift((value / 40) >> 0);
8738
8739 return values.join('.');
8740};
8741
8742
8743Reader.prototype._readTag = function (tag) {
8744 assert.ok(tag !== undefined);
8745
8746 var b = this.peek();
8747
8748 if (b === null)
8749 return null;
8750
8751 if (b !== tag)
8752 throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
8753 ': got 0x' + b.toString(16));
8754
8755 var o = this.readLength(this._offset + 1); // stored in `length`
8756 if (o === null)
8757 return null;
8758
8759 if (this.length > 4)
8760 throw newInvalidAsn1Error('Integer too long: ' + this.length);
8761
8762 if (this.length > this._size - o)
8763 return null;
8764 this._offset = o;
8765
8766 var fb = this._buf[this._offset];
8767 var value = 0;
8768
8769 for (var i = 0; i < this.length; i++) {
8770 value <<= 8;
8771 value |= (this._buf[this._offset++] & 0xff);
8772 }
8773
8774 if ((fb & 0x80) === 0x80 && i !== 4)
8775 value -= (1 << (i * 8));
8776
8777 return value >> 0;
8778};
8779
8780
8781
8782// --- Exported API
8783
8784module.exports = Reader;
8785
8786},{"./errors":61,"./types":64,"assert":68,"safer-buffer":326}],64:[function(require,module,exports){
8787// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8788
8789
8790module.exports = {
8791 EOC: 0,
8792 Boolean: 1,
8793 Integer: 2,
8794 BitString: 3,
8795 OctetString: 4,
8796 Null: 5,
8797 OID: 6,
8798 ObjectDescriptor: 7,
8799 External: 8,
8800 Real: 9, // float
8801 Enumeration: 10,
8802 PDV: 11,
8803 Utf8String: 12,
8804 RelativeOID: 13,
8805 Sequence: 16,
8806 Set: 17,
8807 NumericString: 18,
8808 PrintableString: 19,
8809 T61String: 20,
8810 VideotexString: 21,
8811 IA5String: 22,
8812 UTCTime: 23,
8813 GeneralizedTime: 24,
8814 GraphicString: 25,
8815 VisibleString: 26,
8816 GeneralString: 28,
8817 UniversalString: 29,
8818 CharacterString: 30,
8819 BMPString: 31,
8820 Constructor: 32,
8821 Context: 128
8822};
8823
8824},{}],65:[function(require,module,exports){
8825// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
8826
8827var assert = require('assert');
8828var Buffer = require('safer-buffer').Buffer;
8829var ASN1 = require('./types');
8830var errors = require('./errors');
8831
8832
8833// --- Globals
8834
8835var newInvalidAsn1Error = errors.newInvalidAsn1Error;
8836
8837var DEFAULT_OPTS = {
8838 size: 1024,
8839 growthFactor: 8
8840};
8841
8842
8843// --- Helpers
8844
8845function merge(from, to) {
8846 assert.ok(from);
8847 assert.equal(typeof (from), 'object');
8848 assert.ok(to);
8849 assert.equal(typeof (to), 'object');
8850
8851 var keys = Object.getOwnPropertyNames(from);
8852 keys.forEach(function (key) {
8853 if (to[key])
8854 return;
8855
8856 var value = Object.getOwnPropertyDescriptor(from, key);
8857 Object.defineProperty(to, key, value);
8858 });
8859
8860 return to;
8861}
8862
8863
8864
8865// --- API
8866
8867function Writer(options) {
8868 options = merge(DEFAULT_OPTS, options || {});
8869
8870 this._buf = Buffer.alloc(options.size || 1024);
8871 this._size = this._buf.length;
8872 this._offset = 0;
8873 this._options = options;
8874
8875 // A list of offsets in the buffer where we need to insert
8876 // sequence tag/len pairs.
8877 this._seq = [];
8878}
8879
8880Object.defineProperty(Writer.prototype, 'buffer', {
8881 get: function () {
8882 if (this._seq.length)
8883 throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');
8884
8885 return (this._buf.slice(0, this._offset));
8886 }
8887});
8888
8889Writer.prototype.writeByte = function (b) {
8890 if (typeof (b) !== 'number')
8891 throw new TypeError('argument must be a Number');
8892
8893 this._ensure(1);
8894 this._buf[this._offset++] = b;
8895};
8896
8897
8898Writer.prototype.writeInt = function (i, tag) {
8899 if (typeof (i) !== 'number')
8900 throw new TypeError('argument must be a Number');
8901 if (typeof (tag) !== 'number')
8902 tag = ASN1.Integer;
8903
8904 var sz = 4;
8905
8906 while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
8907 (sz > 1)) {
8908 sz--;
8909 i <<= 8;
8910 }
8911
8912 if (sz > 4)
8913 throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');
8914
8915 this._ensure(2 + sz);
8916 this._buf[this._offset++] = tag;
8917 this._buf[this._offset++] = sz;
8918
8919 while (sz-- > 0) {
8920 this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
8921 i <<= 8;
8922 }
8923
8924};
8925
8926
8927Writer.prototype.writeNull = function () {
8928 this.writeByte(ASN1.Null);
8929 this.writeByte(0x00);
8930};
8931
8932
8933Writer.prototype.writeEnumeration = function (i, tag) {
8934 if (typeof (i) !== 'number')
8935 throw new TypeError('argument must be a Number');
8936 if (typeof (tag) !== 'number')
8937 tag = ASN1.Enumeration;
8938
8939 return this.writeInt(i, tag);
8940};
8941
8942
8943Writer.prototype.writeBoolean = function (b, tag) {
8944 if (typeof (b) !== 'boolean')
8945 throw new TypeError('argument must be a Boolean');
8946 if (typeof (tag) !== 'number')
8947 tag = ASN1.Boolean;
8948
8949 this._ensure(3);
8950 this._buf[this._offset++] = tag;
8951 this._buf[this._offset++] = 0x01;
8952 this._buf[this._offset++] = b ? 0xff : 0x00;
8953};
8954
8955
8956Writer.prototype.writeString = function (s, tag) {
8957 if (typeof (s) !== 'string')
8958 throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');
8959 if (typeof (tag) !== 'number')
8960 tag = ASN1.OctetString;
8961
8962 var len = Buffer.byteLength(s);
8963 this.writeByte(tag);
8964 this.writeLength(len);
8965 if (len) {
8966 this._ensure(len);
8967 this._buf.write(s, this._offset);
8968 this._offset += len;
8969 }
8970};
8971
8972
8973Writer.prototype.writeBuffer = function (buf, tag) {
8974 if (typeof (tag) !== 'number')
8975 throw new TypeError('tag must be a number');
8976 if (!Buffer.isBuffer(buf))
8977 throw new TypeError('argument must be a buffer');
8978
8979 this.writeByte(tag);
8980 this.writeLength(buf.length);
8981 this._ensure(buf.length);
8982 buf.copy(this._buf, this._offset, 0, buf.length);
8983 this._offset += buf.length;
8984};
8985
8986
8987Writer.prototype.writeStringArray = function (strings) {
8988 if ((!strings instanceof Array))
8989 throw new TypeError('argument must be an Array[String]');
8990
8991 var self = this;
8992 strings.forEach(function (s) {
8993 self.writeString(s);
8994 });
8995};
8996
8997// This is really to solve DER cases, but whatever for now
8998Writer.prototype.writeOID = function (s, tag) {
8999 if (typeof (s) !== 'string')
9000 throw new TypeError('argument must be a string');
9001 if (typeof (tag) !== 'number')
9002 tag = ASN1.OID;
9003
9004 if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
9005 throw new Error('argument is not a valid OID string');
9006
9007 function encodeOctet(bytes, octet) {
9008 if (octet < 128) {
9009 bytes.push(octet);
9010 } else if (octet < 16384) {
9011 bytes.push((octet >>> 7) | 0x80);
9012 bytes.push(octet & 0x7F);
9013 } else if (octet < 2097152) {
9014 bytes.push((octet >>> 14) | 0x80);
9015 bytes.push(((octet >>> 7) | 0x80) & 0xFF);
9016 bytes.push(octet & 0x7F);
9017 } else if (octet < 268435456) {
9018 bytes.push((octet >>> 21) | 0x80);
9019 bytes.push(((octet >>> 14) | 0x80) & 0xFF);
9020 bytes.push(((octet >>> 7) | 0x80) & 0xFF);
9021 bytes.push(octet & 0x7F);
9022 } else {
9023 bytes.push(((octet >>> 28) | 0x80) & 0xFF);
9024 bytes.push(((octet >>> 21) | 0x80) & 0xFF);
9025 bytes.push(((octet >>> 14) | 0x80) & 0xFF);
9026 bytes.push(((octet >>> 7) | 0x80) & 0xFF);
9027 bytes.push(octet & 0x7F);
9028 }
9029 }
9030
9031 var tmp = s.split('.');
9032 var bytes = [];
9033 bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
9034 tmp.slice(2).forEach(function (b) {
9035 encodeOctet(bytes, parseInt(b, 10));
9036 });
9037
9038 var self = this;
9039 this._ensure(2 + bytes.length);
9040 this.writeByte(tag);
9041 this.writeLength(bytes.length);
9042 bytes.forEach(function (b) {
9043 self.writeByte(b);
9044 });
9045};
9046
9047
9048Writer.prototype.writeLength = function (len) {
9049 if (typeof (len) !== 'number')
9050 throw new TypeError('argument must be a Number');
9051
9052 this._ensure(4);
9053
9054 if (len <= 0x7f) {
9055 this._buf[this._offset++] = len;
9056 } else if (len <= 0xff) {
9057 this._buf[this._offset++] = 0x81;
9058 this._buf[this._offset++] = len;
9059 } else if (len <= 0xffff) {
9060 this._buf[this._offset++] = 0x82;
9061 this._buf[this._offset++] = len >> 8;
9062 this._buf[this._offset++] = len;
9063 } else if (len <= 0xffffff) {
9064 this._buf[this._offset++] = 0x83;
9065 this._buf[this._offset++] = len >> 16;
9066 this._buf[this._offset++] = len >> 8;
9067 this._buf[this._offset++] = len;
9068 } else {
9069 throw newInvalidAsn1Error('Length too long (> 4 bytes)');
9070 }
9071};
9072
9073Writer.prototype.startSequence = function (tag) {
9074 if (typeof (tag) !== 'number')
9075 tag = ASN1.Sequence | ASN1.Constructor;
9076
9077 this.writeByte(tag);
9078 this._seq.push(this._offset);
9079 this._ensure(3);
9080 this._offset += 3;
9081};
9082
9083
9084Writer.prototype.endSequence = function () {
9085 var seq = this._seq.pop();
9086 var start = seq + 3;
9087 var len = this._offset - start;
9088
9089 if (len <= 0x7f) {
9090 this._shift(start, len, -2);
9091 this._buf[seq] = len;
9092 } else if (len <= 0xff) {
9093 this._shift(start, len, -1);
9094 this._buf[seq] = 0x81;
9095 this._buf[seq + 1] = len;
9096 } else if (len <= 0xffff) {
9097 this._buf[seq] = 0x82;
9098 this._buf[seq + 1] = len >> 8;
9099 this._buf[seq + 2] = len;
9100 } else if (len <= 0xffffff) {
9101 this._shift(start, len, 1);
9102 this._buf[seq] = 0x83;
9103 this._buf[seq + 1] = len >> 16;
9104 this._buf[seq + 2] = len >> 8;
9105 this._buf[seq + 3] = len;
9106 } else {
9107 throw newInvalidAsn1Error('Sequence too long');
9108 }
9109};
9110
9111
9112Writer.prototype._shift = function (start, len, shift) {
9113 assert.ok(start !== undefined);
9114 assert.ok(len !== undefined);
9115 assert.ok(shift);
9116
9117 this._buf.copy(this._buf, start + shift, start, start + len);
9118 this._offset += shift;
9119};
9120
9121Writer.prototype._ensure = function (len) {
9122 assert.ok(len);
9123
9124 if (this._size - this._offset < len) {
9125 var sz = this._size * this._options.growthFactor;
9126 if (sz - this._offset < len)
9127 sz += len;
9128
9129 var buf = Buffer.alloc(sz);
9130
9131 this._buf.copy(buf, 0, 0, this._offset);
9132 this._buf = buf;
9133 this._size = sz;
9134 }
9135};
9136
9137
9138
9139// --- Exported API
9140
9141module.exports = Writer;
9142
9143},{"./errors":61,"./types":64,"assert":68,"safer-buffer":326}],66:[function(require,module,exports){
9144// Copyright 2011 Mark Cavage <mcavage@gmail.com> All rights reserved.
9145
9146// If you have no idea what ASN.1 or BER is, see this:
9147// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
9148
9149var Ber = require('./ber/index');
9150
9151
9152
9153// --- Exported API
9154
9155module.exports = {
9156
9157 Ber: Ber,
9158
9159 BerReader: Ber.Reader,
9160
9161 BerWriter: Ber.Writer
9162
9163};
9164
9165},{"./ber/index":62}],67:[function(require,module,exports){
9166(function (Buffer,process){
9167// Copyright (c) 2012, Mark Cavage. All rights reserved.
9168// Copyright 2015 Joyent, Inc.
9169
9170var assert = require('assert');
9171var Stream = require('stream').Stream;
9172var util = require('util');
9173
9174
9175///--- Globals
9176
9177/* JSSTYLED */
9178var 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}$/;
9179
9180
9181///--- Internal
9182
9183function _capitalize(str) {
9184 return (str.charAt(0).toUpperCase() + str.slice(1));
9185}
9186
9187function _toss(name, expected, oper, arg, actual) {
9188 throw new assert.AssertionError({
9189 message: util.format('%s (%s) is required', name, expected),
9190 actual: (actual === undefined) ? typeof (arg) : actual(arg),
9191 expected: expected,
9192 operator: oper || '===',
9193 stackStartFunction: _toss.caller
9194 });
9195}
9196
9197function _getClass(arg) {
9198 return (Object.prototype.toString.call(arg).slice(8, -1));
9199}
9200
9201function noop() {
9202 // Why even bother with asserts?
9203}
9204
9205
9206///--- Exports
9207
9208var types = {
9209 bool: {
9210 check: function (arg) { return typeof (arg) === 'boolean'; }
9211 },
9212 func: {
9213 check: function (arg) { return typeof (arg) === 'function'; }
9214 },
9215 string: {
9216 check: function (arg) { return typeof (arg) === 'string'; }
9217 },
9218 object: {
9219 check: function (arg) {
9220 return typeof (arg) === 'object' && arg !== null;
9221 }
9222 },
9223 number: {
9224 check: function (arg) {
9225 return typeof (arg) === 'number' && !isNaN(arg);
9226 }
9227 },
9228 finite: {
9229 check: function (arg) {
9230 return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
9231 }
9232 },
9233 buffer: {
9234 check: function (arg) { return Buffer.isBuffer(arg); },
9235 operator: 'Buffer.isBuffer'
9236 },
9237 array: {
9238 check: function (arg) { return Array.isArray(arg); },
9239 operator: 'Array.isArray'
9240 },
9241 stream: {
9242 check: function (arg) { return arg instanceof Stream; },
9243 operator: 'instanceof',
9244 actual: _getClass
9245 },
9246 date: {
9247 check: function (arg) { return arg instanceof Date; },
9248 operator: 'instanceof',
9249 actual: _getClass
9250 },
9251 regexp: {
9252 check: function (arg) { return arg instanceof RegExp; },
9253 operator: 'instanceof',
9254 actual: _getClass
9255 },
9256 uuid: {
9257 check: function (arg) {
9258 return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
9259 },
9260 operator: 'isUUID'
9261 }
9262};
9263
9264function _setExports(ndebug) {
9265 var keys = Object.keys(types);
9266 var out;
9267
9268 /* re-export standard assert */
9269 if (process.env.NODE_NDEBUG) {
9270 out = noop;
9271 } else {
9272 out = function (arg, msg) {
9273 if (!arg) {
9274 _toss(msg, 'true', arg);
9275 }
9276 };
9277 }
9278
9279 /* standard checks */
9280 keys.forEach(function (k) {
9281 if (ndebug) {
9282 out[k] = noop;
9283 return;
9284 }
9285 var type = types[k];
9286 out[k] = function (arg, msg) {
9287 if (!type.check(arg)) {
9288 _toss(msg, k, type.operator, arg, type.actual);
9289 }
9290 };
9291 });
9292
9293 /* optional checks */
9294 keys.forEach(function (k) {
9295 var name = 'optional' + _capitalize(k);
9296 if (ndebug) {
9297 out[name] = noop;
9298 return;
9299 }
9300 var type = types[k];
9301 out[name] = function (arg, msg) {
9302 if (arg === undefined || arg === null) {
9303 return;
9304 }
9305 if (!type.check(arg)) {
9306 _toss(msg, k, type.operator, arg, type.actual);
9307 }
9308 };
9309 });
9310
9311 /* arrayOf checks */
9312 keys.forEach(function (k) {
9313 var name = 'arrayOf' + _capitalize(k);
9314 if (ndebug) {
9315 out[name] = noop;
9316 return;
9317 }
9318 var type = types[k];
9319 var expected = '[' + k + ']';
9320 out[name] = function (arg, msg) {
9321 if (!Array.isArray(arg)) {
9322 _toss(msg, expected, type.operator, arg, type.actual);
9323 }
9324 var i;
9325 for (i = 0; i < arg.length; i++) {
9326 if (!type.check(arg[i])) {
9327 _toss(msg, expected, type.operator, arg, type.actual);
9328 }
9329 }
9330 };
9331 });
9332
9333 /* optionalArrayOf checks */
9334 keys.forEach(function (k) {
9335 var name = 'optionalArrayOf' + _capitalize(k);
9336 if (ndebug) {
9337 out[name] = noop;
9338 return;
9339 }
9340 var type = types[k];
9341 var expected = '[' + k + ']';
9342 out[name] = function (arg, msg) {
9343 if (arg === undefined || arg === null) {
9344 return;
9345 }
9346 if (!Array.isArray(arg)) {
9347 _toss(msg, expected, type.operator, arg, type.actual);
9348 }
9349 var i;
9350 for (i = 0; i < arg.length; i++) {
9351 if (!type.check(arg[i])) {
9352 _toss(msg, expected, type.operator, arg, type.actual);
9353 }
9354 }
9355 };
9356 });
9357
9358 /* re-export built-in assertions */
9359 Object.keys(assert).forEach(function (k) {
9360 if (k === 'AssertionError') {
9361 out[k] = assert[k];
9362 return;
9363 }
9364 if (ndebug) {
9365 out[k] = noop;
9366 return;
9367 }
9368 out[k] = assert[k];
9369 });
9370
9371 /* export ourselves (for unit tests _only_) */
9372 out._setExports = _setExports;
9373
9374 return out;
9375}
9376
9377module.exports = _setExports(process.env.NODE_NDEBUG);
9378
9379}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
9380},{"../is-buffer/index.js":211,"_process":265,"assert":68,"stream":361,"util":397}],68:[function(require,module,exports){
9381(function (global){
9382'use strict';
9383
9384// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
9385// original notice:
9386
9387/*!
9388 * The buffer module from node.js, for the browser.
9389 *
9390 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
9391 * @license MIT
9392 */
9393function compare(a, b) {
9394 if (a === b) {
9395 return 0;
9396 }
9397
9398 var x = a.length;
9399 var y = b.length;
9400
9401 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
9402 if (a[i] !== b[i]) {
9403 x = a[i];
9404 y = b[i];
9405 break;
9406 }
9407 }
9408
9409 if (x < y) {
9410 return -1;
9411 }
9412 if (y < x) {
9413 return 1;
9414 }
9415 return 0;
9416}
9417function isBuffer(b) {
9418 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
9419 return global.Buffer.isBuffer(b);
9420 }
9421 return !!(b != null && b._isBuffer);
9422}
9423
9424// based on node assert, original notice:
9425
9426// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
9427//
9428// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
9429//
9430// Originally from narwhal.js (http://narwhaljs.org)
9431// Copyright (c) 2009 Thomas Robinson <280north.com>
9432//
9433// Permission is hereby granted, free of charge, to any person obtaining a copy
9434// of this software and associated documentation files (the 'Software'), to
9435// deal in the Software without restriction, including without limitation the
9436// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9437// sell copies of the Software, and to permit persons to whom the Software is
9438// furnished to do so, subject to the following conditions:
9439//
9440// The above copyright notice and this permission notice shall be included in
9441// all copies or substantial portions of the Software.
9442//
9443// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9444// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9445// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
9446// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
9447// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
9448// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9449
9450var util = require('util/');
9451var hasOwn = Object.prototype.hasOwnProperty;
9452var pSlice = Array.prototype.slice;
9453var functionsHaveNames = (function () {
9454 return function foo() {}.name === 'foo';
9455}());
9456function pToString (obj) {
9457 return Object.prototype.toString.call(obj);
9458}
9459function isView(arrbuf) {
9460 if (isBuffer(arrbuf)) {
9461 return false;
9462 }
9463 if (typeof global.ArrayBuffer !== 'function') {
9464 return false;
9465 }
9466 if (typeof ArrayBuffer.isView === 'function') {
9467 return ArrayBuffer.isView(arrbuf);
9468 }
9469 if (!arrbuf) {
9470 return false;
9471 }
9472 if (arrbuf instanceof DataView) {
9473 return true;
9474 }
9475 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
9476 return true;
9477 }
9478 return false;
9479}
9480// 1. The assert module provides functions that throw
9481// AssertionError's when particular conditions are not met. The
9482// assert module must conform to the following interface.
9483
9484var assert = module.exports = ok;
9485
9486// 2. The AssertionError is defined in assert.
9487// new assert.AssertionError({ message: message,
9488// actual: actual,
9489// expected: expected })
9490
9491var regex = /\s*function\s+([^\(\s]*)\s*/;
9492// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
9493function getName(func) {
9494 if (!util.isFunction(func)) {
9495 return;
9496 }
9497 if (functionsHaveNames) {
9498 return func.name;
9499 }
9500 var str = func.toString();
9501 var match = str.match(regex);
9502 return match && match[1];
9503}
9504assert.AssertionError = function AssertionError(options) {
9505 this.name = 'AssertionError';
9506 this.actual = options.actual;
9507 this.expected = options.expected;
9508 this.operator = options.operator;
9509 if (options.message) {
9510 this.message = options.message;
9511 this.generatedMessage = false;
9512 } else {
9513 this.message = getMessage(this);
9514 this.generatedMessage = true;
9515 }
9516 var stackStartFunction = options.stackStartFunction || fail;
9517 if (Error.captureStackTrace) {
9518 Error.captureStackTrace(this, stackStartFunction);
9519 } else {
9520 // non v8 browsers so we can have a stacktrace
9521 var err = new Error();
9522 if (err.stack) {
9523 var out = err.stack;
9524
9525 // try to strip useless frames
9526 var fn_name = getName(stackStartFunction);
9527 var idx = out.indexOf('\n' + fn_name);
9528 if (idx >= 0) {
9529 // once we have located the function frame
9530 // we need to strip out everything before it (and its line)
9531 var next_line = out.indexOf('\n', idx + 1);
9532 out = out.substring(next_line + 1);
9533 }
9534
9535 this.stack = out;
9536 }
9537 }
9538};
9539
9540// assert.AssertionError instanceof Error
9541util.inherits(assert.AssertionError, Error);
9542
9543function truncate(s, n) {
9544 if (typeof s === 'string') {
9545 return s.length < n ? s : s.slice(0, n);
9546 } else {
9547 return s;
9548 }
9549}
9550function inspect(something) {
9551 if (functionsHaveNames || !util.isFunction(something)) {
9552 return util.inspect(something);
9553 }
9554 var rawname = getName(something);
9555 var name = rawname ? ': ' + rawname : '';
9556 return '[Function' + name + ']';
9557}
9558function getMessage(self) {
9559 return truncate(inspect(self.actual), 128) + ' ' +
9560 self.operator + ' ' +
9561 truncate(inspect(self.expected), 128);
9562}
9563
9564// At present only the three keys mentioned above are used and
9565// understood by the spec. Implementations or sub modules can pass
9566// other keys to the AssertionError's constructor - they will be
9567// ignored.
9568
9569// 3. All of the following functions must throw an AssertionError
9570// when a corresponding condition is not met, with a message that
9571// may be undefined if not provided. All assertion methods provide
9572// both the actual and expected values to the assertion error for
9573// display purposes.
9574
9575function fail(actual, expected, message, operator, stackStartFunction) {
9576 throw new assert.AssertionError({
9577 message: message,
9578 actual: actual,
9579 expected: expected,
9580 operator: operator,
9581 stackStartFunction: stackStartFunction
9582 });
9583}
9584
9585// EXTENSION! allows for well behaved errors defined elsewhere.
9586assert.fail = fail;
9587
9588// 4. Pure assertion tests whether a value is truthy, as determined
9589// by !!guard.
9590// assert.ok(guard, message_opt);
9591// This statement is equivalent to assert.equal(true, !!guard,
9592// message_opt);. To test strictly for the value true, use
9593// assert.strictEqual(true, guard, message_opt);.
9594
9595function ok(value, message) {
9596 if (!value) fail(value, true, message, '==', assert.ok);
9597}
9598assert.ok = ok;
9599
9600// 5. The equality assertion tests shallow, coercive equality with
9601// ==.
9602// assert.equal(actual, expected, message_opt);
9603
9604assert.equal = function equal(actual, expected, message) {
9605 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
9606};
9607
9608// 6. The non-equality assertion tests for whether two objects are not equal
9609// with != assert.notEqual(actual, expected, message_opt);
9610
9611assert.notEqual = function notEqual(actual, expected, message) {
9612 if (actual == expected) {
9613 fail(actual, expected, message, '!=', assert.notEqual);
9614 }
9615};
9616
9617// 7. The equivalence assertion tests a deep equality relation.
9618// assert.deepEqual(actual, expected, message_opt);
9619
9620assert.deepEqual = function deepEqual(actual, expected, message) {
9621 if (!_deepEqual(actual, expected, false)) {
9622 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
9623 }
9624};
9625
9626assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
9627 if (!_deepEqual(actual, expected, true)) {
9628 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
9629 }
9630};
9631
9632function _deepEqual(actual, expected, strict, memos) {
9633 // 7.1. All identical values are equivalent, as determined by ===.
9634 if (actual === expected) {
9635 return true;
9636 } else if (isBuffer(actual) && isBuffer(expected)) {
9637 return compare(actual, expected) === 0;
9638
9639 // 7.2. If the expected value is a Date object, the actual value is
9640 // equivalent if it is also a Date object that refers to the same time.
9641 } else if (util.isDate(actual) && util.isDate(expected)) {
9642 return actual.getTime() === expected.getTime();
9643
9644 // 7.3 If the expected value is a RegExp object, the actual value is
9645 // equivalent if it is also a RegExp object with the same source and
9646 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
9647 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
9648 return actual.source === expected.source &&
9649 actual.global === expected.global &&
9650 actual.multiline === expected.multiline &&
9651 actual.lastIndex === expected.lastIndex &&
9652 actual.ignoreCase === expected.ignoreCase;
9653
9654 // 7.4. Other pairs that do not both pass typeof value == 'object',
9655 // equivalence is determined by ==.
9656 } else if ((actual === null || typeof actual !== 'object') &&
9657 (expected === null || typeof expected !== 'object')) {
9658 return strict ? actual === expected : actual == expected;
9659
9660 // If both values are instances of typed arrays, wrap their underlying
9661 // ArrayBuffers in a Buffer each to increase performance
9662 // This optimization requires the arrays to have the same type as checked by
9663 // Object.prototype.toString (aka pToString). Never perform binary
9664 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
9665 // bit patterns are not identical.
9666 } else if (isView(actual) && isView(expected) &&
9667 pToString(actual) === pToString(expected) &&
9668 !(actual instanceof Float32Array ||
9669 actual instanceof Float64Array)) {
9670 return compare(new Uint8Array(actual.buffer),
9671 new Uint8Array(expected.buffer)) === 0;
9672
9673 // 7.5 For all other Object pairs, including Array objects, equivalence is
9674 // determined by having the same number of owned properties (as verified
9675 // with Object.prototype.hasOwnProperty.call), the same set of keys
9676 // (although not necessarily the same order), equivalent values for every
9677 // corresponding key, and an identical 'prototype' property. Note: this
9678 // accounts for both named and indexed properties on Arrays.
9679 } else if (isBuffer(actual) !== isBuffer(expected)) {
9680 return false;
9681 } else {
9682 memos = memos || {actual: [], expected: []};
9683
9684 var actualIndex = memos.actual.indexOf(actual);
9685 if (actualIndex !== -1) {
9686 if (actualIndex === memos.expected.indexOf(expected)) {
9687 return true;
9688 }
9689 }
9690
9691 memos.actual.push(actual);
9692 memos.expected.push(expected);
9693
9694 return objEquiv(actual, expected, strict, memos);
9695 }
9696}
9697
9698function isArguments(object) {
9699 return Object.prototype.toString.call(object) == '[object Arguments]';
9700}
9701
9702function objEquiv(a, b, strict, actualVisitedObjects) {
9703 if (a === null || a === undefined || b === null || b === undefined)
9704 return false;
9705 // if one is a primitive, the other must be same
9706 if (util.isPrimitive(a) || util.isPrimitive(b))
9707 return a === b;
9708 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
9709 return false;
9710 var aIsArgs = isArguments(a);
9711 var bIsArgs = isArguments(b);
9712 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
9713 return false;
9714 if (aIsArgs) {
9715 a = pSlice.call(a);
9716 b = pSlice.call(b);
9717 return _deepEqual(a, b, strict);
9718 }
9719 var ka = objectKeys(a);
9720 var kb = objectKeys(b);
9721 var key, i;
9722 // having the same number of owned properties (keys incorporates
9723 // hasOwnProperty)
9724 if (ka.length !== kb.length)
9725 return false;
9726 //the same set of keys (although not necessarily the same order),
9727 ka.sort();
9728 kb.sort();
9729 //~~~cheap key test
9730 for (i = ka.length - 1; i >= 0; i--) {
9731 if (ka[i] !== kb[i])
9732 return false;
9733 }
9734 //equivalent values for every corresponding key, and
9735 //~~~possibly expensive deep test
9736 for (i = ka.length - 1; i >= 0; i--) {
9737 key = ka[i];
9738 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
9739 return false;
9740 }
9741 return true;
9742}
9743
9744// 8. The non-equivalence assertion tests for any deep inequality.
9745// assert.notDeepEqual(actual, expected, message_opt);
9746
9747assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
9748 if (_deepEqual(actual, expected, false)) {
9749 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
9750 }
9751};
9752
9753assert.notDeepStrictEqual = notDeepStrictEqual;
9754function notDeepStrictEqual(actual, expected, message) {
9755 if (_deepEqual(actual, expected, true)) {
9756 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
9757 }
9758}
9759
9760
9761// 9. The strict equality assertion tests strict equality, as determined by ===.
9762// assert.strictEqual(actual, expected, message_opt);
9763
9764assert.strictEqual = function strictEqual(actual, expected, message) {
9765 if (actual !== expected) {
9766 fail(actual, expected, message, '===', assert.strictEqual);
9767 }
9768};
9769
9770// 10. The strict non-equality assertion tests for strict inequality, as
9771// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
9772
9773assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
9774 if (actual === expected) {
9775 fail(actual, expected, message, '!==', assert.notStrictEqual);
9776 }
9777};
9778
9779function expectedException(actual, expected) {
9780 if (!actual || !expected) {
9781 return false;
9782 }
9783
9784 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
9785 return expected.test(actual);
9786 }
9787
9788 try {
9789 if (actual instanceof expected) {
9790 return true;
9791 }
9792 } catch (e) {
9793 // Ignore. The instanceof check doesn't work for arrow functions.
9794 }
9795
9796 if (Error.isPrototypeOf(expected)) {
9797 return false;
9798 }
9799
9800 return expected.call({}, actual) === true;
9801}
9802
9803function _tryBlock(block) {
9804 var error;
9805 try {
9806 block();
9807 } catch (e) {
9808 error = e;
9809 }
9810 return error;
9811}
9812
9813function _throws(shouldThrow, block, expected, message) {
9814 var actual;
9815
9816 if (typeof block !== 'function') {
9817 throw new TypeError('"block" argument must be a function');
9818 }
9819
9820 if (typeof expected === 'string') {
9821 message = expected;
9822 expected = null;
9823 }
9824
9825 actual = _tryBlock(block);
9826
9827 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
9828 (message ? ' ' + message : '.');
9829
9830 if (shouldThrow && !actual) {
9831 fail(actual, expected, 'Missing expected exception' + message);
9832 }
9833
9834 var userProvidedMessage = typeof message === 'string';
9835 var isUnwantedException = !shouldThrow && util.isError(actual);
9836 var isUnexpectedException = !shouldThrow && actual && !expected;
9837
9838 if ((isUnwantedException &&
9839 userProvidedMessage &&
9840 expectedException(actual, expected)) ||
9841 isUnexpectedException) {
9842 fail(actual, expected, 'Got unwanted exception' + message);
9843 }
9844
9845 if ((shouldThrow && actual && expected &&
9846 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
9847 throw actual;
9848 }
9849}
9850
9851// 11. Expected to throw an error:
9852// assert.throws(block, Error_opt, message_opt);
9853
9854assert.throws = function(block, /*optional*/error, /*optional*/message) {
9855 _throws(true, block, error, message);
9856};
9857
9858// EXTENSION! This is annoying to write outside this module.
9859assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
9860 _throws(false, block, error, message);
9861};
9862
9863assert.ifError = function(err) { if (err) throw err; };
9864
9865var objectKeys = Object.keys || function (obj) {
9866 var keys = [];
9867 for (var key in obj) {
9868 if (hasOwn.call(obj, key)) keys.push(key);
9869 }
9870 return keys;
9871};
9872
9873}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
9874},{"util/":71}],69:[function(require,module,exports){
9875if (typeof Object.create === 'function') {
9876 // implementation from standard node.js 'util' module
9877 module.exports = function inherits(ctor, superCtor) {
9878 ctor.super_ = superCtor
9879 ctor.prototype = Object.create(superCtor.prototype, {
9880 constructor: {
9881 value: ctor,
9882 enumerable: false,
9883 writable: true,
9884 configurable: true
9885 }
9886 });
9887 };
9888} else {
9889 // old school shim for old browsers
9890 module.exports = function inherits(ctor, superCtor) {
9891 ctor.super_ = superCtor
9892 var TempCtor = function () {}
9893 TempCtor.prototype = superCtor.prototype
9894 ctor.prototype = new TempCtor()
9895 ctor.prototype.constructor = ctor
9896 }
9897}
9898
9899},{}],70:[function(require,module,exports){
9900module.exports = function isBuffer(arg) {
9901 return arg && typeof arg === 'object'
9902 && typeof arg.copy === 'function'
9903 && typeof arg.fill === 'function'
9904 && typeof arg.readUInt8 === 'function';
9905}
9906},{}],71:[function(require,module,exports){
9907(function (process,global){
9908// Copyright Joyent, Inc. and other Node contributors.
9909//
9910// Permission is hereby granted, free of charge, to any person obtaining a
9911// copy of this software and associated documentation files (the
9912// "Software"), to deal in the Software without restriction, including
9913// without limitation the rights to use, copy, modify, merge, publish,
9914// distribute, sublicense, and/or sell copies of the Software, and to permit
9915// persons to whom the Software is furnished to do so, subject to the
9916// following conditions:
9917//
9918// The above copyright notice and this permission notice shall be included
9919// in all copies or substantial portions of the Software.
9920//
9921// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
9922// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
9923// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
9924// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
9925// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
9926// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
9927// USE OR OTHER DEALINGS IN THE SOFTWARE.
9928
9929var formatRegExp = /%[sdj%]/g;
9930exports.format = function(f) {
9931 if (!isString(f)) {
9932 var objects = [];
9933 for (var i = 0; i < arguments.length; i++) {
9934 objects.push(inspect(arguments[i]));
9935 }
9936 return objects.join(' ');
9937 }
9938
9939 var i = 1;
9940 var args = arguments;
9941 var len = args.length;
9942 var str = String(f).replace(formatRegExp, function(x) {
9943 if (x === '%%') return '%';
9944 if (i >= len) return x;
9945 switch (x) {
9946 case '%s': return String(args[i++]);
9947 case '%d': return Number(args[i++]);
9948 case '%j':
9949 try {
9950 return JSON.stringify(args[i++]);
9951 } catch (_) {
9952 return '[Circular]';
9953 }
9954 default:
9955 return x;
9956 }
9957 });
9958 for (var x = args[i]; i < len; x = args[++i]) {
9959 if (isNull(x) || !isObject(x)) {
9960 str += ' ' + x;
9961 } else {
9962 str += ' ' + inspect(x);
9963 }
9964 }
9965 return str;
9966};
9967
9968
9969// Mark that a method should not be used.
9970// Returns a modified function which warns once by default.
9971// If --no-deprecation is set, then it is a no-op.
9972exports.deprecate = function(fn, msg) {
9973 // Allow for deprecating things in the process of starting up.
9974 if (isUndefined(global.process)) {
9975 return function() {
9976 return exports.deprecate(fn, msg).apply(this, arguments);
9977 };
9978 }
9979
9980 if (process.noDeprecation === true) {
9981 return fn;
9982 }
9983
9984 var warned = false;
9985 function deprecated() {
9986 if (!warned) {
9987 if (process.throwDeprecation) {
9988 throw new Error(msg);
9989 } else if (process.traceDeprecation) {
9990 console.trace(msg);
9991 } else {
9992 console.error(msg);
9993 }
9994 warned = true;
9995 }
9996 return fn.apply(this, arguments);
9997 }
9998
9999 return deprecated;
10000};
10001
10002
10003var debugs = {};
10004var debugEnviron;
10005exports.debuglog = function(set) {
10006 if (isUndefined(debugEnviron))
10007 debugEnviron = process.env.NODE_DEBUG || '';
10008 set = set.toUpperCase();
10009 if (!debugs[set]) {
10010 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
10011 var pid = process.pid;
10012 debugs[set] = function() {
10013 var msg = exports.format.apply(exports, arguments);
10014 console.error('%s %d: %s', set, pid, msg);
10015 };
10016 } else {
10017 debugs[set] = function() {};
10018 }
10019 }
10020 return debugs[set];
10021};
10022
10023
10024/**
10025 * Echos the value of a value. Trys to print the value out
10026 * in the best way possible given the different types.
10027 *
10028 * @param {Object} obj The object to print out.
10029 * @param {Object} opts Optional options object that alters the output.
10030 */
10031/* legacy: obj, showHidden, depth, colors*/
10032function inspect(obj, opts) {
10033 // default options
10034 var ctx = {
10035 seen: [],
10036 stylize: stylizeNoColor
10037 };
10038 // legacy...
10039 if (arguments.length >= 3) ctx.depth = arguments[2];
10040 if (arguments.length >= 4) ctx.colors = arguments[3];
10041 if (isBoolean(opts)) {
10042 // legacy...
10043 ctx.showHidden = opts;
10044 } else if (opts) {
10045 // got an "options" object
10046 exports._extend(ctx, opts);
10047 }
10048 // set default options
10049 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
10050 if (isUndefined(ctx.depth)) ctx.depth = 2;
10051 if (isUndefined(ctx.colors)) ctx.colors = false;
10052 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
10053 if (ctx.colors) ctx.stylize = stylizeWithColor;
10054 return formatValue(ctx, obj, ctx.depth);
10055}
10056exports.inspect = inspect;
10057
10058
10059// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
10060inspect.colors = {
10061 'bold' : [1, 22],
10062 'italic' : [3, 23],
10063 'underline' : [4, 24],
10064 'inverse' : [7, 27],
10065 'white' : [37, 39],
10066 'grey' : [90, 39],
10067 'black' : [30, 39],
10068 'blue' : [34, 39],
10069 'cyan' : [36, 39],
10070 'green' : [32, 39],
10071 'magenta' : [35, 39],
10072 'red' : [31, 39],
10073 'yellow' : [33, 39]
10074};
10075
10076// Don't use 'blue' not visible on cmd.exe
10077inspect.styles = {
10078 'special': 'cyan',
10079 'number': 'yellow',
10080 'boolean': 'yellow',
10081 'undefined': 'grey',
10082 'null': 'bold',
10083 'string': 'green',
10084 'date': 'magenta',
10085 // "name": intentionally not styling
10086 'regexp': 'red'
10087};
10088
10089
10090function stylizeWithColor(str, styleType) {
10091 var style = inspect.styles[styleType];
10092
10093 if (style) {
10094 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
10095 '\u001b[' + inspect.colors[style][1] + 'm';
10096 } else {
10097 return str;
10098 }
10099}
10100
10101
10102function stylizeNoColor(str, styleType) {
10103 return str;
10104}
10105
10106
10107function arrayToHash(array) {
10108 var hash = {};
10109
10110 array.forEach(function(val, idx) {
10111 hash[val] = true;
10112 });
10113
10114 return hash;
10115}
10116
10117
10118function formatValue(ctx, value, recurseTimes) {
10119 // Provide a hook for user-specified inspect functions.
10120 // Check that value is an object with an inspect function on it
10121 if (ctx.customInspect &&
10122 value &&
10123 isFunction(value.inspect) &&
10124 // Filter out the util module, it's inspect function is special
10125 value.inspect !== exports.inspect &&
10126 // Also filter out any prototype objects using the circular check.
10127 !(value.constructor && value.constructor.prototype === value)) {
10128 var ret = value.inspect(recurseTimes, ctx);
10129 if (!isString(ret)) {
10130 ret = formatValue(ctx, ret, recurseTimes);
10131 }
10132 return ret;
10133 }
10134
10135 // Primitive types cannot have properties
10136 var primitive = formatPrimitive(ctx, value);
10137 if (primitive) {
10138 return primitive;
10139 }
10140
10141 // Look up the keys of the object.
10142 var keys = Object.keys(value);
10143 var visibleKeys = arrayToHash(keys);
10144
10145 if (ctx.showHidden) {
10146 keys = Object.getOwnPropertyNames(value);
10147 }
10148
10149 // IE doesn't make error fields non-enumerable
10150 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
10151 if (isError(value)
10152 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
10153 return formatError(value);
10154 }
10155
10156 // Some type of object without properties can be shortcutted.
10157 if (keys.length === 0) {
10158 if (isFunction(value)) {
10159 var name = value.name ? ': ' + value.name : '';
10160 return ctx.stylize('[Function' + name + ']', 'special');
10161 }
10162 if (isRegExp(value)) {
10163 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
10164 }
10165 if (isDate(value)) {
10166 return ctx.stylize(Date.prototype.toString.call(value), 'date');
10167 }
10168 if (isError(value)) {
10169 return formatError(value);
10170 }
10171 }
10172
10173 var base = '', array = false, braces = ['{', '}'];
10174
10175 // Make Array say that they are Array
10176 if (isArray(value)) {
10177 array = true;
10178 braces = ['[', ']'];
10179 }
10180
10181 // Make functions say that they are functions
10182 if (isFunction(value)) {
10183 var n = value.name ? ': ' + value.name : '';
10184 base = ' [Function' + n + ']';
10185 }
10186
10187 // Make RegExps say that they are RegExps
10188 if (isRegExp(value)) {
10189 base = ' ' + RegExp.prototype.toString.call(value);
10190 }
10191
10192 // Make dates with properties first say the date
10193 if (isDate(value)) {
10194 base = ' ' + Date.prototype.toUTCString.call(value);
10195 }
10196
10197 // Make error with message first say the error
10198 if (isError(value)) {
10199 base = ' ' + formatError(value);
10200 }
10201
10202 if (keys.length === 0 && (!array || value.length == 0)) {
10203 return braces[0] + base + braces[1];
10204 }
10205
10206 if (recurseTimes < 0) {
10207 if (isRegExp(value)) {
10208 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
10209 } else {
10210 return ctx.stylize('[Object]', 'special');
10211 }
10212 }
10213
10214 ctx.seen.push(value);
10215
10216 var output;
10217 if (array) {
10218 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
10219 } else {
10220 output = keys.map(function(key) {
10221 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
10222 });
10223 }
10224
10225 ctx.seen.pop();
10226
10227 return reduceToSingleString(output, base, braces);
10228}
10229
10230
10231function formatPrimitive(ctx, value) {
10232 if (isUndefined(value))
10233 return ctx.stylize('undefined', 'undefined');
10234 if (isString(value)) {
10235 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
10236 .replace(/'/g, "\\'")
10237 .replace(/\\"/g, '"') + '\'';
10238 return ctx.stylize(simple, 'string');
10239 }
10240 if (isNumber(value))
10241 return ctx.stylize('' + value, 'number');
10242 if (isBoolean(value))
10243 return ctx.stylize('' + value, 'boolean');
10244 // For some reason typeof null is "object", so special case here.
10245 if (isNull(value))
10246 return ctx.stylize('null', 'null');
10247}
10248
10249
10250function formatError(value) {
10251 return '[' + Error.prototype.toString.call(value) + ']';
10252}
10253
10254
10255function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
10256 var output = [];
10257 for (var i = 0, l = value.length; i < l; ++i) {
10258 if (hasOwnProperty(value, String(i))) {
10259 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
10260 String(i), true));
10261 } else {
10262 output.push('');
10263 }
10264 }
10265 keys.forEach(function(key) {
10266 if (!key.match(/^\d+$/)) {
10267 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
10268 key, true));
10269 }
10270 });
10271 return output;
10272}
10273
10274
10275function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
10276 var name, str, desc;
10277 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
10278 if (desc.get) {
10279 if (desc.set) {
10280 str = ctx.stylize('[Getter/Setter]', 'special');
10281 } else {
10282 str = ctx.stylize('[Getter]', 'special');
10283 }
10284 } else {
10285 if (desc.set) {
10286 str = ctx.stylize('[Setter]', 'special');
10287 }
10288 }
10289 if (!hasOwnProperty(visibleKeys, key)) {
10290 name = '[' + key + ']';
10291 }
10292 if (!str) {
10293 if (ctx.seen.indexOf(desc.value) < 0) {
10294 if (isNull(recurseTimes)) {
10295 str = formatValue(ctx, desc.value, null);
10296 } else {
10297 str = formatValue(ctx, desc.value, recurseTimes - 1);
10298 }
10299 if (str.indexOf('\n') > -1) {
10300 if (array) {
10301 str = str.split('\n').map(function(line) {
10302 return ' ' + line;
10303 }).join('\n').substr(2);
10304 } else {
10305 str = '\n' + str.split('\n').map(function(line) {
10306 return ' ' + line;
10307 }).join('\n');
10308 }
10309 }
10310 } else {
10311 str = ctx.stylize('[Circular]', 'special');
10312 }
10313 }
10314 if (isUndefined(name)) {
10315 if (array && key.match(/^\d+$/)) {
10316 return str;
10317 }
10318 name = JSON.stringify('' + key);
10319 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
10320 name = name.substr(1, name.length - 2);
10321 name = ctx.stylize(name, 'name');
10322 } else {
10323 name = name.replace(/'/g, "\\'")
10324 .replace(/\\"/g, '"')
10325 .replace(/(^"|"$)/g, "'");
10326 name = ctx.stylize(name, 'string');
10327 }
10328 }
10329
10330 return name + ': ' + str;
10331}
10332
10333
10334function reduceToSingleString(output, base, braces) {
10335 var numLinesEst = 0;
10336 var length = output.reduce(function(prev, cur) {
10337 numLinesEst++;
10338 if (cur.indexOf('\n') >= 0) numLinesEst++;
10339 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
10340 }, 0);
10341
10342 if (length > 60) {
10343 return braces[0] +
10344 (base === '' ? '' : base + '\n ') +
10345 ' ' +
10346 output.join(',\n ') +
10347 ' ' +
10348 braces[1];
10349 }
10350
10351 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
10352}
10353
10354
10355// NOTE: These type checking functions intentionally don't use `instanceof`
10356// because it is fragile and can be easily faked with `Object.create()`.
10357function isArray(ar) {
10358 return Array.isArray(ar);
10359}
10360exports.isArray = isArray;
10361
10362function isBoolean(arg) {
10363 return typeof arg === 'boolean';
10364}
10365exports.isBoolean = isBoolean;
10366
10367function isNull(arg) {
10368 return arg === null;
10369}
10370exports.isNull = isNull;
10371
10372function isNullOrUndefined(arg) {
10373 return arg == null;
10374}
10375exports.isNullOrUndefined = isNullOrUndefined;
10376
10377function isNumber(arg) {
10378 return typeof arg === 'number';
10379}
10380exports.isNumber = isNumber;
10381
10382function isString(arg) {
10383 return typeof arg === 'string';
10384}
10385exports.isString = isString;
10386
10387function isSymbol(arg) {
10388 return typeof arg === 'symbol';
10389}
10390exports.isSymbol = isSymbol;
10391
10392function isUndefined(arg) {
10393 return arg === void 0;
10394}
10395exports.isUndefined = isUndefined;
10396
10397function isRegExp(re) {
10398 return isObject(re) && objectToString(re) === '[object RegExp]';
10399}
10400exports.isRegExp = isRegExp;
10401
10402function isObject(arg) {
10403 return typeof arg === 'object' && arg !== null;
10404}
10405exports.isObject = isObject;
10406
10407function isDate(d) {
10408 return isObject(d) && objectToString(d) === '[object Date]';
10409}
10410exports.isDate = isDate;
10411
10412function isError(e) {
10413 return isObject(e) &&
10414 (objectToString(e) === '[object Error]' || e instanceof Error);
10415}
10416exports.isError = isError;
10417
10418function isFunction(arg) {
10419 return typeof arg === 'function';
10420}
10421exports.isFunction = isFunction;
10422
10423function isPrimitive(arg) {
10424 return arg === null ||
10425 typeof arg === 'boolean' ||
10426 typeof arg === 'number' ||
10427 typeof arg === 'string' ||
10428 typeof arg === 'symbol' || // ES6 symbol
10429 typeof arg === 'undefined';
10430}
10431exports.isPrimitive = isPrimitive;
10432
10433exports.isBuffer = require('./support/isBuffer');
10434
10435function objectToString(o) {
10436 return Object.prototype.toString.call(o);
10437}
10438
10439
10440function pad(n) {
10441 return n < 10 ? '0' + n.toString(10) : n.toString(10);
10442}
10443
10444
10445var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
10446 'Oct', 'Nov', 'Dec'];
10447
10448// 26 Feb 16:19:34
10449function timestamp() {
10450 var d = new Date();
10451 var time = [pad(d.getHours()),
10452 pad(d.getMinutes()),
10453 pad(d.getSeconds())].join(':');
10454 return [d.getDate(), months[d.getMonth()], time].join(' ');
10455}
10456
10457
10458// log is just a thin wrapper to console.log that prepends a timestamp
10459exports.log = function() {
10460 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
10461};
10462
10463
10464/**
10465 * Inherit the prototype methods from one constructor into another.
10466 *
10467 * The Function.prototype.inherits from lang.js rewritten as a standalone
10468 * function (not on Function.prototype). NOTE: If this file is to be loaded
10469 * during bootstrapping this function needs to be rewritten using some native
10470 * functions as prototype setup using normal JavaScript does not work as
10471 * expected during bootstrapping (see mirror.js in r114903).
10472 *
10473 * @param {function} ctor Constructor function which needs to inherit the
10474 * prototype.
10475 * @param {function} superCtor Constructor function to inherit prototype from.
10476 */
10477exports.inherits = require('inherits');
10478
10479exports._extend = function(origin, add) {
10480 // Don't do anything if add isn't an object
10481 if (!add || !isObject(add)) return origin;
10482
10483 var keys = Object.keys(add);
10484 var i = keys.length;
10485 while (i--) {
10486 origin[keys[i]] = add[keys[i]];
10487 }
10488 return origin;
10489};
10490
10491function hasOwnProperty(obj, prop) {
10492 return Object.prototype.hasOwnProperty.call(obj, prop);
10493}
10494
10495}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
10496},{"./support/isBuffer":70,"_process":265,"inherits":69}],72:[function(require,module,exports){
10497
10498/*!
10499 * Copyright 2010 LearnBoost <dev@learnboost.com>
10500 *
10501 * Licensed under the Apache License, Version 2.0 (the "License");
10502 * you may not use this file except in compliance with the License.
10503 * You may obtain a copy of the License at
10504 *
10505 * http://www.apache.org/licenses/LICENSE-2.0
10506 *
10507 * Unless required by applicable law or agreed to in writing, software
10508 * distributed under the License is distributed on an "AS IS" BASIS,
10509 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10510 * See the License for the specific language governing permissions and
10511 * limitations under the License.
10512 */
10513
10514/**
10515 * Module dependencies.
10516 */
10517
10518var crypto = require('crypto')
10519 , parse = require('url').parse
10520 ;
10521
10522/**
10523 * Valid keys.
10524 */
10525
10526var keys =
10527 [ 'acl'
10528 , 'location'
10529 , 'logging'
10530 , 'notification'
10531 , 'partNumber'
10532 , 'policy'
10533 , 'requestPayment'
10534 , 'torrent'
10535 , 'uploadId'
10536 , 'uploads'
10537 , 'versionId'
10538 , 'versioning'
10539 , 'versions'
10540 , 'website'
10541 ]
10542
10543/**
10544 * Return an "Authorization" header value with the given `options`
10545 * in the form of "AWS <key>:<signature>"
10546 *
10547 * @param {Object} options
10548 * @return {String}
10549 * @api private
10550 */
10551
10552function authorization (options) {
10553 return 'AWS ' + options.key + ':' + sign(options)
10554}
10555
10556module.exports = authorization
10557module.exports.authorization = authorization
10558
10559/**
10560 * Simple HMAC-SHA1 Wrapper
10561 *
10562 * @param {Object} options
10563 * @return {String}
10564 * @api private
10565 */
10566
10567function hmacSha1 (options) {
10568 return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
10569}
10570
10571module.exports.hmacSha1 = hmacSha1
10572
10573/**
10574 * Create a base64 sha1 HMAC for `options`.
10575 *
10576 * @param {Object} options
10577 * @return {String}
10578 * @api private
10579 */
10580
10581function sign (options) {
10582 options.message = stringToSign(options)
10583 return hmacSha1(options)
10584}
10585module.exports.sign = sign
10586
10587/**
10588 * Create a base64 sha1 HMAC for `options`.
10589 *
10590 * Specifically to be used with S3 presigned URLs
10591 *
10592 * @param {Object} options
10593 * @return {String}
10594 * @api private
10595 */
10596
10597function signQuery (options) {
10598 options.message = queryStringToSign(options)
10599 return hmacSha1(options)
10600}
10601module.exports.signQuery= signQuery
10602
10603/**
10604 * Return a string for sign() with the given `options`.
10605 *
10606 * Spec:
10607 *
10608 * <verb>\n
10609 * <md5>\n
10610 * <content-type>\n
10611 * <date>\n
10612 * [headers\n]
10613 * <resource>
10614 *
10615 * @param {Object} options
10616 * @return {String}
10617 * @api private
10618 */
10619
10620function stringToSign (options) {
10621 var headers = options.amazonHeaders || ''
10622 if (headers) headers += '\n'
10623 var r =
10624 [ options.verb
10625 , options.md5
10626 , options.contentType
10627 , options.date ? options.date.toUTCString() : ''
10628 , headers + options.resource
10629 ]
10630 return r.join('\n')
10631}
10632module.exports.stringToSign = stringToSign
10633
10634/**
10635 * Return a string for sign() with the given `options`, but is meant exclusively
10636 * for S3 presigned URLs
10637 *
10638 * Spec:
10639 *
10640 * <date>\n
10641 * <resource>
10642 *
10643 * @param {Object} options
10644 * @return {String}
10645 * @api private
10646 */
10647
10648function queryStringToSign (options){
10649 return 'GET\n\n\n' + options.date + '\n' + options.resource
10650}
10651module.exports.queryStringToSign = queryStringToSign
10652
10653/**
10654 * Perform the following:
10655 *
10656 * - ignore non-amazon headers
10657 * - lowercase fields
10658 * - sort lexicographically
10659 * - trim whitespace between ":"
10660 * - join with newline
10661 *
10662 * @param {Object} headers
10663 * @return {String}
10664 * @api private
10665 */
10666
10667function canonicalizeHeaders (headers) {
10668 var buf = []
10669 , fields = Object.keys(headers)
10670 ;
10671 for (var i = 0, len = fields.length; i < len; ++i) {
10672 var field = fields[i]
10673 , val = headers[field]
10674 , field = field.toLowerCase()
10675 ;
10676 if (0 !== field.indexOf('x-amz')) continue
10677 buf.push(field + ':' + val)
10678 }
10679 return buf.sort().join('\n')
10680}
10681module.exports.canonicalizeHeaders = canonicalizeHeaders
10682
10683/**
10684 * Perform the following:
10685 *
10686 * - ignore non sub-resources
10687 * - sort lexicographically
10688 *
10689 * @param {String} resource
10690 * @return {String}
10691 * @api private
10692 */
10693
10694function canonicalizeResource (resource) {
10695 var url = parse(resource, true)
10696 , path = url.pathname
10697 , buf = []
10698 ;
10699
10700 Object.keys(url.query).forEach(function(key){
10701 if (!~keys.indexOf(key)) return
10702 var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
10703 buf.push(key + val)
10704 })
10705
10706 return path + (buf.length ? '?' + buf.sort().join('&') : '')
10707}
10708module.exports.canonicalizeResource = canonicalizeResource
10709
10710},{"crypto":126,"url":393}],73:[function(require,module,exports){
10711(function (process,Buffer){
10712var aws4 = exports,
10713 url = require('url'),
10714 querystring = require('querystring'),
10715 crypto = require('crypto'),
10716 lru = require('./lru'),
10717 credentialsCache = lru(1000)
10718
10719// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
10720
10721function hmac(key, string, encoding) {
10722 return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
10723}
10724
10725function hash(string, encoding) {
10726 return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
10727}
10728
10729// This function assumes the string has already been percent encoded
10730function encodeRfc3986(urlEncodedString) {
10731 return urlEncodedString.replace(/[!'()*]/g, function(c) {
10732 return '%' + c.charCodeAt(0).toString(16).toUpperCase()
10733 })
10734}
10735
10736// request: { path | body, [host], [method], [headers], [service], [region] }
10737// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
10738function RequestSigner(request, credentials) {
10739
10740 if (typeof request === 'string') request = url.parse(request)
10741
10742 var headers = request.headers = (request.headers || {}),
10743 hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
10744
10745 this.request = request
10746 this.credentials = credentials || this.defaultCredentials()
10747
10748 this.service = request.service || hostParts[0] || ''
10749 this.region = request.region || hostParts[1] || 'us-east-1'
10750
10751 // SES uses a different domain from the service name
10752 if (this.service === 'email') this.service = 'ses'
10753
10754 if (!request.method && request.body)
10755 request.method = 'POST'
10756
10757 if (!headers.Host && !headers.host) {
10758 headers.Host = request.hostname || request.host || this.createHost()
10759
10760 // If a port is specified explicitly, use it as is
10761 if (request.port)
10762 headers.Host += ':' + request.port
10763 }
10764 if (!request.hostname && !request.host)
10765 request.hostname = headers.Host || headers.host
10766
10767 this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
10768}
10769
10770RequestSigner.prototype.matchHost = function(host) {
10771 var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)
10772 var hostParts = (match || []).slice(1, 3)
10773
10774 // ES's hostParts are sometimes the other way round, if the value that is expected
10775 // to be region equals ‘es’ switch them back
10776 // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
10777 if (hostParts[1] === 'es')
10778 hostParts = hostParts.reverse()
10779
10780 return hostParts
10781}
10782
10783// http://docs.aws.amazon.com/general/latest/gr/rande.html
10784RequestSigner.prototype.isSingleRegion = function() {
10785 // Special case for S3 and SimpleDB in us-east-1
10786 if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
10787
10788 return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
10789 .indexOf(this.service) >= 0
10790}
10791
10792RequestSigner.prototype.createHost = function() {
10793 var region = this.isSingleRegion() ? '' :
10794 (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
10795 service = this.service === 'ses' ? 'email' : this.service
10796 return service + region + '.amazonaws.com'
10797}
10798
10799RequestSigner.prototype.prepareRequest = function() {
10800 this.parsePath()
10801
10802 var request = this.request, headers = request.headers, query
10803
10804 if (request.signQuery) {
10805
10806 this.parsedPath.query = query = this.parsedPath.query || {}
10807
10808 if (this.credentials.sessionToken)
10809 query['X-Amz-Security-Token'] = this.credentials.sessionToken
10810
10811 if (this.service === 's3' && !query['X-Amz-Expires'])
10812 query['X-Amz-Expires'] = 86400
10813
10814 if (query['X-Amz-Date'])
10815 this.datetime = query['X-Amz-Date']
10816 else
10817 query['X-Amz-Date'] = this.getDateTime()
10818
10819 query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
10820 query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
10821 query['X-Amz-SignedHeaders'] = this.signedHeaders()
10822
10823 } else {
10824
10825 if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
10826 if (request.body && !headers['Content-Type'] && !headers['content-type'])
10827 headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
10828
10829 if (request.body && !headers['Content-Length'] && !headers['content-length'])
10830 headers['Content-Length'] = Buffer.byteLength(request.body)
10831
10832 if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
10833 headers['X-Amz-Security-Token'] = this.credentials.sessionToken
10834
10835 if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
10836 headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
10837
10838 if (headers['X-Amz-Date'] || headers['x-amz-date'])
10839 this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
10840 else
10841 headers['X-Amz-Date'] = this.getDateTime()
10842 }
10843
10844 delete headers.Authorization
10845 delete headers.authorization
10846 }
10847}
10848
10849RequestSigner.prototype.sign = function() {
10850 if (!this.parsedPath) this.prepareRequest()
10851
10852 if (this.request.signQuery) {
10853 this.parsedPath.query['X-Amz-Signature'] = this.signature()
10854 } else {
10855 this.request.headers.Authorization = this.authHeader()
10856 }
10857
10858 this.request.path = this.formatPath()
10859
10860 return this.request
10861}
10862
10863RequestSigner.prototype.getDateTime = function() {
10864 if (!this.datetime) {
10865 var headers = this.request.headers,
10866 date = new Date(headers.Date || headers.date || new Date)
10867
10868 this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
10869
10870 // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
10871 if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
10872 }
10873 return this.datetime
10874}
10875
10876RequestSigner.prototype.getDate = function() {
10877 return this.getDateTime().substr(0, 8)
10878}
10879
10880RequestSigner.prototype.authHeader = function() {
10881 return [
10882 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
10883 'SignedHeaders=' + this.signedHeaders(),
10884 'Signature=' + this.signature(),
10885 ].join(', ')
10886}
10887
10888RequestSigner.prototype.signature = function() {
10889 var date = this.getDate(),
10890 cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
10891 kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
10892 if (!kCredentials) {
10893 kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
10894 kRegion = hmac(kDate, this.region)
10895 kService = hmac(kRegion, this.service)
10896 kCredentials = hmac(kService, 'aws4_request')
10897 credentialsCache.set(cacheKey, kCredentials)
10898 }
10899 return hmac(kCredentials, this.stringToSign(), 'hex')
10900}
10901
10902RequestSigner.prototype.stringToSign = function() {
10903 return [
10904 'AWS4-HMAC-SHA256',
10905 this.getDateTime(),
10906 this.credentialString(),
10907 hash(this.canonicalString(), 'hex'),
10908 ].join('\n')
10909}
10910
10911RequestSigner.prototype.canonicalString = function() {
10912 if (!this.parsedPath) this.prepareRequest()
10913
10914 var pathStr = this.parsedPath.path,
10915 query = this.parsedPath.query,
10916 headers = this.request.headers,
10917 queryStr = '',
10918 normalizePath = this.service !== 's3',
10919 decodePath = this.service === 's3' || this.request.doNotEncodePath,
10920 decodeSlashesInPath = this.service === 's3',
10921 firstValOnly = this.service === 's3',
10922 bodyHash
10923
10924 if (this.service === 's3' && this.request.signQuery) {
10925 bodyHash = 'UNSIGNED-PAYLOAD'
10926 } else if (this.isCodeCommitGit) {
10927 bodyHash = ''
10928 } else {
10929 bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
10930 hash(this.request.body || '', 'hex')
10931 }
10932
10933 if (query) {
10934 queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
10935 if (!key) return obj
10936 obj[key] = !Array.isArray(query[key]) ? query[key] :
10937 (firstValOnly ? query[key][0] : query[key].slice().sort())
10938 return obj
10939 }, {})))
10940 }
10941 if (pathStr !== '/') {
10942 if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
10943 pathStr = pathStr.split('/').reduce(function(path, piece) {
10944 if (normalizePath && piece === '..') {
10945 path.pop()
10946 } else if (!normalizePath || piece !== '.') {
10947 if (decodePath) piece = decodeURIComponent(piece)
10948 path.push(encodeRfc3986(encodeURIComponent(piece)))
10949 }
10950 return path
10951 }, []).join('/')
10952 if (pathStr[0] !== '/') pathStr = '/' + pathStr
10953 if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
10954 }
10955
10956 return [
10957 this.request.method || 'GET',
10958 pathStr,
10959 queryStr,
10960 this.canonicalHeaders() + '\n',
10961 this.signedHeaders(),
10962 bodyHash,
10963 ].join('\n')
10964}
10965
10966RequestSigner.prototype.canonicalHeaders = function() {
10967 var headers = this.request.headers
10968 function trimAll(header) {
10969 return header.toString().trim().replace(/\s+/g, ' ')
10970 }
10971 return Object.keys(headers)
10972 .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
10973 .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
10974 .join('\n')
10975}
10976
10977RequestSigner.prototype.signedHeaders = function() {
10978 return Object.keys(this.request.headers)
10979 .map(function(key) { return key.toLowerCase() })
10980 .sort()
10981 .join(';')
10982}
10983
10984RequestSigner.prototype.credentialString = function() {
10985 return [
10986 this.getDate(),
10987 this.region,
10988 this.service,
10989 'aws4_request',
10990 ].join('/')
10991}
10992
10993RequestSigner.prototype.defaultCredentials = function() {
10994 var env = process.env
10995 return {
10996 accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
10997 secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
10998 sessionToken: env.AWS_SESSION_TOKEN,
10999 }
11000}
11001
11002RequestSigner.prototype.parsePath = function() {
11003 var path = this.request.path || '/',
11004 queryIx = path.indexOf('?'),
11005 query = null
11006
11007 if (queryIx >= 0) {
11008 query = querystring.parse(path.slice(queryIx + 1))
11009 path = path.slice(0, queryIx)
11010 }
11011
11012 // S3 doesn't always encode characters > 127 correctly and
11013 // all services don't encode characters > 255 correctly
11014 // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
11015 if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
11016 path = path.split('/').map(function(piece) {
11017 return encodeURIComponent(decodeURIComponent(piece))
11018 }).join('/')
11019 }
11020
11021 this.parsedPath = {
11022 path: path,
11023 query: query,
11024 }
11025}
11026
11027RequestSigner.prototype.formatPath = function() {
11028 var path = this.parsedPath.path,
11029 query = this.parsedPath.query
11030
11031 if (!query) return path
11032
11033 // Services don't support empty query string keys
11034 if (query[''] != null) delete query['']
11035
11036 return path + '?' + encodeRfc3986(querystring.stringify(query))
11037}
11038
11039aws4.RequestSigner = RequestSigner
11040
11041aws4.sign = function(request, credentials) {
11042 return new RequestSigner(request, credentials).sign()
11043}
11044
11045}).call(this,require('_process'),require("buffer").Buffer)
11046},{"./lru":74,"_process":265,"buffer":114,"crypto":126,"querystring":277,"url":393}],74:[function(require,module,exports){
11047module.exports = function(size) {
11048 return new LruCache(size)
11049}
11050
11051function LruCache(size) {
11052 this.capacity = size | 0
11053 this.map = Object.create(null)
11054 this.list = new DoublyLinkedList()
11055}
11056
11057LruCache.prototype.get = function(key) {
11058 var node = this.map[key]
11059 if (node == null) return undefined
11060 this.used(node)
11061 return node.val
11062}
11063
11064LruCache.prototype.set = function(key, val) {
11065 var node = this.map[key]
11066 if (node != null) {
11067 node.val = val
11068 } else {
11069 if (!this.capacity) this.prune()
11070 if (!this.capacity) return false
11071 node = new DoublyLinkedNode(key, val)
11072 this.map[key] = node
11073 this.capacity--
11074 }
11075 this.used(node)
11076 return true
11077}
11078
11079LruCache.prototype.used = function(node) {
11080 this.list.moveToFront(node)
11081}
11082
11083LruCache.prototype.prune = function() {
11084 var node = this.list.pop()
11085 if (node != null) {
11086 delete this.map[node.key]
11087 this.capacity++
11088 }
11089}
11090
11091
11092function DoublyLinkedList() {
11093 this.firstNode = null
11094 this.lastNode = null
11095}
11096
11097DoublyLinkedList.prototype.moveToFront = function(node) {
11098 if (this.firstNode == node) return
11099
11100 this.remove(node)
11101
11102 if (this.firstNode == null) {
11103 this.firstNode = node
11104 this.lastNode = node
11105 node.prev = null
11106 node.next = null
11107 } else {
11108 node.prev = null
11109 node.next = this.firstNode
11110 node.next.prev = node
11111 this.firstNode = node
11112 }
11113}
11114
11115DoublyLinkedList.prototype.pop = function() {
11116 var lastNode = this.lastNode
11117 if (lastNode != null) {
11118 this.remove(lastNode)
11119 }
11120 return lastNode
11121}
11122
11123DoublyLinkedList.prototype.remove = function(node) {
11124 if (this.firstNode == node) {
11125 this.firstNode = node.next
11126 } else if (node.prev != null) {
11127 node.prev.next = node.next
11128 }
11129 if (this.lastNode == node) {
11130 this.lastNode = node.prev
11131 } else if (node.next != null) {
11132 node.next.prev = node.prev
11133 }
11134}
11135
11136
11137function DoublyLinkedNode(key, val) {
11138 this.key = key
11139 this.val = val
11140 this.prev = null
11141 this.next = null
11142}
11143
11144},{}],75:[function(require,module,exports){
11145'use strict'
11146
11147exports.byteLength = byteLength
11148exports.toByteArray = toByteArray
11149exports.fromByteArray = fromByteArray
11150
11151var lookup = []
11152var revLookup = []
11153var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
11154
11155var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
11156for (var i = 0, len = code.length; i < len; ++i) {
11157 lookup[i] = code[i]
11158 revLookup[code.charCodeAt(i)] = i
11159}
11160
11161// Support decoding URL-safe base64 strings, as Node.js does.
11162// See: https://en.wikipedia.org/wiki/Base64#URL_applications
11163revLookup['-'.charCodeAt(0)] = 62
11164revLookup['_'.charCodeAt(0)] = 63
11165
11166function getLens (b64) {
11167 var len = b64.length
11168
11169 if (len % 4 > 0) {
11170 throw new Error('Invalid string. Length must be a multiple of 4')
11171 }
11172
11173 // Trim off extra bytes after placeholder bytes are found
11174 // See: https://github.com/beatgammit/base64-js/issues/42
11175 var validLen = b64.indexOf('=')
11176 if (validLen === -1) validLen = len
11177
11178 var placeHoldersLen = validLen === len
11179 ? 0
11180 : 4 - (validLen % 4)
11181
11182 return [validLen, placeHoldersLen]
11183}
11184
11185// base64 is 4/3 + up to two characters of the original data
11186function byteLength (b64) {
11187 var lens = getLens(b64)
11188 var validLen = lens[0]
11189 var placeHoldersLen = lens[1]
11190 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
11191}
11192
11193function _byteLength (b64, validLen, placeHoldersLen) {
11194 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
11195}
11196
11197function toByteArray (b64) {
11198 var tmp
11199 var lens = getLens(b64)
11200 var validLen = lens[0]
11201 var placeHoldersLen = lens[1]
11202
11203 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
11204
11205 var curByte = 0
11206
11207 // if there are placeholders, only get up to the last complete 4 chars
11208 var len = placeHoldersLen > 0
11209 ? validLen - 4
11210 : validLen
11211
11212 var i
11213 for (i = 0; i < len; i += 4) {
11214 tmp =
11215 (revLookup[b64.charCodeAt(i)] << 18) |
11216 (revLookup[b64.charCodeAt(i + 1)] << 12) |
11217 (revLookup[b64.charCodeAt(i + 2)] << 6) |
11218 revLookup[b64.charCodeAt(i + 3)]
11219 arr[curByte++] = (tmp >> 16) & 0xFF
11220 arr[curByte++] = (tmp >> 8) & 0xFF
11221 arr[curByte++] = tmp & 0xFF
11222 }
11223
11224 if (placeHoldersLen === 2) {
11225 tmp =
11226 (revLookup[b64.charCodeAt(i)] << 2) |
11227 (revLookup[b64.charCodeAt(i + 1)] >> 4)
11228 arr[curByte++] = tmp & 0xFF
11229 }
11230
11231 if (placeHoldersLen === 1) {
11232 tmp =
11233 (revLookup[b64.charCodeAt(i)] << 10) |
11234 (revLookup[b64.charCodeAt(i + 1)] << 4) |
11235 (revLookup[b64.charCodeAt(i + 2)] >> 2)
11236 arr[curByte++] = (tmp >> 8) & 0xFF
11237 arr[curByte++] = tmp & 0xFF
11238 }
11239
11240 return arr
11241}
11242
11243function tripletToBase64 (num) {
11244 return lookup[num >> 18 & 0x3F] +
11245 lookup[num >> 12 & 0x3F] +
11246 lookup[num >> 6 & 0x3F] +
11247 lookup[num & 0x3F]
11248}
11249
11250function encodeChunk (uint8, start, end) {
11251 var tmp
11252 var output = []
11253 for (var i = start; i < end; i += 3) {
11254 tmp =
11255 ((uint8[i] << 16) & 0xFF0000) +
11256 ((uint8[i + 1] << 8) & 0xFF00) +
11257 (uint8[i + 2] & 0xFF)
11258 output.push(tripletToBase64(tmp))
11259 }
11260 return output.join('')
11261}
11262
11263function fromByteArray (uint8) {
11264 var tmp
11265 var len = uint8.length
11266 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
11267 var parts = []
11268 var maxChunkLength = 16383 // must be multiple of 3
11269
11270 // go through the array every three bytes, we'll deal with trailing stuff later
11271 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
11272 parts.push(encodeChunk(
11273 uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
11274 ))
11275 }
11276
11277 // pad the end with zeros, but make sure to not forget the extra bytes
11278 if (extraBytes === 1) {
11279 tmp = uint8[len - 1]
11280 parts.push(
11281 lookup[tmp >> 2] +
11282 lookup[(tmp << 4) & 0x3F] +
11283 '=='
11284 )
11285 } else if (extraBytes === 2) {
11286 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
11287 parts.push(
11288 lookup[tmp >> 10] +
11289 lookup[(tmp >> 4) & 0x3F] +
11290 lookup[(tmp << 2) & 0x3F] +
11291 '='
11292 )
11293 }
11294
11295 return parts.join('')
11296}
11297
11298},{}],76:[function(require,module,exports){
11299'use strict';
11300
11301var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;
11302
11303/*
11304 * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a
11305 * result, it retains the original copyright and license. The two files are
11306 * under slightly different (but compatible) licenses, and are here combined in
11307 * one file.
11308 *
11309 * Credit for the actual porting work goes to:
11310 * Devi Mandiri <me@devi.web.id>
11311 */
11312
11313/*
11314 * The Blowfish portions are under the following license:
11315 *
11316 * Blowfish block cipher for OpenBSD
11317 * Copyright 1997 Niels Provos <provos@physnet.uni-hamburg.de>
11318 * All rights reserved.
11319 *
11320 * Implementation advice by David Mazieres <dm@lcs.mit.edu>.
11321 *
11322 * Redistribution and use in source and binary forms, with or without
11323 * modification, are permitted provided that the following conditions
11324 * are met:
11325 * 1. Redistributions of source code must retain the above copyright
11326 * notice, this list of conditions and the following disclaimer.
11327 * 2. Redistributions in binary form must reproduce the above copyright
11328 * notice, this list of conditions and the following disclaimer in the
11329 * documentation and/or other materials provided with the distribution.
11330 * 3. The name of the author may not be used to endorse or promote products
11331 * derived from this software without specific prior written permission.
11332 *
11333 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
11334 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
11335 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
11336 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
11337 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
11338 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
11339 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11340 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
11341 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
11342 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
11343 */
11344
11345/*
11346 * The bcrypt_pbkdf portions are under the following license:
11347 *
11348 * Copyright (c) 2013 Ted Unangst <tedu@openbsd.org>
11349 *
11350 * Permission to use, copy, modify, and distribute this software for any
11351 * purpose with or without fee is hereby granted, provided that the above
11352 * copyright notice and this permission notice appear in all copies.
11353 *
11354 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11355 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11356 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11357 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11358 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
11359 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
11360 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
11361 */
11362
11363/*
11364 * Performance improvements (Javascript-specific):
11365 *
11366 * Copyright 2016, Joyent Inc
11367 * Author: Alex Wilson <alex.wilson@joyent.com>
11368 *
11369 * Permission to use, copy, modify, and distribute this software for any
11370 * purpose with or without fee is hereby granted, provided that the above
11371 * copyright notice and this permission notice appear in all copies.
11372 *
11373 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11374 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11375 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11376 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11377 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
11378 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
11379 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
11380 */
11381
11382// Ported from OpenBSD bcrypt_pbkdf.c v1.9
11383
11384var BLF_J = 0;
11385
11386var Blowfish = function() {
11387 this.S = [
11388 new Uint32Array([
11389 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
11390 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
11391 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
11392 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
11393 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
11394 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
11395 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
11396 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
11397 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
11398 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
11399 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
11400 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
11401 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
11402 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
11403 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
11404 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
11405 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
11406 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
11407 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
11408 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
11409 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
11410 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
11411 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
11412 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
11413 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
11414 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
11415 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
11416 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
11417 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
11418 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
11419 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
11420 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
11421 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
11422 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
11423 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
11424 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
11425 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
11426 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
11427 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
11428 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
11429 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
11430 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
11431 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
11432 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
11433 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
11434 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
11435 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
11436 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
11437 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
11438 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
11439 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
11440 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
11441 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
11442 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
11443 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
11444 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
11445 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
11446 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
11447 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
11448 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
11449 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
11450 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
11451 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
11452 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),
11453 new Uint32Array([
11454 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
11455 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
11456 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
11457 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
11458 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
11459 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
11460 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
11461 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
11462 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
11463 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
11464 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
11465 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
11466 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
11467 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
11468 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
11469 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
11470 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
11471 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
11472 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
11473 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
11474 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
11475 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
11476 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
11477 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
11478 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
11479 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
11480 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
11481 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
11482 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
11483 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
11484 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
11485 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
11486 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
11487 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
11488 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
11489 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
11490 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
11491 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
11492 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
11493 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
11494 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
11495 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
11496 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
11497 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
11498 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
11499 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
11500 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
11501 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
11502 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
11503 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
11504 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
11505 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
11506 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
11507 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
11508 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
11509 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
11510 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
11511 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
11512 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
11513 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
11514 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
11515 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
11516 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
11517 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),
11518 new Uint32Array([
11519 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
11520 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
11521 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
11522 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
11523 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
11524 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
11525 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
11526 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
11527 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
11528 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
11529 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
11530 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
11531 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
11532 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
11533 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
11534 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
11535 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
11536 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
11537 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
11538 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
11539 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
11540 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
11541 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
11542 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
11543 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
11544 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
11545 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
11546 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
11547 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
11548 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
11549 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
11550 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
11551 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
11552 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
11553 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
11554 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
11555 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
11556 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
11557 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
11558 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
11559 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
11560 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
11561 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
11562 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
11563 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
11564 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
11565 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
11566 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
11567 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
11568 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
11569 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
11570 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
11571 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
11572 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
11573 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
11574 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
11575 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
11576 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
11577 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
11578 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
11579 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
11580 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
11581 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
11582 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),
11583 new Uint32Array([
11584 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
11585 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
11586 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
11587 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
11588 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
11589 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
11590 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
11591 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
11592 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
11593 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
11594 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
11595 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
11596 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
11597 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
11598 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
11599 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
11600 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
11601 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
11602 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
11603 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
11604 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
11605 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
11606 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
11607 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
11608 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
11609 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
11610 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
11611 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
11612 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
11613 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
11614 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
11615 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
11616 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
11617 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
11618 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
11619 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
11620 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
11621 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
11622 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
11623 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
11624 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
11625 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
11626 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
11627 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
11628 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
11629 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
11630 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
11631 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
11632 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
11633 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
11634 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
11635 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
11636 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
11637 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
11638 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
11639 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
11640 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
11641 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
11642 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
11643 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
11644 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
11645 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
11646 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
11647 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])
11648 ];
11649 this.P = new Uint32Array([
11650 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
11651 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
11652 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
11653 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
11654 0x9216d5d9, 0x8979fb1b]);
11655};
11656
11657function F(S, x8, i) {
11658 return (((S[0][x8[i+3]] +
11659 S[1][x8[i+2]]) ^
11660 S[2][x8[i+1]]) +
11661 S[3][x8[i]]);
11662};
11663
11664Blowfish.prototype.encipher = function(x, x8) {
11665 if (x8 === undefined) {
11666 x8 = new Uint8Array(x.buffer);
11667 if (x.byteOffset !== 0)
11668 x8 = x8.subarray(x.byteOffset);
11669 }
11670 x[0] ^= this.P[0];
11671 for (var i = 1; i < 16; i += 2) {
11672 x[1] ^= F(this.S, x8, 0) ^ this.P[i];
11673 x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];
11674 }
11675 var t = x[0];
11676 x[0] = x[1] ^ this.P[17];
11677 x[1] = t;
11678};
11679
11680Blowfish.prototype.decipher = function(x) {
11681 var x8 = new Uint8Array(x.buffer);
11682 if (x.byteOffset !== 0)
11683 x8 = x8.subarray(x.byteOffset);
11684 x[0] ^= this.P[17];
11685 for (var i = 16; i > 0; i -= 2) {
11686 x[1] ^= F(this.S, x8, 0) ^ this.P[i];
11687 x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];
11688 }
11689 var t = x[0];
11690 x[0] = x[1] ^ this.P[0];
11691 x[1] = t;
11692};
11693
11694function stream2word(data, databytes){
11695 var i, temp = 0;
11696 for (i = 0; i < 4; i++, BLF_J++) {
11697 if (BLF_J >= databytes) BLF_J = 0;
11698 temp = (temp << 8) | data[BLF_J];
11699 }
11700 return temp;
11701};
11702
11703Blowfish.prototype.expand0state = function(key, keybytes) {
11704 var d = new Uint32Array(2), i, k;
11705 var d8 = new Uint8Array(d.buffer);
11706
11707 for (i = 0, BLF_J = 0; i < 18; i++) {
11708 this.P[i] ^= stream2word(key, keybytes);
11709 }
11710 BLF_J = 0;
11711
11712 for (i = 0; i < 18; i += 2) {
11713 this.encipher(d, d8);
11714 this.P[i] = d[0];
11715 this.P[i+1] = d[1];
11716 }
11717
11718 for (i = 0; i < 4; i++) {
11719 for (k = 0; k < 256; k += 2) {
11720 this.encipher(d, d8);
11721 this.S[i][k] = d[0];
11722 this.S[i][k+1] = d[1];
11723 }
11724 }
11725};
11726
11727Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) {
11728 var d = new Uint32Array(2), i, k;
11729
11730 for (i = 0, BLF_J = 0; i < 18; i++) {
11731 this.P[i] ^= stream2word(key, keybytes);
11732 }
11733
11734 for (i = 0, BLF_J = 0; i < 18; i += 2) {
11735 d[0] ^= stream2word(data, databytes);
11736 d[1] ^= stream2word(data, databytes);
11737 this.encipher(d);
11738 this.P[i] = d[0];
11739 this.P[i+1] = d[1];
11740 }
11741
11742 for (i = 0; i < 4; i++) {
11743 for (k = 0; k < 256; k += 2) {
11744 d[0] ^= stream2word(data, databytes);
11745 d[1] ^= stream2word(data, databytes);
11746 this.encipher(d);
11747 this.S[i][k] = d[0];
11748 this.S[i][k+1] = d[1];
11749 }
11750 }
11751 BLF_J = 0;
11752};
11753
11754Blowfish.prototype.enc = function(data, blocks) {
11755 for (var i = 0; i < blocks; i++) {
11756 this.encipher(data.subarray(i*2));
11757 }
11758};
11759
11760Blowfish.prototype.dec = function(data, blocks) {
11761 for (var i = 0; i < blocks; i++) {
11762 this.decipher(data.subarray(i*2));
11763 }
11764};
11765
11766var BCRYPT_BLOCKS = 8,
11767 BCRYPT_HASHSIZE = 32;
11768
11769function bcrypt_hash(sha2pass, sha2salt, out) {
11770 var state = new Blowfish(),
11771 cdata = new Uint32Array(BCRYPT_BLOCKS), i,
11772 ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,
11773 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,
11774 105,116,101]); //"OxychromaticBlowfishSwatDynamite"
11775
11776 state.expandstate(sha2salt, 64, sha2pass, 64);
11777 for (i = 0; i < 64; i++) {
11778 state.expand0state(sha2salt, 64);
11779 state.expand0state(sha2pass, 64);
11780 }
11781
11782 for (i = 0; i < BCRYPT_BLOCKS; i++)
11783 cdata[i] = stream2word(ciphertext, ciphertext.byteLength);
11784 for (i = 0; i < 64; i++)
11785 state.enc(cdata, cdata.byteLength / 8);
11786
11787 for (i = 0; i < BCRYPT_BLOCKS; i++) {
11788 out[4*i+3] = cdata[i] >>> 24;
11789 out[4*i+2] = cdata[i] >>> 16;
11790 out[4*i+1] = cdata[i] >>> 8;
11791 out[4*i+0] = cdata[i];
11792 }
11793};
11794
11795function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {
11796 var sha2pass = new Uint8Array(64),
11797 sha2salt = new Uint8Array(64),
11798 out = new Uint8Array(BCRYPT_HASHSIZE),
11799 tmpout = new Uint8Array(BCRYPT_HASHSIZE),
11800 countsalt = new Uint8Array(saltlen+4),
11801 i, j, amt, stride, dest, count,
11802 origkeylen = keylen;
11803
11804 if (rounds < 1)
11805 return -1;
11806 if (passlen === 0 || saltlen === 0 || keylen === 0 ||
11807 keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))
11808 return -1;
11809
11810 stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);
11811 amt = Math.floor((keylen + stride - 1) / stride);
11812
11813 for (i = 0; i < saltlen; i++)
11814 countsalt[i] = salt[i];
11815
11816 crypto_hash_sha512(sha2pass, pass, passlen);
11817
11818 for (count = 1; keylen > 0; count++) {
11819 countsalt[saltlen+0] = count >>> 24;
11820 countsalt[saltlen+1] = count >>> 16;
11821 countsalt[saltlen+2] = count >>> 8;
11822 countsalt[saltlen+3] = count;
11823
11824 crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);
11825 bcrypt_hash(sha2pass, sha2salt, tmpout);
11826 for (i = out.byteLength; i--;)
11827 out[i] = tmpout[i];
11828
11829 for (i = 1; i < rounds; i++) {
11830 crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);
11831 bcrypt_hash(sha2pass, sha2salt, tmpout);
11832 for (j = 0; j < out.byteLength; j++)
11833 out[j] ^= tmpout[j];
11834 }
11835
11836 amt = Math.min(amt, keylen);
11837 for (i = 0; i < amt; i++) {
11838 dest = i * stride + (count - 1);
11839 if (dest >= origkeylen)
11840 break;
11841 key[dest] = out[i];
11842 }
11843 keylen -= i;
11844 }
11845
11846 return 0;
11847};
11848
11849module.exports = {
11850 BLOCKS: BCRYPT_BLOCKS,
11851 HASHSIZE: BCRYPT_HASHSIZE,
11852 hash: bcrypt_hash,
11853 pbkdf: bcrypt_pbkdf
11854};
11855
11856},{"tweetnacl":391}],77:[function(require,module,exports){
11857
11858module.exports = require('./lib/bluebird-retry');
11859
11860},{"./lib/bluebird-retry":78}],78:[function(require,module,exports){
11861var Promise = require('bluebird');
11862
11863// Subclass of Error that can be thrown to indicate that retry should stop.
11864//
11865// If called with an instance of Error subclass, then the retry promise will be
11866// rejected with the given error.
11867//
11868// Otherwise the cancel error object itself is propagated to the caller.
11869//
11870function StopError(err) {
11871 this.name = 'StopError';
11872 if (err instanceof Error) {
11873 this.err = err
11874 } else {
11875 this.message = err || 'cancelled'
11876 }
11877}
11878StopError.prototype = Object.create(Error.prototype);
11879
11880retry.StopError = StopError;
11881
11882
11883// Retry `func` until it succeeds.
11884//
11885// For each attempt, invokes `func` with `options.args` as arguments and
11886// `options.context` as `this`.
11887//
11888// Waits `options.interval` milliseconds (default 1000) between attempts.
11889//
11890// Increases wait by a factor of `options.backoff` each interval, up to
11891// a limit of `options.max_interval`.
11892//
11893// Keeps trying until `options.timeout` milliseconds have elapsed,
11894// or `options.max_tries` have been attempted, whichever comes first.
11895//
11896// If neither is specified, then the default is to make 5 attempts.
11897//
11898
11899function retry(func, options) {
11900 options = options || {};
11901
11902 var interval = typeof options.interval === 'number' ? options.interval : 1000;
11903
11904 var max_tries, giveup_time;
11905 if (typeof(options.max_tries) !== 'undefined') {
11906 max_tries = options.max_tries;
11907 }
11908
11909 if (options.timeout) {
11910 giveup_time = new Date().getTime() + options.timeout;
11911 }
11912
11913 if (!max_tries && !giveup_time) {
11914 max_tries = 5;
11915 }
11916
11917 var tries = 0;
11918 var start = new Date().getTime();
11919
11920 // If the user didn't supply a predicate function then add one that
11921 // always succeeds.
11922 //
11923 // This is used in bluebird's filtered catch to flag the error types
11924 // that should retry.
11925 var predicate = options.predicate || function(err) { return true; }
11926 var stopped = false;
11927
11928 function try_once() {
11929 var tryStart = new Date().getTime();
11930 return Promise.attempt(function() {
11931 return func.apply(options.context, options.args);
11932 })
11933 .caught(StopError, function(err) {
11934 stopped = true;
11935 if (err.err instanceof Error) {
11936 return Promise.reject(err.err);
11937 } else {
11938 return Promise.reject(err);
11939 }
11940 })
11941 .caught(predicate, function(err) {
11942 if (stopped) {
11943 return Promise.reject(err);
11944 }
11945 ++tries;
11946 if (tries > 1) {
11947 interval = backoff(interval, options);
11948 }
11949 var now = new Date().getTime();
11950
11951 if ((max_tries && (tries === max_tries) ||
11952 (giveup_time && (now + interval >= giveup_time)))) {
11953
11954 if (! (err instanceof Error)) {
11955 var failure = err;
11956
11957 if (failure) {
11958 if (typeof failure !== 'string') {
11959 failure = JSON.stringify(failure);
11960 }
11961 }
11962
11963 err = new Error('rejected with non-error: ' + failure);
11964 err.failure = failure;
11965 } else if (options.throw_original) {
11966 return Promise.reject(err);
11967 }
11968
11969 var timeout = new Error('operation timed out after ' + (now - start) + ' ms, ' + tries + ' tries with error: ' + err.message);
11970 timeout.failure = err;
11971 timeout.code = 'ETIMEDOUT';
11972 return Promise.reject(timeout);
11973 } else {
11974 var delay = interval - (now - tryStart);
11975 if (delay <= 0) {
11976 return try_once();
11977 } else {
11978 return Promise.delay(delay).then(try_once);
11979 }
11980 }
11981 });
11982 }
11983 return try_once();
11984}
11985
11986// Return the updated interval after applying the various backoff options
11987function backoff(interval, options) {
11988 if (options.backoff) {
11989 interval = interval * options.backoff;
11990 }
11991
11992 if (options.max_interval) {
11993 interval = Math.min(interval, options.max_interval);
11994 }
11995
11996 return interval;
11997}
11998
11999module.exports = retry;
12000
12001},{"bluebird":79}],79:[function(require,module,exports){
12002(function (process,global,setImmediate){
12003/* @preserve
12004 * The MIT License (MIT)
12005 *
12006 * Copyright (c) 2013-2018 Petka Antonov
12007 *
12008 * Permission is hereby granted, free of charge, to any person obtaining a copy
12009 * of this software and associated documentation files (the "Software"), to deal
12010 * in the Software without restriction, including without limitation the rights
12011 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12012 * copies of the Software, and to permit persons to whom the Software is
12013 * furnished to do so, subject to the following conditions:
12014 *
12015 * The above copyright notice and this permission notice shall be included in
12016 * all copies or substantial portions of the Software.
12017 *
12018 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12019 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12020 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12021 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12022 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12023 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
12024 * THE SOFTWARE.
12025 *
12026 */
12027/**
12028 * bluebird build version 3.5.5
12029 * Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
12030*/
12031!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){
12032"use strict";
12033module.exports = function(Promise) {
12034var SomePromiseArray = Promise._SomePromiseArray;
12035function any(promises) {
12036 var ret = new SomePromiseArray(promises);
12037 var promise = ret.promise();
12038 ret.setHowMany(1);
12039 ret.setUnwrap();
12040 ret.init();
12041 return promise;
12042}
12043
12044Promise.any = function (promises) {
12045 return any(promises);
12046};
12047
12048Promise.prototype.any = function () {
12049 return any(this);
12050};
12051
12052};
12053
12054},{}],2:[function(_dereq_,module,exports){
12055"use strict";
12056var firstLineError;
12057try {throw new Error(); } catch (e) {firstLineError = e;}
12058var schedule = _dereq_("./schedule");
12059var Queue = _dereq_("./queue");
12060var util = _dereq_("./util");
12061
12062function Async() {
12063 this._customScheduler = false;
12064 this._isTickUsed = false;
12065 this._lateQueue = new Queue(16);
12066 this._normalQueue = new Queue(16);
12067 this._haveDrainedQueues = false;
12068 this._trampolineEnabled = true;
12069 var self = this;
12070 this.drainQueues = function () {
12071 self._drainQueues();
12072 };
12073 this._schedule = schedule;
12074}
12075
12076Async.prototype.setScheduler = function(fn) {
12077 var prev = this._schedule;
12078 this._schedule = fn;
12079 this._customScheduler = true;
12080 return prev;
12081};
12082
12083Async.prototype.hasCustomScheduler = function() {
12084 return this._customScheduler;
12085};
12086
12087Async.prototype.enableTrampoline = function() {
12088 this._trampolineEnabled = true;
12089};
12090
12091Async.prototype.disableTrampolineIfNecessary = function() {
12092 if (util.hasDevTools) {
12093 this._trampolineEnabled = false;
12094 }
12095};
12096
12097Async.prototype.haveItemsQueued = function () {
12098 return this._isTickUsed || this._haveDrainedQueues;
12099};
12100
12101
12102Async.prototype.fatalError = function(e, isNode) {
12103 if (isNode) {
12104 process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
12105 "\n");
12106 process.exit(2);
12107 } else {
12108 this.throwLater(e);
12109 }
12110};
12111
12112Async.prototype.throwLater = function(fn, arg) {
12113 if (arguments.length === 1) {
12114 arg = fn;
12115 fn = function () { throw arg; };
12116 }
12117 if (typeof setTimeout !== "undefined") {
12118 setTimeout(function() {
12119 fn(arg);
12120 }, 0);
12121 } else try {
12122 this._schedule(function() {
12123 fn(arg);
12124 });
12125 } catch (e) {
12126 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
12127 }
12128};
12129
12130function AsyncInvokeLater(fn, receiver, arg) {
12131 this._lateQueue.push(fn, receiver, arg);
12132 this._queueTick();
12133}
12134
12135function AsyncInvoke(fn, receiver, arg) {
12136 this._normalQueue.push(fn, receiver, arg);
12137 this._queueTick();
12138}
12139
12140function AsyncSettlePromises(promise) {
12141 this._normalQueue._pushOne(promise);
12142 this._queueTick();
12143}
12144
12145if (!util.hasDevTools) {
12146 Async.prototype.invokeLater = AsyncInvokeLater;
12147 Async.prototype.invoke = AsyncInvoke;
12148 Async.prototype.settlePromises = AsyncSettlePromises;
12149} else {
12150 Async.prototype.invokeLater = function (fn, receiver, arg) {
12151 if (this._trampolineEnabled) {
12152 AsyncInvokeLater.call(this, fn, receiver, arg);
12153 } else {
12154 this._schedule(function() {
12155 setTimeout(function() {
12156 fn.call(receiver, arg);
12157 }, 100);
12158 });
12159 }
12160 };
12161
12162 Async.prototype.invoke = function (fn, receiver, arg) {
12163 if (this._trampolineEnabled) {
12164 AsyncInvoke.call(this, fn, receiver, arg);
12165 } else {
12166 this._schedule(function() {
12167 fn.call(receiver, arg);
12168 });
12169 }
12170 };
12171
12172 Async.prototype.settlePromises = function(promise) {
12173 if (this._trampolineEnabled) {
12174 AsyncSettlePromises.call(this, promise);
12175 } else {
12176 this._schedule(function() {
12177 promise._settlePromises();
12178 });
12179 }
12180 };
12181}
12182
12183function _drainQueue(queue) {
12184 while (queue.length() > 0) {
12185 _drainQueueStep(queue);
12186 }
12187}
12188
12189function _drainQueueStep(queue) {
12190 var fn = queue.shift();
12191 if (typeof fn !== "function") {
12192 fn._settlePromises();
12193 } else {
12194 var receiver = queue.shift();
12195 var arg = queue.shift();
12196 fn.call(receiver, arg);
12197 }
12198}
12199
12200Async.prototype._drainQueues = function () {
12201 _drainQueue(this._normalQueue);
12202 this._reset();
12203 this._haveDrainedQueues = true;
12204 _drainQueue(this._lateQueue);
12205};
12206
12207Async.prototype._queueTick = function () {
12208 if (!this._isTickUsed) {
12209 this._isTickUsed = true;
12210 this._schedule(this.drainQueues);
12211 }
12212};
12213
12214Async.prototype._reset = function () {
12215 this._isTickUsed = false;
12216};
12217
12218module.exports = Async;
12219module.exports.firstLineError = firstLineError;
12220
12221},{"./queue":26,"./schedule":29,"./util":36}],3:[function(_dereq_,module,exports){
12222"use strict";
12223module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
12224var calledBind = false;
12225var rejectThis = function(_, e) {
12226 this._reject(e);
12227};
12228
12229var targetRejected = function(e, context) {
12230 context.promiseRejectionQueued = true;
12231 context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
12232};
12233
12234var bindingResolved = function(thisArg, context) {
12235 if (((this._bitField & 50397184) === 0)) {
12236 this._resolveCallback(context.target);
12237 }
12238};
12239
12240var bindingRejected = function(e, context) {
12241 if (!context.promiseRejectionQueued) this._reject(e);
12242};
12243
12244Promise.prototype.bind = function (thisArg) {
12245 if (!calledBind) {
12246 calledBind = true;
12247 Promise.prototype._propagateFrom = debug.propagateFromFunction();
12248 Promise.prototype._boundValue = debug.boundValueFunction();
12249 }
12250 var maybePromise = tryConvertToPromise(thisArg);
12251 var ret = new Promise(INTERNAL);
12252 ret._propagateFrom(this, 1);
12253 var target = this._target();
12254 ret._setBoundTo(maybePromise);
12255 if (maybePromise instanceof Promise) {
12256 var context = {
12257 promiseRejectionQueued: false,
12258 promise: ret,
12259 target: target,
12260 bindingPromise: maybePromise
12261 };
12262 target._then(INTERNAL, targetRejected, undefined, ret, context);
12263 maybePromise._then(
12264 bindingResolved, bindingRejected, undefined, ret, context);
12265 ret._setOnCancel(maybePromise);
12266 } else {
12267 ret._resolveCallback(target);
12268 }
12269 return ret;
12270};
12271
12272Promise.prototype._setBoundTo = function (obj) {
12273 if (obj !== undefined) {
12274 this._bitField = this._bitField | 2097152;
12275 this._boundTo = obj;
12276 } else {
12277 this._bitField = this._bitField & (~2097152);
12278 }
12279};
12280
12281Promise.prototype._isBound = function () {
12282 return (this._bitField & 2097152) === 2097152;
12283};
12284
12285Promise.bind = function (thisArg, value) {
12286 return Promise.resolve(value).bind(thisArg);
12287};
12288};
12289
12290},{}],4:[function(_dereq_,module,exports){
12291"use strict";
12292var old;
12293if (typeof Promise !== "undefined") old = Promise;
12294function noConflict() {
12295 try { if (Promise === bluebird) Promise = old; }
12296 catch (e) {}
12297 return bluebird;
12298}
12299var bluebird = _dereq_("./promise")();
12300bluebird.noConflict = noConflict;
12301module.exports = bluebird;
12302
12303},{"./promise":22}],5:[function(_dereq_,module,exports){
12304"use strict";
12305var cr = Object.create;
12306if (cr) {
12307 var callerCache = cr(null);
12308 var getterCache = cr(null);
12309 callerCache[" size"] = getterCache[" size"] = 0;
12310}
12311
12312module.exports = function(Promise) {
12313var util = _dereq_("./util");
12314var canEvaluate = util.canEvaluate;
12315var isIdentifier = util.isIdentifier;
12316
12317var getMethodCaller;
12318var getGetter;
12319if (!true) {
12320var makeMethodCaller = function (methodName) {
12321 return new Function("ensureMethod", " \n\
12322 return function(obj) { \n\
12323 'use strict' \n\
12324 var len = this.length; \n\
12325 ensureMethod(obj, 'methodName'); \n\
12326 switch(len) { \n\
12327 case 1: return obj.methodName(this[0]); \n\
12328 case 2: return obj.methodName(this[0], this[1]); \n\
12329 case 3: return obj.methodName(this[0], this[1], this[2]); \n\
12330 case 0: return obj.methodName(); \n\
12331 default: \n\
12332 return obj.methodName.apply(obj, this); \n\
12333 } \n\
12334 }; \n\
12335 ".replace(/methodName/g, methodName))(ensureMethod);
12336};
12337
12338var makeGetter = function (propertyName) {
12339 return new Function("obj", " \n\
12340 'use strict'; \n\
12341 return obj.propertyName; \n\
12342 ".replace("propertyName", propertyName));
12343};
12344
12345var getCompiled = function(name, compiler, cache) {
12346 var ret = cache[name];
12347 if (typeof ret !== "function") {
12348 if (!isIdentifier(name)) {
12349 return null;
12350 }
12351 ret = compiler(name);
12352 cache[name] = ret;
12353 cache[" size"]++;
12354 if (cache[" size"] > 512) {
12355 var keys = Object.keys(cache);
12356 for (var i = 0; i < 256; ++i) delete cache[keys[i]];
12357 cache[" size"] = keys.length - 256;
12358 }
12359 }
12360 return ret;
12361};
12362
12363getMethodCaller = function(name) {
12364 return getCompiled(name, makeMethodCaller, callerCache);
12365};
12366
12367getGetter = function(name) {
12368 return getCompiled(name, makeGetter, getterCache);
12369};
12370}
12371
12372function ensureMethod(obj, methodName) {
12373 var fn;
12374 if (obj != null) fn = obj[methodName];
12375 if (typeof fn !== "function") {
12376 var message = "Object " + util.classString(obj) + " has no method '" +
12377 util.toString(methodName) + "'";
12378 throw new Promise.TypeError(message);
12379 }
12380 return fn;
12381}
12382
12383function caller(obj) {
12384 var methodName = this.pop();
12385 var fn = ensureMethod(obj, methodName);
12386 return fn.apply(obj, this);
12387}
12388Promise.prototype.call = function (methodName) {
12389 var args = [].slice.call(arguments, 1);;
12390 if (!true) {
12391 if (canEvaluate) {
12392 var maybeCaller = getMethodCaller(methodName);
12393 if (maybeCaller !== null) {
12394 return this._then(
12395 maybeCaller, undefined, undefined, args, undefined);
12396 }
12397 }
12398 }
12399 args.push(methodName);
12400 return this._then(caller, undefined, undefined, args, undefined);
12401};
12402
12403function namedGetter(obj) {
12404 return obj[this];
12405}
12406function indexedGetter(obj) {
12407 var index = +this;
12408 if (index < 0) index = Math.max(0, index + obj.length);
12409 return obj[index];
12410}
12411Promise.prototype.get = function (propertyName) {
12412 var isIndex = (typeof propertyName === "number");
12413 var getter;
12414 if (!isIndex) {
12415 if (canEvaluate) {
12416 var maybeGetter = getGetter(propertyName);
12417 getter = maybeGetter !== null ? maybeGetter : namedGetter;
12418 } else {
12419 getter = namedGetter;
12420 }
12421 } else {
12422 getter = indexedGetter;
12423 }
12424 return this._then(getter, undefined, undefined, propertyName, undefined);
12425};
12426};
12427
12428},{"./util":36}],6:[function(_dereq_,module,exports){
12429"use strict";
12430module.exports = function(Promise, PromiseArray, apiRejection, debug) {
12431var util = _dereq_("./util");
12432var tryCatch = util.tryCatch;
12433var errorObj = util.errorObj;
12434var async = Promise._async;
12435
12436Promise.prototype["break"] = Promise.prototype.cancel = function() {
12437 if (!debug.cancellation()) return this._warn("cancellation is disabled");
12438
12439 var promise = this;
12440 var child = promise;
12441 while (promise._isCancellable()) {
12442 if (!promise._cancelBy(child)) {
12443 if (child._isFollowing()) {
12444 child._followee().cancel();
12445 } else {
12446 child._cancelBranched();
12447 }
12448 break;
12449 }
12450
12451 var parent = promise._cancellationParent;
12452 if (parent == null || !parent._isCancellable()) {
12453 if (promise._isFollowing()) {
12454 promise._followee().cancel();
12455 } else {
12456 promise._cancelBranched();
12457 }
12458 break;
12459 } else {
12460 if (promise._isFollowing()) promise._followee().cancel();
12461 promise._setWillBeCancelled();
12462 child = promise;
12463 promise = parent;
12464 }
12465 }
12466};
12467
12468Promise.prototype._branchHasCancelled = function() {
12469 this._branchesRemainingToCancel--;
12470};
12471
12472Promise.prototype._enoughBranchesHaveCancelled = function() {
12473 return this._branchesRemainingToCancel === undefined ||
12474 this._branchesRemainingToCancel <= 0;
12475};
12476
12477Promise.prototype._cancelBy = function(canceller) {
12478 if (canceller === this) {
12479 this._branchesRemainingToCancel = 0;
12480 this._invokeOnCancel();
12481 return true;
12482 } else {
12483 this._branchHasCancelled();
12484 if (this._enoughBranchesHaveCancelled()) {
12485 this._invokeOnCancel();
12486 return true;
12487 }
12488 }
12489 return false;
12490};
12491
12492Promise.prototype._cancelBranched = function() {
12493 if (this._enoughBranchesHaveCancelled()) {
12494 this._cancel();
12495 }
12496};
12497
12498Promise.prototype._cancel = function() {
12499 if (!this._isCancellable()) return;
12500 this._setCancelled();
12501 async.invoke(this._cancelPromises, this, undefined);
12502};
12503
12504Promise.prototype._cancelPromises = function() {
12505 if (this._length() > 0) this._settlePromises();
12506};
12507
12508Promise.prototype._unsetOnCancel = function() {
12509 this._onCancelField = undefined;
12510};
12511
12512Promise.prototype._isCancellable = function() {
12513 return this.isPending() && !this._isCancelled();
12514};
12515
12516Promise.prototype.isCancellable = function() {
12517 return this.isPending() && !this.isCancelled();
12518};
12519
12520Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
12521 if (util.isArray(onCancelCallback)) {
12522 for (var i = 0; i < onCancelCallback.length; ++i) {
12523 this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
12524 }
12525 } else if (onCancelCallback !== undefined) {
12526 if (typeof onCancelCallback === "function") {
12527 if (!internalOnly) {
12528 var e = tryCatch(onCancelCallback).call(this._boundValue());
12529 if (e === errorObj) {
12530 this._attachExtraTrace(e.e);
12531 async.throwLater(e.e);
12532 }
12533 }
12534 } else {
12535 onCancelCallback._resultCancelled(this);
12536 }
12537 }
12538};
12539
12540Promise.prototype._invokeOnCancel = function() {
12541 var onCancelCallback = this._onCancel();
12542 this._unsetOnCancel();
12543 async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
12544};
12545
12546Promise.prototype._invokeInternalOnCancel = function() {
12547 if (this._isCancellable()) {
12548 this._doInvokeOnCancel(this._onCancel(), true);
12549 this._unsetOnCancel();
12550 }
12551};
12552
12553Promise.prototype._resultCancelled = function() {
12554 this.cancel();
12555};
12556
12557};
12558
12559},{"./util":36}],7:[function(_dereq_,module,exports){
12560"use strict";
12561module.exports = function(NEXT_FILTER) {
12562var util = _dereq_("./util");
12563var getKeys = _dereq_("./es5").keys;
12564var tryCatch = util.tryCatch;
12565var errorObj = util.errorObj;
12566
12567function catchFilter(instances, cb, promise) {
12568 return function(e) {
12569 var boundTo = promise._boundValue();
12570 predicateLoop: for (var i = 0; i < instances.length; ++i) {
12571 var item = instances[i];
12572
12573 if (item === Error ||
12574 (item != null && item.prototype instanceof Error)) {
12575 if (e instanceof item) {
12576 return tryCatch(cb).call(boundTo, e);
12577 }
12578 } else if (typeof item === "function") {
12579 var matchesPredicate = tryCatch(item).call(boundTo, e);
12580 if (matchesPredicate === errorObj) {
12581 return matchesPredicate;
12582 } else if (matchesPredicate) {
12583 return tryCatch(cb).call(boundTo, e);
12584 }
12585 } else if (util.isObject(e)) {
12586 var keys = getKeys(item);
12587 for (var j = 0; j < keys.length; ++j) {
12588 var key = keys[j];
12589 if (item[key] != e[key]) {
12590 continue predicateLoop;
12591 }
12592 }
12593 return tryCatch(cb).call(boundTo, e);
12594 }
12595 }
12596 return NEXT_FILTER;
12597 };
12598}
12599
12600return catchFilter;
12601};
12602
12603},{"./es5":13,"./util":36}],8:[function(_dereq_,module,exports){
12604"use strict";
12605module.exports = function(Promise) {
12606var longStackTraces = false;
12607var contextStack = [];
12608
12609Promise.prototype._promiseCreated = function() {};
12610Promise.prototype._pushContext = function() {};
12611Promise.prototype._popContext = function() {return null;};
12612Promise._peekContext = Promise.prototype._peekContext = function() {};
12613
12614function Context() {
12615 this._trace = new Context.CapturedTrace(peekContext());
12616}
12617Context.prototype._pushContext = function () {
12618 if (this._trace !== undefined) {
12619 this._trace._promiseCreated = null;
12620 contextStack.push(this._trace);
12621 }
12622};
12623
12624Context.prototype._popContext = function () {
12625 if (this._trace !== undefined) {
12626 var trace = contextStack.pop();
12627 var ret = trace._promiseCreated;
12628 trace._promiseCreated = null;
12629 return ret;
12630 }
12631 return null;
12632};
12633
12634function createContext() {
12635 if (longStackTraces) return new Context();
12636}
12637
12638function peekContext() {
12639 var lastIndex = contextStack.length - 1;
12640 if (lastIndex >= 0) {
12641 return contextStack[lastIndex];
12642 }
12643 return undefined;
12644}
12645Context.CapturedTrace = null;
12646Context.create = createContext;
12647Context.deactivateLongStackTraces = function() {};
12648Context.activateLongStackTraces = function() {
12649 var Promise_pushContext = Promise.prototype._pushContext;
12650 var Promise_popContext = Promise.prototype._popContext;
12651 var Promise_PeekContext = Promise._peekContext;
12652 var Promise_peekContext = Promise.prototype._peekContext;
12653 var Promise_promiseCreated = Promise.prototype._promiseCreated;
12654 Context.deactivateLongStackTraces = function() {
12655 Promise.prototype._pushContext = Promise_pushContext;
12656 Promise.prototype._popContext = Promise_popContext;
12657 Promise._peekContext = Promise_PeekContext;
12658 Promise.prototype._peekContext = Promise_peekContext;
12659 Promise.prototype._promiseCreated = Promise_promiseCreated;
12660 longStackTraces = false;
12661 };
12662 longStackTraces = true;
12663 Promise.prototype._pushContext = Context.prototype._pushContext;
12664 Promise.prototype._popContext = Context.prototype._popContext;
12665 Promise._peekContext = Promise.prototype._peekContext = peekContext;
12666 Promise.prototype._promiseCreated = function() {
12667 var ctx = this._peekContext();
12668 if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
12669 };
12670};
12671return Context;
12672};
12673
12674},{}],9:[function(_dereq_,module,exports){
12675"use strict";
12676module.exports = function(Promise, Context) {
12677var getDomain = Promise._getDomain;
12678var async = Promise._async;
12679var Warning = _dereq_("./errors").Warning;
12680var util = _dereq_("./util");
12681var es5 = _dereq_("./es5");
12682var canAttachTrace = util.canAttachTrace;
12683var unhandledRejectionHandled;
12684var possiblyUnhandledRejection;
12685var bluebirdFramePattern =
12686 /[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
12687var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
12688var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
12689var stackFramePattern = null;
12690var formatStack = null;
12691var indentStackFrames = false;
12692var printWarning;
12693var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
12694 (true ||
12695 util.env("BLUEBIRD_DEBUG") ||
12696 util.env("NODE_ENV") === "development"));
12697
12698var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
12699 (debugging || util.env("BLUEBIRD_WARNINGS")));
12700
12701var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
12702 (debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
12703
12704var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
12705 (warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
12706
12707Promise.prototype.suppressUnhandledRejections = function() {
12708 var target = this._target();
12709 target._bitField = ((target._bitField & (~1048576)) |
12710 524288);
12711};
12712
12713Promise.prototype._ensurePossibleRejectionHandled = function () {
12714 if ((this._bitField & 524288) !== 0) return;
12715 this._setRejectionIsUnhandled();
12716 var self = this;
12717 setTimeout(function() {
12718 self._notifyUnhandledRejection();
12719 }, 1);
12720};
12721
12722Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
12723 fireRejectionEvent("rejectionHandled",
12724 unhandledRejectionHandled, undefined, this);
12725};
12726
12727Promise.prototype._setReturnedNonUndefined = function() {
12728 this._bitField = this._bitField | 268435456;
12729};
12730
12731Promise.prototype._returnedNonUndefined = function() {
12732 return (this._bitField & 268435456) !== 0;
12733};
12734
12735Promise.prototype._notifyUnhandledRejection = function () {
12736 if (this._isRejectionUnhandled()) {
12737 var reason = this._settledValue();
12738 this._setUnhandledRejectionIsNotified();
12739 fireRejectionEvent("unhandledRejection",
12740 possiblyUnhandledRejection, reason, this);
12741 }
12742};
12743
12744Promise.prototype._setUnhandledRejectionIsNotified = function () {
12745 this._bitField = this._bitField | 262144;
12746};
12747
12748Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
12749 this._bitField = this._bitField & (~262144);
12750};
12751
12752Promise.prototype._isUnhandledRejectionNotified = function () {
12753 return (this._bitField & 262144) > 0;
12754};
12755
12756Promise.prototype._setRejectionIsUnhandled = function () {
12757 this._bitField = this._bitField | 1048576;
12758};
12759
12760Promise.prototype._unsetRejectionIsUnhandled = function () {
12761 this._bitField = this._bitField & (~1048576);
12762 if (this._isUnhandledRejectionNotified()) {
12763 this._unsetUnhandledRejectionIsNotified();
12764 this._notifyUnhandledRejectionIsHandled();
12765 }
12766};
12767
12768Promise.prototype._isRejectionUnhandled = function () {
12769 return (this._bitField & 1048576) > 0;
12770};
12771
12772Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
12773 return warn(message, shouldUseOwnTrace, promise || this);
12774};
12775
12776Promise.onPossiblyUnhandledRejection = function (fn) {
12777 var domain = getDomain();
12778 possiblyUnhandledRejection =
12779 typeof fn === "function" ? (domain === null ?
12780 fn : util.domainBind(domain, fn))
12781 : undefined;
12782};
12783
12784Promise.onUnhandledRejectionHandled = function (fn) {
12785 var domain = getDomain();
12786 unhandledRejectionHandled =
12787 typeof fn === "function" ? (domain === null ?
12788 fn : util.domainBind(domain, fn))
12789 : undefined;
12790};
12791
12792var disableLongStackTraces = function() {};
12793Promise.longStackTraces = function () {
12794 if (async.haveItemsQueued() && !config.longStackTraces) {
12795 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
12796 }
12797 if (!config.longStackTraces && longStackTracesIsSupported()) {
12798 var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
12799 var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
12800 var Promise_dereferenceTrace = Promise.prototype._dereferenceTrace;
12801 config.longStackTraces = true;
12802 disableLongStackTraces = function() {
12803 if (async.haveItemsQueued() && !config.longStackTraces) {
12804 throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
12805 }
12806 Promise.prototype._captureStackTrace = Promise_captureStackTrace;
12807 Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
12808 Promise.prototype._dereferenceTrace = Promise_dereferenceTrace;
12809 Context.deactivateLongStackTraces();
12810 async.enableTrampoline();
12811 config.longStackTraces = false;
12812 };
12813 Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
12814 Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
12815 Promise.prototype._dereferenceTrace = longStackTracesDereferenceTrace;
12816 Context.activateLongStackTraces();
12817 async.disableTrampolineIfNecessary();
12818 }
12819};
12820
12821Promise.hasLongStackTraces = function () {
12822 return config.longStackTraces && longStackTracesIsSupported();
12823};
12824
12825var fireDomEvent = (function() {
12826 try {
12827 if (typeof CustomEvent === "function") {
12828 var event = new CustomEvent("CustomEvent");
12829 util.global.dispatchEvent(event);
12830 return function(name, event) {
12831 var eventData = {
12832 detail: event,
12833 cancelable: true
12834 };
12835 es5.defineProperty(
12836 eventData, "promise", {value: event.promise});
12837 es5.defineProperty(eventData, "reason", {value: event.reason});
12838 var domEvent = new CustomEvent(name.toLowerCase(), eventData);
12839 return !util.global.dispatchEvent(domEvent);
12840 };
12841 } else if (typeof Event === "function") {
12842 var event = new Event("CustomEvent");
12843 util.global.dispatchEvent(event);
12844 return function(name, event) {
12845 var domEvent = new Event(name.toLowerCase(), {
12846 cancelable: true
12847 });
12848 domEvent.detail = event;
12849 es5.defineProperty(domEvent, "promise", {value: event.promise});
12850 es5.defineProperty(domEvent, "reason", {value: event.reason});
12851 return !util.global.dispatchEvent(domEvent);
12852 };
12853 } else {
12854 var event = document.createEvent("CustomEvent");
12855 event.initCustomEvent("testingtheevent", false, true, {});
12856 util.global.dispatchEvent(event);
12857 return function(name, event) {
12858 var domEvent = document.createEvent("CustomEvent");
12859 domEvent.initCustomEvent(name.toLowerCase(), false, true,
12860 event);
12861 return !util.global.dispatchEvent(domEvent);
12862 };
12863 }
12864 } catch (e) {}
12865 return function() {
12866 return false;
12867 };
12868})();
12869
12870var fireGlobalEvent = (function() {
12871 if (util.isNode) {
12872 return function() {
12873 return process.emit.apply(process, arguments);
12874 };
12875 } else {
12876 if (!util.global) {
12877 return function() {
12878 return false;
12879 };
12880 }
12881 return function(name) {
12882 var methodName = "on" + name.toLowerCase();
12883 var method = util.global[methodName];
12884 if (!method) return false;
12885 method.apply(util.global, [].slice.call(arguments, 1));
12886 return true;
12887 };
12888 }
12889})();
12890
12891function generatePromiseLifecycleEventObject(name, promise) {
12892 return {promise: promise};
12893}
12894
12895var eventToObjectGenerator = {
12896 promiseCreated: generatePromiseLifecycleEventObject,
12897 promiseFulfilled: generatePromiseLifecycleEventObject,
12898 promiseRejected: generatePromiseLifecycleEventObject,
12899 promiseResolved: generatePromiseLifecycleEventObject,
12900 promiseCancelled: generatePromiseLifecycleEventObject,
12901 promiseChained: function(name, promise, child) {
12902 return {promise: promise, child: child};
12903 },
12904 warning: function(name, warning) {
12905 return {warning: warning};
12906 },
12907 unhandledRejection: function (name, reason, promise) {
12908 return {reason: reason, promise: promise};
12909 },
12910 rejectionHandled: generatePromiseLifecycleEventObject
12911};
12912
12913var activeFireEvent = function (name) {
12914 var globalEventFired = false;
12915 try {
12916 globalEventFired = fireGlobalEvent.apply(null, arguments);
12917 } catch (e) {
12918 async.throwLater(e);
12919 globalEventFired = true;
12920 }
12921
12922 var domEventFired = false;
12923 try {
12924 domEventFired = fireDomEvent(name,
12925 eventToObjectGenerator[name].apply(null, arguments));
12926 } catch (e) {
12927 async.throwLater(e);
12928 domEventFired = true;
12929 }
12930
12931 return domEventFired || globalEventFired;
12932};
12933
12934Promise.config = function(opts) {
12935 opts = Object(opts);
12936 if ("longStackTraces" in opts) {
12937 if (opts.longStackTraces) {
12938 Promise.longStackTraces();
12939 } else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
12940 disableLongStackTraces();
12941 }
12942 }
12943 if ("warnings" in opts) {
12944 var warningsOption = opts.warnings;
12945 config.warnings = !!warningsOption;
12946 wForgottenReturn = config.warnings;
12947
12948 if (util.isObject(warningsOption)) {
12949 if ("wForgottenReturn" in warningsOption) {
12950 wForgottenReturn = !!warningsOption.wForgottenReturn;
12951 }
12952 }
12953 }
12954 if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
12955 if (async.haveItemsQueued()) {
12956 throw new Error(
12957 "cannot enable cancellation after promises are in use");
12958 }
12959 Promise.prototype._clearCancellationData =
12960 cancellationClearCancellationData;
12961 Promise.prototype._propagateFrom = cancellationPropagateFrom;
12962 Promise.prototype._onCancel = cancellationOnCancel;
12963 Promise.prototype._setOnCancel = cancellationSetOnCancel;
12964 Promise.prototype._attachCancellationCallback =
12965 cancellationAttachCancellationCallback;
12966 Promise.prototype._execute = cancellationExecute;
12967 propagateFromFunction = cancellationPropagateFrom;
12968 config.cancellation = true;
12969 }
12970 if ("monitoring" in opts) {
12971 if (opts.monitoring && !config.monitoring) {
12972 config.monitoring = true;
12973 Promise.prototype._fireEvent = activeFireEvent;
12974 } else if (!opts.monitoring && config.monitoring) {
12975 config.monitoring = false;
12976 Promise.prototype._fireEvent = defaultFireEvent;
12977 }
12978 }
12979 return Promise;
12980};
12981
12982function defaultFireEvent() { return false; }
12983
12984Promise.prototype._fireEvent = defaultFireEvent;
12985Promise.prototype._execute = function(executor, resolve, reject) {
12986 try {
12987 executor(resolve, reject);
12988 } catch (e) {
12989 return e;
12990 }
12991};
12992Promise.prototype._onCancel = function () {};
12993Promise.prototype._setOnCancel = function (handler) { ; };
12994Promise.prototype._attachCancellationCallback = function(onCancel) {
12995 ;
12996};
12997Promise.prototype._captureStackTrace = function () {};
12998Promise.prototype._attachExtraTrace = function () {};
12999Promise.prototype._dereferenceTrace = function () {};
13000Promise.prototype._clearCancellationData = function() {};
13001Promise.prototype._propagateFrom = function (parent, flags) {
13002 ;
13003 ;
13004};
13005
13006function cancellationExecute(executor, resolve, reject) {
13007 var promise = this;
13008 try {
13009 executor(resolve, reject, function(onCancel) {
13010 if (typeof onCancel !== "function") {
13011 throw new TypeError("onCancel must be a function, got: " +
13012 util.toString(onCancel));
13013 }
13014 promise._attachCancellationCallback(onCancel);
13015 });
13016 } catch (e) {
13017 return e;
13018 }
13019}
13020
13021function cancellationAttachCancellationCallback(onCancel) {
13022 if (!this._isCancellable()) return this;
13023
13024 var previousOnCancel = this._onCancel();
13025 if (previousOnCancel !== undefined) {
13026 if (util.isArray(previousOnCancel)) {
13027 previousOnCancel.push(onCancel);
13028 } else {
13029 this._setOnCancel([previousOnCancel, onCancel]);
13030 }
13031 } else {
13032 this._setOnCancel(onCancel);
13033 }
13034}
13035
13036function cancellationOnCancel() {
13037 return this._onCancelField;
13038}
13039
13040function cancellationSetOnCancel(onCancel) {
13041 this._onCancelField = onCancel;
13042}
13043
13044function cancellationClearCancellationData() {
13045 this._cancellationParent = undefined;
13046 this._onCancelField = undefined;
13047}
13048
13049function cancellationPropagateFrom(parent, flags) {
13050 if ((flags & 1) !== 0) {
13051 this._cancellationParent = parent;
13052 var branchesRemainingToCancel = parent._branchesRemainingToCancel;
13053 if (branchesRemainingToCancel === undefined) {
13054 branchesRemainingToCancel = 0;
13055 }
13056 parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
13057 }
13058 if ((flags & 2) !== 0 && parent._isBound()) {
13059 this._setBoundTo(parent._boundTo);
13060 }
13061}
13062
13063function bindingPropagateFrom(parent, flags) {
13064 if ((flags & 2) !== 0 && parent._isBound()) {
13065 this._setBoundTo(parent._boundTo);
13066 }
13067}
13068var propagateFromFunction = bindingPropagateFrom;
13069
13070function boundValueFunction() {
13071 var ret = this._boundTo;
13072 if (ret !== undefined) {
13073 if (ret instanceof Promise) {
13074 if (ret.isFulfilled()) {
13075 return ret.value();
13076 } else {
13077 return undefined;
13078 }
13079 }
13080 }
13081 return ret;
13082}
13083
13084function longStackTracesCaptureStackTrace() {
13085 this._trace = new CapturedTrace(this._peekContext());
13086}
13087
13088function longStackTracesAttachExtraTrace(error, ignoreSelf) {
13089 if (canAttachTrace(error)) {
13090 var trace = this._trace;
13091 if (trace !== undefined) {
13092 if (ignoreSelf) trace = trace._parent;
13093 }
13094 if (trace !== undefined) {
13095 trace.attachExtraTrace(error);
13096 } else if (!error.__stackCleaned__) {
13097 var parsed = parseStackAndMessage(error);
13098 util.notEnumerableProp(error, "stack",
13099 parsed.message + "\n" + parsed.stack.join("\n"));
13100 util.notEnumerableProp(error, "__stackCleaned__", true);
13101 }
13102 }
13103}
13104
13105function longStackTracesDereferenceTrace() {
13106 this._trace = undefined;
13107}
13108
13109function checkForgottenReturns(returnValue, promiseCreated, name, promise,
13110 parent) {
13111 if (returnValue === undefined && promiseCreated !== null &&
13112 wForgottenReturn) {
13113 if (parent !== undefined && parent._returnedNonUndefined()) return;
13114 if ((promise._bitField & 65535) === 0) return;
13115
13116 if (name) name = name + " ";
13117 var handlerLine = "";
13118 var creatorLine = "";
13119 if (promiseCreated._trace) {
13120 var traceLines = promiseCreated._trace.stack.split("\n");
13121 var stack = cleanStack(traceLines);
13122 for (var i = stack.length - 1; i >= 0; --i) {
13123 var line = stack[i];
13124 if (!nodeFramePattern.test(line)) {
13125 var lineMatches = line.match(parseLinePattern);
13126 if (lineMatches) {
13127 handlerLine = "at " + lineMatches[1] +
13128 ":" + lineMatches[2] + ":" + lineMatches[3] + " ";
13129 }
13130 break;
13131 }
13132 }
13133
13134 if (stack.length > 0) {
13135 var firstUserLine = stack[0];
13136 for (var i = 0; i < traceLines.length; ++i) {
13137
13138 if (traceLines[i] === firstUserLine) {
13139 if (i > 0) {
13140 creatorLine = "\n" + traceLines[i - 1];
13141 }
13142 break;
13143 }
13144 }
13145
13146 }
13147 }
13148 var msg = "a promise was created in a " + name +
13149 "handler " + handlerLine + "but was not returned from it, " +
13150 "see http://goo.gl/rRqMUw" +
13151 creatorLine;
13152 promise._warn(msg, true, promiseCreated);
13153 }
13154}
13155
13156function deprecated(name, replacement) {
13157 var message = name +
13158 " is deprecated and will be removed in a future version.";
13159 if (replacement) message += " Use " + replacement + " instead.";
13160 return warn(message);
13161}
13162
13163function warn(message, shouldUseOwnTrace, promise) {
13164 if (!config.warnings) return;
13165 var warning = new Warning(message);
13166 var ctx;
13167 if (shouldUseOwnTrace) {
13168 promise._attachExtraTrace(warning);
13169 } else if (config.longStackTraces && (ctx = Promise._peekContext())) {
13170 ctx.attachExtraTrace(warning);
13171 } else {
13172 var parsed = parseStackAndMessage(warning);
13173 warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
13174 }
13175
13176 if (!activeFireEvent("warning", warning)) {
13177 formatAndLogError(warning, "", true);
13178 }
13179}
13180
13181function reconstructStack(message, stacks) {
13182 for (var i = 0; i < stacks.length - 1; ++i) {
13183 stacks[i].push("From previous event:");
13184 stacks[i] = stacks[i].join("\n");
13185 }
13186 if (i < stacks.length) {
13187 stacks[i] = stacks[i].join("\n");
13188 }
13189 return message + "\n" + stacks.join("\n");
13190}
13191
13192function removeDuplicateOrEmptyJumps(stacks) {
13193 for (var i = 0; i < stacks.length; ++i) {
13194 if (stacks[i].length === 0 ||
13195 ((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
13196 stacks.splice(i, 1);
13197 i--;
13198 }
13199 }
13200}
13201
13202function removeCommonRoots(stacks) {
13203 var current = stacks[0];
13204 for (var i = 1; i < stacks.length; ++i) {
13205 var prev = stacks[i];
13206 var currentLastIndex = current.length - 1;
13207 var currentLastLine = current[currentLastIndex];
13208 var commonRootMeetPoint = -1;
13209
13210 for (var j = prev.length - 1; j >= 0; --j) {
13211 if (prev[j] === currentLastLine) {
13212 commonRootMeetPoint = j;
13213 break;
13214 }
13215 }
13216
13217 for (var j = commonRootMeetPoint; j >= 0; --j) {
13218 var line = prev[j];
13219 if (current[currentLastIndex] === line) {
13220 current.pop();
13221 currentLastIndex--;
13222 } else {
13223 break;
13224 }
13225 }
13226 current = prev;
13227 }
13228}
13229
13230function cleanStack(stack) {
13231 var ret = [];
13232 for (var i = 0; i < stack.length; ++i) {
13233 var line = stack[i];
13234 var isTraceLine = " (No stack trace)" === line ||
13235 stackFramePattern.test(line);
13236 var isInternalFrame = isTraceLine && shouldIgnore(line);
13237 if (isTraceLine && !isInternalFrame) {
13238 if (indentStackFrames && line.charAt(0) !== " ") {
13239 line = " " + line;
13240 }
13241 ret.push(line);
13242 }
13243 }
13244 return ret;
13245}
13246
13247function stackFramesAsArray(error) {
13248 var stack = error.stack.replace(/\s+$/g, "").split("\n");
13249 for (var i = 0; i < stack.length; ++i) {
13250 var line = stack[i];
13251 if (" (No stack trace)" === line || stackFramePattern.test(line)) {
13252 break;
13253 }
13254 }
13255 if (i > 0 && error.name != "SyntaxError") {
13256 stack = stack.slice(i);
13257 }
13258 return stack;
13259}
13260
13261function parseStackAndMessage(error) {
13262 var stack = error.stack;
13263 var message = error.toString();
13264 stack = typeof stack === "string" && stack.length > 0
13265 ? stackFramesAsArray(error) : [" (No stack trace)"];
13266 return {
13267 message: message,
13268 stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
13269 };
13270}
13271
13272function formatAndLogError(error, title, isSoft) {
13273 if (typeof console !== "undefined") {
13274 var message;
13275 if (util.isObject(error)) {
13276 var stack = error.stack;
13277 message = title + formatStack(stack, error);
13278 } else {
13279 message = title + String(error);
13280 }
13281 if (typeof printWarning === "function") {
13282 printWarning(message, isSoft);
13283 } else if (typeof console.log === "function" ||
13284 typeof console.log === "object") {
13285 console.log(message);
13286 }
13287 }
13288}
13289
13290function fireRejectionEvent(name, localHandler, reason, promise) {
13291 var localEventFired = false;
13292 try {
13293 if (typeof localHandler === "function") {
13294 localEventFired = true;
13295 if (name === "rejectionHandled") {
13296 localHandler(promise);
13297 } else {
13298 localHandler(reason, promise);
13299 }
13300 }
13301 } catch (e) {
13302 async.throwLater(e);
13303 }
13304
13305 if (name === "unhandledRejection") {
13306 if (!activeFireEvent(name, reason, promise) && !localEventFired) {
13307 formatAndLogError(reason, "Unhandled rejection ");
13308 }
13309 } else {
13310 activeFireEvent(name, promise);
13311 }
13312}
13313
13314function formatNonError(obj) {
13315 var str;
13316 if (typeof obj === "function") {
13317 str = "[function " +
13318 (obj.name || "anonymous") +
13319 "]";
13320 } else {
13321 str = obj && typeof obj.toString === "function"
13322 ? obj.toString() : util.toString(obj);
13323 var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
13324 if (ruselessToString.test(str)) {
13325 try {
13326 var newStr = JSON.stringify(obj);
13327 str = newStr;
13328 }
13329 catch(e) {
13330
13331 }
13332 }
13333 if (str.length === 0) {
13334 str = "(empty array)";
13335 }
13336 }
13337 return ("(<" + snip(str) + ">, no stack trace)");
13338}
13339
13340function snip(str) {
13341 var maxChars = 41;
13342 if (str.length < maxChars) {
13343 return str;
13344 }
13345 return str.substr(0, maxChars - 3) + "...";
13346}
13347
13348function longStackTracesIsSupported() {
13349 return typeof captureStackTrace === "function";
13350}
13351
13352var shouldIgnore = function() { return false; };
13353var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
13354function parseLineInfo(line) {
13355 var matches = line.match(parseLineInfoRegex);
13356 if (matches) {
13357 return {
13358 fileName: matches[1],
13359 line: parseInt(matches[2], 10)
13360 };
13361 }
13362}
13363
13364function setBounds(firstLineError, lastLineError) {
13365 if (!longStackTracesIsSupported()) return;
13366 var firstStackLines = (firstLineError.stack || "").split("\n");
13367 var lastStackLines = (lastLineError.stack || "").split("\n");
13368 var firstIndex = -1;
13369 var lastIndex = -1;
13370 var firstFileName;
13371 var lastFileName;
13372 for (var i = 0; i < firstStackLines.length; ++i) {
13373 var result = parseLineInfo(firstStackLines[i]);
13374 if (result) {
13375 firstFileName = result.fileName;
13376 firstIndex = result.line;
13377 break;
13378 }
13379 }
13380 for (var i = 0; i < lastStackLines.length; ++i) {
13381 var result = parseLineInfo(lastStackLines[i]);
13382 if (result) {
13383 lastFileName = result.fileName;
13384 lastIndex = result.line;
13385 break;
13386 }
13387 }
13388 if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
13389 firstFileName !== lastFileName || firstIndex >= lastIndex) {
13390 return;
13391 }
13392
13393 shouldIgnore = function(line) {
13394 if (bluebirdFramePattern.test(line)) return true;
13395 var info = parseLineInfo(line);
13396 if (info) {
13397 if (info.fileName === firstFileName &&
13398 (firstIndex <= info.line && info.line <= lastIndex)) {
13399 return true;
13400 }
13401 }
13402 return false;
13403 };
13404}
13405
13406function CapturedTrace(parent) {
13407 this._parent = parent;
13408 this._promisesCreated = 0;
13409 var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
13410 captureStackTrace(this, CapturedTrace);
13411 if (length > 32) this.uncycle();
13412}
13413util.inherits(CapturedTrace, Error);
13414Context.CapturedTrace = CapturedTrace;
13415
13416CapturedTrace.prototype.uncycle = function() {
13417 var length = this._length;
13418 if (length < 2) return;
13419 var nodes = [];
13420 var stackToIndex = {};
13421
13422 for (var i = 0, node = this; node !== undefined; ++i) {
13423 nodes.push(node);
13424 node = node._parent;
13425 }
13426 length = this._length = i;
13427 for (var i = length - 1; i >= 0; --i) {
13428 var stack = nodes[i].stack;
13429 if (stackToIndex[stack] === undefined) {
13430 stackToIndex[stack] = i;
13431 }
13432 }
13433 for (var i = 0; i < length; ++i) {
13434 var currentStack = nodes[i].stack;
13435 var index = stackToIndex[currentStack];
13436 if (index !== undefined && index !== i) {
13437 if (index > 0) {
13438 nodes[index - 1]._parent = undefined;
13439 nodes[index - 1]._length = 1;
13440 }
13441 nodes[i]._parent = undefined;
13442 nodes[i]._length = 1;
13443 var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
13444
13445 if (index < length - 1) {
13446 cycleEdgeNode._parent = nodes[index + 1];
13447 cycleEdgeNode._parent.uncycle();
13448 cycleEdgeNode._length =
13449 cycleEdgeNode._parent._length + 1;
13450 } else {
13451 cycleEdgeNode._parent = undefined;
13452 cycleEdgeNode._length = 1;
13453 }
13454 var currentChildLength = cycleEdgeNode._length + 1;
13455 for (var j = i - 2; j >= 0; --j) {
13456 nodes[j]._length = currentChildLength;
13457 currentChildLength++;
13458 }
13459 return;
13460 }
13461 }
13462};
13463
13464CapturedTrace.prototype.attachExtraTrace = function(error) {
13465 if (error.__stackCleaned__) return;
13466 this.uncycle();
13467 var parsed = parseStackAndMessage(error);
13468 var message = parsed.message;
13469 var stacks = [parsed.stack];
13470
13471 var trace = this;
13472 while (trace !== undefined) {
13473 stacks.push(cleanStack(trace.stack.split("\n")));
13474 trace = trace._parent;
13475 }
13476 removeCommonRoots(stacks);
13477 removeDuplicateOrEmptyJumps(stacks);
13478 util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
13479 util.notEnumerableProp(error, "__stackCleaned__", true);
13480};
13481
13482var captureStackTrace = (function stackDetection() {
13483 var v8stackFramePattern = /^\s*at\s*/;
13484 var v8stackFormatter = function(stack, error) {
13485 if (typeof stack === "string") return stack;
13486
13487 if (error.name !== undefined &&
13488 error.message !== undefined) {
13489 return error.toString();
13490 }
13491 return formatNonError(error);
13492 };
13493
13494 if (typeof Error.stackTraceLimit === "number" &&
13495 typeof Error.captureStackTrace === "function") {
13496 Error.stackTraceLimit += 6;
13497 stackFramePattern = v8stackFramePattern;
13498 formatStack = v8stackFormatter;
13499 var captureStackTrace = Error.captureStackTrace;
13500
13501 shouldIgnore = function(line) {
13502 return bluebirdFramePattern.test(line);
13503 };
13504 return function(receiver, ignoreUntil) {
13505 Error.stackTraceLimit += 6;
13506 captureStackTrace(receiver, ignoreUntil);
13507 Error.stackTraceLimit -= 6;
13508 };
13509 }
13510 var err = new Error();
13511
13512 if (typeof err.stack === "string" &&
13513 err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
13514 stackFramePattern = /@/;
13515 formatStack = v8stackFormatter;
13516 indentStackFrames = true;
13517 return function captureStackTrace(o) {
13518 o.stack = new Error().stack;
13519 };
13520 }
13521
13522 var hasStackAfterThrow;
13523 try { throw new Error(); }
13524 catch(e) {
13525 hasStackAfterThrow = ("stack" in e);
13526 }
13527 if (!("stack" in err) && hasStackAfterThrow &&
13528 typeof Error.stackTraceLimit === "number") {
13529 stackFramePattern = v8stackFramePattern;
13530 formatStack = v8stackFormatter;
13531 return function captureStackTrace(o) {
13532 Error.stackTraceLimit += 6;
13533 try { throw new Error(); }
13534 catch(e) { o.stack = e.stack; }
13535 Error.stackTraceLimit -= 6;
13536 };
13537 }
13538
13539 formatStack = function(stack, error) {
13540 if (typeof stack === "string") return stack;
13541
13542 if ((typeof error === "object" ||
13543 typeof error === "function") &&
13544 error.name !== undefined &&
13545 error.message !== undefined) {
13546 return error.toString();
13547 }
13548 return formatNonError(error);
13549 };
13550
13551 return null;
13552
13553})([]);
13554
13555if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
13556 printWarning = function (message) {
13557 console.warn(message);
13558 };
13559 if (util.isNode && process.stderr.isTTY) {
13560 printWarning = function(message, isSoft) {
13561 var color = isSoft ? "\u001b[33m" : "\u001b[31m";
13562 console.warn(color + message + "\u001b[0m\n");
13563 };
13564 } else if (!util.isNode && typeof (new Error().stack) === "string") {
13565 printWarning = function(message, isSoft) {
13566 console.warn("%c" + message,
13567 isSoft ? "color: darkorange" : "color: red");
13568 };
13569 }
13570}
13571
13572var config = {
13573 warnings: warnings,
13574 longStackTraces: false,
13575 cancellation: false,
13576 monitoring: false
13577};
13578
13579if (longStackTraces) Promise.longStackTraces();
13580
13581return {
13582 longStackTraces: function() {
13583 return config.longStackTraces;
13584 },
13585 warnings: function() {
13586 return config.warnings;
13587 },
13588 cancellation: function() {
13589 return config.cancellation;
13590 },
13591 monitoring: function() {
13592 return config.monitoring;
13593 },
13594 propagateFromFunction: function() {
13595 return propagateFromFunction;
13596 },
13597 boundValueFunction: function() {
13598 return boundValueFunction;
13599 },
13600 checkForgottenReturns: checkForgottenReturns,
13601 setBounds: setBounds,
13602 warn: warn,
13603 deprecated: deprecated,
13604 CapturedTrace: CapturedTrace,
13605 fireDomEvent: fireDomEvent,
13606 fireGlobalEvent: fireGlobalEvent
13607};
13608};
13609
13610},{"./errors":12,"./es5":13,"./util":36}],10:[function(_dereq_,module,exports){
13611"use strict";
13612module.exports = function(Promise) {
13613function returner() {
13614 return this.value;
13615}
13616function thrower() {
13617 throw this.reason;
13618}
13619
13620Promise.prototype["return"] =
13621Promise.prototype.thenReturn = function (value) {
13622 if (value instanceof Promise) value.suppressUnhandledRejections();
13623 return this._then(
13624 returner, undefined, undefined, {value: value}, undefined);
13625};
13626
13627Promise.prototype["throw"] =
13628Promise.prototype.thenThrow = function (reason) {
13629 return this._then(
13630 thrower, undefined, undefined, {reason: reason}, undefined);
13631};
13632
13633Promise.prototype.catchThrow = function (reason) {
13634 if (arguments.length <= 1) {
13635 return this._then(
13636 undefined, thrower, undefined, {reason: reason}, undefined);
13637 } else {
13638 var _reason = arguments[1];
13639 var handler = function() {throw _reason;};
13640 return this.caught(reason, handler);
13641 }
13642};
13643
13644Promise.prototype.catchReturn = function (value) {
13645 if (arguments.length <= 1) {
13646 if (value instanceof Promise) value.suppressUnhandledRejections();
13647 return this._then(
13648 undefined, returner, undefined, {value: value}, undefined);
13649 } else {
13650 var _value = arguments[1];
13651 if (_value instanceof Promise) _value.suppressUnhandledRejections();
13652 var handler = function() {return _value;};
13653 return this.caught(value, handler);
13654 }
13655};
13656};
13657
13658},{}],11:[function(_dereq_,module,exports){
13659"use strict";
13660module.exports = function(Promise, INTERNAL) {
13661var PromiseReduce = Promise.reduce;
13662var PromiseAll = Promise.all;
13663
13664function promiseAllThis() {
13665 return PromiseAll(this);
13666}
13667
13668function PromiseMapSeries(promises, fn) {
13669 return PromiseReduce(promises, fn, INTERNAL, INTERNAL);
13670}
13671
13672Promise.prototype.each = function (fn) {
13673 return PromiseReduce(this, fn, INTERNAL, 0)
13674 ._then(promiseAllThis, undefined, undefined, this, undefined);
13675};
13676
13677Promise.prototype.mapSeries = function (fn) {
13678 return PromiseReduce(this, fn, INTERNAL, INTERNAL);
13679};
13680
13681Promise.each = function (promises, fn) {
13682 return PromiseReduce(promises, fn, INTERNAL, 0)
13683 ._then(promiseAllThis, undefined, undefined, promises, undefined);
13684};
13685
13686Promise.mapSeries = PromiseMapSeries;
13687};
13688
13689
13690},{}],12:[function(_dereq_,module,exports){
13691"use strict";
13692var es5 = _dereq_("./es5");
13693var Objectfreeze = es5.freeze;
13694var util = _dereq_("./util");
13695var inherits = util.inherits;
13696var notEnumerableProp = util.notEnumerableProp;
13697
13698function subError(nameProperty, defaultMessage) {
13699 function SubError(message) {
13700 if (!(this instanceof SubError)) return new SubError(message);
13701 notEnumerableProp(this, "message",
13702 typeof message === "string" ? message : defaultMessage);
13703 notEnumerableProp(this, "name", nameProperty);
13704 if (Error.captureStackTrace) {
13705 Error.captureStackTrace(this, this.constructor);
13706 } else {
13707 Error.call(this);
13708 }
13709 }
13710 inherits(SubError, Error);
13711 return SubError;
13712}
13713
13714var _TypeError, _RangeError;
13715var Warning = subError("Warning", "warning");
13716var CancellationError = subError("CancellationError", "cancellation error");
13717var TimeoutError = subError("TimeoutError", "timeout error");
13718var AggregateError = subError("AggregateError", "aggregate error");
13719try {
13720 _TypeError = TypeError;
13721 _RangeError = RangeError;
13722} catch(e) {
13723 _TypeError = subError("TypeError", "type error");
13724 _RangeError = subError("RangeError", "range error");
13725}
13726
13727var methods = ("join pop push shift unshift slice filter forEach some " +
13728 "every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
13729
13730for (var i = 0; i < methods.length; ++i) {
13731 if (typeof Array.prototype[methods[i]] === "function") {
13732 AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
13733 }
13734}
13735
13736es5.defineProperty(AggregateError.prototype, "length", {
13737 value: 0,
13738 configurable: false,
13739 writable: true,
13740 enumerable: true
13741});
13742AggregateError.prototype["isOperational"] = true;
13743var level = 0;
13744AggregateError.prototype.toString = function() {
13745 var indent = Array(level * 4 + 1).join(" ");
13746 var ret = "\n" + indent + "AggregateError of:" + "\n";
13747 level++;
13748 indent = Array(level * 4 + 1).join(" ");
13749 for (var i = 0; i < this.length; ++i) {
13750 var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
13751 var lines = str.split("\n");
13752 for (var j = 0; j < lines.length; ++j) {
13753 lines[j] = indent + lines[j];
13754 }
13755 str = lines.join("\n");
13756 ret += str + "\n";
13757 }
13758 level--;
13759 return ret;
13760};
13761
13762function OperationalError(message) {
13763 if (!(this instanceof OperationalError))
13764 return new OperationalError(message);
13765 notEnumerableProp(this, "name", "OperationalError");
13766 notEnumerableProp(this, "message", message);
13767 this.cause = message;
13768 this["isOperational"] = true;
13769
13770 if (message instanceof Error) {
13771 notEnumerableProp(this, "message", message.message);
13772 notEnumerableProp(this, "stack", message.stack);
13773 } else if (Error.captureStackTrace) {
13774 Error.captureStackTrace(this, this.constructor);
13775 }
13776
13777}
13778inherits(OperationalError, Error);
13779
13780var errorTypes = Error["__BluebirdErrorTypes__"];
13781if (!errorTypes) {
13782 errorTypes = Objectfreeze({
13783 CancellationError: CancellationError,
13784 TimeoutError: TimeoutError,
13785 OperationalError: OperationalError,
13786 RejectionError: OperationalError,
13787 AggregateError: AggregateError
13788 });
13789 es5.defineProperty(Error, "__BluebirdErrorTypes__", {
13790 value: errorTypes,
13791 writable: false,
13792 enumerable: false,
13793 configurable: false
13794 });
13795}
13796
13797module.exports = {
13798 Error: Error,
13799 TypeError: _TypeError,
13800 RangeError: _RangeError,
13801 CancellationError: errorTypes.CancellationError,
13802 OperationalError: errorTypes.OperationalError,
13803 TimeoutError: errorTypes.TimeoutError,
13804 AggregateError: errorTypes.AggregateError,
13805 Warning: Warning
13806};
13807
13808},{"./es5":13,"./util":36}],13:[function(_dereq_,module,exports){
13809var isES5 = (function(){
13810 "use strict";
13811 return this === undefined;
13812})();
13813
13814if (isES5) {
13815 module.exports = {
13816 freeze: Object.freeze,
13817 defineProperty: Object.defineProperty,
13818 getDescriptor: Object.getOwnPropertyDescriptor,
13819 keys: Object.keys,
13820 names: Object.getOwnPropertyNames,
13821 getPrototypeOf: Object.getPrototypeOf,
13822 isArray: Array.isArray,
13823 isES5: isES5,
13824 propertyIsWritable: function(obj, prop) {
13825 var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
13826 return !!(!descriptor || descriptor.writable || descriptor.set);
13827 }
13828 };
13829} else {
13830 var has = {}.hasOwnProperty;
13831 var str = {}.toString;
13832 var proto = {}.constructor.prototype;
13833
13834 var ObjectKeys = function (o) {
13835 var ret = [];
13836 for (var key in o) {
13837 if (has.call(o, key)) {
13838 ret.push(key);
13839 }
13840 }
13841 return ret;
13842 };
13843
13844 var ObjectGetDescriptor = function(o, key) {
13845 return {value: o[key]};
13846 };
13847
13848 var ObjectDefineProperty = function (o, key, desc) {
13849 o[key] = desc.value;
13850 return o;
13851 };
13852
13853 var ObjectFreeze = function (obj) {
13854 return obj;
13855 };
13856
13857 var ObjectGetPrototypeOf = function (obj) {
13858 try {
13859 return Object(obj).constructor.prototype;
13860 }
13861 catch (e) {
13862 return proto;
13863 }
13864 };
13865
13866 var ArrayIsArray = function (obj) {
13867 try {
13868 return str.call(obj) === "[object Array]";
13869 }
13870 catch(e) {
13871 return false;
13872 }
13873 };
13874
13875 module.exports = {
13876 isArray: ArrayIsArray,
13877 keys: ObjectKeys,
13878 names: ObjectKeys,
13879 defineProperty: ObjectDefineProperty,
13880 getDescriptor: ObjectGetDescriptor,
13881 freeze: ObjectFreeze,
13882 getPrototypeOf: ObjectGetPrototypeOf,
13883 isES5: isES5,
13884 propertyIsWritable: function() {
13885 return true;
13886 }
13887 };
13888}
13889
13890},{}],14:[function(_dereq_,module,exports){
13891"use strict";
13892module.exports = function(Promise, INTERNAL) {
13893var PromiseMap = Promise.map;
13894
13895Promise.prototype.filter = function (fn, options) {
13896 return PromiseMap(this, fn, options, INTERNAL);
13897};
13898
13899Promise.filter = function (promises, fn, options) {
13900 return PromiseMap(promises, fn, options, INTERNAL);
13901};
13902};
13903
13904},{}],15:[function(_dereq_,module,exports){
13905"use strict";
13906module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
13907var util = _dereq_("./util");
13908var CancellationError = Promise.CancellationError;
13909var errorObj = util.errorObj;
13910var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
13911
13912function PassThroughHandlerContext(promise, type, handler) {
13913 this.promise = promise;
13914 this.type = type;
13915 this.handler = handler;
13916 this.called = false;
13917 this.cancelPromise = null;
13918}
13919
13920PassThroughHandlerContext.prototype.isFinallyHandler = function() {
13921 return this.type === 0;
13922};
13923
13924function FinallyHandlerCancelReaction(finallyHandler) {
13925 this.finallyHandler = finallyHandler;
13926}
13927
13928FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
13929 checkCancel(this.finallyHandler);
13930};
13931
13932function checkCancel(ctx, reason) {
13933 if (ctx.cancelPromise != null) {
13934 if (arguments.length > 1) {
13935 ctx.cancelPromise._reject(reason);
13936 } else {
13937 ctx.cancelPromise._cancel();
13938 }
13939 ctx.cancelPromise = null;
13940 return true;
13941 }
13942 return false;
13943}
13944
13945function succeed() {
13946 return finallyHandler.call(this, this.promise._target()._settledValue());
13947}
13948function fail(reason) {
13949 if (checkCancel(this, reason)) return;
13950 errorObj.e = reason;
13951 return errorObj;
13952}
13953function finallyHandler(reasonOrValue) {
13954 var promise = this.promise;
13955 var handler = this.handler;
13956
13957 if (!this.called) {
13958 this.called = true;
13959 var ret = this.isFinallyHandler()
13960 ? handler.call(promise._boundValue())
13961 : handler.call(promise._boundValue(), reasonOrValue);
13962 if (ret === NEXT_FILTER) {
13963 return ret;
13964 } else if (ret !== undefined) {
13965 promise._setReturnedNonUndefined();
13966 var maybePromise = tryConvertToPromise(ret, promise);
13967 if (maybePromise instanceof Promise) {
13968 if (this.cancelPromise != null) {
13969 if (maybePromise._isCancelled()) {
13970 var reason =
13971 new CancellationError("late cancellation observer");
13972 promise._attachExtraTrace(reason);
13973 errorObj.e = reason;
13974 return errorObj;
13975 } else if (maybePromise.isPending()) {
13976 maybePromise._attachCancellationCallback(
13977 new FinallyHandlerCancelReaction(this));
13978 }
13979 }
13980 return maybePromise._then(
13981 succeed, fail, undefined, this, undefined);
13982 }
13983 }
13984 }
13985
13986 if (promise.isRejected()) {
13987 checkCancel(this);
13988 errorObj.e = reasonOrValue;
13989 return errorObj;
13990 } else {
13991 checkCancel(this);
13992 return reasonOrValue;
13993 }
13994}
13995
13996Promise.prototype._passThrough = function(handler, type, success, fail) {
13997 if (typeof handler !== "function") return this.then();
13998 return this._then(success,
13999 fail,
14000 undefined,
14001 new PassThroughHandlerContext(this, type, handler),
14002 undefined);
14003};
14004
14005Promise.prototype.lastly =
14006Promise.prototype["finally"] = function (handler) {
14007 return this._passThrough(handler,
14008 0,
14009 finallyHandler,
14010 finallyHandler);
14011};
14012
14013
14014Promise.prototype.tap = function (handler) {
14015 return this._passThrough(handler, 1, finallyHandler);
14016};
14017
14018Promise.prototype.tapCatch = function (handlerOrPredicate) {
14019 var len = arguments.length;
14020 if(len === 1) {
14021 return this._passThrough(handlerOrPredicate,
14022 1,
14023 undefined,
14024 finallyHandler);
14025 } else {
14026 var catchInstances = new Array(len - 1),
14027 j = 0, i;
14028 for (i = 0; i < len - 1; ++i) {
14029 var item = arguments[i];
14030 if (util.isObject(item)) {
14031 catchInstances[j++] = item;
14032 } else {
14033 return Promise.reject(new TypeError(
14034 "tapCatch statement predicate: "
14035 + "expecting an object but got " + util.classString(item)
14036 ));
14037 }
14038 }
14039 catchInstances.length = j;
14040 var handler = arguments[i];
14041 return this._passThrough(catchFilter(catchInstances, handler, this),
14042 1,
14043 undefined,
14044 finallyHandler);
14045 }
14046
14047};
14048
14049return PassThroughHandlerContext;
14050};
14051
14052},{"./catch_filter":7,"./util":36}],16:[function(_dereq_,module,exports){
14053"use strict";
14054module.exports = function(Promise,
14055 apiRejection,
14056 INTERNAL,
14057 tryConvertToPromise,
14058 Proxyable,
14059 debug) {
14060var errors = _dereq_("./errors");
14061var TypeError = errors.TypeError;
14062var util = _dereq_("./util");
14063var errorObj = util.errorObj;
14064var tryCatch = util.tryCatch;
14065var yieldHandlers = [];
14066
14067function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
14068 for (var i = 0; i < yieldHandlers.length; ++i) {
14069 traceParent._pushContext();
14070 var result = tryCatch(yieldHandlers[i])(value);
14071 traceParent._popContext();
14072 if (result === errorObj) {
14073 traceParent._pushContext();
14074 var ret = Promise.reject(errorObj.e);
14075 traceParent._popContext();
14076 return ret;
14077 }
14078 var maybePromise = tryConvertToPromise(result, traceParent);
14079 if (maybePromise instanceof Promise) return maybePromise;
14080 }
14081 return null;
14082}
14083
14084function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
14085 if (debug.cancellation()) {
14086 var internal = new Promise(INTERNAL);
14087 var _finallyPromise = this._finallyPromise = new Promise(INTERNAL);
14088 this._promise = internal.lastly(function() {
14089 return _finallyPromise;
14090 });
14091 internal._captureStackTrace();
14092 internal._setOnCancel(this);
14093 } else {
14094 var promise = this._promise = new Promise(INTERNAL);
14095 promise._captureStackTrace();
14096 }
14097 this._stack = stack;
14098 this._generatorFunction = generatorFunction;
14099 this._receiver = receiver;
14100 this._generator = undefined;
14101 this._yieldHandlers = typeof yieldHandler === "function"
14102 ? [yieldHandler].concat(yieldHandlers)
14103 : yieldHandlers;
14104 this._yieldedPromise = null;
14105 this._cancellationPhase = false;
14106}
14107util.inherits(PromiseSpawn, Proxyable);
14108
14109PromiseSpawn.prototype._isResolved = function() {
14110 return this._promise === null;
14111};
14112
14113PromiseSpawn.prototype._cleanup = function() {
14114 this._promise = this._generator = null;
14115 if (debug.cancellation() && this._finallyPromise !== null) {
14116 this._finallyPromise._fulfill();
14117 this._finallyPromise = null;
14118 }
14119};
14120
14121PromiseSpawn.prototype._promiseCancelled = function() {
14122 if (this._isResolved()) return;
14123 var implementsReturn = typeof this._generator["return"] !== "undefined";
14124
14125 var result;
14126 if (!implementsReturn) {
14127 var reason = new Promise.CancellationError(
14128 "generator .return() sentinel");
14129 Promise.coroutine.returnSentinel = reason;
14130 this._promise._attachExtraTrace(reason);
14131 this._promise._pushContext();
14132 result = tryCatch(this._generator["throw"]).call(this._generator,
14133 reason);
14134 this._promise._popContext();
14135 } else {
14136 this._promise._pushContext();
14137 result = tryCatch(this._generator["return"]).call(this._generator,
14138 undefined);
14139 this._promise._popContext();
14140 }
14141 this._cancellationPhase = true;
14142 this._yieldedPromise = null;
14143 this._continue(result);
14144};
14145
14146PromiseSpawn.prototype._promiseFulfilled = function(value) {
14147 this._yieldedPromise = null;
14148 this._promise._pushContext();
14149 var result = tryCatch(this._generator.next).call(this._generator, value);
14150 this._promise._popContext();
14151 this._continue(result);
14152};
14153
14154PromiseSpawn.prototype._promiseRejected = function(reason) {
14155 this._yieldedPromise = null;
14156 this._promise._attachExtraTrace(reason);
14157 this._promise._pushContext();
14158 var result = tryCatch(this._generator["throw"])
14159 .call(this._generator, reason);
14160 this._promise._popContext();
14161 this._continue(result);
14162};
14163
14164PromiseSpawn.prototype._resultCancelled = function() {
14165 if (this._yieldedPromise instanceof Promise) {
14166 var promise = this._yieldedPromise;
14167 this._yieldedPromise = null;
14168 promise.cancel();
14169 }
14170};
14171
14172PromiseSpawn.prototype.promise = function () {
14173 return this._promise;
14174};
14175
14176PromiseSpawn.prototype._run = function () {
14177 this._generator = this._generatorFunction.call(this._receiver);
14178 this._receiver =
14179 this._generatorFunction = undefined;
14180 this._promiseFulfilled(undefined);
14181};
14182
14183PromiseSpawn.prototype._continue = function (result) {
14184 var promise = this._promise;
14185 if (result === errorObj) {
14186 this._cleanup();
14187 if (this._cancellationPhase) {
14188 return promise.cancel();
14189 } else {
14190 return promise._rejectCallback(result.e, false);
14191 }
14192 }
14193
14194 var value = result.value;
14195 if (result.done === true) {
14196 this._cleanup();
14197 if (this._cancellationPhase) {
14198 return promise.cancel();
14199 } else {
14200 return promise._resolveCallback(value);
14201 }
14202 } else {
14203 var maybePromise = tryConvertToPromise(value, this._promise);
14204 if (!(maybePromise instanceof Promise)) {
14205 maybePromise =
14206 promiseFromYieldHandler(maybePromise,
14207 this._yieldHandlers,
14208 this._promise);
14209 if (maybePromise === null) {
14210 this._promiseRejected(
14211 new TypeError(
14212 "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)) +
14213 "From coroutine:\u000a" +
14214 this._stack.split("\n").slice(1, -7).join("\n")
14215 )
14216 );
14217 return;
14218 }
14219 }
14220 maybePromise = maybePromise._target();
14221 var bitField = maybePromise._bitField;
14222 ;
14223 if (((bitField & 50397184) === 0)) {
14224 this._yieldedPromise = maybePromise;
14225 maybePromise._proxy(this, null);
14226 } else if (((bitField & 33554432) !== 0)) {
14227 Promise._async.invoke(
14228 this._promiseFulfilled, this, maybePromise._value()
14229 );
14230 } else if (((bitField & 16777216) !== 0)) {
14231 Promise._async.invoke(
14232 this._promiseRejected, this, maybePromise._reason()
14233 );
14234 } else {
14235 this._promiseCancelled();
14236 }
14237 }
14238};
14239
14240Promise.coroutine = function (generatorFunction, options) {
14241 if (typeof generatorFunction !== "function") {
14242 throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
14243 }
14244 var yieldHandler = Object(options).yieldHandler;
14245 var PromiseSpawn$ = PromiseSpawn;
14246 var stack = new Error().stack;
14247 return function () {
14248 var generator = generatorFunction.apply(this, arguments);
14249 var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
14250 stack);
14251 var ret = spawn.promise();
14252 spawn._generator = generator;
14253 spawn._promiseFulfilled(undefined);
14254 return ret;
14255 };
14256};
14257
14258Promise.coroutine.addYieldHandler = function(fn) {
14259 if (typeof fn !== "function") {
14260 throw new TypeError("expecting a function but got " + util.classString(fn));
14261 }
14262 yieldHandlers.push(fn);
14263};
14264
14265Promise.spawn = function (generatorFunction) {
14266 debug.deprecated("Promise.spawn()", "Promise.coroutine()");
14267 if (typeof generatorFunction !== "function") {
14268 return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
14269 }
14270 var spawn = new PromiseSpawn(generatorFunction, this);
14271 var ret = spawn.promise();
14272 spawn._run(Promise.spawn);
14273 return ret;
14274};
14275};
14276
14277},{"./errors":12,"./util":36}],17:[function(_dereq_,module,exports){
14278"use strict";
14279module.exports =
14280function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
14281 getDomain) {
14282var util = _dereq_("./util");
14283var canEvaluate = util.canEvaluate;
14284var tryCatch = util.tryCatch;
14285var errorObj = util.errorObj;
14286var reject;
14287
14288if (!true) {
14289if (canEvaluate) {
14290 var thenCallback = function(i) {
14291 return new Function("value", "holder", " \n\
14292 'use strict'; \n\
14293 holder.pIndex = value; \n\
14294 holder.checkFulfillment(this); \n\
14295 ".replace(/Index/g, i));
14296 };
14297
14298 var promiseSetter = function(i) {
14299 return new Function("promise", "holder", " \n\
14300 'use strict'; \n\
14301 holder.pIndex = promise; \n\
14302 ".replace(/Index/g, i));
14303 };
14304
14305 var generateHolderClass = function(total) {
14306 var props = new Array(total);
14307 for (var i = 0; i < props.length; ++i) {
14308 props[i] = "this.p" + (i+1);
14309 }
14310 var assignment = props.join(" = ") + " = null;";
14311 var cancellationCode= "var promise;\n" + props.map(function(prop) {
14312 return " \n\
14313 promise = " + prop + "; \n\
14314 if (promise instanceof Promise) { \n\
14315 promise.cancel(); \n\
14316 } \n\
14317 ";
14318 }).join("\n");
14319 var passedArguments = props.join(", ");
14320 var name = "Holder$" + total;
14321
14322
14323 var code = "return function(tryCatch, errorObj, Promise, async) { \n\
14324 'use strict'; \n\
14325 function [TheName](fn) { \n\
14326 [TheProperties] \n\
14327 this.fn = fn; \n\
14328 this.asyncNeeded = true; \n\
14329 this.now = 0; \n\
14330 } \n\
14331 \n\
14332 [TheName].prototype._callFunction = function(promise) { \n\
14333 promise._pushContext(); \n\
14334 var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
14335 promise._popContext(); \n\
14336 if (ret === errorObj) { \n\
14337 promise._rejectCallback(ret.e, false); \n\
14338 } else { \n\
14339 promise._resolveCallback(ret); \n\
14340 } \n\
14341 }; \n\
14342 \n\
14343 [TheName].prototype.checkFulfillment = function(promise) { \n\
14344 var now = ++this.now; \n\
14345 if (now === [TheTotal]) { \n\
14346 if (this.asyncNeeded) { \n\
14347 async.invoke(this._callFunction, this, promise); \n\
14348 } else { \n\
14349 this._callFunction(promise); \n\
14350 } \n\
14351 \n\
14352 } \n\
14353 }; \n\
14354 \n\
14355 [TheName].prototype._resultCancelled = function() { \n\
14356 [CancellationCode] \n\
14357 }; \n\
14358 \n\
14359 return [TheName]; \n\
14360 }(tryCatch, errorObj, Promise, async); \n\
14361 ";
14362
14363 code = code.replace(/\[TheName\]/g, name)
14364 .replace(/\[TheTotal\]/g, total)
14365 .replace(/\[ThePassedArguments\]/g, passedArguments)
14366 .replace(/\[TheProperties\]/g, assignment)
14367 .replace(/\[CancellationCode\]/g, cancellationCode);
14368
14369 return new Function("tryCatch", "errorObj", "Promise", "async", code)
14370 (tryCatch, errorObj, Promise, async);
14371 };
14372
14373 var holderClasses = [];
14374 var thenCallbacks = [];
14375 var promiseSetters = [];
14376
14377 for (var i = 0; i < 8; ++i) {
14378 holderClasses.push(generateHolderClass(i + 1));
14379 thenCallbacks.push(thenCallback(i + 1));
14380 promiseSetters.push(promiseSetter(i + 1));
14381 }
14382
14383 reject = function (reason) {
14384 this._reject(reason);
14385 };
14386}}
14387
14388Promise.join = function () {
14389 var last = arguments.length - 1;
14390 var fn;
14391 if (last > 0 && typeof arguments[last] === "function") {
14392 fn = arguments[last];
14393 if (!true) {
14394 if (last <= 8 && canEvaluate) {
14395 var ret = new Promise(INTERNAL);
14396 ret._captureStackTrace();
14397 var HolderClass = holderClasses[last - 1];
14398 var holder = new HolderClass(fn);
14399 var callbacks = thenCallbacks;
14400
14401 for (var i = 0; i < last; ++i) {
14402 var maybePromise = tryConvertToPromise(arguments[i], ret);
14403 if (maybePromise instanceof Promise) {
14404 maybePromise = maybePromise._target();
14405 var bitField = maybePromise._bitField;
14406 ;
14407 if (((bitField & 50397184) === 0)) {
14408 maybePromise._then(callbacks[i], reject,
14409 undefined, ret, holder);
14410 promiseSetters[i](maybePromise, holder);
14411 holder.asyncNeeded = false;
14412 } else if (((bitField & 33554432) !== 0)) {
14413 callbacks[i].call(ret,
14414 maybePromise._value(), holder);
14415 } else if (((bitField & 16777216) !== 0)) {
14416 ret._reject(maybePromise._reason());
14417 } else {
14418 ret._cancel();
14419 }
14420 } else {
14421 callbacks[i].call(ret, maybePromise, holder);
14422 }
14423 }
14424
14425 if (!ret._isFateSealed()) {
14426 if (holder.asyncNeeded) {
14427 var domain = getDomain();
14428 if (domain !== null) {
14429 holder.fn = util.domainBind(domain, holder.fn);
14430 }
14431 }
14432 ret._setAsyncGuaranteed();
14433 ret._setOnCancel(holder);
14434 }
14435 return ret;
14436 }
14437 }
14438 }
14439 var args = [].slice.call(arguments);;
14440 if (fn) args.pop();
14441 var ret = new PromiseArray(args).promise();
14442 return fn !== undefined ? ret.spread(fn) : ret;
14443};
14444
14445};
14446
14447},{"./util":36}],18:[function(_dereq_,module,exports){
14448"use strict";
14449module.exports = function(Promise,
14450 PromiseArray,
14451 apiRejection,
14452 tryConvertToPromise,
14453 INTERNAL,
14454 debug) {
14455var getDomain = Promise._getDomain;
14456var util = _dereq_("./util");
14457var tryCatch = util.tryCatch;
14458var errorObj = util.errorObj;
14459var async = Promise._async;
14460
14461function MappingPromiseArray(promises, fn, limit, _filter) {
14462 this.constructor$(promises);
14463 this._promise._captureStackTrace();
14464 var domain = getDomain();
14465 this._callback = domain === null ? fn : util.domainBind(domain, fn);
14466 this._preservedValues = _filter === INTERNAL
14467 ? new Array(this.length())
14468 : null;
14469 this._limit = limit;
14470 this._inFlight = 0;
14471 this._queue = [];
14472 async.invoke(this._asyncInit, this, undefined);
14473}
14474util.inherits(MappingPromiseArray, PromiseArray);
14475
14476MappingPromiseArray.prototype._asyncInit = function() {
14477 this._init$(undefined, -2);
14478};
14479
14480MappingPromiseArray.prototype._init = function () {};
14481
14482MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
14483 var values = this._values;
14484 var length = this.length();
14485 var preservedValues = this._preservedValues;
14486 var limit = this._limit;
14487
14488 if (index < 0) {
14489 index = (index * -1) - 1;
14490 values[index] = value;
14491 if (limit >= 1) {
14492 this._inFlight--;
14493 this._drainQueue();
14494 if (this._isResolved()) return true;
14495 }
14496 } else {
14497 if (limit >= 1 && this._inFlight >= limit) {
14498 values[index] = value;
14499 this._queue.push(index);
14500 return false;
14501 }
14502 if (preservedValues !== null) preservedValues[index] = value;
14503
14504 var promise = this._promise;
14505 var callback = this._callback;
14506 var receiver = promise._boundValue();
14507 promise._pushContext();
14508 var ret = tryCatch(callback).call(receiver, value, index, length);
14509 var promiseCreated = promise._popContext();
14510 debug.checkForgottenReturns(
14511 ret,
14512 promiseCreated,
14513 preservedValues !== null ? "Promise.filter" : "Promise.map",
14514 promise
14515 );
14516 if (ret === errorObj) {
14517 this._reject(ret.e);
14518 return true;
14519 }
14520
14521 var maybePromise = tryConvertToPromise(ret, this._promise);
14522 if (maybePromise instanceof Promise) {
14523 maybePromise = maybePromise._target();
14524 var bitField = maybePromise._bitField;
14525 ;
14526 if (((bitField & 50397184) === 0)) {
14527 if (limit >= 1) this._inFlight++;
14528 values[index] = maybePromise;
14529 maybePromise._proxy(this, (index + 1) * -1);
14530 return false;
14531 } else if (((bitField & 33554432) !== 0)) {
14532 ret = maybePromise._value();
14533 } else if (((bitField & 16777216) !== 0)) {
14534 this._reject(maybePromise._reason());
14535 return true;
14536 } else {
14537 this._cancel();
14538 return true;
14539 }
14540 }
14541 values[index] = ret;
14542 }
14543 var totalResolved = ++this._totalResolved;
14544 if (totalResolved >= length) {
14545 if (preservedValues !== null) {
14546 this._filter(values, preservedValues);
14547 } else {
14548 this._resolve(values);
14549 }
14550 return true;
14551 }
14552 return false;
14553};
14554
14555MappingPromiseArray.prototype._drainQueue = function () {
14556 var queue = this._queue;
14557 var limit = this._limit;
14558 var values = this._values;
14559 while (queue.length > 0 && this._inFlight < limit) {
14560 if (this._isResolved()) return;
14561 var index = queue.pop();
14562 this._promiseFulfilled(values[index], index);
14563 }
14564};
14565
14566MappingPromiseArray.prototype._filter = function (booleans, values) {
14567 var len = values.length;
14568 var ret = new Array(len);
14569 var j = 0;
14570 for (var i = 0; i < len; ++i) {
14571 if (booleans[i]) ret[j++] = values[i];
14572 }
14573 ret.length = j;
14574 this._resolve(ret);
14575};
14576
14577MappingPromiseArray.prototype.preservedValues = function () {
14578 return this._preservedValues;
14579};
14580
14581function map(promises, fn, options, _filter) {
14582 if (typeof fn !== "function") {
14583 return apiRejection("expecting a function but got " + util.classString(fn));
14584 }
14585
14586 var limit = 0;
14587 if (options !== undefined) {
14588 if (typeof options === "object" && options !== null) {
14589 if (typeof options.concurrency !== "number") {
14590 return Promise.reject(
14591 new TypeError("'concurrency' must be a number but it is " +
14592 util.classString(options.concurrency)));
14593 }
14594 limit = options.concurrency;
14595 } else {
14596 return Promise.reject(new TypeError(
14597 "options argument must be an object but it is " +
14598 util.classString(options)));
14599 }
14600 }
14601 limit = typeof limit === "number" &&
14602 isFinite(limit) && limit >= 1 ? limit : 0;
14603 return new MappingPromiseArray(promises, fn, limit, _filter).promise();
14604}
14605
14606Promise.prototype.map = function (fn, options) {
14607 return map(this, fn, options, null);
14608};
14609
14610Promise.map = function (promises, fn, options, _filter) {
14611 return map(promises, fn, options, _filter);
14612};
14613
14614
14615};
14616
14617},{"./util":36}],19:[function(_dereq_,module,exports){
14618"use strict";
14619module.exports =
14620function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
14621var util = _dereq_("./util");
14622var tryCatch = util.tryCatch;
14623
14624Promise.method = function (fn) {
14625 if (typeof fn !== "function") {
14626 throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
14627 }
14628 return function () {
14629 var ret = new Promise(INTERNAL);
14630 ret._captureStackTrace();
14631 ret._pushContext();
14632 var value = tryCatch(fn).apply(this, arguments);
14633 var promiseCreated = ret._popContext();
14634 debug.checkForgottenReturns(
14635 value, promiseCreated, "Promise.method", ret);
14636 ret._resolveFromSyncValue(value);
14637 return ret;
14638 };
14639};
14640
14641Promise.attempt = Promise["try"] = function (fn) {
14642 if (typeof fn !== "function") {
14643 return apiRejection("expecting a function but got " + util.classString(fn));
14644 }
14645 var ret = new Promise(INTERNAL);
14646 ret._captureStackTrace();
14647 ret._pushContext();
14648 var value;
14649 if (arguments.length > 1) {
14650 debug.deprecated("calling Promise.try with more than 1 argument");
14651 var arg = arguments[1];
14652 var ctx = arguments[2];
14653 value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
14654 : tryCatch(fn).call(ctx, arg);
14655 } else {
14656 value = tryCatch(fn)();
14657 }
14658 var promiseCreated = ret._popContext();
14659 debug.checkForgottenReturns(
14660 value, promiseCreated, "Promise.try", ret);
14661 ret._resolveFromSyncValue(value);
14662 return ret;
14663};
14664
14665Promise.prototype._resolveFromSyncValue = function (value) {
14666 if (value === util.errorObj) {
14667 this._rejectCallback(value.e, false);
14668 } else {
14669 this._resolveCallback(value, true);
14670 }
14671};
14672};
14673
14674},{"./util":36}],20:[function(_dereq_,module,exports){
14675"use strict";
14676var util = _dereq_("./util");
14677var maybeWrapAsError = util.maybeWrapAsError;
14678var errors = _dereq_("./errors");
14679var OperationalError = errors.OperationalError;
14680var es5 = _dereq_("./es5");
14681
14682function isUntypedError(obj) {
14683 return obj instanceof Error &&
14684 es5.getPrototypeOf(obj) === Error.prototype;
14685}
14686
14687var rErrorKey = /^(?:name|message|stack|cause)$/;
14688function wrapAsOperationalError(obj) {
14689 var ret;
14690 if (isUntypedError(obj)) {
14691 ret = new OperationalError(obj);
14692 ret.name = obj.name;
14693 ret.message = obj.message;
14694 ret.stack = obj.stack;
14695 var keys = es5.keys(obj);
14696 for (var i = 0; i < keys.length; ++i) {
14697 var key = keys[i];
14698 if (!rErrorKey.test(key)) {
14699 ret[key] = obj[key];
14700 }
14701 }
14702 return ret;
14703 }
14704 util.markAsOriginatingFromRejection(obj);
14705 return obj;
14706}
14707
14708function nodebackForPromise(promise, multiArgs) {
14709 return function(err, value) {
14710 if (promise === null) return;
14711 if (err) {
14712 var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
14713 promise._attachExtraTrace(wrapped);
14714 promise._reject(wrapped);
14715 } else if (!multiArgs) {
14716 promise._fulfill(value);
14717 } else {
14718 var args = [].slice.call(arguments, 1);;
14719 promise._fulfill(args);
14720 }
14721 promise = null;
14722 };
14723}
14724
14725module.exports = nodebackForPromise;
14726
14727},{"./errors":12,"./es5":13,"./util":36}],21:[function(_dereq_,module,exports){
14728"use strict";
14729module.exports = function(Promise) {
14730var util = _dereq_("./util");
14731var async = Promise._async;
14732var tryCatch = util.tryCatch;
14733var errorObj = util.errorObj;
14734
14735function spreadAdapter(val, nodeback) {
14736 var promise = this;
14737 if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
14738 var ret =
14739 tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
14740 if (ret === errorObj) {
14741 async.throwLater(ret.e);
14742 }
14743}
14744
14745function successAdapter(val, nodeback) {
14746 var promise = this;
14747 var receiver = promise._boundValue();
14748 var ret = val === undefined
14749 ? tryCatch(nodeback).call(receiver, null)
14750 : tryCatch(nodeback).call(receiver, null, val);
14751 if (ret === errorObj) {
14752 async.throwLater(ret.e);
14753 }
14754}
14755function errorAdapter(reason, nodeback) {
14756 var promise = this;
14757 if (!reason) {
14758 var newReason = new Error(reason + "");
14759 newReason.cause = reason;
14760 reason = newReason;
14761 }
14762 var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
14763 if (ret === errorObj) {
14764 async.throwLater(ret.e);
14765 }
14766}
14767
14768Promise.prototype.asCallback = Promise.prototype.nodeify = function (nodeback,
14769 options) {
14770 if (typeof nodeback == "function") {
14771 var adapter = successAdapter;
14772 if (options !== undefined && Object(options).spread) {
14773 adapter = spreadAdapter;
14774 }
14775 this._then(
14776 adapter,
14777 errorAdapter,
14778 undefined,
14779 this,
14780 nodeback
14781 );
14782 }
14783 return this;
14784};
14785};
14786
14787},{"./util":36}],22:[function(_dereq_,module,exports){
14788"use strict";
14789module.exports = function() {
14790var makeSelfResolutionError = function () {
14791 return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
14792};
14793var reflectHandler = function() {
14794 return new Promise.PromiseInspection(this._target());
14795};
14796var apiRejection = function(msg) {
14797 return Promise.reject(new TypeError(msg));
14798};
14799function Proxyable() {}
14800var UNDEFINED_BINDING = {};
14801var util = _dereq_("./util");
14802
14803var getDomain;
14804if (util.isNode) {
14805 getDomain = function() {
14806 var ret = process.domain;
14807 if (ret === undefined) ret = null;
14808 return ret;
14809 };
14810} else {
14811 getDomain = function() {
14812 return null;
14813 };
14814}
14815util.notEnumerableProp(Promise, "_getDomain", getDomain);
14816
14817var es5 = _dereq_("./es5");
14818var Async = _dereq_("./async");
14819var async = new Async();
14820es5.defineProperty(Promise, "_async", {value: async});
14821var errors = _dereq_("./errors");
14822var TypeError = Promise.TypeError = errors.TypeError;
14823Promise.RangeError = errors.RangeError;
14824var CancellationError = Promise.CancellationError = errors.CancellationError;
14825Promise.TimeoutError = errors.TimeoutError;
14826Promise.OperationalError = errors.OperationalError;
14827Promise.RejectionError = errors.OperationalError;
14828Promise.AggregateError = errors.AggregateError;
14829var INTERNAL = function(){};
14830var APPLY = {};
14831var NEXT_FILTER = {};
14832var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
14833var PromiseArray =
14834 _dereq_("./promise_array")(Promise, INTERNAL,
14835 tryConvertToPromise, apiRejection, Proxyable);
14836var Context = _dereq_("./context")(Promise);
14837 /*jshint unused:false*/
14838var createContext = Context.create;
14839var debug = _dereq_("./debuggability")(Promise, Context);
14840var CapturedTrace = debug.CapturedTrace;
14841var PassThroughHandlerContext =
14842 _dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
14843var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
14844var nodebackForPromise = _dereq_("./nodeback");
14845var errorObj = util.errorObj;
14846var tryCatch = util.tryCatch;
14847function check(self, executor) {
14848 if (self == null || self.constructor !== Promise) {
14849 throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
14850 }
14851 if (typeof executor !== "function") {
14852 throw new TypeError("expecting a function but got " + util.classString(executor));
14853 }
14854
14855}
14856
14857function Promise(executor) {
14858 if (executor !== INTERNAL) {
14859 check(this, executor);
14860 }
14861 this._bitField = 0;
14862 this._fulfillmentHandler0 = undefined;
14863 this._rejectionHandler0 = undefined;
14864 this._promise0 = undefined;
14865 this._receiver0 = undefined;
14866 this._resolveFromExecutor(executor);
14867 this._promiseCreated();
14868 this._fireEvent("promiseCreated", this);
14869}
14870
14871Promise.prototype.toString = function () {
14872 return "[object Promise]";
14873};
14874
14875Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
14876 var len = arguments.length;
14877 if (len > 1) {
14878 var catchInstances = new Array(len - 1),
14879 j = 0, i;
14880 for (i = 0; i < len - 1; ++i) {
14881 var item = arguments[i];
14882 if (util.isObject(item)) {
14883 catchInstances[j++] = item;
14884 } else {
14885 return apiRejection("Catch statement predicate: " +
14886 "expecting an object but got " + util.classString(item));
14887 }
14888 }
14889 catchInstances.length = j;
14890 fn = arguments[i];
14891
14892 if (typeof fn !== "function") {
14893 throw new TypeError("The last argument to .catch() " +
14894 "must be a function, got " + util.toString(fn));
14895 }
14896 return this.then(undefined, catchFilter(catchInstances, fn, this));
14897 }
14898 return this.then(undefined, fn);
14899};
14900
14901Promise.prototype.reflect = function () {
14902 return this._then(reflectHandler,
14903 reflectHandler, undefined, this, undefined);
14904};
14905
14906Promise.prototype.then = function (didFulfill, didReject) {
14907 if (debug.warnings() && arguments.length > 0 &&
14908 typeof didFulfill !== "function" &&
14909 typeof didReject !== "function") {
14910 var msg = ".then() only accepts functions but was passed: " +
14911 util.classString(didFulfill);
14912 if (arguments.length > 1) {
14913 msg += ", " + util.classString(didReject);
14914 }
14915 this._warn(msg);
14916 }
14917 return this._then(didFulfill, didReject, undefined, undefined, undefined);
14918};
14919
14920Promise.prototype.done = function (didFulfill, didReject) {
14921 var promise =
14922 this._then(didFulfill, didReject, undefined, undefined, undefined);
14923 promise._setIsFinal();
14924};
14925
14926Promise.prototype.spread = function (fn) {
14927 if (typeof fn !== "function") {
14928 return apiRejection("expecting a function but got " + util.classString(fn));
14929 }
14930 return this.all()._then(fn, undefined, undefined, APPLY, undefined);
14931};
14932
14933Promise.prototype.toJSON = function () {
14934 var ret = {
14935 isFulfilled: false,
14936 isRejected: false,
14937 fulfillmentValue: undefined,
14938 rejectionReason: undefined
14939 };
14940 if (this.isFulfilled()) {
14941 ret.fulfillmentValue = this.value();
14942 ret.isFulfilled = true;
14943 } else if (this.isRejected()) {
14944 ret.rejectionReason = this.reason();
14945 ret.isRejected = true;
14946 }
14947 return ret;
14948};
14949
14950Promise.prototype.all = function () {
14951 if (arguments.length > 0) {
14952 this._warn(".all() was passed arguments but it does not take any");
14953 }
14954 return new PromiseArray(this).promise();
14955};
14956
14957Promise.prototype.error = function (fn) {
14958 return this.caught(util.originatesFromRejection, fn);
14959};
14960
14961Promise.getNewLibraryCopy = module.exports;
14962
14963Promise.is = function (val) {
14964 return val instanceof Promise;
14965};
14966
14967Promise.fromNode = Promise.fromCallback = function(fn) {
14968 var ret = new Promise(INTERNAL);
14969 ret._captureStackTrace();
14970 var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
14971 : false;
14972 var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
14973 if (result === errorObj) {
14974 ret._rejectCallback(result.e, true);
14975 }
14976 if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
14977 return ret;
14978};
14979
14980Promise.all = function (promises) {
14981 return new PromiseArray(promises).promise();
14982};
14983
14984Promise.cast = function (obj) {
14985 var ret = tryConvertToPromise(obj);
14986 if (!(ret instanceof Promise)) {
14987 ret = new Promise(INTERNAL);
14988 ret._captureStackTrace();
14989 ret._setFulfilled();
14990 ret._rejectionHandler0 = obj;
14991 }
14992 return ret;
14993};
14994
14995Promise.resolve = Promise.fulfilled = Promise.cast;
14996
14997Promise.reject = Promise.rejected = function (reason) {
14998 var ret = new Promise(INTERNAL);
14999 ret._captureStackTrace();
15000 ret._rejectCallback(reason, true);
15001 return ret;
15002};
15003
15004Promise.setScheduler = function(fn) {
15005 if (typeof fn !== "function") {
15006 throw new TypeError("expecting a function but got " + util.classString(fn));
15007 }
15008 return async.setScheduler(fn);
15009};
15010
15011Promise.prototype._then = function (
15012 didFulfill,
15013 didReject,
15014 _, receiver,
15015 internalData
15016) {
15017 var haveInternalData = internalData !== undefined;
15018 var promise = haveInternalData ? internalData : new Promise(INTERNAL);
15019 var target = this._target();
15020 var bitField = target._bitField;
15021
15022 if (!haveInternalData) {
15023 promise._propagateFrom(this, 3);
15024 promise._captureStackTrace();
15025 if (receiver === undefined &&
15026 ((this._bitField & 2097152) !== 0)) {
15027 if (!((bitField & 50397184) === 0)) {
15028 receiver = this._boundValue();
15029 } else {
15030 receiver = target === this ? undefined : this._boundTo;
15031 }
15032 }
15033 this._fireEvent("promiseChained", this, promise);
15034 }
15035
15036 var domain = getDomain();
15037 if (!((bitField & 50397184) === 0)) {
15038 var handler, value, settler = target._settlePromiseCtx;
15039 if (((bitField & 33554432) !== 0)) {
15040 value = target._rejectionHandler0;
15041 handler = didFulfill;
15042 } else if (((bitField & 16777216) !== 0)) {
15043 value = target._fulfillmentHandler0;
15044 handler = didReject;
15045 target._unsetRejectionIsUnhandled();
15046 } else {
15047 settler = target._settlePromiseLateCancellationObserver;
15048 value = new CancellationError("late cancellation observer");
15049 target._attachExtraTrace(value);
15050 handler = didReject;
15051 }
15052
15053 async.invoke(settler, target, {
15054 handler: domain === null ? handler
15055 : (typeof handler === "function" &&
15056 util.domainBind(domain, handler)),
15057 promise: promise,
15058 receiver: receiver,
15059 value: value
15060 });
15061 } else {
15062 target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
15063 }
15064
15065 return promise;
15066};
15067
15068Promise.prototype._length = function () {
15069 return this._bitField & 65535;
15070};
15071
15072Promise.prototype._isFateSealed = function () {
15073 return (this._bitField & 117506048) !== 0;
15074};
15075
15076Promise.prototype._isFollowing = function () {
15077 return (this._bitField & 67108864) === 67108864;
15078};
15079
15080Promise.prototype._setLength = function (len) {
15081 this._bitField = (this._bitField & -65536) |
15082 (len & 65535);
15083};
15084
15085Promise.prototype._setFulfilled = function () {
15086 this._bitField = this._bitField | 33554432;
15087 this._fireEvent("promiseFulfilled", this);
15088};
15089
15090Promise.prototype._setRejected = function () {
15091 this._bitField = this._bitField | 16777216;
15092 this._fireEvent("promiseRejected", this);
15093};
15094
15095Promise.prototype._setFollowing = function () {
15096 this._bitField = this._bitField | 67108864;
15097 this._fireEvent("promiseResolved", this);
15098};
15099
15100Promise.prototype._setIsFinal = function () {
15101 this._bitField = this._bitField | 4194304;
15102};
15103
15104Promise.prototype._isFinal = function () {
15105 return (this._bitField & 4194304) > 0;
15106};
15107
15108Promise.prototype._unsetCancelled = function() {
15109 this._bitField = this._bitField & (~65536);
15110};
15111
15112Promise.prototype._setCancelled = function() {
15113 this._bitField = this._bitField | 65536;
15114 this._fireEvent("promiseCancelled", this);
15115};
15116
15117Promise.prototype._setWillBeCancelled = function() {
15118 this._bitField = this._bitField | 8388608;
15119};
15120
15121Promise.prototype._setAsyncGuaranteed = function() {
15122 if (async.hasCustomScheduler()) return;
15123 this._bitField = this._bitField | 134217728;
15124};
15125
15126Promise.prototype._receiverAt = function (index) {
15127 var ret = index === 0 ? this._receiver0 : this[
15128 index * 4 - 4 + 3];
15129 if (ret === UNDEFINED_BINDING) {
15130 return undefined;
15131 } else if (ret === undefined && this._isBound()) {
15132 return this._boundValue();
15133 }
15134 return ret;
15135};
15136
15137Promise.prototype._promiseAt = function (index) {
15138 return this[
15139 index * 4 - 4 + 2];
15140};
15141
15142Promise.prototype._fulfillmentHandlerAt = function (index) {
15143 return this[
15144 index * 4 - 4 + 0];
15145};
15146
15147Promise.prototype._rejectionHandlerAt = function (index) {
15148 return this[
15149 index * 4 - 4 + 1];
15150};
15151
15152Promise.prototype._boundValue = function() {};
15153
15154Promise.prototype._migrateCallback0 = function (follower) {
15155 var bitField = follower._bitField;
15156 var fulfill = follower._fulfillmentHandler0;
15157 var reject = follower._rejectionHandler0;
15158 var promise = follower._promise0;
15159 var receiver = follower._receiverAt(0);
15160 if (receiver === undefined) receiver = UNDEFINED_BINDING;
15161 this._addCallbacks(fulfill, reject, promise, receiver, null);
15162};
15163
15164Promise.prototype._migrateCallbackAt = function (follower, index) {
15165 var fulfill = follower._fulfillmentHandlerAt(index);
15166 var reject = follower._rejectionHandlerAt(index);
15167 var promise = follower._promiseAt(index);
15168 var receiver = follower._receiverAt(index);
15169 if (receiver === undefined) receiver = UNDEFINED_BINDING;
15170 this._addCallbacks(fulfill, reject, promise, receiver, null);
15171};
15172
15173Promise.prototype._addCallbacks = function (
15174 fulfill,
15175 reject,
15176 promise,
15177 receiver,
15178 domain
15179) {
15180 var index = this._length();
15181
15182 if (index >= 65535 - 4) {
15183 index = 0;
15184 this._setLength(0);
15185 }
15186
15187 if (index === 0) {
15188 this._promise0 = promise;
15189 this._receiver0 = receiver;
15190 if (typeof fulfill === "function") {
15191 this._fulfillmentHandler0 =
15192 domain === null ? fulfill : util.domainBind(domain, fulfill);
15193 }
15194 if (typeof reject === "function") {
15195 this._rejectionHandler0 =
15196 domain === null ? reject : util.domainBind(domain, reject);
15197 }
15198 } else {
15199 var base = index * 4 - 4;
15200 this[base + 2] = promise;
15201 this[base + 3] = receiver;
15202 if (typeof fulfill === "function") {
15203 this[base + 0] =
15204 domain === null ? fulfill : util.domainBind(domain, fulfill);
15205 }
15206 if (typeof reject === "function") {
15207 this[base + 1] =
15208 domain === null ? reject : util.domainBind(domain, reject);
15209 }
15210 }
15211 this._setLength(index + 1);
15212 return index;
15213};
15214
15215Promise.prototype._proxy = function (proxyable, arg) {
15216 this._addCallbacks(undefined, undefined, arg, proxyable, null);
15217};
15218
15219Promise.prototype._resolveCallback = function(value, shouldBind) {
15220 if (((this._bitField & 117506048) !== 0)) return;
15221 if (value === this)
15222 return this._rejectCallback(makeSelfResolutionError(), false);
15223 var maybePromise = tryConvertToPromise(value, this);
15224 if (!(maybePromise instanceof Promise)) return this._fulfill(value);
15225
15226 if (shouldBind) this._propagateFrom(maybePromise, 2);
15227
15228 var promise = maybePromise._target();
15229
15230 if (promise === this) {
15231 this._reject(makeSelfResolutionError());
15232 return;
15233 }
15234
15235 var bitField = promise._bitField;
15236 if (((bitField & 50397184) === 0)) {
15237 var len = this._length();
15238 if (len > 0) promise._migrateCallback0(this);
15239 for (var i = 1; i < len; ++i) {
15240 promise._migrateCallbackAt(this, i);
15241 }
15242 this._setFollowing();
15243 this._setLength(0);
15244 this._setFollowee(promise);
15245 } else if (((bitField & 33554432) !== 0)) {
15246 this._fulfill(promise._value());
15247 } else if (((bitField & 16777216) !== 0)) {
15248 this._reject(promise._reason());
15249 } else {
15250 var reason = new CancellationError("late cancellation observer");
15251 promise._attachExtraTrace(reason);
15252 this._reject(reason);
15253 }
15254};
15255
15256Promise.prototype._rejectCallback =
15257function(reason, synchronous, ignoreNonErrorWarnings) {
15258 var trace = util.ensureErrorObject(reason);
15259 var hasStack = trace === reason;
15260 if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
15261 var message = "a promise was rejected with a non-error: " +
15262 util.classString(reason);
15263 this._warn(message, true);
15264 }
15265 this._attachExtraTrace(trace, synchronous ? hasStack : false);
15266 this._reject(reason);
15267};
15268
15269Promise.prototype._resolveFromExecutor = function (executor) {
15270 if (executor === INTERNAL) return;
15271 var promise = this;
15272 this._captureStackTrace();
15273 this._pushContext();
15274 var synchronous = true;
15275 var r = this._execute(executor, function(value) {
15276 promise._resolveCallback(value);
15277 }, function (reason) {
15278 promise._rejectCallback(reason, synchronous);
15279 });
15280 synchronous = false;
15281 this._popContext();
15282
15283 if (r !== undefined) {
15284 promise._rejectCallback(r, true);
15285 }
15286};
15287
15288Promise.prototype._settlePromiseFromHandler = function (
15289 handler, receiver, value, promise
15290) {
15291 var bitField = promise._bitField;
15292 if (((bitField & 65536) !== 0)) return;
15293 promise._pushContext();
15294 var x;
15295 if (receiver === APPLY) {
15296 if (!value || typeof value.length !== "number") {
15297 x = errorObj;
15298 x.e = new TypeError("cannot .spread() a non-array: " +
15299 util.classString(value));
15300 } else {
15301 x = tryCatch(handler).apply(this._boundValue(), value);
15302 }
15303 } else {
15304 x = tryCatch(handler).call(receiver, value);
15305 }
15306 var promiseCreated = promise._popContext();
15307 bitField = promise._bitField;
15308 if (((bitField & 65536) !== 0)) return;
15309
15310 if (x === NEXT_FILTER) {
15311 promise._reject(value);
15312 } else if (x === errorObj) {
15313 promise._rejectCallback(x.e, false);
15314 } else {
15315 debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
15316 promise._resolveCallback(x);
15317 }
15318};
15319
15320Promise.prototype._target = function() {
15321 var ret = this;
15322 while (ret._isFollowing()) ret = ret._followee();
15323 return ret;
15324};
15325
15326Promise.prototype._followee = function() {
15327 return this._rejectionHandler0;
15328};
15329
15330Promise.prototype._setFollowee = function(promise) {
15331 this._rejectionHandler0 = promise;
15332};
15333
15334Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
15335 var isPromise = promise instanceof Promise;
15336 var bitField = this._bitField;
15337 var asyncGuaranteed = ((bitField & 134217728) !== 0);
15338 if (((bitField & 65536) !== 0)) {
15339 if (isPromise) promise._invokeInternalOnCancel();
15340
15341 if (receiver instanceof PassThroughHandlerContext &&
15342 receiver.isFinallyHandler()) {
15343 receiver.cancelPromise = promise;
15344 if (tryCatch(handler).call(receiver, value) === errorObj) {
15345 promise._reject(errorObj.e);
15346 }
15347 } else if (handler === reflectHandler) {
15348 promise._fulfill(reflectHandler.call(receiver));
15349 } else if (receiver instanceof Proxyable) {
15350 receiver._promiseCancelled(promise);
15351 } else if (isPromise || promise instanceof PromiseArray) {
15352 promise._cancel();
15353 } else {
15354 receiver.cancel();
15355 }
15356 } else if (typeof handler === "function") {
15357 if (!isPromise) {
15358 handler.call(receiver, value, promise);
15359 } else {
15360 if (asyncGuaranteed) promise._setAsyncGuaranteed();
15361 this._settlePromiseFromHandler(handler, receiver, value, promise);
15362 }
15363 } else if (receiver instanceof Proxyable) {
15364 if (!receiver._isResolved()) {
15365 if (((bitField & 33554432) !== 0)) {
15366 receiver._promiseFulfilled(value, promise);
15367 } else {
15368 receiver._promiseRejected(value, promise);
15369 }
15370 }
15371 } else if (isPromise) {
15372 if (asyncGuaranteed) promise._setAsyncGuaranteed();
15373 if (((bitField & 33554432) !== 0)) {
15374 promise._fulfill(value);
15375 } else {
15376 promise._reject(value);
15377 }
15378 }
15379};
15380
15381Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
15382 var handler = ctx.handler;
15383 var promise = ctx.promise;
15384 var receiver = ctx.receiver;
15385 var value = ctx.value;
15386 if (typeof handler === "function") {
15387 if (!(promise instanceof Promise)) {
15388 handler.call(receiver, value, promise);
15389 } else {
15390 this._settlePromiseFromHandler(handler, receiver, value, promise);
15391 }
15392 } else if (promise instanceof Promise) {
15393 promise._reject(value);
15394 }
15395};
15396
15397Promise.prototype._settlePromiseCtx = function(ctx) {
15398 this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
15399};
15400
15401Promise.prototype._settlePromise0 = function(handler, value, bitField) {
15402 var promise = this._promise0;
15403 var receiver = this._receiverAt(0);
15404 this._promise0 = undefined;
15405 this._receiver0 = undefined;
15406 this._settlePromise(promise, handler, receiver, value);
15407};
15408
15409Promise.prototype._clearCallbackDataAtIndex = function(index) {
15410 var base = index * 4 - 4;
15411 this[base + 2] =
15412 this[base + 3] =
15413 this[base + 0] =
15414 this[base + 1] = undefined;
15415};
15416
15417Promise.prototype._fulfill = function (value) {
15418 var bitField = this._bitField;
15419 if (((bitField & 117506048) >>> 16)) return;
15420 if (value === this) {
15421 var err = makeSelfResolutionError();
15422 this._attachExtraTrace(err);
15423 return this._reject(err);
15424 }
15425 this._setFulfilled();
15426 this._rejectionHandler0 = value;
15427
15428 if ((bitField & 65535) > 0) {
15429 if (((bitField & 134217728) !== 0)) {
15430 this._settlePromises();
15431 } else {
15432 async.settlePromises(this);
15433 }
15434 this._dereferenceTrace();
15435 }
15436};
15437
15438Promise.prototype._reject = function (reason) {
15439 var bitField = this._bitField;
15440 if (((bitField & 117506048) >>> 16)) return;
15441 this._setRejected();
15442 this._fulfillmentHandler0 = reason;
15443
15444 if (this._isFinal()) {
15445 return async.fatalError(reason, util.isNode);
15446 }
15447
15448 if ((bitField & 65535) > 0) {
15449 async.settlePromises(this);
15450 } else {
15451 this._ensurePossibleRejectionHandled();
15452 }
15453};
15454
15455Promise.prototype._fulfillPromises = function (len, value) {
15456 for (var i = 1; i < len; i++) {
15457 var handler = this._fulfillmentHandlerAt(i);
15458 var promise = this._promiseAt(i);
15459 var receiver = this._receiverAt(i);
15460 this._clearCallbackDataAtIndex(i);
15461 this._settlePromise(promise, handler, receiver, value);
15462 }
15463};
15464
15465Promise.prototype._rejectPromises = function (len, reason) {
15466 for (var i = 1; i < len; i++) {
15467 var handler = this._rejectionHandlerAt(i);
15468 var promise = this._promiseAt(i);
15469 var receiver = this._receiverAt(i);
15470 this._clearCallbackDataAtIndex(i);
15471 this._settlePromise(promise, handler, receiver, reason);
15472 }
15473};
15474
15475Promise.prototype._settlePromises = function () {
15476 var bitField = this._bitField;
15477 var len = (bitField & 65535);
15478
15479 if (len > 0) {
15480 if (((bitField & 16842752) !== 0)) {
15481 var reason = this._fulfillmentHandler0;
15482 this._settlePromise0(this._rejectionHandler0, reason, bitField);
15483 this._rejectPromises(len, reason);
15484 } else {
15485 var value = this._rejectionHandler0;
15486 this._settlePromise0(this._fulfillmentHandler0, value, bitField);
15487 this._fulfillPromises(len, value);
15488 }
15489 this._setLength(0);
15490 }
15491 this._clearCancellationData();
15492};
15493
15494Promise.prototype._settledValue = function() {
15495 var bitField = this._bitField;
15496 if (((bitField & 33554432) !== 0)) {
15497 return this._rejectionHandler0;
15498 } else if (((bitField & 16777216) !== 0)) {
15499 return this._fulfillmentHandler0;
15500 }
15501};
15502
15503if (typeof Symbol !== "undefined" && Symbol.toStringTag) {
15504 es5.defineProperty(Promise.prototype, Symbol.toStringTag, {
15505 get: function () {
15506 return "Object";
15507 }
15508 });
15509}
15510
15511function deferResolve(v) {this.promise._resolveCallback(v);}
15512function deferReject(v) {this.promise._rejectCallback(v, false);}
15513
15514Promise.defer = Promise.pending = function() {
15515 debug.deprecated("Promise.defer", "new Promise");
15516 var promise = new Promise(INTERNAL);
15517 return {
15518 promise: promise,
15519 resolve: deferResolve,
15520 reject: deferReject
15521 };
15522};
15523
15524util.notEnumerableProp(Promise,
15525 "_makeSelfResolutionError",
15526 makeSelfResolutionError);
15527
15528_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
15529 debug);
15530_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
15531_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
15532_dereq_("./direct_resolve")(Promise);
15533_dereq_("./synchronous_inspection")(Promise);
15534_dereq_("./join")(
15535 Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
15536Promise.Promise = Promise;
15537Promise.version = "3.5.5";
15538_dereq_('./call_get.js')(Promise);
15539_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug);
15540_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
15541_dereq_('./nodeify.js')(Promise);
15542_dereq_('./promisify.js')(Promise, INTERNAL);
15543_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
15544_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
15545_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug);
15546_dereq_('./settle.js')(Promise, PromiseArray, debug);
15547_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
15548_dereq_('./timers.js')(Promise, INTERNAL, debug);
15549_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug);
15550_dereq_('./any.js')(Promise);
15551_dereq_('./each.js')(Promise, INTERNAL);
15552_dereq_('./filter.js')(Promise, INTERNAL);
15553
15554 util.toFastProperties(Promise);
15555 util.toFastProperties(Promise.prototype);
15556 function fillTypes(value) {
15557 var p = new Promise(INTERNAL);
15558 p._fulfillmentHandler0 = value;
15559 p._rejectionHandler0 = value;
15560 p._promise0 = value;
15561 p._receiver0 = value;
15562 }
15563 // Complete slack tracking, opt out of field-type tracking and
15564 // stabilize map
15565 fillTypes({a: 1});
15566 fillTypes({b: 2});
15567 fillTypes({c: 3});
15568 fillTypes(1);
15569 fillTypes(function(){});
15570 fillTypes(undefined);
15571 fillTypes(false);
15572 fillTypes(new Promise(INTERNAL));
15573 debug.setBounds(Async.firstLineError, util.lastLineError);
15574 return Promise;
15575
15576};
15577
15578},{"./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){
15579"use strict";
15580module.exports = function(Promise, INTERNAL, tryConvertToPromise,
15581 apiRejection, Proxyable) {
15582var util = _dereq_("./util");
15583var isArray = util.isArray;
15584
15585function toResolutionValue(val) {
15586 switch(val) {
15587 case -2: return [];
15588 case -3: return {};
15589 case -6: return new Map();
15590 }
15591}
15592
15593function PromiseArray(values) {
15594 var promise = this._promise = new Promise(INTERNAL);
15595 if (values instanceof Promise) {
15596 promise._propagateFrom(values, 3);
15597 }
15598 promise._setOnCancel(this);
15599 this._values = values;
15600 this._length = 0;
15601 this._totalResolved = 0;
15602 this._init(undefined, -2);
15603}
15604util.inherits(PromiseArray, Proxyable);
15605
15606PromiseArray.prototype.length = function () {
15607 return this._length;
15608};
15609
15610PromiseArray.prototype.promise = function () {
15611 return this._promise;
15612};
15613
15614PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
15615 var values = tryConvertToPromise(this._values, this._promise);
15616 if (values instanceof Promise) {
15617 values = values._target();
15618 var bitField = values._bitField;
15619 ;
15620 this._values = values;
15621
15622 if (((bitField & 50397184) === 0)) {
15623 this._promise._setAsyncGuaranteed();
15624 return values._then(
15625 init,
15626 this._reject,
15627 undefined,
15628 this,
15629 resolveValueIfEmpty
15630 );
15631 } else if (((bitField & 33554432) !== 0)) {
15632 values = values._value();
15633 } else if (((bitField & 16777216) !== 0)) {
15634 return this._reject(values._reason());
15635 } else {
15636 return this._cancel();
15637 }
15638 }
15639 values = util.asArray(values);
15640 if (values === null) {
15641 var err = apiRejection(
15642 "expecting an array or an iterable object but got " + util.classString(values)).reason();
15643 this._promise._rejectCallback(err, false);
15644 return;
15645 }
15646
15647 if (values.length === 0) {
15648 if (resolveValueIfEmpty === -5) {
15649 this._resolveEmptyArray();
15650 }
15651 else {
15652 this._resolve(toResolutionValue(resolveValueIfEmpty));
15653 }
15654 return;
15655 }
15656 this._iterate(values);
15657};
15658
15659PromiseArray.prototype._iterate = function(values) {
15660 var len = this.getActualLength(values.length);
15661 this._length = len;
15662 this._values = this.shouldCopyValues() ? new Array(len) : this._values;
15663 var result = this._promise;
15664 var isResolved = false;
15665 var bitField = null;
15666 for (var i = 0; i < len; ++i) {
15667 var maybePromise = tryConvertToPromise(values[i], result);
15668
15669 if (maybePromise instanceof Promise) {
15670 maybePromise = maybePromise._target();
15671 bitField = maybePromise._bitField;
15672 } else {
15673 bitField = null;
15674 }
15675
15676 if (isResolved) {
15677 if (bitField !== null) {
15678 maybePromise.suppressUnhandledRejections();
15679 }
15680 } else if (bitField !== null) {
15681 if (((bitField & 50397184) === 0)) {
15682 maybePromise._proxy(this, i);
15683 this._values[i] = maybePromise;
15684 } else if (((bitField & 33554432) !== 0)) {
15685 isResolved = this._promiseFulfilled(maybePromise._value(), i);
15686 } else if (((bitField & 16777216) !== 0)) {
15687 isResolved = this._promiseRejected(maybePromise._reason(), i);
15688 } else {
15689 isResolved = this._promiseCancelled(i);
15690 }
15691 } else {
15692 isResolved = this._promiseFulfilled(maybePromise, i);
15693 }
15694 }
15695 if (!isResolved) result._setAsyncGuaranteed();
15696};
15697
15698PromiseArray.prototype._isResolved = function () {
15699 return this._values === null;
15700};
15701
15702PromiseArray.prototype._resolve = function (value) {
15703 this._values = null;
15704 this._promise._fulfill(value);
15705};
15706
15707PromiseArray.prototype._cancel = function() {
15708 if (this._isResolved() || !this._promise._isCancellable()) return;
15709 this._values = null;
15710 this._promise._cancel();
15711};
15712
15713PromiseArray.prototype._reject = function (reason) {
15714 this._values = null;
15715 this._promise._rejectCallback(reason, false);
15716};
15717
15718PromiseArray.prototype._promiseFulfilled = function (value, index) {
15719 this._values[index] = value;
15720 var totalResolved = ++this._totalResolved;
15721 if (totalResolved >= this._length) {
15722 this._resolve(this._values);
15723 return true;
15724 }
15725 return false;
15726};
15727
15728PromiseArray.prototype._promiseCancelled = function() {
15729 this._cancel();
15730 return true;
15731};
15732
15733PromiseArray.prototype._promiseRejected = function (reason) {
15734 this._totalResolved++;
15735 this._reject(reason);
15736 return true;
15737};
15738
15739PromiseArray.prototype._resultCancelled = function() {
15740 if (this._isResolved()) return;
15741 var values = this._values;
15742 this._cancel();
15743 if (values instanceof Promise) {
15744 values.cancel();
15745 } else {
15746 for (var i = 0; i < values.length; ++i) {
15747 if (values[i] instanceof Promise) {
15748 values[i].cancel();
15749 }
15750 }
15751 }
15752};
15753
15754PromiseArray.prototype.shouldCopyValues = function () {
15755 return true;
15756};
15757
15758PromiseArray.prototype.getActualLength = function (len) {
15759 return len;
15760};
15761
15762return PromiseArray;
15763};
15764
15765},{"./util":36}],24:[function(_dereq_,module,exports){
15766"use strict";
15767module.exports = function(Promise, INTERNAL) {
15768var THIS = {};
15769var util = _dereq_("./util");
15770var nodebackForPromise = _dereq_("./nodeback");
15771var withAppended = util.withAppended;
15772var maybeWrapAsError = util.maybeWrapAsError;
15773var canEvaluate = util.canEvaluate;
15774var TypeError = _dereq_("./errors").TypeError;
15775var defaultSuffix = "Async";
15776var defaultPromisified = {__isPromisified__: true};
15777var noCopyProps = [
15778 "arity", "length",
15779 "name",
15780 "arguments",
15781 "caller",
15782 "callee",
15783 "prototype",
15784 "__isPromisified__"
15785];
15786var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
15787
15788var defaultFilter = function(name) {
15789 return util.isIdentifier(name) &&
15790 name.charAt(0) !== "_" &&
15791 name !== "constructor";
15792};
15793
15794function propsFilter(key) {
15795 return !noCopyPropsPattern.test(key);
15796}
15797
15798function isPromisified(fn) {
15799 try {
15800 return fn.__isPromisified__ === true;
15801 }
15802 catch (e) {
15803 return false;
15804 }
15805}
15806
15807function hasPromisified(obj, key, suffix) {
15808 var val = util.getDataPropertyOrDefault(obj, key + suffix,
15809 defaultPromisified);
15810 return val ? isPromisified(val) : false;
15811}
15812function checkValid(ret, suffix, suffixRegexp) {
15813 for (var i = 0; i < ret.length; i += 2) {
15814 var key = ret[i];
15815 if (suffixRegexp.test(key)) {
15816 var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
15817 for (var j = 0; j < ret.length; j += 2) {
15818 if (ret[j] === keyWithoutAsyncSuffix) {
15819 throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/MqrFmX\u000a"
15820 .replace("%s", suffix));
15821 }
15822 }
15823 }
15824 }
15825}
15826
15827function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
15828 var keys = util.inheritedDataKeys(obj);
15829 var ret = [];
15830 for (var i = 0; i < keys.length; ++i) {
15831 var key = keys[i];
15832 var value = obj[key];
15833 var passesDefaultFilter = filter === defaultFilter
15834 ? true : defaultFilter(key, value, obj);
15835 if (typeof value === "function" &&
15836 !isPromisified(value) &&
15837 !hasPromisified(obj, key, suffix) &&
15838 filter(key, value, obj, passesDefaultFilter)) {
15839 ret.push(key, value);
15840 }
15841 }
15842 checkValid(ret, suffix, suffixRegexp);
15843 return ret;
15844}
15845
15846var escapeIdentRegex = function(str) {
15847 return str.replace(/([$])/, "\\$");
15848};
15849
15850var makeNodePromisifiedEval;
15851if (!true) {
15852var switchCaseArgumentOrder = function(likelyArgumentCount) {
15853 var ret = [likelyArgumentCount];
15854 var min = Math.max(0, likelyArgumentCount - 1 - 3);
15855 for(var i = likelyArgumentCount - 1; i >= min; --i) {
15856 ret.push(i);
15857 }
15858 for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
15859 ret.push(i);
15860 }
15861 return ret;
15862};
15863
15864var argumentSequence = function(argumentCount) {
15865 return util.filledRange(argumentCount, "_arg", "");
15866};
15867
15868var parameterDeclaration = function(parameterCount) {
15869 return util.filledRange(
15870 Math.max(parameterCount, 3), "_arg", "");
15871};
15872
15873var parameterCount = function(fn) {
15874 if (typeof fn.length === "number") {
15875 return Math.max(Math.min(fn.length, 1023 + 1), 0);
15876 }
15877 return 0;
15878};
15879
15880makeNodePromisifiedEval =
15881function(callback, receiver, originalName, fn, _, multiArgs) {
15882 var newParameterCount = Math.max(0, parameterCount(fn) - 1);
15883 var argumentOrder = switchCaseArgumentOrder(newParameterCount);
15884 var shouldProxyThis = typeof callback === "string" || receiver === THIS;
15885
15886 function generateCallForArgumentCount(count) {
15887 var args = argumentSequence(count).join(", ");
15888 var comma = count > 0 ? ", " : "";
15889 var ret;
15890 if (shouldProxyThis) {
15891 ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
15892 } else {
15893 ret = receiver === undefined
15894 ? "ret = callback({{args}}, nodeback); break;\n"
15895 : "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
15896 }
15897 return ret.replace("{{args}}", args).replace(", ", comma);
15898 }
15899
15900 function generateArgumentSwitchCase() {
15901 var ret = "";
15902 for (var i = 0; i < argumentOrder.length; ++i) {
15903 ret += "case " + argumentOrder[i] +":" +
15904 generateCallForArgumentCount(argumentOrder[i]);
15905 }
15906
15907 ret += " \n\
15908 default: \n\
15909 var args = new Array(len + 1); \n\
15910 var i = 0; \n\
15911 for (var i = 0; i < len; ++i) { \n\
15912 args[i] = arguments[i]; \n\
15913 } \n\
15914 args[i] = nodeback; \n\
15915 [CodeForCall] \n\
15916 break; \n\
15917 ".replace("[CodeForCall]", (shouldProxyThis
15918 ? "ret = callback.apply(this, args);\n"
15919 : "ret = callback.apply(receiver, args);\n"));
15920 return ret;
15921 }
15922
15923 var getFunctionCode = typeof callback === "string"
15924 ? ("this != null ? this['"+callback+"'] : fn")
15925 : "fn";
15926 var body = "'use strict'; \n\
15927 var ret = function (Parameters) { \n\
15928 'use strict'; \n\
15929 var len = arguments.length; \n\
15930 var promise = new Promise(INTERNAL); \n\
15931 promise._captureStackTrace(); \n\
15932 var nodeback = nodebackForPromise(promise, " + multiArgs + "); \n\
15933 var ret; \n\
15934 var callback = tryCatch([GetFunctionCode]); \n\
15935 switch(len) { \n\
15936 [CodeForSwitchCase] \n\
15937 } \n\
15938 if (ret === errorObj) { \n\
15939 promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
15940 } \n\
15941 if (!promise._isFateSealed()) promise._setAsyncGuaranteed(); \n\
15942 return promise; \n\
15943 }; \n\
15944 notEnumerableProp(ret, '__isPromisified__', true); \n\
15945 return ret; \n\
15946 ".replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
15947 .replace("[GetFunctionCode]", getFunctionCode);
15948 body = body.replace("Parameters", parameterDeclaration(newParameterCount));
15949 return new Function("Promise",
15950 "fn",
15951 "receiver",
15952 "withAppended",
15953 "maybeWrapAsError",
15954 "nodebackForPromise",
15955 "tryCatch",
15956 "errorObj",
15957 "notEnumerableProp",
15958 "INTERNAL",
15959 body)(
15960 Promise,
15961 fn,
15962 receiver,
15963 withAppended,
15964 maybeWrapAsError,
15965 nodebackForPromise,
15966 util.tryCatch,
15967 util.errorObj,
15968 util.notEnumerableProp,
15969 INTERNAL);
15970};
15971}
15972
15973function makeNodePromisifiedClosure(callback, receiver, _, fn, __, multiArgs) {
15974 var defaultThis = (function() {return this;})();
15975 var method = callback;
15976 if (typeof method === "string") {
15977 callback = fn;
15978 }
15979 function promisified() {
15980 var _receiver = receiver;
15981 if (receiver === THIS) _receiver = this;
15982 var promise = new Promise(INTERNAL);
15983 promise._captureStackTrace();
15984 var cb = typeof method === "string" && this !== defaultThis
15985 ? this[method] : callback;
15986 var fn = nodebackForPromise(promise, multiArgs);
15987 try {
15988 cb.apply(_receiver, withAppended(arguments, fn));
15989 } catch(e) {
15990 promise._rejectCallback(maybeWrapAsError(e), true, true);
15991 }
15992 if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
15993 return promise;
15994 }
15995 util.notEnumerableProp(promisified, "__isPromisified__", true);
15996 return promisified;
15997}
15998
15999var makeNodePromisified = canEvaluate
16000 ? makeNodePromisifiedEval
16001 : makeNodePromisifiedClosure;
16002
16003function promisifyAll(obj, suffix, filter, promisifier, multiArgs) {
16004 var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
16005 var methods =
16006 promisifiableMethods(obj, suffix, suffixRegexp, filter);
16007
16008 for (var i = 0, len = methods.length; i < len; i+= 2) {
16009 var key = methods[i];
16010 var fn = methods[i+1];
16011 var promisifiedKey = key + suffix;
16012 if (promisifier === makeNodePromisified) {
16013 obj[promisifiedKey] =
16014 makeNodePromisified(key, THIS, key, fn, suffix, multiArgs);
16015 } else {
16016 var promisified = promisifier(fn, function() {
16017 return makeNodePromisified(key, THIS, key,
16018 fn, suffix, multiArgs);
16019 });
16020 util.notEnumerableProp(promisified, "__isPromisified__", true);
16021 obj[promisifiedKey] = promisified;
16022 }
16023 }
16024 util.toFastProperties(obj);
16025 return obj;
16026}
16027
16028function promisify(callback, receiver, multiArgs) {
16029 return makeNodePromisified(callback, receiver, undefined,
16030 callback, null, multiArgs);
16031}
16032
16033Promise.promisify = function (fn, options) {
16034 if (typeof fn !== "function") {
16035 throw new TypeError("expecting a function but got " + util.classString(fn));
16036 }
16037 if (isPromisified(fn)) {
16038 return fn;
16039 }
16040 options = Object(options);
16041 var receiver = options.context === undefined ? THIS : options.context;
16042 var multiArgs = !!options.multiArgs;
16043 var ret = promisify(fn, receiver, multiArgs);
16044 util.copyDescriptors(fn, ret, propsFilter);
16045 return ret;
16046};
16047
16048Promise.promisifyAll = function (target, options) {
16049 if (typeof target !== "function" && typeof target !== "object") {
16050 throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16051 }
16052 options = Object(options);
16053 var multiArgs = !!options.multiArgs;
16054 var suffix = options.suffix;
16055 if (typeof suffix !== "string") suffix = defaultSuffix;
16056 var filter = options.filter;
16057 if (typeof filter !== "function") filter = defaultFilter;
16058 var promisifier = options.promisifier;
16059 if (typeof promisifier !== "function") promisifier = makeNodePromisified;
16060
16061 if (!util.isIdentifier(suffix)) {
16062 throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16063 }
16064
16065 var keys = util.inheritedDataKeys(target);
16066 for (var i = 0; i < keys.length; ++i) {
16067 var value = target[keys[i]];
16068 if (keys[i] !== "constructor" &&
16069 util.isClass(value)) {
16070 promisifyAll(value.prototype, suffix, filter, promisifier,
16071 multiArgs);
16072 promisifyAll(value, suffix, filter, promisifier, multiArgs);
16073 }
16074 }
16075
16076 return promisifyAll(target, suffix, filter, promisifier, multiArgs);
16077};
16078};
16079
16080
16081},{"./errors":12,"./nodeback":20,"./util":36}],25:[function(_dereq_,module,exports){
16082"use strict";
16083module.exports = function(
16084 Promise, PromiseArray, tryConvertToPromise, apiRejection) {
16085var util = _dereq_("./util");
16086var isObject = util.isObject;
16087var es5 = _dereq_("./es5");
16088var Es6Map;
16089if (typeof Map === "function") Es6Map = Map;
16090
16091var mapToEntries = (function() {
16092 var index = 0;
16093 var size = 0;
16094
16095 function extractEntry(value, key) {
16096 this[index] = value;
16097 this[index + size] = key;
16098 index++;
16099 }
16100
16101 return function mapToEntries(map) {
16102 size = map.size;
16103 index = 0;
16104 var ret = new Array(map.size * 2);
16105 map.forEach(extractEntry, ret);
16106 return ret;
16107 };
16108})();
16109
16110var entriesToMap = function(entries) {
16111 var ret = new Es6Map();
16112 var length = entries.length / 2 | 0;
16113 for (var i = 0; i < length; ++i) {
16114 var key = entries[length + i];
16115 var value = entries[i];
16116 ret.set(key, value);
16117 }
16118 return ret;
16119};
16120
16121function PropertiesPromiseArray(obj) {
16122 var isMap = false;
16123 var entries;
16124 if (Es6Map !== undefined && obj instanceof Es6Map) {
16125 entries = mapToEntries(obj);
16126 isMap = true;
16127 } else {
16128 var keys = es5.keys(obj);
16129 var len = keys.length;
16130 entries = new Array(len * 2);
16131 for (var i = 0; i < len; ++i) {
16132 var key = keys[i];
16133 entries[i] = obj[key];
16134 entries[i + len] = key;
16135 }
16136 }
16137 this.constructor$(entries);
16138 this._isMap = isMap;
16139 this._init$(undefined, isMap ? -6 : -3);
16140}
16141util.inherits(PropertiesPromiseArray, PromiseArray);
16142
16143PropertiesPromiseArray.prototype._init = function () {};
16144
16145PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
16146 this._values[index] = value;
16147 var totalResolved = ++this._totalResolved;
16148 if (totalResolved >= this._length) {
16149 var val;
16150 if (this._isMap) {
16151 val = entriesToMap(this._values);
16152 } else {
16153 val = {};
16154 var keyOffset = this.length();
16155 for (var i = 0, len = this.length(); i < len; ++i) {
16156 val[this._values[i + keyOffset]] = this._values[i];
16157 }
16158 }
16159 this._resolve(val);
16160 return true;
16161 }
16162 return false;
16163};
16164
16165PropertiesPromiseArray.prototype.shouldCopyValues = function () {
16166 return false;
16167};
16168
16169PropertiesPromiseArray.prototype.getActualLength = function (len) {
16170 return len >> 1;
16171};
16172
16173function props(promises) {
16174 var ret;
16175 var castValue = tryConvertToPromise(promises);
16176
16177 if (!isObject(castValue)) {
16178 return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16179 } else if (castValue instanceof Promise) {
16180 ret = castValue._then(
16181 Promise.props, undefined, undefined, undefined, undefined);
16182 } else {
16183 ret = new PropertiesPromiseArray(castValue).promise();
16184 }
16185
16186 if (castValue instanceof Promise) {
16187 ret._propagateFrom(castValue, 2);
16188 }
16189 return ret;
16190}
16191
16192Promise.prototype.props = function () {
16193 return props(this);
16194};
16195
16196Promise.props = function (promises) {
16197 return props(promises);
16198};
16199};
16200
16201},{"./es5":13,"./util":36}],26:[function(_dereq_,module,exports){
16202"use strict";
16203function arrayMove(src, srcIndex, dst, dstIndex, len) {
16204 for (var j = 0; j < len; ++j) {
16205 dst[j + dstIndex] = src[j + srcIndex];
16206 src[j + srcIndex] = void 0;
16207 }
16208}
16209
16210function Queue(capacity) {
16211 this._capacity = capacity;
16212 this._length = 0;
16213 this._front = 0;
16214}
16215
16216Queue.prototype._willBeOverCapacity = function (size) {
16217 return this._capacity < size;
16218};
16219
16220Queue.prototype._pushOne = function (arg) {
16221 var length = this.length();
16222 this._checkCapacity(length + 1);
16223 var i = (this._front + length) & (this._capacity - 1);
16224 this[i] = arg;
16225 this._length = length + 1;
16226};
16227
16228Queue.prototype.push = function (fn, receiver, arg) {
16229 var length = this.length() + 3;
16230 if (this._willBeOverCapacity(length)) {
16231 this._pushOne(fn);
16232 this._pushOne(receiver);
16233 this._pushOne(arg);
16234 return;
16235 }
16236 var j = this._front + length - 3;
16237 this._checkCapacity(length);
16238 var wrapMask = this._capacity - 1;
16239 this[(j + 0) & wrapMask] = fn;
16240 this[(j + 1) & wrapMask] = receiver;
16241 this[(j + 2) & wrapMask] = arg;
16242 this._length = length;
16243};
16244
16245Queue.prototype.shift = function () {
16246 var front = this._front,
16247 ret = this[front];
16248
16249 this[front] = undefined;
16250 this._front = (front + 1) & (this._capacity - 1);
16251 this._length--;
16252 return ret;
16253};
16254
16255Queue.prototype.length = function () {
16256 return this._length;
16257};
16258
16259Queue.prototype._checkCapacity = function (size) {
16260 if (this._capacity < size) {
16261 this._resizeTo(this._capacity << 1);
16262 }
16263};
16264
16265Queue.prototype._resizeTo = function (capacity) {
16266 var oldCapacity = this._capacity;
16267 this._capacity = capacity;
16268 var front = this._front;
16269 var length = this._length;
16270 var moveItemsCount = (front + length) & (oldCapacity - 1);
16271 arrayMove(this, 0, this, oldCapacity, moveItemsCount);
16272};
16273
16274module.exports = Queue;
16275
16276},{}],27:[function(_dereq_,module,exports){
16277"use strict";
16278module.exports = function(
16279 Promise, INTERNAL, tryConvertToPromise, apiRejection) {
16280var util = _dereq_("./util");
16281
16282var raceLater = function (promise) {
16283 return promise.then(function(array) {
16284 return race(array, promise);
16285 });
16286};
16287
16288function race(promises, parent) {
16289 var maybePromise = tryConvertToPromise(promises);
16290
16291 if (maybePromise instanceof Promise) {
16292 return raceLater(maybePromise);
16293 } else {
16294 promises = util.asArray(promises);
16295 if (promises === null)
16296 return apiRejection("expecting an array or an iterable object but got " + util.classString(promises));
16297 }
16298
16299 var ret = new Promise(INTERNAL);
16300 if (parent !== undefined) {
16301 ret._propagateFrom(parent, 3);
16302 }
16303 var fulfill = ret._fulfill;
16304 var reject = ret._reject;
16305 for (var i = 0, len = promises.length; i < len; ++i) {
16306 var val = promises[i];
16307
16308 if (val === undefined && !(i in promises)) {
16309 continue;
16310 }
16311
16312 Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
16313 }
16314 return ret;
16315}
16316
16317Promise.race = function (promises) {
16318 return race(promises, undefined);
16319};
16320
16321Promise.prototype.race = function () {
16322 return race(this, undefined);
16323};
16324
16325};
16326
16327},{"./util":36}],28:[function(_dereq_,module,exports){
16328"use strict";
16329module.exports = function(Promise,
16330 PromiseArray,
16331 apiRejection,
16332 tryConvertToPromise,
16333 INTERNAL,
16334 debug) {
16335var getDomain = Promise._getDomain;
16336var util = _dereq_("./util");
16337var tryCatch = util.tryCatch;
16338
16339function ReductionPromiseArray(promises, fn, initialValue, _each) {
16340 this.constructor$(promises);
16341 var domain = getDomain();
16342 this._fn = domain === null ? fn : util.domainBind(domain, fn);
16343 if (initialValue !== undefined) {
16344 initialValue = Promise.resolve(initialValue);
16345 initialValue._attachCancellationCallback(this);
16346 }
16347 this._initialValue = initialValue;
16348 this._currentCancellable = null;
16349 if(_each === INTERNAL) {
16350 this._eachValues = Array(this._length);
16351 } else if (_each === 0) {
16352 this._eachValues = null;
16353 } else {
16354 this._eachValues = undefined;
16355 }
16356 this._promise._captureStackTrace();
16357 this._init$(undefined, -5);
16358}
16359util.inherits(ReductionPromiseArray, PromiseArray);
16360
16361ReductionPromiseArray.prototype._gotAccum = function(accum) {
16362 if (this._eachValues !== undefined &&
16363 this._eachValues !== null &&
16364 accum !== INTERNAL) {
16365 this._eachValues.push(accum);
16366 }
16367};
16368
16369ReductionPromiseArray.prototype._eachComplete = function(value) {
16370 if (this._eachValues !== null) {
16371 this._eachValues.push(value);
16372 }
16373 return this._eachValues;
16374};
16375
16376ReductionPromiseArray.prototype._init = function() {};
16377
16378ReductionPromiseArray.prototype._resolveEmptyArray = function() {
16379 this._resolve(this._eachValues !== undefined ? this._eachValues
16380 : this._initialValue);
16381};
16382
16383ReductionPromiseArray.prototype.shouldCopyValues = function () {
16384 return false;
16385};
16386
16387ReductionPromiseArray.prototype._resolve = function(value) {
16388 this._promise._resolveCallback(value);
16389 this._values = null;
16390};
16391
16392ReductionPromiseArray.prototype._resultCancelled = function(sender) {
16393 if (sender === this._initialValue) return this._cancel();
16394 if (this._isResolved()) return;
16395 this._resultCancelled$();
16396 if (this._currentCancellable instanceof Promise) {
16397 this._currentCancellable.cancel();
16398 }
16399 if (this._initialValue instanceof Promise) {
16400 this._initialValue.cancel();
16401 }
16402};
16403
16404ReductionPromiseArray.prototype._iterate = function (values) {
16405 this._values = values;
16406 var value;
16407 var i;
16408 var length = values.length;
16409 if (this._initialValue !== undefined) {
16410 value = this._initialValue;
16411 i = 0;
16412 } else {
16413 value = Promise.resolve(values[0]);
16414 i = 1;
16415 }
16416
16417 this._currentCancellable = value;
16418
16419 if (!value.isRejected()) {
16420 for (; i < length; ++i) {
16421 var ctx = {
16422 accum: null,
16423 value: values[i],
16424 index: i,
16425 length: length,
16426 array: this
16427 };
16428 value = value._then(gotAccum, undefined, undefined, ctx, undefined);
16429 }
16430 }
16431
16432 if (this._eachValues !== undefined) {
16433 value = value
16434 ._then(this._eachComplete, undefined, undefined, this, undefined);
16435 }
16436 value._then(completed, completed, undefined, value, this);
16437};
16438
16439Promise.prototype.reduce = function (fn, initialValue) {
16440 return reduce(this, fn, initialValue, null);
16441};
16442
16443Promise.reduce = function (promises, fn, initialValue, _each) {
16444 return reduce(promises, fn, initialValue, _each);
16445};
16446
16447function completed(valueOrReason, array) {
16448 if (this.isFulfilled()) {
16449 array._resolve(valueOrReason);
16450 } else {
16451 array._reject(valueOrReason);
16452 }
16453}
16454
16455function reduce(promises, fn, initialValue, _each) {
16456 if (typeof fn !== "function") {
16457 return apiRejection("expecting a function but got " + util.classString(fn));
16458 }
16459 var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
16460 return array.promise();
16461}
16462
16463function gotAccum(accum) {
16464 this.accum = accum;
16465 this.array._gotAccum(accum);
16466 var value = tryConvertToPromise(this.value, this.array._promise);
16467 if (value instanceof Promise) {
16468 this.array._currentCancellable = value;
16469 return value._then(gotValue, undefined, undefined, this, undefined);
16470 } else {
16471 return gotValue.call(this, value);
16472 }
16473}
16474
16475function gotValue(value) {
16476 var array = this.array;
16477 var promise = array._promise;
16478 var fn = tryCatch(array._fn);
16479 promise._pushContext();
16480 var ret;
16481 if (array._eachValues !== undefined) {
16482 ret = fn.call(promise._boundValue(), value, this.index, this.length);
16483 } else {
16484 ret = fn.call(promise._boundValue(),
16485 this.accum, value, this.index, this.length);
16486 }
16487 if (ret instanceof Promise) {
16488 array._currentCancellable = ret;
16489 }
16490 var promiseCreated = promise._popContext();
16491 debug.checkForgottenReturns(
16492 ret,
16493 promiseCreated,
16494 array._eachValues !== undefined ? "Promise.each" : "Promise.reduce",
16495 promise
16496 );
16497 return ret;
16498}
16499};
16500
16501},{"./util":36}],29:[function(_dereq_,module,exports){
16502"use strict";
16503var util = _dereq_("./util");
16504var schedule;
16505var noAsyncScheduler = function() {
16506 throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16507};
16508var NativePromise = util.getNativePromise();
16509if (util.isNode && typeof MutationObserver === "undefined") {
16510 var GlobalSetImmediate = global.setImmediate;
16511 var ProcessNextTick = process.nextTick;
16512 schedule = util.isRecentNode
16513 ? function(fn) { GlobalSetImmediate.call(global, fn); }
16514 : function(fn) { ProcessNextTick.call(process, fn); };
16515} else if (typeof NativePromise === "function" &&
16516 typeof NativePromise.resolve === "function") {
16517 var nativePromise = NativePromise.resolve();
16518 schedule = function(fn) {
16519 nativePromise.then(fn);
16520 };
16521} else if ((typeof MutationObserver !== "undefined") &&
16522 !(typeof window !== "undefined" &&
16523 window.navigator &&
16524 (window.navigator.standalone || window.cordova)) &&
16525 ("classList" in document.documentElement)) {
16526 schedule = (function() {
16527 var div = document.createElement("div");
16528 var opts = {attributes: true};
16529 var toggleScheduled = false;
16530 var div2 = document.createElement("div");
16531 var o2 = new MutationObserver(function() {
16532 div.classList.toggle("foo");
16533 toggleScheduled = false;
16534 });
16535 o2.observe(div2, opts);
16536
16537 var scheduleToggle = function() {
16538 if (toggleScheduled) return;
16539 toggleScheduled = true;
16540 div2.classList.toggle("foo");
16541 };
16542
16543 return function schedule(fn) {
16544 var o = new MutationObserver(function() {
16545 o.disconnect();
16546 fn();
16547 });
16548 o.observe(div, opts);
16549 scheduleToggle();
16550 };
16551 })();
16552} else if (typeof setImmediate !== "undefined") {
16553 schedule = function (fn) {
16554 setImmediate(fn);
16555 };
16556} else if (typeof setTimeout !== "undefined") {
16557 schedule = function (fn) {
16558 setTimeout(fn, 0);
16559 };
16560} else {
16561 schedule = noAsyncScheduler;
16562}
16563module.exports = schedule;
16564
16565},{"./util":36}],30:[function(_dereq_,module,exports){
16566"use strict";
16567module.exports =
16568 function(Promise, PromiseArray, debug) {
16569var PromiseInspection = Promise.PromiseInspection;
16570var util = _dereq_("./util");
16571
16572function SettledPromiseArray(values) {
16573 this.constructor$(values);
16574}
16575util.inherits(SettledPromiseArray, PromiseArray);
16576
16577SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
16578 this._values[index] = inspection;
16579 var totalResolved = ++this._totalResolved;
16580 if (totalResolved >= this._length) {
16581 this._resolve(this._values);
16582 return true;
16583 }
16584 return false;
16585};
16586
16587SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
16588 var ret = new PromiseInspection();
16589 ret._bitField = 33554432;
16590 ret._settledValueField = value;
16591 return this._promiseResolved(index, ret);
16592};
16593SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
16594 var ret = new PromiseInspection();
16595 ret._bitField = 16777216;
16596 ret._settledValueField = reason;
16597 return this._promiseResolved(index, ret);
16598};
16599
16600Promise.settle = function (promises) {
16601 debug.deprecated(".settle()", ".reflect()");
16602 return new SettledPromiseArray(promises).promise();
16603};
16604
16605Promise.prototype.settle = function () {
16606 return Promise.settle(this);
16607};
16608};
16609
16610},{"./util":36}],31:[function(_dereq_,module,exports){
16611"use strict";
16612module.exports =
16613function(Promise, PromiseArray, apiRejection) {
16614var util = _dereq_("./util");
16615var RangeError = _dereq_("./errors").RangeError;
16616var AggregateError = _dereq_("./errors").AggregateError;
16617var isArray = util.isArray;
16618var CANCELLATION = {};
16619
16620
16621function SomePromiseArray(values) {
16622 this.constructor$(values);
16623 this._howMany = 0;
16624 this._unwrap = false;
16625 this._initialized = false;
16626}
16627util.inherits(SomePromiseArray, PromiseArray);
16628
16629SomePromiseArray.prototype._init = function () {
16630 if (!this._initialized) {
16631 return;
16632 }
16633 if (this._howMany === 0) {
16634 this._resolve([]);
16635 return;
16636 }
16637 this._init$(undefined, -5);
16638 var isArrayResolved = isArray(this._values);
16639 if (!this._isResolved() &&
16640 isArrayResolved &&
16641 this._howMany > this._canPossiblyFulfill()) {
16642 this._reject(this._getRangeError(this.length()));
16643 }
16644};
16645
16646SomePromiseArray.prototype.init = function () {
16647 this._initialized = true;
16648 this._init();
16649};
16650
16651SomePromiseArray.prototype.setUnwrap = function () {
16652 this._unwrap = true;
16653};
16654
16655SomePromiseArray.prototype.howMany = function () {
16656 return this._howMany;
16657};
16658
16659SomePromiseArray.prototype.setHowMany = function (count) {
16660 this._howMany = count;
16661};
16662
16663SomePromiseArray.prototype._promiseFulfilled = function (value) {
16664 this._addFulfilled(value);
16665 if (this._fulfilled() === this.howMany()) {
16666 this._values.length = this.howMany();
16667 if (this.howMany() === 1 && this._unwrap) {
16668 this._resolve(this._values[0]);
16669 } else {
16670 this._resolve(this._values);
16671 }
16672 return true;
16673 }
16674 return false;
16675
16676};
16677SomePromiseArray.prototype._promiseRejected = function (reason) {
16678 this._addRejected(reason);
16679 return this._checkOutcome();
16680};
16681
16682SomePromiseArray.prototype._promiseCancelled = function () {
16683 if (this._values instanceof Promise || this._values == null) {
16684 return this._cancel();
16685 }
16686 this._addRejected(CANCELLATION);
16687 return this._checkOutcome();
16688};
16689
16690SomePromiseArray.prototype._checkOutcome = function() {
16691 if (this.howMany() > this._canPossiblyFulfill()) {
16692 var e = new AggregateError();
16693 for (var i = this.length(); i < this._values.length; ++i) {
16694 if (this._values[i] !== CANCELLATION) {
16695 e.push(this._values[i]);
16696 }
16697 }
16698 if (e.length > 0) {
16699 this._reject(e);
16700 } else {
16701 this._cancel();
16702 }
16703 return true;
16704 }
16705 return false;
16706};
16707
16708SomePromiseArray.prototype._fulfilled = function () {
16709 return this._totalResolved;
16710};
16711
16712SomePromiseArray.prototype._rejected = function () {
16713 return this._values.length - this.length();
16714};
16715
16716SomePromiseArray.prototype._addRejected = function (reason) {
16717 this._values.push(reason);
16718};
16719
16720SomePromiseArray.prototype._addFulfilled = function (value) {
16721 this._values[this._totalResolved++] = value;
16722};
16723
16724SomePromiseArray.prototype._canPossiblyFulfill = function () {
16725 return this.length() - this._rejected();
16726};
16727
16728SomePromiseArray.prototype._getRangeError = function (count) {
16729 var message = "Input array must contain at least " +
16730 this._howMany + " items but contains only " + count + " items";
16731 return new RangeError(message);
16732};
16733
16734SomePromiseArray.prototype._resolveEmptyArray = function () {
16735 this._reject(this._getRangeError(0));
16736};
16737
16738function some(promises, howMany) {
16739 if ((howMany | 0) !== howMany || howMany < 0) {
16740 return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16741 }
16742 var ret = new SomePromiseArray(promises);
16743 var promise = ret.promise();
16744 ret.setHowMany(howMany);
16745 ret.init();
16746 return promise;
16747}
16748
16749Promise.some = function (promises, howMany) {
16750 return some(promises, howMany);
16751};
16752
16753Promise.prototype.some = function (howMany) {
16754 return some(this, howMany);
16755};
16756
16757Promise._SomePromiseArray = SomePromiseArray;
16758};
16759
16760},{"./errors":12,"./util":36}],32:[function(_dereq_,module,exports){
16761"use strict";
16762module.exports = function(Promise) {
16763function PromiseInspection(promise) {
16764 if (promise !== undefined) {
16765 promise = promise._target();
16766 this._bitField = promise._bitField;
16767 this._settledValueField = promise._isFateSealed()
16768 ? promise._settledValue() : undefined;
16769 }
16770 else {
16771 this._bitField = 0;
16772 this._settledValueField = undefined;
16773 }
16774}
16775
16776PromiseInspection.prototype._settledValue = function() {
16777 return this._settledValueField;
16778};
16779
16780var value = PromiseInspection.prototype.value = function () {
16781 if (!this.isFulfilled()) {
16782 throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16783 }
16784 return this._settledValue();
16785};
16786
16787var reason = PromiseInspection.prototype.error =
16788PromiseInspection.prototype.reason = function () {
16789 if (!this.isRejected()) {
16790 throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
16791 }
16792 return this._settledValue();
16793};
16794
16795var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
16796 return (this._bitField & 33554432) !== 0;
16797};
16798
16799var isRejected = PromiseInspection.prototype.isRejected = function () {
16800 return (this._bitField & 16777216) !== 0;
16801};
16802
16803var isPending = PromiseInspection.prototype.isPending = function () {
16804 return (this._bitField & 50397184) === 0;
16805};
16806
16807var isResolved = PromiseInspection.prototype.isResolved = function () {
16808 return (this._bitField & 50331648) !== 0;
16809};
16810
16811PromiseInspection.prototype.isCancelled = function() {
16812 return (this._bitField & 8454144) !== 0;
16813};
16814
16815Promise.prototype.__isCancelled = function() {
16816 return (this._bitField & 65536) === 65536;
16817};
16818
16819Promise.prototype._isCancelled = function() {
16820 return this._target().__isCancelled();
16821};
16822
16823Promise.prototype.isCancelled = function() {
16824 return (this._target()._bitField & 8454144) !== 0;
16825};
16826
16827Promise.prototype.isPending = function() {
16828 return isPending.call(this._target());
16829};
16830
16831Promise.prototype.isRejected = function() {
16832 return isRejected.call(this._target());
16833};
16834
16835Promise.prototype.isFulfilled = function() {
16836 return isFulfilled.call(this._target());
16837};
16838
16839Promise.prototype.isResolved = function() {
16840 return isResolved.call(this._target());
16841};
16842
16843Promise.prototype.value = function() {
16844 return value.call(this._target());
16845};
16846
16847Promise.prototype.reason = function() {
16848 var target = this._target();
16849 target._unsetRejectionIsUnhandled();
16850 return reason.call(target);
16851};
16852
16853Promise.prototype._value = function() {
16854 return this._settledValue();
16855};
16856
16857Promise.prototype._reason = function() {
16858 this._unsetRejectionIsUnhandled();
16859 return this._settledValue();
16860};
16861
16862Promise.PromiseInspection = PromiseInspection;
16863};
16864
16865},{}],33:[function(_dereq_,module,exports){
16866"use strict";
16867module.exports = function(Promise, INTERNAL) {
16868var util = _dereq_("./util");
16869var errorObj = util.errorObj;
16870var isObject = util.isObject;
16871
16872function tryConvertToPromise(obj, context) {
16873 if (isObject(obj)) {
16874 if (obj instanceof Promise) return obj;
16875 var then = getThen(obj);
16876 if (then === errorObj) {
16877 if (context) context._pushContext();
16878 var ret = Promise.reject(then.e);
16879 if (context) context._popContext();
16880 return ret;
16881 } else if (typeof then === "function") {
16882 if (isAnyBluebirdPromise(obj)) {
16883 var ret = new Promise(INTERNAL);
16884 obj._then(
16885 ret._fulfill,
16886 ret._reject,
16887 undefined,
16888 ret,
16889 null
16890 );
16891 return ret;
16892 }
16893 return doThenable(obj, then, context);
16894 }
16895 }
16896 return obj;
16897}
16898
16899function doGetThen(obj) {
16900 return obj.then;
16901}
16902
16903function getThen(obj) {
16904 try {
16905 return doGetThen(obj);
16906 } catch (e) {
16907 errorObj.e = e;
16908 return errorObj;
16909 }
16910}
16911
16912var hasProp = {}.hasOwnProperty;
16913function isAnyBluebirdPromise(obj) {
16914 try {
16915 return hasProp.call(obj, "_promise0");
16916 } catch (e) {
16917 return false;
16918 }
16919}
16920
16921function doThenable(x, then, context) {
16922 var promise = new Promise(INTERNAL);
16923 var ret = promise;
16924 if (context) context._pushContext();
16925 promise._captureStackTrace();
16926 if (context) context._popContext();
16927 var synchronous = true;
16928 var result = util.tryCatch(then).call(x, resolve, reject);
16929 synchronous = false;
16930
16931 if (promise && result === errorObj) {
16932 promise._rejectCallback(result.e, true, true);
16933 promise = null;
16934 }
16935
16936 function resolve(value) {
16937 if (!promise) return;
16938 promise._resolveCallback(value);
16939 promise = null;
16940 }
16941
16942 function reject(reason) {
16943 if (!promise) return;
16944 promise._rejectCallback(reason, synchronous, true);
16945 promise = null;
16946 }
16947 return ret;
16948}
16949
16950return tryConvertToPromise;
16951};
16952
16953},{"./util":36}],34:[function(_dereq_,module,exports){
16954"use strict";
16955module.exports = function(Promise, INTERNAL, debug) {
16956var util = _dereq_("./util");
16957var TimeoutError = Promise.TimeoutError;
16958
16959function HandleWrapper(handle) {
16960 this.handle = handle;
16961}
16962
16963HandleWrapper.prototype._resultCancelled = function() {
16964 clearTimeout(this.handle);
16965};
16966
16967var afterValue = function(value) { return delay(+this).thenReturn(value); };
16968var delay = Promise.delay = function (ms, value) {
16969 var ret;
16970 var handle;
16971 if (value !== undefined) {
16972 ret = Promise.resolve(value)
16973 ._then(afterValue, null, null, ms, undefined);
16974 if (debug.cancellation() && value instanceof Promise) {
16975 ret._setOnCancel(value);
16976 }
16977 } else {
16978 ret = new Promise(INTERNAL);
16979 handle = setTimeout(function() { ret._fulfill(); }, +ms);
16980 if (debug.cancellation()) {
16981 ret._setOnCancel(new HandleWrapper(handle));
16982 }
16983 ret._captureStackTrace();
16984 }
16985 ret._setAsyncGuaranteed();
16986 return ret;
16987};
16988
16989Promise.prototype.delay = function (ms) {
16990 return delay(ms, this);
16991};
16992
16993var afterTimeout = function (promise, message, parent) {
16994 var err;
16995 if (typeof message !== "string") {
16996 if (message instanceof Error) {
16997 err = message;
16998 } else {
16999 err = new TimeoutError("operation timed out");
17000 }
17001 } else {
17002 err = new TimeoutError(message);
17003 }
17004 util.markAsOriginatingFromRejection(err);
17005 promise._attachExtraTrace(err);
17006 promise._reject(err);
17007
17008 if (parent != null) {
17009 parent.cancel();
17010 }
17011};
17012
17013function successClear(value) {
17014 clearTimeout(this.handle);
17015 return value;
17016}
17017
17018function failureClear(reason) {
17019 clearTimeout(this.handle);
17020 throw reason;
17021}
17022
17023Promise.prototype.timeout = function (ms, message) {
17024 ms = +ms;
17025 var ret, parent;
17026
17027 var handleWrapper = new HandleWrapper(setTimeout(function timeoutTimeout() {
17028 if (ret.isPending()) {
17029 afterTimeout(ret, message, parent);
17030 }
17031 }, ms));
17032
17033 if (debug.cancellation()) {
17034 parent = this.then();
17035 ret = parent._then(successClear, failureClear,
17036 undefined, handleWrapper, undefined);
17037 ret._setOnCancel(handleWrapper);
17038 } else {
17039 ret = this._then(successClear, failureClear,
17040 undefined, handleWrapper, undefined);
17041 }
17042
17043 return ret;
17044};
17045
17046};
17047
17048},{"./util":36}],35:[function(_dereq_,module,exports){
17049"use strict";
17050module.exports = function (Promise, apiRejection, tryConvertToPromise,
17051 createContext, INTERNAL, debug) {
17052 var util = _dereq_("./util");
17053 var TypeError = _dereq_("./errors").TypeError;
17054 var inherits = _dereq_("./util").inherits;
17055 var errorObj = util.errorObj;
17056 var tryCatch = util.tryCatch;
17057 var NULL = {};
17058
17059 function thrower(e) {
17060 setTimeout(function(){throw e;}, 0);
17061 }
17062
17063 function castPreservingDisposable(thenable) {
17064 var maybePromise = tryConvertToPromise(thenable);
17065 if (maybePromise !== thenable &&
17066 typeof thenable._isDisposable === "function" &&
17067 typeof thenable._getDisposer === "function" &&
17068 thenable._isDisposable()) {
17069 maybePromise._setDisposable(thenable._getDisposer());
17070 }
17071 return maybePromise;
17072 }
17073 function dispose(resources, inspection) {
17074 var i = 0;
17075 var len = resources.length;
17076 var ret = new Promise(INTERNAL);
17077 function iterator() {
17078 if (i >= len) return ret._fulfill();
17079 var maybePromise = castPreservingDisposable(resources[i++]);
17080 if (maybePromise instanceof Promise &&
17081 maybePromise._isDisposable()) {
17082 try {
17083 maybePromise = tryConvertToPromise(
17084 maybePromise._getDisposer().tryDispose(inspection),
17085 resources.promise);
17086 } catch (e) {
17087 return thrower(e);
17088 }
17089 if (maybePromise instanceof Promise) {
17090 return maybePromise._then(iterator, thrower,
17091 null, null, null);
17092 }
17093 }
17094 iterator();
17095 }
17096 iterator();
17097 return ret;
17098 }
17099
17100 function Disposer(data, promise, context) {
17101 this._data = data;
17102 this._promise = promise;
17103 this._context = context;
17104 }
17105
17106 Disposer.prototype.data = function () {
17107 return this._data;
17108 };
17109
17110 Disposer.prototype.promise = function () {
17111 return this._promise;
17112 };
17113
17114 Disposer.prototype.resource = function () {
17115 if (this.promise().isFulfilled()) {
17116 return this.promise().value();
17117 }
17118 return NULL;
17119 };
17120
17121 Disposer.prototype.tryDispose = function(inspection) {
17122 var resource = this.resource();
17123 var context = this._context;
17124 if (context !== undefined) context._pushContext();
17125 var ret = resource !== NULL
17126 ? this.doDispose(resource, inspection) : null;
17127 if (context !== undefined) context._popContext();
17128 this._promise._unsetDisposable();
17129 this._data = null;
17130 return ret;
17131 };
17132
17133 Disposer.isDisposer = function (d) {
17134 return (d != null &&
17135 typeof d.resource === "function" &&
17136 typeof d.tryDispose === "function");
17137 };
17138
17139 function FunctionDisposer(fn, promise, context) {
17140 this.constructor$(fn, promise, context);
17141 }
17142 inherits(FunctionDisposer, Disposer);
17143
17144 FunctionDisposer.prototype.doDispose = function (resource, inspection) {
17145 var fn = this.data();
17146 return fn.call(resource, resource, inspection);
17147 };
17148
17149 function maybeUnwrapDisposer(value) {
17150 if (Disposer.isDisposer(value)) {
17151 this.resources[this.index]._setDisposable(value);
17152 return value.promise();
17153 }
17154 return value;
17155 }
17156
17157 function ResourceList(length) {
17158 this.length = length;
17159 this.promise = null;
17160 this[length-1] = null;
17161 }
17162
17163 ResourceList.prototype._resultCancelled = function() {
17164 var len = this.length;
17165 for (var i = 0; i < len; ++i) {
17166 var item = this[i];
17167 if (item instanceof Promise) {
17168 item.cancel();
17169 }
17170 }
17171 };
17172
17173 Promise.using = function () {
17174 var len = arguments.length;
17175 if (len < 2) return apiRejection(
17176 "you must pass at least 2 arguments to Promise.using");
17177 var fn = arguments[len - 1];
17178 if (typeof fn !== "function") {
17179 return apiRejection("expecting a function but got " + util.classString(fn));
17180 }
17181 var input;
17182 var spreadArgs = true;
17183 if (len === 2 && Array.isArray(arguments[0])) {
17184 input = arguments[0];
17185 len = input.length;
17186 spreadArgs = false;
17187 } else {
17188 input = arguments;
17189 len--;
17190 }
17191 var resources = new ResourceList(len);
17192 for (var i = 0; i < len; ++i) {
17193 var resource = input[i];
17194 if (Disposer.isDisposer(resource)) {
17195 var disposer = resource;
17196 resource = resource.promise();
17197 resource._setDisposable(disposer);
17198 } else {
17199 var maybePromise = tryConvertToPromise(resource);
17200 if (maybePromise instanceof Promise) {
17201 resource =
17202 maybePromise._then(maybeUnwrapDisposer, null, null, {
17203 resources: resources,
17204 index: i
17205 }, undefined);
17206 }
17207 }
17208 resources[i] = resource;
17209 }
17210
17211 var reflectedResources = new Array(resources.length);
17212 for (var i = 0; i < reflectedResources.length; ++i) {
17213 reflectedResources[i] = Promise.resolve(resources[i]).reflect();
17214 }
17215
17216 var resultPromise = Promise.all(reflectedResources)
17217 .then(function(inspections) {
17218 for (var i = 0; i < inspections.length; ++i) {
17219 var inspection = inspections[i];
17220 if (inspection.isRejected()) {
17221 errorObj.e = inspection.error();
17222 return errorObj;
17223 } else if (!inspection.isFulfilled()) {
17224 resultPromise.cancel();
17225 return;
17226 }
17227 inspections[i] = inspection.value();
17228 }
17229 promise._pushContext();
17230
17231 fn = tryCatch(fn);
17232 var ret = spreadArgs
17233 ? fn.apply(undefined, inspections) : fn(inspections);
17234 var promiseCreated = promise._popContext();
17235 debug.checkForgottenReturns(
17236 ret, promiseCreated, "Promise.using", promise);
17237 return ret;
17238 });
17239
17240 var promise = resultPromise.lastly(function() {
17241 var inspection = new Promise.PromiseInspection(resultPromise);
17242 return dispose(resources, inspection);
17243 });
17244 resources.promise = promise;
17245 promise._setOnCancel(resources);
17246 return promise;
17247 };
17248
17249 Promise.prototype._setDisposable = function (disposer) {
17250 this._bitField = this._bitField | 131072;
17251 this._disposer = disposer;
17252 };
17253
17254 Promise.prototype._isDisposable = function () {
17255 return (this._bitField & 131072) > 0;
17256 };
17257
17258 Promise.prototype._getDisposer = function () {
17259 return this._disposer;
17260 };
17261
17262 Promise.prototype._unsetDisposable = function () {
17263 this._bitField = this._bitField & (~131072);
17264 this._disposer = undefined;
17265 };
17266
17267 Promise.prototype.disposer = function (fn) {
17268 if (typeof fn === "function") {
17269 return new FunctionDisposer(fn, this, createContext());
17270 }
17271 throw new TypeError();
17272 };
17273
17274};
17275
17276},{"./errors":12,"./util":36}],36:[function(_dereq_,module,exports){
17277"use strict";
17278var es5 = _dereq_("./es5");
17279var canEvaluate = typeof navigator == "undefined";
17280
17281var errorObj = {e: {}};
17282var tryCatchTarget;
17283var globalObject = typeof self !== "undefined" ? self :
17284 typeof window !== "undefined" ? window :
17285 typeof global !== "undefined" ? global :
17286 this !== undefined ? this : null;
17287
17288function tryCatcher() {
17289 try {
17290 var target = tryCatchTarget;
17291 tryCatchTarget = null;
17292 return target.apply(this, arguments);
17293 } catch (e) {
17294 errorObj.e = e;
17295 return errorObj;
17296 }
17297}
17298function tryCatch(fn) {
17299 tryCatchTarget = fn;
17300 return tryCatcher;
17301}
17302
17303var inherits = function(Child, Parent) {
17304 var hasProp = {}.hasOwnProperty;
17305
17306 function T() {
17307 this.constructor = Child;
17308 this.constructor$ = Parent;
17309 for (var propertyName in Parent.prototype) {
17310 if (hasProp.call(Parent.prototype, propertyName) &&
17311 propertyName.charAt(propertyName.length-1) !== "$"
17312 ) {
17313 this[propertyName + "$"] = Parent.prototype[propertyName];
17314 }
17315 }
17316 }
17317 T.prototype = Parent.prototype;
17318 Child.prototype = new T();
17319 return Child.prototype;
17320};
17321
17322
17323function isPrimitive(val) {
17324 return val == null || val === true || val === false ||
17325 typeof val === "string" || typeof val === "number";
17326
17327}
17328
17329function isObject(value) {
17330 return typeof value === "function" ||
17331 typeof value === "object" && value !== null;
17332}
17333
17334function maybeWrapAsError(maybeError) {
17335 if (!isPrimitive(maybeError)) return maybeError;
17336
17337 return new Error(safeToString(maybeError));
17338}
17339
17340function withAppended(target, appendee) {
17341 var len = target.length;
17342 var ret = new Array(len + 1);
17343 var i;
17344 for (i = 0; i < len; ++i) {
17345 ret[i] = target[i];
17346 }
17347 ret[i] = appendee;
17348 return ret;
17349}
17350
17351function getDataPropertyOrDefault(obj, key, defaultValue) {
17352 if (es5.isES5) {
17353 var desc = Object.getOwnPropertyDescriptor(obj, key);
17354
17355 if (desc != null) {
17356 return desc.get == null && desc.set == null
17357 ? desc.value
17358 : defaultValue;
17359 }
17360 } else {
17361 return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
17362 }
17363}
17364
17365function notEnumerableProp(obj, name, value) {
17366 if (isPrimitive(obj)) return obj;
17367 var descriptor = {
17368 value: value,
17369 configurable: true,
17370 enumerable: false,
17371 writable: true
17372 };
17373 es5.defineProperty(obj, name, descriptor);
17374 return obj;
17375}
17376
17377function thrower(r) {
17378 throw r;
17379}
17380
17381var inheritedDataKeys = (function() {
17382 var excludedPrototypes = [
17383 Array.prototype,
17384 Object.prototype,
17385 Function.prototype
17386 ];
17387
17388 var isExcludedProto = function(val) {
17389 for (var i = 0; i < excludedPrototypes.length; ++i) {
17390 if (excludedPrototypes[i] === val) {
17391 return true;
17392 }
17393 }
17394 return false;
17395 };
17396
17397 if (es5.isES5) {
17398 var getKeys = Object.getOwnPropertyNames;
17399 return function(obj) {
17400 var ret = [];
17401 var visitedKeys = Object.create(null);
17402 while (obj != null && !isExcludedProto(obj)) {
17403 var keys;
17404 try {
17405 keys = getKeys(obj);
17406 } catch (e) {
17407 return ret;
17408 }
17409 for (var i = 0; i < keys.length; ++i) {
17410 var key = keys[i];
17411 if (visitedKeys[key]) continue;
17412 visitedKeys[key] = true;
17413 var desc = Object.getOwnPropertyDescriptor(obj, key);
17414 if (desc != null && desc.get == null && desc.set == null) {
17415 ret.push(key);
17416 }
17417 }
17418 obj = es5.getPrototypeOf(obj);
17419 }
17420 return ret;
17421 };
17422 } else {
17423 var hasProp = {}.hasOwnProperty;
17424 return function(obj) {
17425 if (isExcludedProto(obj)) return [];
17426 var ret = [];
17427
17428 /*jshint forin:false */
17429 enumeration: for (var key in obj) {
17430 if (hasProp.call(obj, key)) {
17431 ret.push(key);
17432 } else {
17433 for (var i = 0; i < excludedPrototypes.length; ++i) {
17434 if (hasProp.call(excludedPrototypes[i], key)) {
17435 continue enumeration;
17436 }
17437 }
17438 ret.push(key);
17439 }
17440 }
17441 return ret;
17442 };
17443 }
17444
17445})();
17446
17447var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
17448function isClass(fn) {
17449 try {
17450 if (typeof fn === "function") {
17451 var keys = es5.names(fn.prototype);
17452
17453 var hasMethods = es5.isES5 && keys.length > 1;
17454 var hasMethodsOtherThanConstructor = keys.length > 0 &&
17455 !(keys.length === 1 && keys[0] === "constructor");
17456 var hasThisAssignmentAndStaticMethods =
17457 thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
17458
17459 if (hasMethods || hasMethodsOtherThanConstructor ||
17460 hasThisAssignmentAndStaticMethods) {
17461 return true;
17462 }
17463 }
17464 return false;
17465 } catch (e) {
17466 return false;
17467 }
17468}
17469
17470function toFastProperties(obj) {
17471 /*jshint -W027,-W055,-W031*/
17472 function FakeConstructor() {}
17473 FakeConstructor.prototype = obj;
17474 var receiver = new FakeConstructor();
17475 function ic() {
17476 return typeof receiver.foo;
17477 }
17478 ic();
17479 ic();
17480 return obj;
17481 eval(obj);
17482}
17483
17484var rident = /^[a-z$_][a-z$_0-9]*$/i;
17485function isIdentifier(str) {
17486 return rident.test(str);
17487}
17488
17489function filledRange(count, prefix, suffix) {
17490 var ret = new Array(count);
17491 for(var i = 0; i < count; ++i) {
17492 ret[i] = prefix + i + suffix;
17493 }
17494 return ret;
17495}
17496
17497function safeToString(obj) {
17498 try {
17499 return obj + "";
17500 } catch (e) {
17501 return "[no string representation]";
17502 }
17503}
17504
17505function isError(obj) {
17506 return obj instanceof Error ||
17507 (obj !== null &&
17508 typeof obj === "object" &&
17509 typeof obj.message === "string" &&
17510 typeof obj.name === "string");
17511}
17512
17513function markAsOriginatingFromRejection(e) {
17514 try {
17515 notEnumerableProp(e, "isOperational", true);
17516 }
17517 catch(ignore) {}
17518}
17519
17520function originatesFromRejection(e) {
17521 if (e == null) return false;
17522 return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
17523 e["isOperational"] === true);
17524}
17525
17526function canAttachTrace(obj) {
17527 return isError(obj) && es5.propertyIsWritable(obj, "stack");
17528}
17529
17530var ensureErrorObject = (function() {
17531 if (!("stack" in new Error())) {
17532 return function(value) {
17533 if (canAttachTrace(value)) return value;
17534 try {throw new Error(safeToString(value));}
17535 catch(err) {return err;}
17536 };
17537 } else {
17538 return function(value) {
17539 if (canAttachTrace(value)) return value;
17540 return new Error(safeToString(value));
17541 };
17542 }
17543})();
17544
17545function classString(obj) {
17546 return {}.toString.call(obj);
17547}
17548
17549function copyDescriptors(from, to, filter) {
17550 var keys = es5.names(from);
17551 for (var i = 0; i < keys.length; ++i) {
17552 var key = keys[i];
17553 if (filter(key)) {
17554 try {
17555 es5.defineProperty(to, key, es5.getDescriptor(from, key));
17556 } catch (ignore) {}
17557 }
17558 }
17559}
17560
17561var asArray = function(v) {
17562 if (es5.isArray(v)) {
17563 return v;
17564 }
17565 return null;
17566};
17567
17568if (typeof Symbol !== "undefined" && Symbol.iterator) {
17569 var ArrayFrom = typeof Array.from === "function" ? function(v) {
17570 return Array.from(v);
17571 } : function(v) {
17572 var ret = [];
17573 var it = v[Symbol.iterator]();
17574 var itResult;
17575 while (!((itResult = it.next()).done)) {
17576 ret.push(itResult.value);
17577 }
17578 return ret;
17579 };
17580
17581 asArray = function(v) {
17582 if (es5.isArray(v)) {
17583 return v;
17584 } else if (v != null && typeof v[Symbol.iterator] === "function") {
17585 return ArrayFrom(v);
17586 }
17587 return null;
17588 };
17589}
17590
17591var isNode = typeof process !== "undefined" &&
17592 classString(process).toLowerCase() === "[object process]";
17593
17594var hasEnvVariables = typeof process !== "undefined" &&
17595 typeof process.env !== "undefined";
17596
17597function env(key) {
17598 return hasEnvVariables ? process.env[key] : undefined;
17599}
17600
17601function getNativePromise() {
17602 if (typeof Promise === "function") {
17603 try {
17604 var promise = new Promise(function(){});
17605 if ({}.toString.call(promise) === "[object Promise]") {
17606 return Promise;
17607 }
17608 } catch (e) {}
17609 }
17610}
17611
17612function domainBind(self, cb) {
17613 return self.bind(cb);
17614}
17615
17616var ret = {
17617 isClass: isClass,
17618 isIdentifier: isIdentifier,
17619 inheritedDataKeys: inheritedDataKeys,
17620 getDataPropertyOrDefault: getDataPropertyOrDefault,
17621 thrower: thrower,
17622 isArray: es5.isArray,
17623 asArray: asArray,
17624 notEnumerableProp: notEnumerableProp,
17625 isPrimitive: isPrimitive,
17626 isObject: isObject,
17627 isError: isError,
17628 canEvaluate: canEvaluate,
17629 errorObj: errorObj,
17630 tryCatch: tryCatch,
17631 inherits: inherits,
17632 withAppended: withAppended,
17633 maybeWrapAsError: maybeWrapAsError,
17634 toFastProperties: toFastProperties,
17635 filledRange: filledRange,
17636 toString: safeToString,
17637 canAttachTrace: canAttachTrace,
17638 ensureErrorObject: ensureErrorObject,
17639 originatesFromRejection: originatesFromRejection,
17640 markAsOriginatingFromRejection: markAsOriginatingFromRejection,
17641 classString: classString,
17642 copyDescriptors: copyDescriptors,
17643 hasDevTools: typeof chrome !== "undefined" && chrome &&
17644 typeof chrome.loadTimes === "function",
17645 isNode: isNode,
17646 hasEnvVariables: hasEnvVariables,
17647 env: env,
17648 global: globalObject,
17649 getNativePromise: getNativePromise,
17650 domainBind: domainBind
17651};
17652ret.isRecentNode = ret.isNode && (function() {
17653 var version;
17654 if (process.versions && process.versions.node) {
17655 version = process.versions.node.split(".").map(Number);
17656 } else if (process.version) {
17657 version = process.version.split(".").map(Number);
17658 }
17659 return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
17660})();
17661
17662if (ret.isNode) ret.toFastProperties(process);
17663
17664try {throw new Error(); } catch (e) {ret.lastLineError = e;}
17665module.exports = ret;
17666
17667},{"./es5":13}]},{},[4])(4)
17668}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
17669}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
17670},{"_process":265,"timers":382}],80:[function(require,module,exports){
17671(function (module, exports) {
17672 'use strict';
17673
17674 // Utils
17675 function assert (val, msg) {
17676 if (!val) throw new Error(msg || 'Assertion failed');
17677 }
17678
17679 // Could use `inherits` module, but don't want to move from single file
17680 // architecture yet.
17681 function inherits (ctor, superCtor) {
17682 ctor.super_ = superCtor;
17683 var TempCtor = function () {};
17684 TempCtor.prototype = superCtor.prototype;
17685 ctor.prototype = new TempCtor();
17686 ctor.prototype.constructor = ctor;
17687 }
17688
17689 // BN
17690
17691 function BN (number, base, endian) {
17692 if (BN.isBN(number)) {
17693 return number;
17694 }
17695
17696 this.negative = 0;
17697 this.words = null;
17698 this.length = 0;
17699
17700 // Reduction context
17701 this.red = null;
17702
17703 if (number !== null) {
17704 if (base === 'le' || base === 'be') {
17705 endian = base;
17706 base = 10;
17707 }
17708
17709 this._init(number || 0, base || 10, endian || 'be');
17710 }
17711 }
17712 if (typeof module === 'object') {
17713 module.exports = BN;
17714 } else {
17715 exports.BN = BN;
17716 }
17717
17718 BN.BN = BN;
17719 BN.wordSize = 26;
17720
17721 var Buffer;
17722 try {
17723 Buffer = require('buffer').Buffer;
17724 } catch (e) {
17725 }
17726
17727 BN.isBN = function isBN (num) {
17728 if (num instanceof BN) {
17729 return true;
17730 }
17731
17732 return num !== null && typeof num === 'object' &&
17733 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
17734 };
17735
17736 BN.max = function max (left, right) {
17737 if (left.cmp(right) > 0) return left;
17738 return right;
17739 };
17740
17741 BN.min = function min (left, right) {
17742 if (left.cmp(right) < 0) return left;
17743 return right;
17744 };
17745
17746 BN.prototype._init = function init (number, base, endian) {
17747 if (typeof number === 'number') {
17748 return this._initNumber(number, base, endian);
17749 }
17750
17751 if (typeof number === 'object') {
17752 return this._initArray(number, base, endian);
17753 }
17754
17755 if (base === 'hex') {
17756 base = 16;
17757 }
17758 assert(base === (base | 0) && base >= 2 && base <= 36);
17759
17760 number = number.toString().replace(/\s+/g, '');
17761 var start = 0;
17762 if (number[0] === '-') {
17763 start++;
17764 }
17765
17766 if (base === 16) {
17767 this._parseHex(number, start);
17768 } else {
17769 this._parseBase(number, base, start);
17770 }
17771
17772 if (number[0] === '-') {
17773 this.negative = 1;
17774 }
17775
17776 this.strip();
17777
17778 if (endian !== 'le') return;
17779
17780 this._initArray(this.toArray(), base, endian);
17781 };
17782
17783 BN.prototype._initNumber = function _initNumber (number, base, endian) {
17784 if (number < 0) {
17785 this.negative = 1;
17786 number = -number;
17787 }
17788 if (number < 0x4000000) {
17789 this.words = [ number & 0x3ffffff ];
17790 this.length = 1;
17791 } else if (number < 0x10000000000000) {
17792 this.words = [
17793 number & 0x3ffffff,
17794 (number / 0x4000000) & 0x3ffffff
17795 ];
17796 this.length = 2;
17797 } else {
17798 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
17799 this.words = [
17800 number & 0x3ffffff,
17801 (number / 0x4000000) & 0x3ffffff,
17802 1
17803 ];
17804 this.length = 3;
17805 }
17806
17807 if (endian !== 'le') return;
17808
17809 // Reverse the bytes
17810 this._initArray(this.toArray(), base, endian);
17811 };
17812
17813 BN.prototype._initArray = function _initArray (number, base, endian) {
17814 // Perhaps a Uint8Array
17815 assert(typeof number.length === 'number');
17816 if (number.length <= 0) {
17817 this.words = [ 0 ];
17818 this.length = 1;
17819 return this;
17820 }
17821
17822 this.length = Math.ceil(number.length / 3);
17823 this.words = new Array(this.length);
17824 for (var i = 0; i < this.length; i++) {
17825 this.words[i] = 0;
17826 }
17827
17828 var j, w;
17829 var off = 0;
17830 if (endian === 'be') {
17831 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
17832 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
17833 this.words[j] |= (w << off) & 0x3ffffff;
17834 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
17835 off += 24;
17836 if (off >= 26) {
17837 off -= 26;
17838 j++;
17839 }
17840 }
17841 } else if (endian === 'le') {
17842 for (i = 0, j = 0; i < number.length; i += 3) {
17843 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
17844 this.words[j] |= (w << off) & 0x3ffffff;
17845 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
17846 off += 24;
17847 if (off >= 26) {
17848 off -= 26;
17849 j++;
17850 }
17851 }
17852 }
17853 return this.strip();
17854 };
17855
17856 function parseHex (str, start, end) {
17857 var r = 0;
17858 var len = Math.min(str.length, end);
17859 for (var i = start; i < len; i++) {
17860 var c = str.charCodeAt(i) - 48;
17861
17862 r <<= 4;
17863
17864 // 'a' - 'f'
17865 if (c >= 49 && c <= 54) {
17866 r |= c - 49 + 0xa;
17867
17868 // 'A' - 'F'
17869 } else if (c >= 17 && c <= 22) {
17870 r |= c - 17 + 0xa;
17871
17872 // '0' - '9'
17873 } else {
17874 r |= c & 0xf;
17875 }
17876 }
17877 return r;
17878 }
17879
17880 BN.prototype._parseHex = function _parseHex (number, start) {
17881 // Create possibly bigger array to ensure that it fits the number
17882 this.length = Math.ceil((number.length - start) / 6);
17883 this.words = new Array(this.length);
17884 for (var i = 0; i < this.length; i++) {
17885 this.words[i] = 0;
17886 }
17887
17888 var j, w;
17889 // Scan 24-bit chunks and add them to the number
17890 var off = 0;
17891 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
17892 w = parseHex(number, i, i + 6);
17893 this.words[j] |= (w << off) & 0x3ffffff;
17894 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
17895 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
17896 off += 24;
17897 if (off >= 26) {
17898 off -= 26;
17899 j++;
17900 }
17901 }
17902 if (i + 6 !== start) {
17903 w = parseHex(number, start, i + 6);
17904 this.words[j] |= (w << off) & 0x3ffffff;
17905 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
17906 }
17907 this.strip();
17908 };
17909
17910 function parseBase (str, start, end, mul) {
17911 var r = 0;
17912 var len = Math.min(str.length, end);
17913 for (var i = start; i < len; i++) {
17914 var c = str.charCodeAt(i) - 48;
17915
17916 r *= mul;
17917
17918 // 'a'
17919 if (c >= 49) {
17920 r += c - 49 + 0xa;
17921
17922 // 'A'
17923 } else if (c >= 17) {
17924 r += c - 17 + 0xa;
17925
17926 // '0' - '9'
17927 } else {
17928 r += c;
17929 }
17930 }
17931 return r;
17932 }
17933
17934 BN.prototype._parseBase = function _parseBase (number, base, start) {
17935 // Initialize as zero
17936 this.words = [ 0 ];
17937 this.length = 1;
17938
17939 // Find length of limb in base
17940 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
17941 limbLen++;
17942 }
17943 limbLen--;
17944 limbPow = (limbPow / base) | 0;
17945
17946 var total = number.length - start;
17947 var mod = total % limbLen;
17948 var end = Math.min(total, total - mod) + start;
17949
17950 var word = 0;
17951 for (var i = start; i < end; i += limbLen) {
17952 word = parseBase(number, i, i + limbLen, base);
17953
17954 this.imuln(limbPow);
17955 if (this.words[0] + word < 0x4000000) {
17956 this.words[0] += word;
17957 } else {
17958 this._iaddn(word);
17959 }
17960 }
17961
17962 if (mod !== 0) {
17963 var pow = 1;
17964 word = parseBase(number, i, number.length, base);
17965
17966 for (i = 0; i < mod; i++) {
17967 pow *= base;
17968 }
17969
17970 this.imuln(pow);
17971 if (this.words[0] + word < 0x4000000) {
17972 this.words[0] += word;
17973 } else {
17974 this._iaddn(word);
17975 }
17976 }
17977 };
17978
17979 BN.prototype.copy = function copy (dest) {
17980 dest.words = new Array(this.length);
17981 for (var i = 0; i < this.length; i++) {
17982 dest.words[i] = this.words[i];
17983 }
17984 dest.length = this.length;
17985 dest.negative = this.negative;
17986 dest.red = this.red;
17987 };
17988
17989 BN.prototype.clone = function clone () {
17990 var r = new BN(null);
17991 this.copy(r);
17992 return r;
17993 };
17994
17995 BN.prototype._expand = function _expand (size) {
17996 while (this.length < size) {
17997 this.words[this.length++] = 0;
17998 }
17999 return this;
18000 };
18001
18002 // Remove leading `0` from `this`
18003 BN.prototype.strip = function strip () {
18004 while (this.length > 1 && this.words[this.length - 1] === 0) {
18005 this.length--;
18006 }
18007 return this._normSign();
18008 };
18009
18010 BN.prototype._normSign = function _normSign () {
18011 // -0 = 0
18012 if (this.length === 1 && this.words[0] === 0) {
18013 this.negative = 0;
18014 }
18015 return this;
18016 };
18017
18018 BN.prototype.inspect = function inspect () {
18019 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
18020 };
18021
18022 /*
18023
18024 var zeros = [];
18025 var groupSizes = [];
18026 var groupBases = [];
18027
18028 var s = '';
18029 var i = -1;
18030 while (++i < BN.wordSize) {
18031 zeros[i] = s;
18032 s += '0';
18033 }
18034 groupSizes[0] = 0;
18035 groupSizes[1] = 0;
18036 groupBases[0] = 0;
18037 groupBases[1] = 0;
18038 var base = 2 - 1;
18039 while (++base < 36 + 1) {
18040 var groupSize = 0;
18041 var groupBase = 1;
18042 while (groupBase < (1 << BN.wordSize) / base) {
18043 groupBase *= base;
18044 groupSize += 1;
18045 }
18046 groupSizes[base] = groupSize;
18047 groupBases[base] = groupBase;
18048 }
18049
18050 */
18051
18052 var zeros = [
18053 '',
18054 '0',
18055 '00',
18056 '000',
18057 '0000',
18058 '00000',
18059 '000000',
18060 '0000000',
18061 '00000000',
18062 '000000000',
18063 '0000000000',
18064 '00000000000',
18065 '000000000000',
18066 '0000000000000',
18067 '00000000000000',
18068 '000000000000000',
18069 '0000000000000000',
18070 '00000000000000000',
18071 '000000000000000000',
18072 '0000000000000000000',
18073 '00000000000000000000',
18074 '000000000000000000000',
18075 '0000000000000000000000',
18076 '00000000000000000000000',
18077 '000000000000000000000000',
18078 '0000000000000000000000000'
18079 ];
18080
18081 var groupSizes = [
18082 0, 0,
18083 25, 16, 12, 11, 10, 9, 8,
18084 8, 7, 7, 7, 7, 6, 6,
18085 6, 6, 6, 6, 6, 5, 5,
18086 5, 5, 5, 5, 5, 5, 5,
18087 5, 5, 5, 5, 5, 5, 5
18088 ];
18089
18090 var groupBases = [
18091 0, 0,
18092 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
18093 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
18094 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
18095 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
18096 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
18097 ];
18098
18099 BN.prototype.toString = function toString (base, padding) {
18100 base = base || 10;
18101 padding = padding | 0 || 1;
18102
18103 var out;
18104 if (base === 16 || base === 'hex') {
18105 out = '';
18106 var off = 0;
18107 var carry = 0;
18108 for (var i = 0; i < this.length; i++) {
18109 var w = this.words[i];
18110 var word = (((w << off) | carry) & 0xffffff).toString(16);
18111 carry = (w >>> (24 - off)) & 0xffffff;
18112 if (carry !== 0 || i !== this.length - 1) {
18113 out = zeros[6 - word.length] + word + out;
18114 } else {
18115 out = word + out;
18116 }
18117 off += 2;
18118 if (off >= 26) {
18119 off -= 26;
18120 i--;
18121 }
18122 }
18123 if (carry !== 0) {
18124 out = carry.toString(16) + out;
18125 }
18126 while (out.length % padding !== 0) {
18127 out = '0' + out;
18128 }
18129 if (this.negative !== 0) {
18130 out = '-' + out;
18131 }
18132 return out;
18133 }
18134
18135 if (base === (base | 0) && base >= 2 && base <= 36) {
18136 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
18137 var groupSize = groupSizes[base];
18138 // var groupBase = Math.pow(base, groupSize);
18139 var groupBase = groupBases[base];
18140 out = '';
18141 var c = this.clone();
18142 c.negative = 0;
18143 while (!c.isZero()) {
18144 var r = c.modn(groupBase).toString(base);
18145 c = c.idivn(groupBase);
18146
18147 if (!c.isZero()) {
18148 out = zeros[groupSize - r.length] + r + out;
18149 } else {
18150 out = r + out;
18151 }
18152 }
18153 if (this.isZero()) {
18154 out = '0' + out;
18155 }
18156 while (out.length % padding !== 0) {
18157 out = '0' + out;
18158 }
18159 if (this.negative !== 0) {
18160 out = '-' + out;
18161 }
18162 return out;
18163 }
18164
18165 assert(false, 'Base should be between 2 and 36');
18166 };
18167
18168 BN.prototype.toNumber = function toNumber () {
18169 var ret = this.words[0];
18170 if (this.length === 2) {
18171 ret += this.words[1] * 0x4000000;
18172 } else if (this.length === 3 && this.words[2] === 0x01) {
18173 // NOTE: at this stage it is known that the top bit is set
18174 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
18175 } else if (this.length > 2) {
18176 assert(false, 'Number can only safely store up to 53 bits');
18177 }
18178 return (this.negative !== 0) ? -ret : ret;
18179 };
18180
18181 BN.prototype.toJSON = function toJSON () {
18182 return this.toString(16);
18183 };
18184
18185 BN.prototype.toBuffer = function toBuffer (endian, length) {
18186 assert(typeof Buffer !== 'undefined');
18187 return this.toArrayLike(Buffer, endian, length);
18188 };
18189
18190 BN.prototype.toArray = function toArray (endian, length) {
18191 return this.toArrayLike(Array, endian, length);
18192 };
18193
18194 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
18195 var byteLength = this.byteLength();
18196 var reqLength = length || Math.max(1, byteLength);
18197 assert(byteLength <= reqLength, 'byte array longer than desired length');
18198 assert(reqLength > 0, 'Requested array length <= 0');
18199
18200 this.strip();
18201 var littleEndian = endian === 'le';
18202 var res = new ArrayType(reqLength);
18203
18204 var b, i;
18205 var q = this.clone();
18206 if (!littleEndian) {
18207 // Assume big-endian
18208 for (i = 0; i < reqLength - byteLength; i++) {
18209 res[i] = 0;
18210 }
18211
18212 for (i = 0; !q.isZero(); i++) {
18213 b = q.andln(0xff);
18214 q.iushrn(8);
18215
18216 res[reqLength - i - 1] = b;
18217 }
18218 } else {
18219 for (i = 0; !q.isZero(); i++) {
18220 b = q.andln(0xff);
18221 q.iushrn(8);
18222
18223 res[i] = b;
18224 }
18225
18226 for (; i < reqLength; i++) {
18227 res[i] = 0;
18228 }
18229 }
18230
18231 return res;
18232 };
18233
18234 if (Math.clz32) {
18235 BN.prototype._countBits = function _countBits (w) {
18236 return 32 - Math.clz32(w);
18237 };
18238 } else {
18239 BN.prototype._countBits = function _countBits (w) {
18240 var t = w;
18241 var r = 0;
18242 if (t >= 0x1000) {
18243 r += 13;
18244 t >>>= 13;
18245 }
18246 if (t >= 0x40) {
18247 r += 7;
18248 t >>>= 7;
18249 }
18250 if (t >= 0x8) {
18251 r += 4;
18252 t >>>= 4;
18253 }
18254 if (t >= 0x02) {
18255 r += 2;
18256 t >>>= 2;
18257 }
18258 return r + t;
18259 };
18260 }
18261
18262 BN.prototype._zeroBits = function _zeroBits (w) {
18263 // Short-cut
18264 if (w === 0) return 26;
18265
18266 var t = w;
18267 var r = 0;
18268 if ((t & 0x1fff) === 0) {
18269 r += 13;
18270 t >>>= 13;
18271 }
18272 if ((t & 0x7f) === 0) {
18273 r += 7;
18274 t >>>= 7;
18275 }
18276 if ((t & 0xf) === 0) {
18277 r += 4;
18278 t >>>= 4;
18279 }
18280 if ((t & 0x3) === 0) {
18281 r += 2;
18282 t >>>= 2;
18283 }
18284 if ((t & 0x1) === 0) {
18285 r++;
18286 }
18287 return r;
18288 };
18289
18290 // Return number of used bits in a BN
18291 BN.prototype.bitLength = function bitLength () {
18292 var w = this.words[this.length - 1];
18293 var hi = this._countBits(w);
18294 return (this.length - 1) * 26 + hi;
18295 };
18296
18297 function toBitArray (num) {
18298 var w = new Array(num.bitLength());
18299
18300 for (var bit = 0; bit < w.length; bit++) {
18301 var off = (bit / 26) | 0;
18302 var wbit = bit % 26;
18303
18304 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
18305 }
18306
18307 return w;
18308 }
18309
18310 // Number of trailing zero bits
18311 BN.prototype.zeroBits = function zeroBits () {
18312 if (this.isZero()) return 0;
18313
18314 var r = 0;
18315 for (var i = 0; i < this.length; i++) {
18316 var b = this._zeroBits(this.words[i]);
18317 r += b;
18318 if (b !== 26) break;
18319 }
18320 return r;
18321 };
18322
18323 BN.prototype.byteLength = function byteLength () {
18324 return Math.ceil(this.bitLength() / 8);
18325 };
18326
18327 BN.prototype.toTwos = function toTwos (width) {
18328 if (this.negative !== 0) {
18329 return this.abs().inotn(width).iaddn(1);
18330 }
18331 return this.clone();
18332 };
18333
18334 BN.prototype.fromTwos = function fromTwos (width) {
18335 if (this.testn(width - 1)) {
18336 return this.notn(width).iaddn(1).ineg();
18337 }
18338 return this.clone();
18339 };
18340
18341 BN.prototype.isNeg = function isNeg () {
18342 return this.negative !== 0;
18343 };
18344
18345 // Return negative clone of `this`
18346 BN.prototype.neg = function neg () {
18347 return this.clone().ineg();
18348 };
18349
18350 BN.prototype.ineg = function ineg () {
18351 if (!this.isZero()) {
18352 this.negative ^= 1;
18353 }
18354
18355 return this;
18356 };
18357
18358 // Or `num` with `this` in-place
18359 BN.prototype.iuor = function iuor (num) {
18360 while (this.length < num.length) {
18361 this.words[this.length++] = 0;
18362 }
18363
18364 for (var i = 0; i < num.length; i++) {
18365 this.words[i] = this.words[i] | num.words[i];
18366 }
18367
18368 return this.strip();
18369 };
18370
18371 BN.prototype.ior = function ior (num) {
18372 assert((this.negative | num.negative) === 0);
18373 return this.iuor(num);
18374 };
18375
18376 // Or `num` with `this`
18377 BN.prototype.or = function or (num) {
18378 if (this.length > num.length) return this.clone().ior(num);
18379 return num.clone().ior(this);
18380 };
18381
18382 BN.prototype.uor = function uor (num) {
18383 if (this.length > num.length) return this.clone().iuor(num);
18384 return num.clone().iuor(this);
18385 };
18386
18387 // And `num` with `this` in-place
18388 BN.prototype.iuand = function iuand (num) {
18389 // b = min-length(num, this)
18390 var b;
18391 if (this.length > num.length) {
18392 b = num;
18393 } else {
18394 b = this;
18395 }
18396
18397 for (var i = 0; i < b.length; i++) {
18398 this.words[i] = this.words[i] & num.words[i];
18399 }
18400
18401 this.length = b.length;
18402
18403 return this.strip();
18404 };
18405
18406 BN.prototype.iand = function iand (num) {
18407 assert((this.negative | num.negative) === 0);
18408 return this.iuand(num);
18409 };
18410
18411 // And `num` with `this`
18412 BN.prototype.and = function and (num) {
18413 if (this.length > num.length) return this.clone().iand(num);
18414 return num.clone().iand(this);
18415 };
18416
18417 BN.prototype.uand = function uand (num) {
18418 if (this.length > num.length) return this.clone().iuand(num);
18419 return num.clone().iuand(this);
18420 };
18421
18422 // Xor `num` with `this` in-place
18423 BN.prototype.iuxor = function iuxor (num) {
18424 // a.length > b.length
18425 var a;
18426 var b;
18427 if (this.length > num.length) {
18428 a = this;
18429 b = num;
18430 } else {
18431 a = num;
18432 b = this;
18433 }
18434
18435 for (var i = 0; i < b.length; i++) {
18436 this.words[i] = a.words[i] ^ b.words[i];
18437 }
18438
18439 if (this !== a) {
18440 for (; i < a.length; i++) {
18441 this.words[i] = a.words[i];
18442 }
18443 }
18444
18445 this.length = a.length;
18446
18447 return this.strip();
18448 };
18449
18450 BN.prototype.ixor = function ixor (num) {
18451 assert((this.negative | num.negative) === 0);
18452 return this.iuxor(num);
18453 };
18454
18455 // Xor `num` with `this`
18456 BN.prototype.xor = function xor (num) {
18457 if (this.length > num.length) return this.clone().ixor(num);
18458 return num.clone().ixor(this);
18459 };
18460
18461 BN.prototype.uxor = function uxor (num) {
18462 if (this.length > num.length) return this.clone().iuxor(num);
18463 return num.clone().iuxor(this);
18464 };
18465
18466 // Not ``this`` with ``width`` bitwidth
18467 BN.prototype.inotn = function inotn (width) {
18468 assert(typeof width === 'number' && width >= 0);
18469
18470 var bytesNeeded = Math.ceil(width / 26) | 0;
18471 var bitsLeft = width % 26;
18472
18473 // Extend the buffer with leading zeroes
18474 this._expand(bytesNeeded);
18475
18476 if (bitsLeft > 0) {
18477 bytesNeeded--;
18478 }
18479
18480 // Handle complete words
18481 for (var i = 0; i < bytesNeeded; i++) {
18482 this.words[i] = ~this.words[i] & 0x3ffffff;
18483 }
18484
18485 // Handle the residue
18486 if (bitsLeft > 0) {
18487 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
18488 }
18489
18490 // And remove leading zeroes
18491 return this.strip();
18492 };
18493
18494 BN.prototype.notn = function notn (width) {
18495 return this.clone().inotn(width);
18496 };
18497
18498 // Set `bit` of `this`
18499 BN.prototype.setn = function setn (bit, val) {
18500 assert(typeof bit === 'number' && bit >= 0);
18501
18502 var off = (bit / 26) | 0;
18503 var wbit = bit % 26;
18504
18505 this._expand(off + 1);
18506
18507 if (val) {
18508 this.words[off] = this.words[off] | (1 << wbit);
18509 } else {
18510 this.words[off] = this.words[off] & ~(1 << wbit);
18511 }
18512
18513 return this.strip();
18514 };
18515
18516 // Add `num` to `this` in-place
18517 BN.prototype.iadd = function iadd (num) {
18518 var r;
18519
18520 // negative + positive
18521 if (this.negative !== 0 && num.negative === 0) {
18522 this.negative = 0;
18523 r = this.isub(num);
18524 this.negative ^= 1;
18525 return this._normSign();
18526
18527 // positive + negative
18528 } else if (this.negative === 0 && num.negative !== 0) {
18529 num.negative = 0;
18530 r = this.isub(num);
18531 num.negative = 1;
18532 return r._normSign();
18533 }
18534
18535 // a.length > b.length
18536 var a, b;
18537 if (this.length > num.length) {
18538 a = this;
18539 b = num;
18540 } else {
18541 a = num;
18542 b = this;
18543 }
18544
18545 var carry = 0;
18546 for (var i = 0; i < b.length; i++) {
18547 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
18548 this.words[i] = r & 0x3ffffff;
18549 carry = r >>> 26;
18550 }
18551 for (; carry !== 0 && i < a.length; i++) {
18552 r = (a.words[i] | 0) + carry;
18553 this.words[i] = r & 0x3ffffff;
18554 carry = r >>> 26;
18555 }
18556
18557 this.length = a.length;
18558 if (carry !== 0) {
18559 this.words[this.length] = carry;
18560 this.length++;
18561 // Copy the rest of the words
18562 } else if (a !== this) {
18563 for (; i < a.length; i++) {
18564 this.words[i] = a.words[i];
18565 }
18566 }
18567
18568 return this;
18569 };
18570
18571 // Add `num` to `this`
18572 BN.prototype.add = function add (num) {
18573 var res;
18574 if (num.negative !== 0 && this.negative === 0) {
18575 num.negative = 0;
18576 res = this.sub(num);
18577 num.negative ^= 1;
18578 return res;
18579 } else if (num.negative === 0 && this.negative !== 0) {
18580 this.negative = 0;
18581 res = num.sub(this);
18582 this.negative = 1;
18583 return res;
18584 }
18585
18586 if (this.length > num.length) return this.clone().iadd(num);
18587
18588 return num.clone().iadd(this);
18589 };
18590
18591 // Subtract `num` from `this` in-place
18592 BN.prototype.isub = function isub (num) {
18593 // this - (-num) = this + num
18594 if (num.negative !== 0) {
18595 num.negative = 0;
18596 var r = this.iadd(num);
18597 num.negative = 1;
18598 return r._normSign();
18599
18600 // -this - num = -(this + num)
18601 } else if (this.negative !== 0) {
18602 this.negative = 0;
18603 this.iadd(num);
18604 this.negative = 1;
18605 return this._normSign();
18606 }
18607
18608 // At this point both numbers are positive
18609 var cmp = this.cmp(num);
18610
18611 // Optimization - zeroify
18612 if (cmp === 0) {
18613 this.negative = 0;
18614 this.length = 1;
18615 this.words[0] = 0;
18616 return this;
18617 }
18618
18619 // a > b
18620 var a, b;
18621 if (cmp > 0) {
18622 a = this;
18623 b = num;
18624 } else {
18625 a = num;
18626 b = this;
18627 }
18628
18629 var carry = 0;
18630 for (var i = 0; i < b.length; i++) {
18631 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
18632 carry = r >> 26;
18633 this.words[i] = r & 0x3ffffff;
18634 }
18635 for (; carry !== 0 && i < a.length; i++) {
18636 r = (a.words[i] | 0) + carry;
18637 carry = r >> 26;
18638 this.words[i] = r & 0x3ffffff;
18639 }
18640
18641 // Copy rest of the words
18642 if (carry === 0 && i < a.length && a !== this) {
18643 for (; i < a.length; i++) {
18644 this.words[i] = a.words[i];
18645 }
18646 }
18647
18648 this.length = Math.max(this.length, i);
18649
18650 if (a !== this) {
18651 this.negative = 1;
18652 }
18653
18654 return this.strip();
18655 };
18656
18657 // Subtract `num` from `this`
18658 BN.prototype.sub = function sub (num) {
18659 return this.clone().isub(num);
18660 };
18661
18662 function smallMulTo (self, num, out) {
18663 out.negative = num.negative ^ self.negative;
18664 var len = (self.length + num.length) | 0;
18665 out.length = len;
18666 len = (len - 1) | 0;
18667
18668 // Peel one iteration (compiler can't do it, because of code complexity)
18669 var a = self.words[0] | 0;
18670 var b = num.words[0] | 0;
18671 var r = a * b;
18672
18673 var lo = r & 0x3ffffff;
18674 var carry = (r / 0x4000000) | 0;
18675 out.words[0] = lo;
18676
18677 for (var k = 1; k < len; k++) {
18678 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
18679 // note that ncarry could be >= 0x3ffffff
18680 var ncarry = carry >>> 26;
18681 var rword = carry & 0x3ffffff;
18682 var maxJ = Math.min(k, num.length - 1);
18683 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
18684 var i = (k - j) | 0;
18685 a = self.words[i] | 0;
18686 b = num.words[j] | 0;
18687 r = a * b + rword;
18688 ncarry += (r / 0x4000000) | 0;
18689 rword = r & 0x3ffffff;
18690 }
18691 out.words[k] = rword | 0;
18692 carry = ncarry | 0;
18693 }
18694 if (carry !== 0) {
18695 out.words[k] = carry | 0;
18696 } else {
18697 out.length--;
18698 }
18699
18700 return out.strip();
18701 }
18702
18703 // TODO(indutny): it may be reasonable to omit it for users who don't need
18704 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
18705 // multiplication (like elliptic secp256k1).
18706 var comb10MulTo = function comb10MulTo (self, num, out) {
18707 var a = self.words;
18708 var b = num.words;
18709 var o = out.words;
18710 var c = 0;
18711 var lo;
18712 var mid;
18713 var hi;
18714 var a0 = a[0] | 0;
18715 var al0 = a0 & 0x1fff;
18716 var ah0 = a0 >>> 13;
18717 var a1 = a[1] | 0;
18718 var al1 = a1 & 0x1fff;
18719 var ah1 = a1 >>> 13;
18720 var a2 = a[2] | 0;
18721 var al2 = a2 & 0x1fff;
18722 var ah2 = a2 >>> 13;
18723 var a3 = a[3] | 0;
18724 var al3 = a3 & 0x1fff;
18725 var ah3 = a3 >>> 13;
18726 var a4 = a[4] | 0;
18727 var al4 = a4 & 0x1fff;
18728 var ah4 = a4 >>> 13;
18729 var a5 = a[5] | 0;
18730 var al5 = a5 & 0x1fff;
18731 var ah5 = a5 >>> 13;
18732 var a6 = a[6] | 0;
18733 var al6 = a6 & 0x1fff;
18734 var ah6 = a6 >>> 13;
18735 var a7 = a[7] | 0;
18736 var al7 = a7 & 0x1fff;
18737 var ah7 = a7 >>> 13;
18738 var a8 = a[8] | 0;
18739 var al8 = a8 & 0x1fff;
18740 var ah8 = a8 >>> 13;
18741 var a9 = a[9] | 0;
18742 var al9 = a9 & 0x1fff;
18743 var ah9 = a9 >>> 13;
18744 var b0 = b[0] | 0;
18745 var bl0 = b0 & 0x1fff;
18746 var bh0 = b0 >>> 13;
18747 var b1 = b[1] | 0;
18748 var bl1 = b1 & 0x1fff;
18749 var bh1 = b1 >>> 13;
18750 var b2 = b[2] | 0;
18751 var bl2 = b2 & 0x1fff;
18752 var bh2 = b2 >>> 13;
18753 var b3 = b[3] | 0;
18754 var bl3 = b3 & 0x1fff;
18755 var bh3 = b3 >>> 13;
18756 var b4 = b[4] | 0;
18757 var bl4 = b4 & 0x1fff;
18758 var bh4 = b4 >>> 13;
18759 var b5 = b[5] | 0;
18760 var bl5 = b5 & 0x1fff;
18761 var bh5 = b5 >>> 13;
18762 var b6 = b[6] | 0;
18763 var bl6 = b6 & 0x1fff;
18764 var bh6 = b6 >>> 13;
18765 var b7 = b[7] | 0;
18766 var bl7 = b7 & 0x1fff;
18767 var bh7 = b7 >>> 13;
18768 var b8 = b[8] | 0;
18769 var bl8 = b8 & 0x1fff;
18770 var bh8 = b8 >>> 13;
18771 var b9 = b[9] | 0;
18772 var bl9 = b9 & 0x1fff;
18773 var bh9 = b9 >>> 13;
18774
18775 out.negative = self.negative ^ num.negative;
18776 out.length = 19;
18777 /* k = 0 */
18778 lo = Math.imul(al0, bl0);
18779 mid = Math.imul(al0, bh0);
18780 mid = (mid + Math.imul(ah0, bl0)) | 0;
18781 hi = Math.imul(ah0, bh0);
18782 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18783 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
18784 w0 &= 0x3ffffff;
18785 /* k = 1 */
18786 lo = Math.imul(al1, bl0);
18787 mid = Math.imul(al1, bh0);
18788 mid = (mid + Math.imul(ah1, bl0)) | 0;
18789 hi = Math.imul(ah1, bh0);
18790 lo = (lo + Math.imul(al0, bl1)) | 0;
18791 mid = (mid + Math.imul(al0, bh1)) | 0;
18792 mid = (mid + Math.imul(ah0, bl1)) | 0;
18793 hi = (hi + Math.imul(ah0, bh1)) | 0;
18794 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18795 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
18796 w1 &= 0x3ffffff;
18797 /* k = 2 */
18798 lo = Math.imul(al2, bl0);
18799 mid = Math.imul(al2, bh0);
18800 mid = (mid + Math.imul(ah2, bl0)) | 0;
18801 hi = Math.imul(ah2, bh0);
18802 lo = (lo + Math.imul(al1, bl1)) | 0;
18803 mid = (mid + Math.imul(al1, bh1)) | 0;
18804 mid = (mid + Math.imul(ah1, bl1)) | 0;
18805 hi = (hi + Math.imul(ah1, bh1)) | 0;
18806 lo = (lo + Math.imul(al0, bl2)) | 0;
18807 mid = (mid + Math.imul(al0, bh2)) | 0;
18808 mid = (mid + Math.imul(ah0, bl2)) | 0;
18809 hi = (hi + Math.imul(ah0, bh2)) | 0;
18810 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18811 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
18812 w2 &= 0x3ffffff;
18813 /* k = 3 */
18814 lo = Math.imul(al3, bl0);
18815 mid = Math.imul(al3, bh0);
18816 mid = (mid + Math.imul(ah3, bl0)) | 0;
18817 hi = Math.imul(ah3, bh0);
18818 lo = (lo + Math.imul(al2, bl1)) | 0;
18819 mid = (mid + Math.imul(al2, bh1)) | 0;
18820 mid = (mid + Math.imul(ah2, bl1)) | 0;
18821 hi = (hi + Math.imul(ah2, bh1)) | 0;
18822 lo = (lo + Math.imul(al1, bl2)) | 0;
18823 mid = (mid + Math.imul(al1, bh2)) | 0;
18824 mid = (mid + Math.imul(ah1, bl2)) | 0;
18825 hi = (hi + Math.imul(ah1, bh2)) | 0;
18826 lo = (lo + Math.imul(al0, bl3)) | 0;
18827 mid = (mid + Math.imul(al0, bh3)) | 0;
18828 mid = (mid + Math.imul(ah0, bl3)) | 0;
18829 hi = (hi + Math.imul(ah0, bh3)) | 0;
18830 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18831 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
18832 w3 &= 0x3ffffff;
18833 /* k = 4 */
18834 lo = Math.imul(al4, bl0);
18835 mid = Math.imul(al4, bh0);
18836 mid = (mid + Math.imul(ah4, bl0)) | 0;
18837 hi = Math.imul(ah4, bh0);
18838 lo = (lo + Math.imul(al3, bl1)) | 0;
18839 mid = (mid + Math.imul(al3, bh1)) | 0;
18840 mid = (mid + Math.imul(ah3, bl1)) | 0;
18841 hi = (hi + Math.imul(ah3, bh1)) | 0;
18842 lo = (lo + Math.imul(al2, bl2)) | 0;
18843 mid = (mid + Math.imul(al2, bh2)) | 0;
18844 mid = (mid + Math.imul(ah2, bl2)) | 0;
18845 hi = (hi + Math.imul(ah2, bh2)) | 0;
18846 lo = (lo + Math.imul(al1, bl3)) | 0;
18847 mid = (mid + Math.imul(al1, bh3)) | 0;
18848 mid = (mid + Math.imul(ah1, bl3)) | 0;
18849 hi = (hi + Math.imul(ah1, bh3)) | 0;
18850 lo = (lo + Math.imul(al0, bl4)) | 0;
18851 mid = (mid + Math.imul(al0, bh4)) | 0;
18852 mid = (mid + Math.imul(ah0, bl4)) | 0;
18853 hi = (hi + Math.imul(ah0, bh4)) | 0;
18854 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18855 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
18856 w4 &= 0x3ffffff;
18857 /* k = 5 */
18858 lo = Math.imul(al5, bl0);
18859 mid = Math.imul(al5, bh0);
18860 mid = (mid + Math.imul(ah5, bl0)) | 0;
18861 hi = Math.imul(ah5, bh0);
18862 lo = (lo + Math.imul(al4, bl1)) | 0;
18863 mid = (mid + Math.imul(al4, bh1)) | 0;
18864 mid = (mid + Math.imul(ah4, bl1)) | 0;
18865 hi = (hi + Math.imul(ah4, bh1)) | 0;
18866 lo = (lo + Math.imul(al3, bl2)) | 0;
18867 mid = (mid + Math.imul(al3, bh2)) | 0;
18868 mid = (mid + Math.imul(ah3, bl2)) | 0;
18869 hi = (hi + Math.imul(ah3, bh2)) | 0;
18870 lo = (lo + Math.imul(al2, bl3)) | 0;
18871 mid = (mid + Math.imul(al2, bh3)) | 0;
18872 mid = (mid + Math.imul(ah2, bl3)) | 0;
18873 hi = (hi + Math.imul(ah2, bh3)) | 0;
18874 lo = (lo + Math.imul(al1, bl4)) | 0;
18875 mid = (mid + Math.imul(al1, bh4)) | 0;
18876 mid = (mid + Math.imul(ah1, bl4)) | 0;
18877 hi = (hi + Math.imul(ah1, bh4)) | 0;
18878 lo = (lo + Math.imul(al0, bl5)) | 0;
18879 mid = (mid + Math.imul(al0, bh5)) | 0;
18880 mid = (mid + Math.imul(ah0, bl5)) | 0;
18881 hi = (hi + Math.imul(ah0, bh5)) | 0;
18882 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18883 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
18884 w5 &= 0x3ffffff;
18885 /* k = 6 */
18886 lo = Math.imul(al6, bl0);
18887 mid = Math.imul(al6, bh0);
18888 mid = (mid + Math.imul(ah6, bl0)) | 0;
18889 hi = Math.imul(ah6, bh0);
18890 lo = (lo + Math.imul(al5, bl1)) | 0;
18891 mid = (mid + Math.imul(al5, bh1)) | 0;
18892 mid = (mid + Math.imul(ah5, bl1)) | 0;
18893 hi = (hi + Math.imul(ah5, bh1)) | 0;
18894 lo = (lo + Math.imul(al4, bl2)) | 0;
18895 mid = (mid + Math.imul(al4, bh2)) | 0;
18896 mid = (mid + Math.imul(ah4, bl2)) | 0;
18897 hi = (hi + Math.imul(ah4, bh2)) | 0;
18898 lo = (lo + Math.imul(al3, bl3)) | 0;
18899 mid = (mid + Math.imul(al3, bh3)) | 0;
18900 mid = (mid + Math.imul(ah3, bl3)) | 0;
18901 hi = (hi + Math.imul(ah3, bh3)) | 0;
18902 lo = (lo + Math.imul(al2, bl4)) | 0;
18903 mid = (mid + Math.imul(al2, bh4)) | 0;
18904 mid = (mid + Math.imul(ah2, bl4)) | 0;
18905 hi = (hi + Math.imul(ah2, bh4)) | 0;
18906 lo = (lo + Math.imul(al1, bl5)) | 0;
18907 mid = (mid + Math.imul(al1, bh5)) | 0;
18908 mid = (mid + Math.imul(ah1, bl5)) | 0;
18909 hi = (hi + Math.imul(ah1, bh5)) | 0;
18910 lo = (lo + Math.imul(al0, bl6)) | 0;
18911 mid = (mid + Math.imul(al0, bh6)) | 0;
18912 mid = (mid + Math.imul(ah0, bl6)) | 0;
18913 hi = (hi + Math.imul(ah0, bh6)) | 0;
18914 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18915 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
18916 w6 &= 0x3ffffff;
18917 /* k = 7 */
18918 lo = Math.imul(al7, bl0);
18919 mid = Math.imul(al7, bh0);
18920 mid = (mid + Math.imul(ah7, bl0)) | 0;
18921 hi = Math.imul(ah7, bh0);
18922 lo = (lo + Math.imul(al6, bl1)) | 0;
18923 mid = (mid + Math.imul(al6, bh1)) | 0;
18924 mid = (mid + Math.imul(ah6, bl1)) | 0;
18925 hi = (hi + Math.imul(ah6, bh1)) | 0;
18926 lo = (lo + Math.imul(al5, bl2)) | 0;
18927 mid = (mid + Math.imul(al5, bh2)) | 0;
18928 mid = (mid + Math.imul(ah5, bl2)) | 0;
18929 hi = (hi + Math.imul(ah5, bh2)) | 0;
18930 lo = (lo + Math.imul(al4, bl3)) | 0;
18931 mid = (mid + Math.imul(al4, bh3)) | 0;
18932 mid = (mid + Math.imul(ah4, bl3)) | 0;
18933 hi = (hi + Math.imul(ah4, bh3)) | 0;
18934 lo = (lo + Math.imul(al3, bl4)) | 0;
18935 mid = (mid + Math.imul(al3, bh4)) | 0;
18936 mid = (mid + Math.imul(ah3, bl4)) | 0;
18937 hi = (hi + Math.imul(ah3, bh4)) | 0;
18938 lo = (lo + Math.imul(al2, bl5)) | 0;
18939 mid = (mid + Math.imul(al2, bh5)) | 0;
18940 mid = (mid + Math.imul(ah2, bl5)) | 0;
18941 hi = (hi + Math.imul(ah2, bh5)) | 0;
18942 lo = (lo + Math.imul(al1, bl6)) | 0;
18943 mid = (mid + Math.imul(al1, bh6)) | 0;
18944 mid = (mid + Math.imul(ah1, bl6)) | 0;
18945 hi = (hi + Math.imul(ah1, bh6)) | 0;
18946 lo = (lo + Math.imul(al0, bl7)) | 0;
18947 mid = (mid + Math.imul(al0, bh7)) | 0;
18948 mid = (mid + Math.imul(ah0, bl7)) | 0;
18949 hi = (hi + Math.imul(ah0, bh7)) | 0;
18950 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18951 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
18952 w7 &= 0x3ffffff;
18953 /* k = 8 */
18954 lo = Math.imul(al8, bl0);
18955 mid = Math.imul(al8, bh0);
18956 mid = (mid + Math.imul(ah8, bl0)) | 0;
18957 hi = Math.imul(ah8, bh0);
18958 lo = (lo + Math.imul(al7, bl1)) | 0;
18959 mid = (mid + Math.imul(al7, bh1)) | 0;
18960 mid = (mid + Math.imul(ah7, bl1)) | 0;
18961 hi = (hi + Math.imul(ah7, bh1)) | 0;
18962 lo = (lo + Math.imul(al6, bl2)) | 0;
18963 mid = (mid + Math.imul(al6, bh2)) | 0;
18964 mid = (mid + Math.imul(ah6, bl2)) | 0;
18965 hi = (hi + Math.imul(ah6, bh2)) | 0;
18966 lo = (lo + Math.imul(al5, bl3)) | 0;
18967 mid = (mid + Math.imul(al5, bh3)) | 0;
18968 mid = (mid + Math.imul(ah5, bl3)) | 0;
18969 hi = (hi + Math.imul(ah5, bh3)) | 0;
18970 lo = (lo + Math.imul(al4, bl4)) | 0;
18971 mid = (mid + Math.imul(al4, bh4)) | 0;
18972 mid = (mid + Math.imul(ah4, bl4)) | 0;
18973 hi = (hi + Math.imul(ah4, bh4)) | 0;
18974 lo = (lo + Math.imul(al3, bl5)) | 0;
18975 mid = (mid + Math.imul(al3, bh5)) | 0;
18976 mid = (mid + Math.imul(ah3, bl5)) | 0;
18977 hi = (hi + Math.imul(ah3, bh5)) | 0;
18978 lo = (lo + Math.imul(al2, bl6)) | 0;
18979 mid = (mid + Math.imul(al2, bh6)) | 0;
18980 mid = (mid + Math.imul(ah2, bl6)) | 0;
18981 hi = (hi + Math.imul(ah2, bh6)) | 0;
18982 lo = (lo + Math.imul(al1, bl7)) | 0;
18983 mid = (mid + Math.imul(al1, bh7)) | 0;
18984 mid = (mid + Math.imul(ah1, bl7)) | 0;
18985 hi = (hi + Math.imul(ah1, bh7)) | 0;
18986 lo = (lo + Math.imul(al0, bl8)) | 0;
18987 mid = (mid + Math.imul(al0, bh8)) | 0;
18988 mid = (mid + Math.imul(ah0, bl8)) | 0;
18989 hi = (hi + Math.imul(ah0, bh8)) | 0;
18990 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
18991 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
18992 w8 &= 0x3ffffff;
18993 /* k = 9 */
18994 lo = Math.imul(al9, bl0);
18995 mid = Math.imul(al9, bh0);
18996 mid = (mid + Math.imul(ah9, bl0)) | 0;
18997 hi = Math.imul(ah9, bh0);
18998 lo = (lo + Math.imul(al8, bl1)) | 0;
18999 mid = (mid + Math.imul(al8, bh1)) | 0;
19000 mid = (mid + Math.imul(ah8, bl1)) | 0;
19001 hi = (hi + Math.imul(ah8, bh1)) | 0;
19002 lo = (lo + Math.imul(al7, bl2)) | 0;
19003 mid = (mid + Math.imul(al7, bh2)) | 0;
19004 mid = (mid + Math.imul(ah7, bl2)) | 0;
19005 hi = (hi + Math.imul(ah7, bh2)) | 0;
19006 lo = (lo + Math.imul(al6, bl3)) | 0;
19007 mid = (mid + Math.imul(al6, bh3)) | 0;
19008 mid = (mid + Math.imul(ah6, bl3)) | 0;
19009 hi = (hi + Math.imul(ah6, bh3)) | 0;
19010 lo = (lo + Math.imul(al5, bl4)) | 0;
19011 mid = (mid + Math.imul(al5, bh4)) | 0;
19012 mid = (mid + Math.imul(ah5, bl4)) | 0;
19013 hi = (hi + Math.imul(ah5, bh4)) | 0;
19014 lo = (lo + Math.imul(al4, bl5)) | 0;
19015 mid = (mid + Math.imul(al4, bh5)) | 0;
19016 mid = (mid + Math.imul(ah4, bl5)) | 0;
19017 hi = (hi + Math.imul(ah4, bh5)) | 0;
19018 lo = (lo + Math.imul(al3, bl6)) | 0;
19019 mid = (mid + Math.imul(al3, bh6)) | 0;
19020 mid = (mid + Math.imul(ah3, bl6)) | 0;
19021 hi = (hi + Math.imul(ah3, bh6)) | 0;
19022 lo = (lo + Math.imul(al2, bl7)) | 0;
19023 mid = (mid + Math.imul(al2, bh7)) | 0;
19024 mid = (mid + Math.imul(ah2, bl7)) | 0;
19025 hi = (hi + Math.imul(ah2, bh7)) | 0;
19026 lo = (lo + Math.imul(al1, bl8)) | 0;
19027 mid = (mid + Math.imul(al1, bh8)) | 0;
19028 mid = (mid + Math.imul(ah1, bl8)) | 0;
19029 hi = (hi + Math.imul(ah1, bh8)) | 0;
19030 lo = (lo + Math.imul(al0, bl9)) | 0;
19031 mid = (mid + Math.imul(al0, bh9)) | 0;
19032 mid = (mid + Math.imul(ah0, bl9)) | 0;
19033 hi = (hi + Math.imul(ah0, bh9)) | 0;
19034 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19035 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
19036 w9 &= 0x3ffffff;
19037 /* k = 10 */
19038 lo = Math.imul(al9, bl1);
19039 mid = Math.imul(al9, bh1);
19040 mid = (mid + Math.imul(ah9, bl1)) | 0;
19041 hi = Math.imul(ah9, bh1);
19042 lo = (lo + Math.imul(al8, bl2)) | 0;
19043 mid = (mid + Math.imul(al8, bh2)) | 0;
19044 mid = (mid + Math.imul(ah8, bl2)) | 0;
19045 hi = (hi + Math.imul(ah8, bh2)) | 0;
19046 lo = (lo + Math.imul(al7, bl3)) | 0;
19047 mid = (mid + Math.imul(al7, bh3)) | 0;
19048 mid = (mid + Math.imul(ah7, bl3)) | 0;
19049 hi = (hi + Math.imul(ah7, bh3)) | 0;
19050 lo = (lo + Math.imul(al6, bl4)) | 0;
19051 mid = (mid + Math.imul(al6, bh4)) | 0;
19052 mid = (mid + Math.imul(ah6, bl4)) | 0;
19053 hi = (hi + Math.imul(ah6, bh4)) | 0;
19054 lo = (lo + Math.imul(al5, bl5)) | 0;
19055 mid = (mid + Math.imul(al5, bh5)) | 0;
19056 mid = (mid + Math.imul(ah5, bl5)) | 0;
19057 hi = (hi + Math.imul(ah5, bh5)) | 0;
19058 lo = (lo + Math.imul(al4, bl6)) | 0;
19059 mid = (mid + Math.imul(al4, bh6)) | 0;
19060 mid = (mid + Math.imul(ah4, bl6)) | 0;
19061 hi = (hi + Math.imul(ah4, bh6)) | 0;
19062 lo = (lo + Math.imul(al3, bl7)) | 0;
19063 mid = (mid + Math.imul(al3, bh7)) | 0;
19064 mid = (mid + Math.imul(ah3, bl7)) | 0;
19065 hi = (hi + Math.imul(ah3, bh7)) | 0;
19066 lo = (lo + Math.imul(al2, bl8)) | 0;
19067 mid = (mid + Math.imul(al2, bh8)) | 0;
19068 mid = (mid + Math.imul(ah2, bl8)) | 0;
19069 hi = (hi + Math.imul(ah2, bh8)) | 0;
19070 lo = (lo + Math.imul(al1, bl9)) | 0;
19071 mid = (mid + Math.imul(al1, bh9)) | 0;
19072 mid = (mid + Math.imul(ah1, bl9)) | 0;
19073 hi = (hi + Math.imul(ah1, bh9)) | 0;
19074 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19075 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
19076 w10 &= 0x3ffffff;
19077 /* k = 11 */
19078 lo = Math.imul(al9, bl2);
19079 mid = Math.imul(al9, bh2);
19080 mid = (mid + Math.imul(ah9, bl2)) | 0;
19081 hi = Math.imul(ah9, bh2);
19082 lo = (lo + Math.imul(al8, bl3)) | 0;
19083 mid = (mid + Math.imul(al8, bh3)) | 0;
19084 mid = (mid + Math.imul(ah8, bl3)) | 0;
19085 hi = (hi + Math.imul(ah8, bh3)) | 0;
19086 lo = (lo + Math.imul(al7, bl4)) | 0;
19087 mid = (mid + Math.imul(al7, bh4)) | 0;
19088 mid = (mid + Math.imul(ah7, bl4)) | 0;
19089 hi = (hi + Math.imul(ah7, bh4)) | 0;
19090 lo = (lo + Math.imul(al6, bl5)) | 0;
19091 mid = (mid + Math.imul(al6, bh5)) | 0;
19092 mid = (mid + Math.imul(ah6, bl5)) | 0;
19093 hi = (hi + Math.imul(ah6, bh5)) | 0;
19094 lo = (lo + Math.imul(al5, bl6)) | 0;
19095 mid = (mid + Math.imul(al5, bh6)) | 0;
19096 mid = (mid + Math.imul(ah5, bl6)) | 0;
19097 hi = (hi + Math.imul(ah5, bh6)) | 0;
19098 lo = (lo + Math.imul(al4, bl7)) | 0;
19099 mid = (mid + Math.imul(al4, bh7)) | 0;
19100 mid = (mid + Math.imul(ah4, bl7)) | 0;
19101 hi = (hi + Math.imul(ah4, bh7)) | 0;
19102 lo = (lo + Math.imul(al3, bl8)) | 0;
19103 mid = (mid + Math.imul(al3, bh8)) | 0;
19104 mid = (mid + Math.imul(ah3, bl8)) | 0;
19105 hi = (hi + Math.imul(ah3, bh8)) | 0;
19106 lo = (lo + Math.imul(al2, bl9)) | 0;
19107 mid = (mid + Math.imul(al2, bh9)) | 0;
19108 mid = (mid + Math.imul(ah2, bl9)) | 0;
19109 hi = (hi + Math.imul(ah2, bh9)) | 0;
19110 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19111 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
19112 w11 &= 0x3ffffff;
19113 /* k = 12 */
19114 lo = Math.imul(al9, bl3);
19115 mid = Math.imul(al9, bh3);
19116 mid = (mid + Math.imul(ah9, bl3)) | 0;
19117 hi = Math.imul(ah9, bh3);
19118 lo = (lo + Math.imul(al8, bl4)) | 0;
19119 mid = (mid + Math.imul(al8, bh4)) | 0;
19120 mid = (mid + Math.imul(ah8, bl4)) | 0;
19121 hi = (hi + Math.imul(ah8, bh4)) | 0;
19122 lo = (lo + Math.imul(al7, bl5)) | 0;
19123 mid = (mid + Math.imul(al7, bh5)) | 0;
19124 mid = (mid + Math.imul(ah7, bl5)) | 0;
19125 hi = (hi + Math.imul(ah7, bh5)) | 0;
19126 lo = (lo + Math.imul(al6, bl6)) | 0;
19127 mid = (mid + Math.imul(al6, bh6)) | 0;
19128 mid = (mid + Math.imul(ah6, bl6)) | 0;
19129 hi = (hi + Math.imul(ah6, bh6)) | 0;
19130 lo = (lo + Math.imul(al5, bl7)) | 0;
19131 mid = (mid + Math.imul(al5, bh7)) | 0;
19132 mid = (mid + Math.imul(ah5, bl7)) | 0;
19133 hi = (hi + Math.imul(ah5, bh7)) | 0;
19134 lo = (lo + Math.imul(al4, bl8)) | 0;
19135 mid = (mid + Math.imul(al4, bh8)) | 0;
19136 mid = (mid + Math.imul(ah4, bl8)) | 0;
19137 hi = (hi + Math.imul(ah4, bh8)) | 0;
19138 lo = (lo + Math.imul(al3, bl9)) | 0;
19139 mid = (mid + Math.imul(al3, bh9)) | 0;
19140 mid = (mid + Math.imul(ah3, bl9)) | 0;
19141 hi = (hi + Math.imul(ah3, bh9)) | 0;
19142 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19143 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
19144 w12 &= 0x3ffffff;
19145 /* k = 13 */
19146 lo = Math.imul(al9, bl4);
19147 mid = Math.imul(al9, bh4);
19148 mid = (mid + Math.imul(ah9, bl4)) | 0;
19149 hi = Math.imul(ah9, bh4);
19150 lo = (lo + Math.imul(al8, bl5)) | 0;
19151 mid = (mid + Math.imul(al8, bh5)) | 0;
19152 mid = (mid + Math.imul(ah8, bl5)) | 0;
19153 hi = (hi + Math.imul(ah8, bh5)) | 0;
19154 lo = (lo + Math.imul(al7, bl6)) | 0;
19155 mid = (mid + Math.imul(al7, bh6)) | 0;
19156 mid = (mid + Math.imul(ah7, bl6)) | 0;
19157 hi = (hi + Math.imul(ah7, bh6)) | 0;
19158 lo = (lo + Math.imul(al6, bl7)) | 0;
19159 mid = (mid + Math.imul(al6, bh7)) | 0;
19160 mid = (mid + Math.imul(ah6, bl7)) | 0;
19161 hi = (hi + Math.imul(ah6, bh7)) | 0;
19162 lo = (lo + Math.imul(al5, bl8)) | 0;
19163 mid = (mid + Math.imul(al5, bh8)) | 0;
19164 mid = (mid + Math.imul(ah5, bl8)) | 0;
19165 hi = (hi + Math.imul(ah5, bh8)) | 0;
19166 lo = (lo + Math.imul(al4, bl9)) | 0;
19167 mid = (mid + Math.imul(al4, bh9)) | 0;
19168 mid = (mid + Math.imul(ah4, bl9)) | 0;
19169 hi = (hi + Math.imul(ah4, bh9)) | 0;
19170 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19171 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
19172 w13 &= 0x3ffffff;
19173 /* k = 14 */
19174 lo = Math.imul(al9, bl5);
19175 mid = Math.imul(al9, bh5);
19176 mid = (mid + Math.imul(ah9, bl5)) | 0;
19177 hi = Math.imul(ah9, bh5);
19178 lo = (lo + Math.imul(al8, bl6)) | 0;
19179 mid = (mid + Math.imul(al8, bh6)) | 0;
19180 mid = (mid + Math.imul(ah8, bl6)) | 0;
19181 hi = (hi + Math.imul(ah8, bh6)) | 0;
19182 lo = (lo + Math.imul(al7, bl7)) | 0;
19183 mid = (mid + Math.imul(al7, bh7)) | 0;
19184 mid = (mid + Math.imul(ah7, bl7)) | 0;
19185 hi = (hi + Math.imul(ah7, bh7)) | 0;
19186 lo = (lo + Math.imul(al6, bl8)) | 0;
19187 mid = (mid + Math.imul(al6, bh8)) | 0;
19188 mid = (mid + Math.imul(ah6, bl8)) | 0;
19189 hi = (hi + Math.imul(ah6, bh8)) | 0;
19190 lo = (lo + Math.imul(al5, bl9)) | 0;
19191 mid = (mid + Math.imul(al5, bh9)) | 0;
19192 mid = (mid + Math.imul(ah5, bl9)) | 0;
19193 hi = (hi + Math.imul(ah5, bh9)) | 0;
19194 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19195 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
19196 w14 &= 0x3ffffff;
19197 /* k = 15 */
19198 lo = Math.imul(al9, bl6);
19199 mid = Math.imul(al9, bh6);
19200 mid = (mid + Math.imul(ah9, bl6)) | 0;
19201 hi = Math.imul(ah9, bh6);
19202 lo = (lo + Math.imul(al8, bl7)) | 0;
19203 mid = (mid + Math.imul(al8, bh7)) | 0;
19204 mid = (mid + Math.imul(ah8, bl7)) | 0;
19205 hi = (hi + Math.imul(ah8, bh7)) | 0;
19206 lo = (lo + Math.imul(al7, bl8)) | 0;
19207 mid = (mid + Math.imul(al7, bh8)) | 0;
19208 mid = (mid + Math.imul(ah7, bl8)) | 0;
19209 hi = (hi + Math.imul(ah7, bh8)) | 0;
19210 lo = (lo + Math.imul(al6, bl9)) | 0;
19211 mid = (mid + Math.imul(al6, bh9)) | 0;
19212 mid = (mid + Math.imul(ah6, bl9)) | 0;
19213 hi = (hi + Math.imul(ah6, bh9)) | 0;
19214 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19215 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
19216 w15 &= 0x3ffffff;
19217 /* k = 16 */
19218 lo = Math.imul(al9, bl7);
19219 mid = Math.imul(al9, bh7);
19220 mid = (mid + Math.imul(ah9, bl7)) | 0;
19221 hi = Math.imul(ah9, bh7);
19222 lo = (lo + Math.imul(al8, bl8)) | 0;
19223 mid = (mid + Math.imul(al8, bh8)) | 0;
19224 mid = (mid + Math.imul(ah8, bl8)) | 0;
19225 hi = (hi + Math.imul(ah8, bh8)) | 0;
19226 lo = (lo + Math.imul(al7, bl9)) | 0;
19227 mid = (mid + Math.imul(al7, bh9)) | 0;
19228 mid = (mid + Math.imul(ah7, bl9)) | 0;
19229 hi = (hi + Math.imul(ah7, bh9)) | 0;
19230 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19231 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
19232 w16 &= 0x3ffffff;
19233 /* k = 17 */
19234 lo = Math.imul(al9, bl8);
19235 mid = Math.imul(al9, bh8);
19236 mid = (mid + Math.imul(ah9, bl8)) | 0;
19237 hi = Math.imul(ah9, bh8);
19238 lo = (lo + Math.imul(al8, bl9)) | 0;
19239 mid = (mid + Math.imul(al8, bh9)) | 0;
19240 mid = (mid + Math.imul(ah8, bl9)) | 0;
19241 hi = (hi + Math.imul(ah8, bh9)) | 0;
19242 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19243 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
19244 w17 &= 0x3ffffff;
19245 /* k = 18 */
19246 lo = Math.imul(al9, bl9);
19247 mid = Math.imul(al9, bh9);
19248 mid = (mid + Math.imul(ah9, bl9)) | 0;
19249 hi = Math.imul(ah9, bh9);
19250 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19251 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
19252 w18 &= 0x3ffffff;
19253 o[0] = w0;
19254 o[1] = w1;
19255 o[2] = w2;
19256 o[3] = w3;
19257 o[4] = w4;
19258 o[5] = w5;
19259 o[6] = w6;
19260 o[7] = w7;
19261 o[8] = w8;
19262 o[9] = w9;
19263 o[10] = w10;
19264 o[11] = w11;
19265 o[12] = w12;
19266 o[13] = w13;
19267 o[14] = w14;
19268 o[15] = w15;
19269 o[16] = w16;
19270 o[17] = w17;
19271 o[18] = w18;
19272 if (c !== 0) {
19273 o[19] = c;
19274 out.length++;
19275 }
19276 return out;
19277 };
19278
19279 // Polyfill comb
19280 if (!Math.imul) {
19281 comb10MulTo = smallMulTo;
19282 }
19283
19284 function bigMulTo (self, num, out) {
19285 out.negative = num.negative ^ self.negative;
19286 out.length = self.length + num.length;
19287
19288 var carry = 0;
19289 var hncarry = 0;
19290 for (var k = 0; k < out.length - 1; k++) {
19291 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
19292 // note that ncarry could be >= 0x3ffffff
19293 var ncarry = hncarry;
19294 hncarry = 0;
19295 var rword = carry & 0x3ffffff;
19296 var maxJ = Math.min(k, num.length - 1);
19297 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
19298 var i = k - j;
19299 var a = self.words[i] | 0;
19300 var b = num.words[j] | 0;
19301 var r = a * b;
19302
19303 var lo = r & 0x3ffffff;
19304 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
19305 lo = (lo + rword) | 0;
19306 rword = lo & 0x3ffffff;
19307 ncarry = (ncarry + (lo >>> 26)) | 0;
19308
19309 hncarry += ncarry >>> 26;
19310 ncarry &= 0x3ffffff;
19311 }
19312 out.words[k] = rword;
19313 carry = ncarry;
19314 ncarry = hncarry;
19315 }
19316 if (carry !== 0) {
19317 out.words[k] = carry;
19318 } else {
19319 out.length--;
19320 }
19321
19322 return out.strip();
19323 }
19324
19325 function jumboMulTo (self, num, out) {
19326 var fftm = new FFTM();
19327 return fftm.mulp(self, num, out);
19328 }
19329
19330 BN.prototype.mulTo = function mulTo (num, out) {
19331 var res;
19332 var len = this.length + num.length;
19333 if (this.length === 10 && num.length === 10) {
19334 res = comb10MulTo(this, num, out);
19335 } else if (len < 63) {
19336 res = smallMulTo(this, num, out);
19337 } else if (len < 1024) {
19338 res = bigMulTo(this, num, out);
19339 } else {
19340 res = jumboMulTo(this, num, out);
19341 }
19342
19343 return res;
19344 };
19345
19346 // Cooley-Tukey algorithm for FFT
19347 // slightly revisited to rely on looping instead of recursion
19348
19349 function FFTM (x, y) {
19350 this.x = x;
19351 this.y = y;
19352 }
19353
19354 FFTM.prototype.makeRBT = function makeRBT (N) {
19355 var t = new Array(N);
19356 var l = BN.prototype._countBits(N) - 1;
19357 for (var i = 0; i < N; i++) {
19358 t[i] = this.revBin(i, l, N);
19359 }
19360
19361 return t;
19362 };
19363
19364 // Returns binary-reversed representation of `x`
19365 FFTM.prototype.revBin = function revBin (x, l, N) {
19366 if (x === 0 || x === N - 1) return x;
19367
19368 var rb = 0;
19369 for (var i = 0; i < l; i++) {
19370 rb |= (x & 1) << (l - i - 1);
19371 x >>= 1;
19372 }
19373
19374 return rb;
19375 };
19376
19377 // Performs "tweedling" phase, therefore 'emulating'
19378 // behaviour of the recursive algorithm
19379 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
19380 for (var i = 0; i < N; i++) {
19381 rtws[i] = rws[rbt[i]];
19382 itws[i] = iws[rbt[i]];
19383 }
19384 };
19385
19386 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
19387 this.permute(rbt, rws, iws, rtws, itws, N);
19388
19389 for (var s = 1; s < N; s <<= 1) {
19390 var l = s << 1;
19391
19392 var rtwdf = Math.cos(2 * Math.PI / l);
19393 var itwdf = Math.sin(2 * Math.PI / l);
19394
19395 for (var p = 0; p < N; p += l) {
19396 var rtwdf_ = rtwdf;
19397 var itwdf_ = itwdf;
19398
19399 for (var j = 0; j < s; j++) {
19400 var re = rtws[p + j];
19401 var ie = itws[p + j];
19402
19403 var ro = rtws[p + j + s];
19404 var io = itws[p + j + s];
19405
19406 var rx = rtwdf_ * ro - itwdf_ * io;
19407
19408 io = rtwdf_ * io + itwdf_ * ro;
19409 ro = rx;
19410
19411 rtws[p + j] = re + ro;
19412 itws[p + j] = ie + io;
19413
19414 rtws[p + j + s] = re - ro;
19415 itws[p + j + s] = ie - io;
19416
19417 /* jshint maxdepth : false */
19418 if (j !== l) {
19419 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
19420
19421 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
19422 rtwdf_ = rx;
19423 }
19424 }
19425 }
19426 }
19427 };
19428
19429 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
19430 var N = Math.max(m, n) | 1;
19431 var odd = N & 1;
19432 var i = 0;
19433 for (N = N / 2 | 0; N; N = N >>> 1) {
19434 i++;
19435 }
19436
19437 return 1 << i + 1 + odd;
19438 };
19439
19440 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
19441 if (N <= 1) return;
19442
19443 for (var i = 0; i < N / 2; i++) {
19444 var t = rws[i];
19445
19446 rws[i] = rws[N - i - 1];
19447 rws[N - i - 1] = t;
19448
19449 t = iws[i];
19450
19451 iws[i] = -iws[N - i - 1];
19452 iws[N - i - 1] = -t;
19453 }
19454 };
19455
19456 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
19457 var carry = 0;
19458 for (var i = 0; i < N / 2; i++) {
19459 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
19460 Math.round(ws[2 * i] / N) +
19461 carry;
19462
19463 ws[i] = w & 0x3ffffff;
19464
19465 if (w < 0x4000000) {
19466 carry = 0;
19467 } else {
19468 carry = w / 0x4000000 | 0;
19469 }
19470 }
19471
19472 return ws;
19473 };
19474
19475 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
19476 var carry = 0;
19477 for (var i = 0; i < len; i++) {
19478 carry = carry + (ws[i] | 0);
19479
19480 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
19481 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
19482 }
19483
19484 // Pad with zeroes
19485 for (i = 2 * len; i < N; ++i) {
19486 rws[i] = 0;
19487 }
19488
19489 assert(carry === 0);
19490 assert((carry & ~0x1fff) === 0);
19491 };
19492
19493 FFTM.prototype.stub = function stub (N) {
19494 var ph = new Array(N);
19495 for (var i = 0; i < N; i++) {
19496 ph[i] = 0;
19497 }
19498
19499 return ph;
19500 };
19501
19502 FFTM.prototype.mulp = function mulp (x, y, out) {
19503 var N = 2 * this.guessLen13b(x.length, y.length);
19504
19505 var rbt = this.makeRBT(N);
19506
19507 var _ = this.stub(N);
19508
19509 var rws = new Array(N);
19510 var rwst = new Array(N);
19511 var iwst = new Array(N);
19512
19513 var nrws = new Array(N);
19514 var nrwst = new Array(N);
19515 var niwst = new Array(N);
19516
19517 var rmws = out.words;
19518 rmws.length = N;
19519
19520 this.convert13b(x.words, x.length, rws, N);
19521 this.convert13b(y.words, y.length, nrws, N);
19522
19523 this.transform(rws, _, rwst, iwst, N, rbt);
19524 this.transform(nrws, _, nrwst, niwst, N, rbt);
19525
19526 for (var i = 0; i < N; i++) {
19527 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
19528 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
19529 rwst[i] = rx;
19530 }
19531
19532 this.conjugate(rwst, iwst, N);
19533 this.transform(rwst, iwst, rmws, _, N, rbt);
19534 this.conjugate(rmws, _, N);
19535 this.normalize13b(rmws, N);
19536
19537 out.negative = x.negative ^ y.negative;
19538 out.length = x.length + y.length;
19539 return out.strip();
19540 };
19541
19542 // Multiply `this` by `num`
19543 BN.prototype.mul = function mul (num) {
19544 var out = new BN(null);
19545 out.words = new Array(this.length + num.length);
19546 return this.mulTo(num, out);
19547 };
19548
19549 // Multiply employing FFT
19550 BN.prototype.mulf = function mulf (num) {
19551 var out = new BN(null);
19552 out.words = new Array(this.length + num.length);
19553 return jumboMulTo(this, num, out);
19554 };
19555
19556 // In-place Multiplication
19557 BN.prototype.imul = function imul (num) {
19558 return this.clone().mulTo(num, this);
19559 };
19560
19561 BN.prototype.imuln = function imuln (num) {
19562 assert(typeof num === 'number');
19563 assert(num < 0x4000000);
19564
19565 // Carry
19566 var carry = 0;
19567 for (var i = 0; i < this.length; i++) {
19568 var w = (this.words[i] | 0) * num;
19569 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
19570 carry >>= 26;
19571 carry += (w / 0x4000000) | 0;
19572 // NOTE: lo is 27bit maximum
19573 carry += lo >>> 26;
19574 this.words[i] = lo & 0x3ffffff;
19575 }
19576
19577 if (carry !== 0) {
19578 this.words[i] = carry;
19579 this.length++;
19580 }
19581
19582 return this;
19583 };
19584
19585 BN.prototype.muln = function muln (num) {
19586 return this.clone().imuln(num);
19587 };
19588
19589 // `this` * `this`
19590 BN.prototype.sqr = function sqr () {
19591 return this.mul(this);
19592 };
19593
19594 // `this` * `this` in-place
19595 BN.prototype.isqr = function isqr () {
19596 return this.imul(this.clone());
19597 };
19598
19599 // Math.pow(`this`, `num`)
19600 BN.prototype.pow = function pow (num) {
19601 var w = toBitArray(num);
19602 if (w.length === 0) return new BN(1);
19603
19604 // Skip leading zeroes
19605 var res = this;
19606 for (var i = 0; i < w.length; i++, res = res.sqr()) {
19607 if (w[i] !== 0) break;
19608 }
19609
19610 if (++i < w.length) {
19611 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
19612 if (w[i] === 0) continue;
19613
19614 res = res.mul(q);
19615 }
19616 }
19617
19618 return res;
19619 };
19620
19621 // Shift-left in-place
19622 BN.prototype.iushln = function iushln (bits) {
19623 assert(typeof bits === 'number' && bits >= 0);
19624 var r = bits % 26;
19625 var s = (bits - r) / 26;
19626 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
19627 var i;
19628
19629 if (r !== 0) {
19630 var carry = 0;
19631
19632 for (i = 0; i < this.length; i++) {
19633 var newCarry = this.words[i] & carryMask;
19634 var c = ((this.words[i] | 0) - newCarry) << r;
19635 this.words[i] = c | carry;
19636 carry = newCarry >>> (26 - r);
19637 }
19638
19639 if (carry) {
19640 this.words[i] = carry;
19641 this.length++;
19642 }
19643 }
19644
19645 if (s !== 0) {
19646 for (i = this.length - 1; i >= 0; i--) {
19647 this.words[i + s] = this.words[i];
19648 }
19649
19650 for (i = 0; i < s; i++) {
19651 this.words[i] = 0;
19652 }
19653
19654 this.length += s;
19655 }
19656
19657 return this.strip();
19658 };
19659
19660 BN.prototype.ishln = function ishln (bits) {
19661 // TODO(indutny): implement me
19662 assert(this.negative === 0);
19663 return this.iushln(bits);
19664 };
19665
19666 // Shift-right in-place
19667 // NOTE: `hint` is a lowest bit before trailing zeroes
19668 // NOTE: if `extended` is present - it will be filled with destroyed bits
19669 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
19670 assert(typeof bits === 'number' && bits >= 0);
19671 var h;
19672 if (hint) {
19673 h = (hint - (hint % 26)) / 26;
19674 } else {
19675 h = 0;
19676 }
19677
19678 var r = bits % 26;
19679 var s = Math.min((bits - r) / 26, this.length);
19680 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
19681 var maskedWords = extended;
19682
19683 h -= s;
19684 h = Math.max(0, h);
19685
19686 // Extended mode, copy masked part
19687 if (maskedWords) {
19688 for (var i = 0; i < s; i++) {
19689 maskedWords.words[i] = this.words[i];
19690 }
19691 maskedWords.length = s;
19692 }
19693
19694 if (s === 0) {
19695 // No-op, we should not move anything at all
19696 } else if (this.length > s) {
19697 this.length -= s;
19698 for (i = 0; i < this.length; i++) {
19699 this.words[i] = this.words[i + s];
19700 }
19701 } else {
19702 this.words[0] = 0;
19703 this.length = 1;
19704 }
19705
19706 var carry = 0;
19707 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
19708 var word = this.words[i] | 0;
19709 this.words[i] = (carry << (26 - r)) | (word >>> r);
19710 carry = word & mask;
19711 }
19712
19713 // Push carried bits as a mask
19714 if (maskedWords && carry !== 0) {
19715 maskedWords.words[maskedWords.length++] = carry;
19716 }
19717
19718 if (this.length === 0) {
19719 this.words[0] = 0;
19720 this.length = 1;
19721 }
19722
19723 return this.strip();
19724 };
19725
19726 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
19727 // TODO(indutny): implement me
19728 assert(this.negative === 0);
19729 return this.iushrn(bits, hint, extended);
19730 };
19731
19732 // Shift-left
19733 BN.prototype.shln = function shln (bits) {
19734 return this.clone().ishln(bits);
19735 };
19736
19737 BN.prototype.ushln = function ushln (bits) {
19738 return this.clone().iushln(bits);
19739 };
19740
19741 // Shift-right
19742 BN.prototype.shrn = function shrn (bits) {
19743 return this.clone().ishrn(bits);
19744 };
19745
19746 BN.prototype.ushrn = function ushrn (bits) {
19747 return this.clone().iushrn(bits);
19748 };
19749
19750 // Test if n bit is set
19751 BN.prototype.testn = function testn (bit) {
19752 assert(typeof bit === 'number' && bit >= 0);
19753 var r = bit % 26;
19754 var s = (bit - r) / 26;
19755 var q = 1 << r;
19756
19757 // Fast case: bit is much higher than all existing words
19758 if (this.length <= s) return false;
19759
19760 // Check bit and return
19761 var w = this.words[s];
19762
19763 return !!(w & q);
19764 };
19765
19766 // Return only lowers bits of number (in-place)
19767 BN.prototype.imaskn = function imaskn (bits) {
19768 assert(typeof bits === 'number' && bits >= 0);
19769 var r = bits % 26;
19770 var s = (bits - r) / 26;
19771
19772 assert(this.negative === 0, 'imaskn works only with positive numbers');
19773
19774 if (this.length <= s) {
19775 return this;
19776 }
19777
19778 if (r !== 0) {
19779 s++;
19780 }
19781 this.length = Math.min(s, this.length);
19782
19783 if (r !== 0) {
19784 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
19785 this.words[this.length - 1] &= mask;
19786 }
19787
19788 return this.strip();
19789 };
19790
19791 // Return only lowers bits of number
19792 BN.prototype.maskn = function maskn (bits) {
19793 return this.clone().imaskn(bits);
19794 };
19795
19796 // Add plain number `num` to `this`
19797 BN.prototype.iaddn = function iaddn (num) {
19798 assert(typeof num === 'number');
19799 assert(num < 0x4000000);
19800 if (num < 0) return this.isubn(-num);
19801
19802 // Possible sign change
19803 if (this.negative !== 0) {
19804 if (this.length === 1 && (this.words[0] | 0) < num) {
19805 this.words[0] = num - (this.words[0] | 0);
19806 this.negative = 0;
19807 return this;
19808 }
19809
19810 this.negative = 0;
19811 this.isubn(num);
19812 this.negative = 1;
19813 return this;
19814 }
19815
19816 // Add without checks
19817 return this._iaddn(num);
19818 };
19819
19820 BN.prototype._iaddn = function _iaddn (num) {
19821 this.words[0] += num;
19822
19823 // Carry
19824 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
19825 this.words[i] -= 0x4000000;
19826 if (i === this.length - 1) {
19827 this.words[i + 1] = 1;
19828 } else {
19829 this.words[i + 1]++;
19830 }
19831 }
19832 this.length = Math.max(this.length, i + 1);
19833
19834 return this;
19835 };
19836
19837 // Subtract plain number `num` from `this`
19838 BN.prototype.isubn = function isubn (num) {
19839 assert(typeof num === 'number');
19840 assert(num < 0x4000000);
19841 if (num < 0) return this.iaddn(-num);
19842
19843 if (this.negative !== 0) {
19844 this.negative = 0;
19845 this.iaddn(num);
19846 this.negative = 1;
19847 return this;
19848 }
19849
19850 this.words[0] -= num;
19851
19852 if (this.length === 1 && this.words[0] < 0) {
19853 this.words[0] = -this.words[0];
19854 this.negative = 1;
19855 } else {
19856 // Carry
19857 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
19858 this.words[i] += 0x4000000;
19859 this.words[i + 1] -= 1;
19860 }
19861 }
19862
19863 return this.strip();
19864 };
19865
19866 BN.prototype.addn = function addn (num) {
19867 return this.clone().iaddn(num);
19868 };
19869
19870 BN.prototype.subn = function subn (num) {
19871 return this.clone().isubn(num);
19872 };
19873
19874 BN.prototype.iabs = function iabs () {
19875 this.negative = 0;
19876
19877 return this;
19878 };
19879
19880 BN.prototype.abs = function abs () {
19881 return this.clone().iabs();
19882 };
19883
19884 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
19885 var len = num.length + shift;
19886 var i;
19887
19888 this._expand(len);
19889
19890 var w;
19891 var carry = 0;
19892 for (i = 0; i < num.length; i++) {
19893 w = (this.words[i + shift] | 0) + carry;
19894 var right = (num.words[i] | 0) * mul;
19895 w -= right & 0x3ffffff;
19896 carry = (w >> 26) - ((right / 0x4000000) | 0);
19897 this.words[i + shift] = w & 0x3ffffff;
19898 }
19899 for (; i < this.length - shift; i++) {
19900 w = (this.words[i + shift] | 0) + carry;
19901 carry = w >> 26;
19902 this.words[i + shift] = w & 0x3ffffff;
19903 }
19904
19905 if (carry === 0) return this.strip();
19906
19907 // Subtraction overflow
19908 assert(carry === -1);
19909 carry = 0;
19910 for (i = 0; i < this.length; i++) {
19911 w = -(this.words[i] | 0) + carry;
19912 carry = w >> 26;
19913 this.words[i] = w & 0x3ffffff;
19914 }
19915 this.negative = 1;
19916
19917 return this.strip();
19918 };
19919
19920 BN.prototype._wordDiv = function _wordDiv (num, mode) {
19921 var shift = this.length - num.length;
19922
19923 var a = this.clone();
19924 var b = num;
19925
19926 // Normalize
19927 var bhi = b.words[b.length - 1] | 0;
19928 var bhiBits = this._countBits(bhi);
19929 shift = 26 - bhiBits;
19930 if (shift !== 0) {
19931 b = b.ushln(shift);
19932 a.iushln(shift);
19933 bhi = b.words[b.length - 1] | 0;
19934 }
19935
19936 // Initialize quotient
19937 var m = a.length - b.length;
19938 var q;
19939
19940 if (mode !== 'mod') {
19941 q = new BN(null);
19942 q.length = m + 1;
19943 q.words = new Array(q.length);
19944 for (var i = 0; i < q.length; i++) {
19945 q.words[i] = 0;
19946 }
19947 }
19948
19949 var diff = a.clone()._ishlnsubmul(b, 1, m);
19950 if (diff.negative === 0) {
19951 a = diff;
19952 if (q) {
19953 q.words[m] = 1;
19954 }
19955 }
19956
19957 for (var j = m - 1; j >= 0; j--) {
19958 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
19959 (a.words[b.length + j - 1] | 0);
19960
19961 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
19962 // (0x7ffffff)
19963 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
19964
19965 a._ishlnsubmul(b, qj, j);
19966 while (a.negative !== 0) {
19967 qj--;
19968 a.negative = 0;
19969 a._ishlnsubmul(b, 1, j);
19970 if (!a.isZero()) {
19971 a.negative ^= 1;
19972 }
19973 }
19974 if (q) {
19975 q.words[j] = qj;
19976 }
19977 }
19978 if (q) {
19979 q.strip();
19980 }
19981 a.strip();
19982
19983 // Denormalize
19984 if (mode !== 'div' && shift !== 0) {
19985 a.iushrn(shift);
19986 }
19987
19988 return {
19989 div: q || null,
19990 mod: a
19991 };
19992 };
19993
19994 // NOTE: 1) `mode` can be set to `mod` to request mod only,
19995 // to `div` to request div only, or be absent to
19996 // request both div & mod
19997 // 2) `positive` is true if unsigned mod is requested
19998 BN.prototype.divmod = function divmod (num, mode, positive) {
19999 assert(!num.isZero());
20000
20001 if (this.isZero()) {
20002 return {
20003 div: new BN(0),
20004 mod: new BN(0)
20005 };
20006 }
20007
20008 var div, mod, res;
20009 if (this.negative !== 0 && num.negative === 0) {
20010 res = this.neg().divmod(num, mode);
20011
20012 if (mode !== 'mod') {
20013 div = res.div.neg();
20014 }
20015
20016 if (mode !== 'div') {
20017 mod = res.mod.neg();
20018 if (positive && mod.negative !== 0) {
20019 mod.iadd(num);
20020 }
20021 }
20022
20023 return {
20024 div: div,
20025 mod: mod
20026 };
20027 }
20028
20029 if (this.negative === 0 && num.negative !== 0) {
20030 res = this.divmod(num.neg(), mode);
20031
20032 if (mode !== 'mod') {
20033 div = res.div.neg();
20034 }
20035
20036 return {
20037 div: div,
20038 mod: res.mod
20039 };
20040 }
20041
20042 if ((this.negative & num.negative) !== 0) {
20043 res = this.neg().divmod(num.neg(), mode);
20044
20045 if (mode !== 'div') {
20046 mod = res.mod.neg();
20047 if (positive && mod.negative !== 0) {
20048 mod.isub(num);
20049 }
20050 }
20051
20052 return {
20053 div: res.div,
20054 mod: mod
20055 };
20056 }
20057
20058 // Both numbers are positive at this point
20059
20060 // Strip both numbers to approximate shift value
20061 if (num.length > this.length || this.cmp(num) < 0) {
20062 return {
20063 div: new BN(0),
20064 mod: this
20065 };
20066 }
20067
20068 // Very short reduction
20069 if (num.length === 1) {
20070 if (mode === 'div') {
20071 return {
20072 div: this.divn(num.words[0]),
20073 mod: null
20074 };
20075 }
20076
20077 if (mode === 'mod') {
20078 return {
20079 div: null,
20080 mod: new BN(this.modn(num.words[0]))
20081 };
20082 }
20083
20084 return {
20085 div: this.divn(num.words[0]),
20086 mod: new BN(this.modn(num.words[0]))
20087 };
20088 }
20089
20090 return this._wordDiv(num, mode);
20091 };
20092
20093 // Find `this` / `num`
20094 BN.prototype.div = function div (num) {
20095 return this.divmod(num, 'div', false).div;
20096 };
20097
20098 // Find `this` % `num`
20099 BN.prototype.mod = function mod (num) {
20100 return this.divmod(num, 'mod', false).mod;
20101 };
20102
20103 BN.prototype.umod = function umod (num) {
20104 return this.divmod(num, 'mod', true).mod;
20105 };
20106
20107 // Find Round(`this` / `num`)
20108 BN.prototype.divRound = function divRound (num) {
20109 var dm = this.divmod(num);
20110
20111 // Fast case - exact division
20112 if (dm.mod.isZero()) return dm.div;
20113
20114 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
20115
20116 var half = num.ushrn(1);
20117 var r2 = num.andln(1);
20118 var cmp = mod.cmp(half);
20119
20120 // Round down
20121 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
20122
20123 // Round up
20124 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
20125 };
20126
20127 BN.prototype.modn = function modn (num) {
20128 assert(num <= 0x3ffffff);
20129 var p = (1 << 26) % num;
20130
20131 var acc = 0;
20132 for (var i = this.length - 1; i >= 0; i--) {
20133 acc = (p * acc + (this.words[i] | 0)) % num;
20134 }
20135
20136 return acc;
20137 };
20138
20139 // In-place division by number
20140 BN.prototype.idivn = function idivn (num) {
20141 assert(num <= 0x3ffffff);
20142
20143 var carry = 0;
20144 for (var i = this.length - 1; i >= 0; i--) {
20145 var w = (this.words[i] | 0) + carry * 0x4000000;
20146 this.words[i] = (w / num) | 0;
20147 carry = w % num;
20148 }
20149
20150 return this.strip();
20151 };
20152
20153 BN.prototype.divn = function divn (num) {
20154 return this.clone().idivn(num);
20155 };
20156
20157 BN.prototype.egcd = function egcd (p) {
20158 assert(p.negative === 0);
20159 assert(!p.isZero());
20160
20161 var x = this;
20162 var y = p.clone();
20163
20164 if (x.negative !== 0) {
20165 x = x.umod(p);
20166 } else {
20167 x = x.clone();
20168 }
20169
20170 // A * x + B * y = x
20171 var A = new BN(1);
20172 var B = new BN(0);
20173
20174 // C * x + D * y = y
20175 var C = new BN(0);
20176 var D = new BN(1);
20177
20178 var g = 0;
20179
20180 while (x.isEven() && y.isEven()) {
20181 x.iushrn(1);
20182 y.iushrn(1);
20183 ++g;
20184 }
20185
20186 var yp = y.clone();
20187 var xp = x.clone();
20188
20189 while (!x.isZero()) {
20190 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
20191 if (i > 0) {
20192 x.iushrn(i);
20193 while (i-- > 0) {
20194 if (A.isOdd() || B.isOdd()) {
20195 A.iadd(yp);
20196 B.isub(xp);
20197 }
20198
20199 A.iushrn(1);
20200 B.iushrn(1);
20201 }
20202 }
20203
20204 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
20205 if (j > 0) {
20206 y.iushrn(j);
20207 while (j-- > 0) {
20208 if (C.isOdd() || D.isOdd()) {
20209 C.iadd(yp);
20210 D.isub(xp);
20211 }
20212
20213 C.iushrn(1);
20214 D.iushrn(1);
20215 }
20216 }
20217
20218 if (x.cmp(y) >= 0) {
20219 x.isub(y);
20220 A.isub(C);
20221 B.isub(D);
20222 } else {
20223 y.isub(x);
20224 C.isub(A);
20225 D.isub(B);
20226 }
20227 }
20228
20229 return {
20230 a: C,
20231 b: D,
20232 gcd: y.iushln(g)
20233 };
20234 };
20235
20236 // This is reduced incarnation of the binary EEA
20237 // above, designated to invert members of the
20238 // _prime_ fields F(p) at a maximal speed
20239 BN.prototype._invmp = function _invmp (p) {
20240 assert(p.negative === 0);
20241 assert(!p.isZero());
20242
20243 var a = this;
20244 var b = p.clone();
20245
20246 if (a.negative !== 0) {
20247 a = a.umod(p);
20248 } else {
20249 a = a.clone();
20250 }
20251
20252 var x1 = new BN(1);
20253 var x2 = new BN(0);
20254
20255 var delta = b.clone();
20256
20257 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
20258 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
20259 if (i > 0) {
20260 a.iushrn(i);
20261 while (i-- > 0) {
20262 if (x1.isOdd()) {
20263 x1.iadd(delta);
20264 }
20265
20266 x1.iushrn(1);
20267 }
20268 }
20269
20270 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
20271 if (j > 0) {
20272 b.iushrn(j);
20273 while (j-- > 0) {
20274 if (x2.isOdd()) {
20275 x2.iadd(delta);
20276 }
20277
20278 x2.iushrn(1);
20279 }
20280 }
20281
20282 if (a.cmp(b) >= 0) {
20283 a.isub(b);
20284 x1.isub(x2);
20285 } else {
20286 b.isub(a);
20287 x2.isub(x1);
20288 }
20289 }
20290
20291 var res;
20292 if (a.cmpn(1) === 0) {
20293 res = x1;
20294 } else {
20295 res = x2;
20296 }
20297
20298 if (res.cmpn(0) < 0) {
20299 res.iadd(p);
20300 }
20301
20302 return res;
20303 };
20304
20305 BN.prototype.gcd = function gcd (num) {
20306 if (this.isZero()) return num.abs();
20307 if (num.isZero()) return this.abs();
20308
20309 var a = this.clone();
20310 var b = num.clone();
20311 a.negative = 0;
20312 b.negative = 0;
20313
20314 // Remove common factor of two
20315 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
20316 a.iushrn(1);
20317 b.iushrn(1);
20318 }
20319
20320 do {
20321 while (a.isEven()) {
20322 a.iushrn(1);
20323 }
20324 while (b.isEven()) {
20325 b.iushrn(1);
20326 }
20327
20328 var r = a.cmp(b);
20329 if (r < 0) {
20330 // Swap `a` and `b` to make `a` always bigger than `b`
20331 var t = a;
20332 a = b;
20333 b = t;
20334 } else if (r === 0 || b.cmpn(1) === 0) {
20335 break;
20336 }
20337
20338 a.isub(b);
20339 } while (true);
20340
20341 return b.iushln(shift);
20342 };
20343
20344 // Invert number in the field F(num)
20345 BN.prototype.invm = function invm (num) {
20346 return this.egcd(num).a.umod(num);
20347 };
20348
20349 BN.prototype.isEven = function isEven () {
20350 return (this.words[0] & 1) === 0;
20351 };
20352
20353 BN.prototype.isOdd = function isOdd () {
20354 return (this.words[0] & 1) === 1;
20355 };
20356
20357 // And first word and num
20358 BN.prototype.andln = function andln (num) {
20359 return this.words[0] & num;
20360 };
20361
20362 // Increment at the bit position in-line
20363 BN.prototype.bincn = function bincn (bit) {
20364 assert(typeof bit === 'number');
20365 var r = bit % 26;
20366 var s = (bit - r) / 26;
20367 var q = 1 << r;
20368
20369 // Fast case: bit is much higher than all existing words
20370 if (this.length <= s) {
20371 this._expand(s + 1);
20372 this.words[s] |= q;
20373 return this;
20374 }
20375
20376 // Add bit and propagate, if needed
20377 var carry = q;
20378 for (var i = s; carry !== 0 && i < this.length; i++) {
20379 var w = this.words[i] | 0;
20380 w += carry;
20381 carry = w >>> 26;
20382 w &= 0x3ffffff;
20383 this.words[i] = w;
20384 }
20385 if (carry !== 0) {
20386 this.words[i] = carry;
20387 this.length++;
20388 }
20389 return this;
20390 };
20391
20392 BN.prototype.isZero = function isZero () {
20393 return this.length === 1 && this.words[0] === 0;
20394 };
20395
20396 BN.prototype.cmpn = function cmpn (num) {
20397 var negative = num < 0;
20398
20399 if (this.negative !== 0 && !negative) return -1;
20400 if (this.negative === 0 && negative) return 1;
20401
20402 this.strip();
20403
20404 var res;
20405 if (this.length > 1) {
20406 res = 1;
20407 } else {
20408 if (negative) {
20409 num = -num;
20410 }
20411
20412 assert(num <= 0x3ffffff, 'Number is too big');
20413
20414 var w = this.words[0] | 0;
20415 res = w === num ? 0 : w < num ? -1 : 1;
20416 }
20417 if (this.negative !== 0) return -res | 0;
20418 return res;
20419 };
20420
20421 // Compare two numbers and return:
20422 // 1 - if `this` > `num`
20423 // 0 - if `this` == `num`
20424 // -1 - if `this` < `num`
20425 BN.prototype.cmp = function cmp (num) {
20426 if (this.negative !== 0 && num.negative === 0) return -1;
20427 if (this.negative === 0 && num.negative !== 0) return 1;
20428
20429 var res = this.ucmp(num);
20430 if (this.negative !== 0) return -res | 0;
20431 return res;
20432 };
20433
20434 // Unsigned comparison
20435 BN.prototype.ucmp = function ucmp (num) {
20436 // At this point both numbers have the same sign
20437 if (this.length > num.length) return 1;
20438 if (this.length < num.length) return -1;
20439
20440 var res = 0;
20441 for (var i = this.length - 1; i >= 0; i--) {
20442 var a = this.words[i] | 0;
20443 var b = num.words[i] | 0;
20444
20445 if (a === b) continue;
20446 if (a < b) {
20447 res = -1;
20448 } else if (a > b) {
20449 res = 1;
20450 }
20451 break;
20452 }
20453 return res;
20454 };
20455
20456 BN.prototype.gtn = function gtn (num) {
20457 return this.cmpn(num) === 1;
20458 };
20459
20460 BN.prototype.gt = function gt (num) {
20461 return this.cmp(num) === 1;
20462 };
20463
20464 BN.prototype.gten = function gten (num) {
20465 return this.cmpn(num) >= 0;
20466 };
20467
20468 BN.prototype.gte = function gte (num) {
20469 return this.cmp(num) >= 0;
20470 };
20471
20472 BN.prototype.ltn = function ltn (num) {
20473 return this.cmpn(num) === -1;
20474 };
20475
20476 BN.prototype.lt = function lt (num) {
20477 return this.cmp(num) === -1;
20478 };
20479
20480 BN.prototype.lten = function lten (num) {
20481 return this.cmpn(num) <= 0;
20482 };
20483
20484 BN.prototype.lte = function lte (num) {
20485 return this.cmp(num) <= 0;
20486 };
20487
20488 BN.prototype.eqn = function eqn (num) {
20489 return this.cmpn(num) === 0;
20490 };
20491
20492 BN.prototype.eq = function eq (num) {
20493 return this.cmp(num) === 0;
20494 };
20495
20496 //
20497 // A reduce context, could be using montgomery or something better, depending
20498 // on the `m` itself.
20499 //
20500 BN.red = function red (num) {
20501 return new Red(num);
20502 };
20503
20504 BN.prototype.toRed = function toRed (ctx) {
20505 assert(!this.red, 'Already a number in reduction context');
20506 assert(this.negative === 0, 'red works only with positives');
20507 return ctx.convertTo(this)._forceRed(ctx);
20508 };
20509
20510 BN.prototype.fromRed = function fromRed () {
20511 assert(this.red, 'fromRed works only with numbers in reduction context');
20512 return this.red.convertFrom(this);
20513 };
20514
20515 BN.prototype._forceRed = function _forceRed (ctx) {
20516 this.red = ctx;
20517 return this;
20518 };
20519
20520 BN.prototype.forceRed = function forceRed (ctx) {
20521 assert(!this.red, 'Already a number in reduction context');
20522 return this._forceRed(ctx);
20523 };
20524
20525 BN.prototype.redAdd = function redAdd (num) {
20526 assert(this.red, 'redAdd works only with red numbers');
20527 return this.red.add(this, num);
20528 };
20529
20530 BN.prototype.redIAdd = function redIAdd (num) {
20531 assert(this.red, 'redIAdd works only with red numbers');
20532 return this.red.iadd(this, num);
20533 };
20534
20535 BN.prototype.redSub = function redSub (num) {
20536 assert(this.red, 'redSub works only with red numbers');
20537 return this.red.sub(this, num);
20538 };
20539
20540 BN.prototype.redISub = function redISub (num) {
20541 assert(this.red, 'redISub works only with red numbers');
20542 return this.red.isub(this, num);
20543 };
20544
20545 BN.prototype.redShl = function redShl (num) {
20546 assert(this.red, 'redShl works only with red numbers');
20547 return this.red.shl(this, num);
20548 };
20549
20550 BN.prototype.redMul = function redMul (num) {
20551 assert(this.red, 'redMul works only with red numbers');
20552 this.red._verify2(this, num);
20553 return this.red.mul(this, num);
20554 };
20555
20556 BN.prototype.redIMul = function redIMul (num) {
20557 assert(this.red, 'redMul works only with red numbers');
20558 this.red._verify2(this, num);
20559 return this.red.imul(this, num);
20560 };
20561
20562 BN.prototype.redSqr = function redSqr () {
20563 assert(this.red, 'redSqr works only with red numbers');
20564 this.red._verify1(this);
20565 return this.red.sqr(this);
20566 };
20567
20568 BN.prototype.redISqr = function redISqr () {
20569 assert(this.red, 'redISqr works only with red numbers');
20570 this.red._verify1(this);
20571 return this.red.isqr(this);
20572 };
20573
20574 // Square root over p
20575 BN.prototype.redSqrt = function redSqrt () {
20576 assert(this.red, 'redSqrt works only with red numbers');
20577 this.red._verify1(this);
20578 return this.red.sqrt(this);
20579 };
20580
20581 BN.prototype.redInvm = function redInvm () {
20582 assert(this.red, 'redInvm works only with red numbers');
20583 this.red._verify1(this);
20584 return this.red.invm(this);
20585 };
20586
20587 // Return negative clone of `this` % `red modulo`
20588 BN.prototype.redNeg = function redNeg () {
20589 assert(this.red, 'redNeg works only with red numbers');
20590 this.red._verify1(this);
20591 return this.red.neg(this);
20592 };
20593
20594 BN.prototype.redPow = function redPow (num) {
20595 assert(this.red && !num.red, 'redPow(normalNum)');
20596 this.red._verify1(this);
20597 return this.red.pow(this, num);
20598 };
20599
20600 // Prime numbers with efficient reduction
20601 var primes = {
20602 k256: null,
20603 p224: null,
20604 p192: null,
20605 p25519: null
20606 };
20607
20608 // Pseudo-Mersenne prime
20609 function MPrime (name, p) {
20610 // P = 2 ^ N - K
20611 this.name = name;
20612 this.p = new BN(p, 16);
20613 this.n = this.p.bitLength();
20614 this.k = new BN(1).iushln(this.n).isub(this.p);
20615
20616 this.tmp = this._tmp();
20617 }
20618
20619 MPrime.prototype._tmp = function _tmp () {
20620 var tmp = new BN(null);
20621 tmp.words = new Array(Math.ceil(this.n / 13));
20622 return tmp;
20623 };
20624
20625 MPrime.prototype.ireduce = function ireduce (num) {
20626 // Assumes that `num` is less than `P^2`
20627 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
20628 var r = num;
20629 var rlen;
20630
20631 do {
20632 this.split(r, this.tmp);
20633 r = this.imulK(r);
20634 r = r.iadd(this.tmp);
20635 rlen = r.bitLength();
20636 } while (rlen > this.n);
20637
20638 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
20639 if (cmp === 0) {
20640 r.words[0] = 0;
20641 r.length = 1;
20642 } else if (cmp > 0) {
20643 r.isub(this.p);
20644 } else {
20645 r.strip();
20646 }
20647
20648 return r;
20649 };
20650
20651 MPrime.prototype.split = function split (input, out) {
20652 input.iushrn(this.n, 0, out);
20653 };
20654
20655 MPrime.prototype.imulK = function imulK (num) {
20656 return num.imul(this.k);
20657 };
20658
20659 function K256 () {
20660 MPrime.call(
20661 this,
20662 'k256',
20663 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
20664 }
20665 inherits(K256, MPrime);
20666
20667 K256.prototype.split = function split (input, output) {
20668 // 256 = 9 * 26 + 22
20669 var mask = 0x3fffff;
20670
20671 var outLen = Math.min(input.length, 9);
20672 for (var i = 0; i < outLen; i++) {
20673 output.words[i] = input.words[i];
20674 }
20675 output.length = outLen;
20676
20677 if (input.length <= 9) {
20678 input.words[0] = 0;
20679 input.length = 1;
20680 return;
20681 }
20682
20683 // Shift by 9 limbs
20684 var prev = input.words[9];
20685 output.words[output.length++] = prev & mask;
20686
20687 for (i = 10; i < input.length; i++) {
20688 var next = input.words[i] | 0;
20689 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
20690 prev = next;
20691 }
20692 prev >>>= 22;
20693 input.words[i - 10] = prev;
20694 if (prev === 0 && input.length > 10) {
20695 input.length -= 10;
20696 } else {
20697 input.length -= 9;
20698 }
20699 };
20700
20701 K256.prototype.imulK = function imulK (num) {
20702 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
20703 num.words[num.length] = 0;
20704 num.words[num.length + 1] = 0;
20705 num.length += 2;
20706
20707 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
20708 var lo = 0;
20709 for (var i = 0; i < num.length; i++) {
20710 var w = num.words[i] | 0;
20711 lo += w * 0x3d1;
20712 num.words[i] = lo & 0x3ffffff;
20713 lo = w * 0x40 + ((lo / 0x4000000) | 0);
20714 }
20715
20716 // Fast length reduction
20717 if (num.words[num.length - 1] === 0) {
20718 num.length--;
20719 if (num.words[num.length - 1] === 0) {
20720 num.length--;
20721 }
20722 }
20723 return num;
20724 };
20725
20726 function P224 () {
20727 MPrime.call(
20728 this,
20729 'p224',
20730 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
20731 }
20732 inherits(P224, MPrime);
20733
20734 function P192 () {
20735 MPrime.call(
20736 this,
20737 'p192',
20738 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
20739 }
20740 inherits(P192, MPrime);
20741
20742 function P25519 () {
20743 // 2 ^ 255 - 19
20744 MPrime.call(
20745 this,
20746 '25519',
20747 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
20748 }
20749 inherits(P25519, MPrime);
20750
20751 P25519.prototype.imulK = function imulK (num) {
20752 // K = 0x13
20753 var carry = 0;
20754 for (var i = 0; i < num.length; i++) {
20755 var hi = (num.words[i] | 0) * 0x13 + carry;
20756 var lo = hi & 0x3ffffff;
20757 hi >>>= 26;
20758
20759 num.words[i] = lo;
20760 carry = hi;
20761 }
20762 if (carry !== 0) {
20763 num.words[num.length++] = carry;
20764 }
20765 return num;
20766 };
20767
20768 // Exported mostly for testing purposes, use plain name instead
20769 BN._prime = function prime (name) {
20770 // Cached version of prime
20771 if (primes[name]) return primes[name];
20772
20773 var prime;
20774 if (name === 'k256') {
20775 prime = new K256();
20776 } else if (name === 'p224') {
20777 prime = new P224();
20778 } else if (name === 'p192') {
20779 prime = new P192();
20780 } else if (name === 'p25519') {
20781 prime = new P25519();
20782 } else {
20783 throw new Error('Unknown prime ' + name);
20784 }
20785 primes[name] = prime;
20786
20787 return prime;
20788 };
20789
20790 //
20791 // Base reduction engine
20792 //
20793 function Red (m) {
20794 if (typeof m === 'string') {
20795 var prime = BN._prime(m);
20796 this.m = prime.p;
20797 this.prime = prime;
20798 } else {
20799 assert(m.gtn(1), 'modulus must be greater than 1');
20800 this.m = m;
20801 this.prime = null;
20802 }
20803 }
20804
20805 Red.prototype._verify1 = function _verify1 (a) {
20806 assert(a.negative === 0, 'red works only with positives');
20807 assert(a.red, 'red works only with red numbers');
20808 };
20809
20810 Red.prototype._verify2 = function _verify2 (a, b) {
20811 assert((a.negative | b.negative) === 0, 'red works only with positives');
20812 assert(a.red && a.red === b.red,
20813 'red works only with red numbers');
20814 };
20815
20816 Red.prototype.imod = function imod (a) {
20817 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
20818 return a.umod(this.m)._forceRed(this);
20819 };
20820
20821 Red.prototype.neg = function neg (a) {
20822 if (a.isZero()) {
20823 return a.clone();
20824 }
20825
20826 return this.m.sub(a)._forceRed(this);
20827 };
20828
20829 Red.prototype.add = function add (a, b) {
20830 this._verify2(a, b);
20831
20832 var res = a.add(b);
20833 if (res.cmp(this.m) >= 0) {
20834 res.isub(this.m);
20835 }
20836 return res._forceRed(this);
20837 };
20838
20839 Red.prototype.iadd = function iadd (a, b) {
20840 this._verify2(a, b);
20841
20842 var res = a.iadd(b);
20843 if (res.cmp(this.m) >= 0) {
20844 res.isub(this.m);
20845 }
20846 return res;
20847 };
20848
20849 Red.prototype.sub = function sub (a, b) {
20850 this._verify2(a, b);
20851
20852 var res = a.sub(b);
20853 if (res.cmpn(0) < 0) {
20854 res.iadd(this.m);
20855 }
20856 return res._forceRed(this);
20857 };
20858
20859 Red.prototype.isub = function isub (a, b) {
20860 this._verify2(a, b);
20861
20862 var res = a.isub(b);
20863 if (res.cmpn(0) < 0) {
20864 res.iadd(this.m);
20865 }
20866 return res;
20867 };
20868
20869 Red.prototype.shl = function shl (a, num) {
20870 this._verify1(a);
20871 return this.imod(a.ushln(num));
20872 };
20873
20874 Red.prototype.imul = function imul (a, b) {
20875 this._verify2(a, b);
20876 return this.imod(a.imul(b));
20877 };
20878
20879 Red.prototype.mul = function mul (a, b) {
20880 this._verify2(a, b);
20881 return this.imod(a.mul(b));
20882 };
20883
20884 Red.prototype.isqr = function isqr (a) {
20885 return this.imul(a, a.clone());
20886 };
20887
20888 Red.prototype.sqr = function sqr (a) {
20889 return this.mul(a, a);
20890 };
20891
20892 Red.prototype.sqrt = function sqrt (a) {
20893 if (a.isZero()) return a.clone();
20894
20895 var mod3 = this.m.andln(3);
20896 assert(mod3 % 2 === 1);
20897
20898 // Fast case
20899 if (mod3 === 3) {
20900 var pow = this.m.add(new BN(1)).iushrn(2);
20901 return this.pow(a, pow);
20902 }
20903
20904 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
20905 //
20906 // Find Q and S, that Q * 2 ^ S = (P - 1)
20907 var q = this.m.subn(1);
20908 var s = 0;
20909 while (!q.isZero() && q.andln(1) === 0) {
20910 s++;
20911 q.iushrn(1);
20912 }
20913 assert(!q.isZero());
20914
20915 var one = new BN(1).toRed(this);
20916 var nOne = one.redNeg();
20917
20918 // Find quadratic non-residue
20919 // NOTE: Max is such because of generalized Riemann hypothesis.
20920 var lpow = this.m.subn(1).iushrn(1);
20921 var z = this.m.bitLength();
20922 z = new BN(2 * z * z).toRed(this);
20923
20924 while (this.pow(z, lpow).cmp(nOne) !== 0) {
20925 z.redIAdd(nOne);
20926 }
20927
20928 var c = this.pow(z, q);
20929 var r = this.pow(a, q.addn(1).iushrn(1));
20930 var t = this.pow(a, q);
20931 var m = s;
20932 while (t.cmp(one) !== 0) {
20933 var tmp = t;
20934 for (var i = 0; tmp.cmp(one) !== 0; i++) {
20935 tmp = tmp.redSqr();
20936 }
20937 assert(i < m);
20938 var b = this.pow(c, new BN(1).iushln(m - i - 1));
20939
20940 r = r.redMul(b);
20941 c = b.redSqr();
20942 t = t.redMul(c);
20943 m = i;
20944 }
20945
20946 return r;
20947 };
20948
20949 Red.prototype.invm = function invm (a) {
20950 var inv = a._invmp(this.m);
20951 if (inv.negative !== 0) {
20952 inv.negative = 0;
20953 return this.imod(inv).redNeg();
20954 } else {
20955 return this.imod(inv);
20956 }
20957 };
20958
20959 Red.prototype.pow = function pow (a, num) {
20960 if (num.isZero()) return new BN(1).toRed(this);
20961 if (num.cmpn(1) === 0) return a.clone();
20962
20963 var windowSize = 4;
20964 var wnd = new Array(1 << windowSize);
20965 wnd[0] = new BN(1).toRed(this);
20966 wnd[1] = a;
20967 for (var i = 2; i < wnd.length; i++) {
20968 wnd[i] = this.mul(wnd[i - 1], a);
20969 }
20970
20971 var res = wnd[0];
20972 var current = 0;
20973 var currentLen = 0;
20974 var start = num.bitLength() % 26;
20975 if (start === 0) {
20976 start = 26;
20977 }
20978
20979 for (i = num.length - 1; i >= 0; i--) {
20980 var word = num.words[i];
20981 for (var j = start - 1; j >= 0; j--) {
20982 var bit = (word >> j) & 1;
20983 if (res !== wnd[0]) {
20984 res = this.sqr(res);
20985 }
20986
20987 if (bit === 0 && current === 0) {
20988 currentLen = 0;
20989 continue;
20990 }
20991
20992 current <<= 1;
20993 current |= bit;
20994 currentLen++;
20995 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
20996
20997 res = this.mul(res, wnd[current]);
20998 currentLen = 0;
20999 current = 0;
21000 }
21001 start = 26;
21002 }
21003
21004 return res;
21005 };
21006
21007 Red.prototype.convertTo = function convertTo (num) {
21008 var r = num.umod(this.m);
21009
21010 return r === num ? r.clone() : r;
21011 };
21012
21013 Red.prototype.convertFrom = function convertFrom (num) {
21014 var res = num.clone();
21015 res.red = null;
21016 return res;
21017 };
21018
21019 //
21020 // Montgomery method engine
21021 //
21022
21023 BN.mont = function mont (num) {
21024 return new Mont(num);
21025 };
21026
21027 function Mont (m) {
21028 Red.call(this, m);
21029
21030 this.shift = this.m.bitLength();
21031 if (this.shift % 26 !== 0) {
21032 this.shift += 26 - (this.shift % 26);
21033 }
21034
21035 this.r = new BN(1).iushln(this.shift);
21036 this.r2 = this.imod(this.r.sqr());
21037 this.rinv = this.r._invmp(this.m);
21038
21039 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
21040 this.minv = this.minv.umod(this.r);
21041 this.minv = this.r.sub(this.minv);
21042 }
21043 inherits(Mont, Red);
21044
21045 Mont.prototype.convertTo = function convertTo (num) {
21046 return this.imod(num.ushln(this.shift));
21047 };
21048
21049 Mont.prototype.convertFrom = function convertFrom (num) {
21050 var r = this.imod(num.mul(this.rinv));
21051 r.red = null;
21052 return r;
21053 };
21054
21055 Mont.prototype.imul = function imul (a, b) {
21056 if (a.isZero() || b.isZero()) {
21057 a.words[0] = 0;
21058 a.length = 1;
21059 return a;
21060 }
21061
21062 var t = a.imul(b);
21063 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
21064 var u = t.isub(c).iushrn(this.shift);
21065 var res = u;
21066
21067 if (u.cmp(this.m) >= 0) {
21068 res = u.isub(this.m);
21069 } else if (u.cmpn(0) < 0) {
21070 res = u.iadd(this.m);
21071 }
21072
21073 return res._forceRed(this);
21074 };
21075
21076 Mont.prototype.mul = function mul (a, b) {
21077 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
21078
21079 var t = a.mul(b);
21080 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
21081 var u = t.isub(c).iushrn(this.shift);
21082 var res = u;
21083 if (u.cmp(this.m) >= 0) {
21084 res = u.isub(this.m);
21085 } else if (u.cmpn(0) < 0) {
21086 res = u.iadd(this.m);
21087 }
21088
21089 return res._forceRed(this);
21090 };
21091
21092 Mont.prototype.invm = function invm (a) {
21093 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
21094 var res = this.imod(a._invmp(this.m).mul(this.r2));
21095 return res._forceRed(this);
21096 };
21097})(typeof module === 'undefined' || module, this);
21098
21099},{"buffer":82}],81:[function(require,module,exports){
21100var r;
21101
21102module.exports = function rand(len) {
21103 if (!r)
21104 r = new Rand(null);
21105
21106 return r.generate(len);
21107};
21108
21109function Rand(rand) {
21110 this.rand = rand;
21111}
21112module.exports.Rand = Rand;
21113
21114Rand.prototype.generate = function generate(len) {
21115 return this._rand(len);
21116};
21117
21118// Emulate crypto API using randy
21119Rand.prototype._rand = function _rand(n) {
21120 if (this.rand.getBytes)
21121 return this.rand.getBytes(n);
21122
21123 var res = new Uint8Array(n);
21124 for (var i = 0; i < res.length; i++)
21125 res[i] = this.rand.getByte();
21126 return res;
21127};
21128
21129if (typeof self === 'object') {
21130 if (self.crypto && self.crypto.getRandomValues) {
21131 // Modern browsers
21132 Rand.prototype._rand = function _rand(n) {
21133 var arr = new Uint8Array(n);
21134 self.crypto.getRandomValues(arr);
21135 return arr;
21136 };
21137 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
21138 // IE
21139 Rand.prototype._rand = function _rand(n) {
21140 var arr = new Uint8Array(n);
21141 self.msCrypto.getRandomValues(arr);
21142 return arr;
21143 };
21144
21145 // Safari's WebWorkers do not have `crypto`
21146 } else if (typeof window === 'object') {
21147 // Old junk
21148 Rand.prototype._rand = function() {
21149 throw new Error('Not implemented yet');
21150 };
21151 }
21152} else {
21153 // Node.js or Web worker with no crypto support
21154 try {
21155 var crypto = require('crypto');
21156 if (typeof crypto.randomBytes !== 'function')
21157 throw new Error('Not supported');
21158
21159 Rand.prototype._rand = function _rand(n) {
21160 return crypto.randomBytes(n);
21161 };
21162 } catch (e) {
21163 }
21164}
21165
21166},{"crypto":82}],82:[function(require,module,exports){
21167
21168},{}],83:[function(require,module,exports){
21169// based on the aes implimentation in triple sec
21170// https://github.com/keybase/triplesec
21171// which is in turn based on the one from crypto-js
21172// https://code.google.com/p/crypto-js/
21173
21174var Buffer = require('safe-buffer').Buffer
21175
21176function asUInt32Array (buf) {
21177 if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
21178
21179 var len = (buf.length / 4) | 0
21180 var out = new Array(len)
21181
21182 for (var i = 0; i < len; i++) {
21183 out[i] = buf.readUInt32BE(i * 4)
21184 }
21185
21186 return out
21187}
21188
21189function scrubVec (v) {
21190 for (var i = 0; i < v.length; v++) {
21191 v[i] = 0
21192 }
21193}
21194
21195function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
21196 var SUB_MIX0 = SUB_MIX[0]
21197 var SUB_MIX1 = SUB_MIX[1]
21198 var SUB_MIX2 = SUB_MIX[2]
21199 var SUB_MIX3 = SUB_MIX[3]
21200
21201 var s0 = M[0] ^ keySchedule[0]
21202 var s1 = M[1] ^ keySchedule[1]
21203 var s2 = M[2] ^ keySchedule[2]
21204 var s3 = M[3] ^ keySchedule[3]
21205 var t0, t1, t2, t3
21206 var ksRow = 4
21207
21208 for (var round = 1; round < nRounds; round++) {
21209 t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
21210 t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
21211 t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
21212 t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
21213 s0 = t0
21214 s1 = t1
21215 s2 = t2
21216 s3 = t3
21217 }
21218
21219 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
21220 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
21221 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
21222 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
21223 t0 = t0 >>> 0
21224 t1 = t1 >>> 0
21225 t2 = t2 >>> 0
21226 t3 = t3 >>> 0
21227
21228 return [t0, t1, t2, t3]
21229}
21230
21231// AES constants
21232var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
21233var G = (function () {
21234 // Compute double table
21235 var d = new Array(256)
21236 for (var j = 0; j < 256; j++) {
21237 if (j < 128) {
21238 d[j] = j << 1
21239 } else {
21240 d[j] = (j << 1) ^ 0x11b
21241 }
21242 }
21243
21244 var SBOX = []
21245 var INV_SBOX = []
21246 var SUB_MIX = [[], [], [], []]
21247 var INV_SUB_MIX = [[], [], [], []]
21248
21249 // Walk GF(2^8)
21250 var x = 0
21251 var xi = 0
21252 for (var i = 0; i < 256; ++i) {
21253 // Compute sbox
21254 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
21255 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
21256 SBOX[x] = sx
21257 INV_SBOX[sx] = x
21258
21259 // Compute multiplication
21260 var x2 = d[x]
21261 var x4 = d[x2]
21262 var x8 = d[x4]
21263
21264 // Compute sub bytes, mix columns tables
21265 var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
21266 SUB_MIX[0][x] = (t << 24) | (t >>> 8)
21267 SUB_MIX[1][x] = (t << 16) | (t >>> 16)
21268 SUB_MIX[2][x] = (t << 8) | (t >>> 24)
21269 SUB_MIX[3][x] = t
21270
21271 // Compute inv sub bytes, inv mix columns tables
21272 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
21273 INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
21274 INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
21275 INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
21276 INV_SUB_MIX[3][sx] = t
21277
21278 if (x === 0) {
21279 x = xi = 1
21280 } else {
21281 x = x2 ^ d[d[d[x8 ^ x2]]]
21282 xi ^= d[d[xi]]
21283 }
21284 }
21285
21286 return {
21287 SBOX: SBOX,
21288 INV_SBOX: INV_SBOX,
21289 SUB_MIX: SUB_MIX,
21290 INV_SUB_MIX: INV_SUB_MIX
21291 }
21292})()
21293
21294function AES (key) {
21295 this._key = asUInt32Array(key)
21296 this._reset()
21297}
21298
21299AES.blockSize = 4 * 4
21300AES.keySize = 256 / 8
21301AES.prototype.blockSize = AES.blockSize
21302AES.prototype.keySize = AES.keySize
21303AES.prototype._reset = function () {
21304 var keyWords = this._key
21305 var keySize = keyWords.length
21306 var nRounds = keySize + 6
21307 var ksRows = (nRounds + 1) * 4
21308
21309 var keySchedule = []
21310 for (var k = 0; k < keySize; k++) {
21311 keySchedule[k] = keyWords[k]
21312 }
21313
21314 for (k = keySize; k < ksRows; k++) {
21315 var t = keySchedule[k - 1]
21316
21317 if (k % keySize === 0) {
21318 t = (t << 8) | (t >>> 24)
21319 t =
21320 (G.SBOX[t >>> 24] << 24) |
21321 (G.SBOX[(t >>> 16) & 0xff] << 16) |
21322 (G.SBOX[(t >>> 8) & 0xff] << 8) |
21323 (G.SBOX[t & 0xff])
21324
21325 t ^= RCON[(k / keySize) | 0] << 24
21326 } else if (keySize > 6 && k % keySize === 4) {
21327 t =
21328 (G.SBOX[t >>> 24] << 24) |
21329 (G.SBOX[(t >>> 16) & 0xff] << 16) |
21330 (G.SBOX[(t >>> 8) & 0xff] << 8) |
21331 (G.SBOX[t & 0xff])
21332 }
21333
21334 keySchedule[k] = keySchedule[k - keySize] ^ t
21335 }
21336
21337 var invKeySchedule = []
21338 for (var ik = 0; ik < ksRows; ik++) {
21339 var ksR = ksRows - ik
21340 var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
21341
21342 if (ik < 4 || ksR <= 4) {
21343 invKeySchedule[ik] = tt
21344 } else {
21345 invKeySchedule[ik] =
21346 G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
21347 G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
21348 G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
21349 G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
21350 }
21351 }
21352
21353 this._nRounds = nRounds
21354 this._keySchedule = keySchedule
21355 this._invKeySchedule = invKeySchedule
21356}
21357
21358AES.prototype.encryptBlockRaw = function (M) {
21359 M = asUInt32Array(M)
21360 return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
21361}
21362
21363AES.prototype.encryptBlock = function (M) {
21364 var out = this.encryptBlockRaw(M)
21365 var buf = Buffer.allocUnsafe(16)
21366 buf.writeUInt32BE(out[0], 0)
21367 buf.writeUInt32BE(out[1], 4)
21368 buf.writeUInt32BE(out[2], 8)
21369 buf.writeUInt32BE(out[3], 12)
21370 return buf
21371}
21372
21373AES.prototype.decryptBlock = function (M) {
21374 M = asUInt32Array(M)
21375
21376 // swap
21377 var m1 = M[1]
21378 M[1] = M[3]
21379 M[3] = m1
21380
21381 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
21382 var buf = Buffer.allocUnsafe(16)
21383 buf.writeUInt32BE(out[0], 0)
21384 buf.writeUInt32BE(out[3], 4)
21385 buf.writeUInt32BE(out[2], 8)
21386 buf.writeUInt32BE(out[1], 12)
21387 return buf
21388}
21389
21390AES.prototype.scrub = function () {
21391 scrubVec(this._keySchedule)
21392 scrubVec(this._invKeySchedule)
21393 scrubVec(this._key)
21394}
21395
21396module.exports.AES = AES
21397
21398},{"safe-buffer":325}],84:[function(require,module,exports){
21399var aes = require('./aes')
21400var Buffer = require('safe-buffer').Buffer
21401var Transform = require('cipher-base')
21402var inherits = require('inherits')
21403var GHASH = require('./ghash')
21404var xor = require('buffer-xor')
21405var incr32 = require('./incr32')
21406
21407function xorTest (a, b) {
21408 var out = 0
21409 if (a.length !== b.length) out++
21410
21411 var len = Math.min(a.length, b.length)
21412 for (var i = 0; i < len; ++i) {
21413 out += (a[i] ^ b[i])
21414 }
21415
21416 return out
21417}
21418
21419function calcIv (self, iv, ck) {
21420 if (iv.length === 12) {
21421 self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
21422 return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
21423 }
21424 var ghash = new GHASH(ck)
21425 var len = iv.length
21426 var toPad = len % 16
21427 ghash.update(iv)
21428 if (toPad) {
21429 toPad = 16 - toPad
21430 ghash.update(Buffer.alloc(toPad, 0))
21431 }
21432 ghash.update(Buffer.alloc(8, 0))
21433 var ivBits = len * 8
21434 var tail = Buffer.alloc(8)
21435 tail.writeUIntBE(ivBits, 0, 8)
21436 ghash.update(tail)
21437 self._finID = ghash.state
21438 var out = Buffer.from(self._finID)
21439 incr32(out)
21440 return out
21441}
21442function StreamCipher (mode, key, iv, decrypt) {
21443 Transform.call(this)
21444
21445 var h = Buffer.alloc(4, 0)
21446
21447 this._cipher = new aes.AES(key)
21448 var ck = this._cipher.encryptBlock(h)
21449 this._ghash = new GHASH(ck)
21450 iv = calcIv(this, iv, ck)
21451
21452 this._prev = Buffer.from(iv)
21453 this._cache = Buffer.allocUnsafe(0)
21454 this._secCache = Buffer.allocUnsafe(0)
21455 this._decrypt = decrypt
21456 this._alen = 0
21457 this._len = 0
21458 this._mode = mode
21459
21460 this._authTag = null
21461 this._called = false
21462}
21463
21464inherits(StreamCipher, Transform)
21465
21466StreamCipher.prototype._update = function (chunk) {
21467 if (!this._called && this._alen) {
21468 var rump = 16 - (this._alen % 16)
21469 if (rump < 16) {
21470 rump = Buffer.alloc(rump, 0)
21471 this._ghash.update(rump)
21472 }
21473 }
21474
21475 this._called = true
21476 var out = this._mode.encrypt(this, chunk)
21477 if (this._decrypt) {
21478 this._ghash.update(chunk)
21479 } else {
21480 this._ghash.update(out)
21481 }
21482 this._len += chunk.length
21483 return out
21484}
21485
21486StreamCipher.prototype._final = function () {
21487 if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
21488
21489 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
21490 if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
21491
21492 this._authTag = tag
21493 this._cipher.scrub()
21494}
21495
21496StreamCipher.prototype.getAuthTag = function getAuthTag () {
21497 if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
21498
21499 return this._authTag
21500}
21501
21502StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
21503 if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
21504
21505 this._authTag = tag
21506}
21507
21508StreamCipher.prototype.setAAD = function setAAD (buf) {
21509 if (this._called) throw new Error('Attempting to set AAD in unsupported state')
21510
21511 this._ghash.update(buf)
21512 this._alen += buf.length
21513}
21514
21515module.exports = StreamCipher
21516
21517},{"./aes":83,"./ghash":88,"./incr32":89,"buffer-xor":113,"cipher-base":117,"inherits":210,"safe-buffer":325}],85:[function(require,module,exports){
21518var ciphers = require('./encrypter')
21519var deciphers = require('./decrypter')
21520var modes = require('./modes/list.json')
21521
21522function getCiphers () {
21523 return Object.keys(modes)
21524}
21525
21526exports.createCipher = exports.Cipher = ciphers.createCipher
21527exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
21528exports.createDecipher = exports.Decipher = deciphers.createDecipher
21529exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
21530exports.listCiphers = exports.getCiphers = getCiphers
21531
21532},{"./decrypter":86,"./encrypter":87,"./modes/list.json":97}],86:[function(require,module,exports){
21533var AuthCipher = require('./authCipher')
21534var Buffer = require('safe-buffer').Buffer
21535var MODES = require('./modes')
21536var StreamCipher = require('./streamCipher')
21537var Transform = require('cipher-base')
21538var aes = require('./aes')
21539var ebtk = require('evp_bytestokey')
21540var inherits = require('inherits')
21541
21542function Decipher (mode, key, iv) {
21543 Transform.call(this)
21544
21545 this._cache = new Splitter()
21546 this._last = void 0
21547 this._cipher = new aes.AES(key)
21548 this._prev = Buffer.from(iv)
21549 this._mode = mode
21550 this._autopadding = true
21551}
21552
21553inherits(Decipher, Transform)
21554
21555Decipher.prototype._update = function (data) {
21556 this._cache.add(data)
21557 var chunk
21558 var thing
21559 var out = []
21560 while ((chunk = this._cache.get(this._autopadding))) {
21561 thing = this._mode.decrypt(this, chunk)
21562 out.push(thing)
21563 }
21564 return Buffer.concat(out)
21565}
21566
21567Decipher.prototype._final = function () {
21568 var chunk = this._cache.flush()
21569 if (this._autopadding) {
21570 return unpad(this._mode.decrypt(this, chunk))
21571 } else if (chunk) {
21572 throw new Error('data not multiple of block length')
21573 }
21574}
21575
21576Decipher.prototype.setAutoPadding = function (setTo) {
21577 this._autopadding = !!setTo
21578 return this
21579}
21580
21581function Splitter () {
21582 this.cache = Buffer.allocUnsafe(0)
21583}
21584
21585Splitter.prototype.add = function (data) {
21586 this.cache = Buffer.concat([this.cache, data])
21587}
21588
21589Splitter.prototype.get = function (autoPadding) {
21590 var out
21591 if (autoPadding) {
21592 if (this.cache.length > 16) {
21593 out = this.cache.slice(0, 16)
21594 this.cache = this.cache.slice(16)
21595 return out
21596 }
21597 } else {
21598 if (this.cache.length >= 16) {
21599 out = this.cache.slice(0, 16)
21600 this.cache = this.cache.slice(16)
21601 return out
21602 }
21603 }
21604
21605 return null
21606}
21607
21608Splitter.prototype.flush = function () {
21609 if (this.cache.length) return this.cache
21610}
21611
21612function unpad (last) {
21613 var padded = last[15]
21614 if (padded < 1 || padded > 16) {
21615 throw new Error('unable to decrypt data')
21616 }
21617 var i = -1
21618 while (++i < padded) {
21619 if (last[(i + (16 - padded))] !== padded) {
21620 throw new Error('unable to decrypt data')
21621 }
21622 }
21623 if (padded === 16) return
21624
21625 return last.slice(0, 16 - padded)
21626}
21627
21628function createDecipheriv (suite, password, iv) {
21629 var config = MODES[suite.toLowerCase()]
21630 if (!config) throw new TypeError('invalid suite type')
21631
21632 if (typeof iv === 'string') iv = Buffer.from(iv)
21633 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
21634
21635 if (typeof password === 'string') password = Buffer.from(password)
21636 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
21637
21638 if (config.type === 'stream') {
21639 return new StreamCipher(config.module, password, iv, true)
21640 } else if (config.type === 'auth') {
21641 return new AuthCipher(config.module, password, iv, true)
21642 }
21643
21644 return new Decipher(config.module, password, iv)
21645}
21646
21647function createDecipher (suite, password) {
21648 var config = MODES[suite.toLowerCase()]
21649 if (!config) throw new TypeError('invalid suite type')
21650
21651 var keys = ebtk(password, false, config.key, config.iv)
21652 return createDecipheriv(suite, keys.key, keys.iv)
21653}
21654
21655exports.createDecipher = createDecipher
21656exports.createDecipheriv = createDecipheriv
21657
21658},{"./aes":83,"./authCipher":84,"./modes":96,"./streamCipher":99,"cipher-base":117,"evp_bytestokey":160,"inherits":210,"safe-buffer":325}],87:[function(require,module,exports){
21659var MODES = require('./modes')
21660var AuthCipher = require('./authCipher')
21661var Buffer = require('safe-buffer').Buffer
21662var StreamCipher = require('./streamCipher')
21663var Transform = require('cipher-base')
21664var aes = require('./aes')
21665var ebtk = require('evp_bytestokey')
21666var inherits = require('inherits')
21667
21668function Cipher (mode, key, iv) {
21669 Transform.call(this)
21670
21671 this._cache = new Splitter()
21672 this._cipher = new aes.AES(key)
21673 this._prev = Buffer.from(iv)
21674 this._mode = mode
21675 this._autopadding = true
21676}
21677
21678inherits(Cipher, Transform)
21679
21680Cipher.prototype._update = function (data) {
21681 this._cache.add(data)
21682 var chunk
21683 var thing
21684 var out = []
21685
21686 while ((chunk = this._cache.get())) {
21687 thing = this._mode.encrypt(this, chunk)
21688 out.push(thing)
21689 }
21690
21691 return Buffer.concat(out)
21692}
21693
21694var PADDING = Buffer.alloc(16, 0x10)
21695
21696Cipher.prototype._final = function () {
21697 var chunk = this._cache.flush()
21698 if (this._autopadding) {
21699 chunk = this._mode.encrypt(this, chunk)
21700 this._cipher.scrub()
21701 return chunk
21702 }
21703
21704 if (!chunk.equals(PADDING)) {
21705 this._cipher.scrub()
21706 throw new Error('data not multiple of block length')
21707 }
21708}
21709
21710Cipher.prototype.setAutoPadding = function (setTo) {
21711 this._autopadding = !!setTo
21712 return this
21713}
21714
21715function Splitter () {
21716 this.cache = Buffer.allocUnsafe(0)
21717}
21718
21719Splitter.prototype.add = function (data) {
21720 this.cache = Buffer.concat([this.cache, data])
21721}
21722
21723Splitter.prototype.get = function () {
21724 if (this.cache.length > 15) {
21725 var out = this.cache.slice(0, 16)
21726 this.cache = this.cache.slice(16)
21727 return out
21728 }
21729 return null
21730}
21731
21732Splitter.prototype.flush = function () {
21733 var len = 16 - this.cache.length
21734 var padBuff = Buffer.allocUnsafe(len)
21735
21736 var i = -1
21737 while (++i < len) {
21738 padBuff.writeUInt8(len, i)
21739 }
21740
21741 return Buffer.concat([this.cache, padBuff])
21742}
21743
21744function createCipheriv (suite, password, iv) {
21745 var config = MODES[suite.toLowerCase()]
21746 if (!config) throw new TypeError('invalid suite type')
21747
21748 if (typeof password === 'string') password = Buffer.from(password)
21749 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
21750
21751 if (typeof iv === 'string') iv = Buffer.from(iv)
21752 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
21753
21754 if (config.type === 'stream') {
21755 return new StreamCipher(config.module, password, iv)
21756 } else if (config.type === 'auth') {
21757 return new AuthCipher(config.module, password, iv)
21758 }
21759
21760 return new Cipher(config.module, password, iv)
21761}
21762
21763function createCipher (suite, password) {
21764 var config = MODES[suite.toLowerCase()]
21765 if (!config) throw new TypeError('invalid suite type')
21766
21767 var keys = ebtk(password, false, config.key, config.iv)
21768 return createCipheriv(suite, keys.key, keys.iv)
21769}
21770
21771exports.createCipheriv = createCipheriv
21772exports.createCipher = createCipher
21773
21774},{"./aes":83,"./authCipher":84,"./modes":96,"./streamCipher":99,"cipher-base":117,"evp_bytestokey":160,"inherits":210,"safe-buffer":325}],88:[function(require,module,exports){
21775var Buffer = require('safe-buffer').Buffer
21776var ZEROES = Buffer.alloc(16, 0)
21777
21778function toArray (buf) {
21779 return [
21780 buf.readUInt32BE(0),
21781 buf.readUInt32BE(4),
21782 buf.readUInt32BE(8),
21783 buf.readUInt32BE(12)
21784 ]
21785}
21786
21787function fromArray (out) {
21788 var buf = Buffer.allocUnsafe(16)
21789 buf.writeUInt32BE(out[0] >>> 0, 0)
21790 buf.writeUInt32BE(out[1] >>> 0, 4)
21791 buf.writeUInt32BE(out[2] >>> 0, 8)
21792 buf.writeUInt32BE(out[3] >>> 0, 12)
21793 return buf
21794}
21795
21796function GHASH (key) {
21797 this.h = key
21798 this.state = Buffer.alloc(16, 0)
21799 this.cache = Buffer.allocUnsafe(0)
21800}
21801
21802// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
21803// by Juho Vähä-Herttua
21804GHASH.prototype.ghash = function (block) {
21805 var i = -1
21806 while (++i < block.length) {
21807 this.state[i] ^= block[i]
21808 }
21809 this._multiply()
21810}
21811
21812GHASH.prototype._multiply = function () {
21813 var Vi = toArray(this.h)
21814 var Zi = [0, 0, 0, 0]
21815 var j, xi, lsbVi
21816 var i = -1
21817 while (++i < 128) {
21818 xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
21819 if (xi) {
21820 // Z_i+1 = Z_i ^ V_i
21821 Zi[0] ^= Vi[0]
21822 Zi[1] ^= Vi[1]
21823 Zi[2] ^= Vi[2]
21824 Zi[3] ^= Vi[3]
21825 }
21826
21827 // Store the value of LSB(V_i)
21828 lsbVi = (Vi[3] & 1) !== 0
21829
21830 // V_i+1 = V_i >> 1
21831 for (j = 3; j > 0; j--) {
21832 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
21833 }
21834 Vi[0] = Vi[0] >>> 1
21835
21836 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
21837 if (lsbVi) {
21838 Vi[0] = Vi[0] ^ (0xe1 << 24)
21839 }
21840 }
21841 this.state = fromArray(Zi)
21842}
21843
21844GHASH.prototype.update = function (buf) {
21845 this.cache = Buffer.concat([this.cache, buf])
21846 var chunk
21847 while (this.cache.length >= 16) {
21848 chunk = this.cache.slice(0, 16)
21849 this.cache = this.cache.slice(16)
21850 this.ghash(chunk)
21851 }
21852}
21853
21854GHASH.prototype.final = function (abl, bl) {
21855 if (this.cache.length) {
21856 this.ghash(Buffer.concat([this.cache, ZEROES], 16))
21857 }
21858
21859 this.ghash(fromArray([0, abl, 0, bl]))
21860 return this.state
21861}
21862
21863module.exports = GHASH
21864
21865},{"safe-buffer":325}],89:[function(require,module,exports){
21866function incr32 (iv) {
21867 var len = iv.length
21868 var item
21869 while (len--) {
21870 item = iv.readUInt8(len)
21871 if (item === 255) {
21872 iv.writeUInt8(0, len)
21873 } else {
21874 item++
21875 iv.writeUInt8(item, len)
21876 break
21877 }
21878 }
21879}
21880module.exports = incr32
21881
21882},{}],90:[function(require,module,exports){
21883var xor = require('buffer-xor')
21884
21885exports.encrypt = function (self, block) {
21886 var data = xor(block, self._prev)
21887
21888 self._prev = self._cipher.encryptBlock(data)
21889 return self._prev
21890}
21891
21892exports.decrypt = function (self, block) {
21893 var pad = self._prev
21894
21895 self._prev = block
21896 var out = self._cipher.decryptBlock(block)
21897
21898 return xor(out, pad)
21899}
21900
21901},{"buffer-xor":113}],91:[function(require,module,exports){
21902var Buffer = require('safe-buffer').Buffer
21903var xor = require('buffer-xor')
21904
21905function encryptStart (self, data, decrypt) {
21906 var len = data.length
21907 var out = xor(data, self._cache)
21908 self._cache = self._cache.slice(len)
21909 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
21910 return out
21911}
21912
21913exports.encrypt = function (self, data, decrypt) {
21914 var out = Buffer.allocUnsafe(0)
21915 var len
21916
21917 while (data.length) {
21918 if (self._cache.length === 0) {
21919 self._cache = self._cipher.encryptBlock(self._prev)
21920 self._prev = Buffer.allocUnsafe(0)
21921 }
21922
21923 if (self._cache.length <= data.length) {
21924 len = self._cache.length
21925 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
21926 data = data.slice(len)
21927 } else {
21928 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
21929 break
21930 }
21931 }
21932
21933 return out
21934}
21935
21936},{"buffer-xor":113,"safe-buffer":325}],92:[function(require,module,exports){
21937var Buffer = require('safe-buffer').Buffer
21938
21939function encryptByte (self, byteParam, decrypt) {
21940 var pad
21941 var i = -1
21942 var len = 8
21943 var out = 0
21944 var bit, value
21945 while (++i < len) {
21946 pad = self._cipher.encryptBlock(self._prev)
21947 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
21948 value = pad[0] ^ bit
21949 out += ((value & 0x80) >> (i % 8))
21950 self._prev = shiftIn(self._prev, decrypt ? bit : value)
21951 }
21952 return out
21953}
21954
21955function shiftIn (buffer, value) {
21956 var len = buffer.length
21957 var i = -1
21958 var out = Buffer.allocUnsafe(buffer.length)
21959 buffer = Buffer.concat([buffer, Buffer.from([value])])
21960
21961 while (++i < len) {
21962 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
21963 }
21964
21965 return out
21966}
21967
21968exports.encrypt = function (self, chunk, decrypt) {
21969 var len = chunk.length
21970 var out = Buffer.allocUnsafe(len)
21971 var i = -1
21972
21973 while (++i < len) {
21974 out[i] = encryptByte(self, chunk[i], decrypt)
21975 }
21976
21977 return out
21978}
21979
21980},{"safe-buffer":325}],93:[function(require,module,exports){
21981var Buffer = require('safe-buffer').Buffer
21982
21983function encryptByte (self, byteParam, decrypt) {
21984 var pad = self._cipher.encryptBlock(self._prev)
21985 var out = pad[0] ^ byteParam
21986
21987 self._prev = Buffer.concat([
21988 self._prev.slice(1),
21989 Buffer.from([decrypt ? byteParam : out])
21990 ])
21991
21992 return out
21993}
21994
21995exports.encrypt = function (self, chunk, decrypt) {
21996 var len = chunk.length
21997 var out = Buffer.allocUnsafe(len)
21998 var i = -1
21999
22000 while (++i < len) {
22001 out[i] = encryptByte(self, chunk[i], decrypt)
22002 }
22003
22004 return out
22005}
22006
22007},{"safe-buffer":325}],94:[function(require,module,exports){
22008var xor = require('buffer-xor')
22009var Buffer = require('safe-buffer').Buffer
22010var incr32 = require('../incr32')
22011
22012function getBlock (self) {
22013 var out = self._cipher.encryptBlockRaw(self._prev)
22014 incr32(self._prev)
22015 return out
22016}
22017
22018var blockSize = 16
22019exports.encrypt = function (self, chunk) {
22020 var chunkNum = Math.ceil(chunk.length / blockSize)
22021 var start = self._cache.length
22022 self._cache = Buffer.concat([
22023 self._cache,
22024 Buffer.allocUnsafe(chunkNum * blockSize)
22025 ])
22026 for (var i = 0; i < chunkNum; i++) {
22027 var out = getBlock(self)
22028 var offset = start + i * blockSize
22029 self._cache.writeUInt32BE(out[0], offset + 0)
22030 self._cache.writeUInt32BE(out[1], offset + 4)
22031 self._cache.writeUInt32BE(out[2], offset + 8)
22032 self._cache.writeUInt32BE(out[3], offset + 12)
22033 }
22034 var pad = self._cache.slice(0, chunk.length)
22035 self._cache = self._cache.slice(chunk.length)
22036 return xor(chunk, pad)
22037}
22038
22039},{"../incr32":89,"buffer-xor":113,"safe-buffer":325}],95:[function(require,module,exports){
22040exports.encrypt = function (self, block) {
22041 return self._cipher.encryptBlock(block)
22042}
22043
22044exports.decrypt = function (self, block) {
22045 return self._cipher.decryptBlock(block)
22046}
22047
22048},{}],96:[function(require,module,exports){
22049var modeModules = {
22050 ECB: require('./ecb'),
22051 CBC: require('./cbc'),
22052 CFB: require('./cfb'),
22053 CFB8: require('./cfb8'),
22054 CFB1: require('./cfb1'),
22055 OFB: require('./ofb'),
22056 CTR: require('./ctr'),
22057 GCM: require('./ctr')
22058}
22059
22060var modes = require('./list.json')
22061
22062for (var key in modes) {
22063 modes[key].module = modeModules[modes[key].mode]
22064}
22065
22066module.exports = modes
22067
22068},{"./cbc":90,"./cfb":91,"./cfb1":92,"./cfb8":93,"./ctr":94,"./ecb":95,"./list.json":97,"./ofb":98}],97:[function(require,module,exports){
22069module.exports={
22070 "aes-128-ecb": {
22071 "cipher": "AES",
22072 "key": 128,
22073 "iv": 0,
22074 "mode": "ECB",
22075 "type": "block"
22076 },
22077 "aes-192-ecb": {
22078 "cipher": "AES",
22079 "key": 192,
22080 "iv": 0,
22081 "mode": "ECB",
22082 "type": "block"
22083 },
22084 "aes-256-ecb": {
22085 "cipher": "AES",
22086 "key": 256,
22087 "iv": 0,
22088 "mode": "ECB",
22089 "type": "block"
22090 },
22091 "aes-128-cbc": {
22092 "cipher": "AES",
22093 "key": 128,
22094 "iv": 16,
22095 "mode": "CBC",
22096 "type": "block"
22097 },
22098 "aes-192-cbc": {
22099 "cipher": "AES",
22100 "key": 192,
22101 "iv": 16,
22102 "mode": "CBC",
22103 "type": "block"
22104 },
22105 "aes-256-cbc": {
22106 "cipher": "AES",
22107 "key": 256,
22108 "iv": 16,
22109 "mode": "CBC",
22110 "type": "block"
22111 },
22112 "aes128": {
22113 "cipher": "AES",
22114 "key": 128,
22115 "iv": 16,
22116 "mode": "CBC",
22117 "type": "block"
22118 },
22119 "aes192": {
22120 "cipher": "AES",
22121 "key": 192,
22122 "iv": 16,
22123 "mode": "CBC",
22124 "type": "block"
22125 },
22126 "aes256": {
22127 "cipher": "AES",
22128 "key": 256,
22129 "iv": 16,
22130 "mode": "CBC",
22131 "type": "block"
22132 },
22133 "aes-128-cfb": {
22134 "cipher": "AES",
22135 "key": 128,
22136 "iv": 16,
22137 "mode": "CFB",
22138 "type": "stream"
22139 },
22140 "aes-192-cfb": {
22141 "cipher": "AES",
22142 "key": 192,
22143 "iv": 16,
22144 "mode": "CFB",
22145 "type": "stream"
22146 },
22147 "aes-256-cfb": {
22148 "cipher": "AES",
22149 "key": 256,
22150 "iv": 16,
22151 "mode": "CFB",
22152 "type": "stream"
22153 },
22154 "aes-128-cfb8": {
22155 "cipher": "AES",
22156 "key": 128,
22157 "iv": 16,
22158 "mode": "CFB8",
22159 "type": "stream"
22160 },
22161 "aes-192-cfb8": {
22162 "cipher": "AES",
22163 "key": 192,
22164 "iv": 16,
22165 "mode": "CFB8",
22166 "type": "stream"
22167 },
22168 "aes-256-cfb8": {
22169 "cipher": "AES",
22170 "key": 256,
22171 "iv": 16,
22172 "mode": "CFB8",
22173 "type": "stream"
22174 },
22175 "aes-128-cfb1": {
22176 "cipher": "AES",
22177 "key": 128,
22178 "iv": 16,
22179 "mode": "CFB1",
22180 "type": "stream"
22181 },
22182 "aes-192-cfb1": {
22183 "cipher": "AES",
22184 "key": 192,
22185 "iv": 16,
22186 "mode": "CFB1",
22187 "type": "stream"
22188 },
22189 "aes-256-cfb1": {
22190 "cipher": "AES",
22191 "key": 256,
22192 "iv": 16,
22193 "mode": "CFB1",
22194 "type": "stream"
22195 },
22196 "aes-128-ofb": {
22197 "cipher": "AES",
22198 "key": 128,
22199 "iv": 16,
22200 "mode": "OFB",
22201 "type": "stream"
22202 },
22203 "aes-192-ofb": {
22204 "cipher": "AES",
22205 "key": 192,
22206 "iv": 16,
22207 "mode": "OFB",
22208 "type": "stream"
22209 },
22210 "aes-256-ofb": {
22211 "cipher": "AES",
22212 "key": 256,
22213 "iv": 16,
22214 "mode": "OFB",
22215 "type": "stream"
22216 },
22217 "aes-128-ctr": {
22218 "cipher": "AES",
22219 "key": 128,
22220 "iv": 16,
22221 "mode": "CTR",
22222 "type": "stream"
22223 },
22224 "aes-192-ctr": {
22225 "cipher": "AES",
22226 "key": 192,
22227 "iv": 16,
22228 "mode": "CTR",
22229 "type": "stream"
22230 },
22231 "aes-256-ctr": {
22232 "cipher": "AES",
22233 "key": 256,
22234 "iv": 16,
22235 "mode": "CTR",
22236 "type": "stream"
22237 },
22238 "aes-128-gcm": {
22239 "cipher": "AES",
22240 "key": 128,
22241 "iv": 12,
22242 "mode": "GCM",
22243 "type": "auth"
22244 },
22245 "aes-192-gcm": {
22246 "cipher": "AES",
22247 "key": 192,
22248 "iv": 12,
22249 "mode": "GCM",
22250 "type": "auth"
22251 },
22252 "aes-256-gcm": {
22253 "cipher": "AES",
22254 "key": 256,
22255 "iv": 12,
22256 "mode": "GCM",
22257 "type": "auth"
22258 }
22259}
22260
22261},{}],98:[function(require,module,exports){
22262(function (Buffer){
22263var xor = require('buffer-xor')
22264
22265function getBlock (self) {
22266 self._prev = self._cipher.encryptBlock(self._prev)
22267 return self._prev
22268}
22269
22270exports.encrypt = function (self, chunk) {
22271 while (self._cache.length < chunk.length) {
22272 self._cache = Buffer.concat([self._cache, getBlock(self)])
22273 }
22274
22275 var pad = self._cache.slice(0, chunk.length)
22276 self._cache = self._cache.slice(chunk.length)
22277 return xor(chunk, pad)
22278}
22279
22280}).call(this,require("buffer").Buffer)
22281},{"buffer":114,"buffer-xor":113}],99:[function(require,module,exports){
22282var aes = require('./aes')
22283var Buffer = require('safe-buffer').Buffer
22284var Transform = require('cipher-base')
22285var inherits = require('inherits')
22286
22287function StreamCipher (mode, key, iv, decrypt) {
22288 Transform.call(this)
22289
22290 this._cipher = new aes.AES(key)
22291 this._prev = Buffer.from(iv)
22292 this._cache = Buffer.allocUnsafe(0)
22293 this._secCache = Buffer.allocUnsafe(0)
22294 this._decrypt = decrypt
22295 this._mode = mode
22296}
22297
22298inherits(StreamCipher, Transform)
22299
22300StreamCipher.prototype._update = function (chunk) {
22301 return this._mode.encrypt(this, chunk, this._decrypt)
22302}
22303
22304StreamCipher.prototype._final = function () {
22305 this._cipher.scrub()
22306}
22307
22308module.exports = StreamCipher
22309
22310},{"./aes":83,"cipher-base":117,"inherits":210,"safe-buffer":325}],100:[function(require,module,exports){
22311var DES = require('browserify-des')
22312var aes = require('browserify-aes/browser')
22313var aesModes = require('browserify-aes/modes')
22314var desModes = require('browserify-des/modes')
22315var ebtk = require('evp_bytestokey')
22316
22317function createCipher (suite, password) {
22318 suite = suite.toLowerCase()
22319
22320 var keyLen, ivLen
22321 if (aesModes[suite]) {
22322 keyLen = aesModes[suite].key
22323 ivLen = aesModes[suite].iv
22324 } else if (desModes[suite]) {
22325 keyLen = desModes[suite].key * 8
22326 ivLen = desModes[suite].iv
22327 } else {
22328 throw new TypeError('invalid suite type')
22329 }
22330
22331 var keys = ebtk(password, false, keyLen, ivLen)
22332 return createCipheriv(suite, keys.key, keys.iv)
22333}
22334
22335function createDecipher (suite, password) {
22336 suite = suite.toLowerCase()
22337
22338 var keyLen, ivLen
22339 if (aesModes[suite]) {
22340 keyLen = aesModes[suite].key
22341 ivLen = aesModes[suite].iv
22342 } else if (desModes[suite]) {
22343 keyLen = desModes[suite].key * 8
22344 ivLen = desModes[suite].iv
22345 } else {
22346 throw new TypeError('invalid suite type')
22347 }
22348
22349 var keys = ebtk(password, false, keyLen, ivLen)
22350 return createDecipheriv(suite, keys.key, keys.iv)
22351}
22352
22353function createCipheriv (suite, key, iv) {
22354 suite = suite.toLowerCase()
22355 if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)
22356 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })
22357
22358 throw new TypeError('invalid suite type')
22359}
22360
22361function createDecipheriv (suite, key, iv) {
22362 suite = suite.toLowerCase()
22363 if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)
22364 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })
22365
22366 throw new TypeError('invalid suite type')
22367}
22368
22369function getCiphers () {
22370 return Object.keys(desModes).concat(aes.getCiphers())
22371}
22372
22373exports.createCipher = exports.Cipher = createCipher
22374exports.createCipheriv = exports.Cipheriv = createCipheriv
22375exports.createDecipher = exports.Decipher = createDecipher
22376exports.createDecipheriv = exports.Decipheriv = createDecipheriv
22377exports.listCiphers = exports.getCiphers = getCiphers
22378
22379},{"browserify-aes/browser":85,"browserify-aes/modes":96,"browserify-des":101,"browserify-des/modes":102,"evp_bytestokey":160}],101:[function(require,module,exports){
22380var CipherBase = require('cipher-base')
22381var des = require('des.js')
22382var inherits = require('inherits')
22383var Buffer = require('safe-buffer').Buffer
22384
22385var modes = {
22386 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
22387 'des-ede3': des.EDE,
22388 'des-ede-cbc': des.CBC.instantiate(des.EDE),
22389 'des-ede': des.EDE,
22390 'des-cbc': des.CBC.instantiate(des.DES),
22391 'des-ecb': des.DES
22392}
22393modes.des = modes['des-cbc']
22394modes.des3 = modes['des-ede3-cbc']
22395module.exports = DES
22396inherits(DES, CipherBase)
22397function DES (opts) {
22398 CipherBase.call(this)
22399 var modeName = opts.mode.toLowerCase()
22400 var mode = modes[modeName]
22401 var type
22402 if (opts.decrypt) {
22403 type = 'decrypt'
22404 } else {
22405 type = 'encrypt'
22406 }
22407 var key = opts.key
22408 if (!Buffer.isBuffer(key)) {
22409 key = Buffer.from(key)
22410 }
22411 if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
22412 key = Buffer.concat([key, key.slice(0, 8)])
22413 }
22414 var iv = opts.iv
22415 if (!Buffer.isBuffer(iv)) {
22416 iv = Buffer.from(iv)
22417 }
22418 this._des = mode.create({
22419 key: key,
22420 iv: iv,
22421 type: type
22422 })
22423}
22424DES.prototype._update = function (data) {
22425 return Buffer.from(this._des.update(data))
22426}
22427DES.prototype._final = function () {
22428 return Buffer.from(this._des.final())
22429}
22430
22431},{"cipher-base":117,"des.js":128,"inherits":210,"safe-buffer":325}],102:[function(require,module,exports){
22432exports['des-ecb'] = {
22433 key: 8,
22434 iv: 0
22435}
22436exports['des-cbc'] = exports.des = {
22437 key: 8,
22438 iv: 8
22439}
22440exports['des-ede3-cbc'] = exports.des3 = {
22441 key: 24,
22442 iv: 8
22443}
22444exports['des-ede3'] = {
22445 key: 24,
22446 iv: 0
22447}
22448exports['des-ede-cbc'] = {
22449 key: 16,
22450 iv: 8
22451}
22452exports['des-ede'] = {
22453 key: 16,
22454 iv: 0
22455}
22456
22457},{}],103:[function(require,module,exports){
22458(function (Buffer){
22459var bn = require('bn.js');
22460var randomBytes = require('randombytes');
22461module.exports = crt;
22462function blind(priv) {
22463 var r = getr(priv);
22464 var blinder = r.toRed(bn.mont(priv.modulus))
22465 .redPow(new bn(priv.publicExponent)).fromRed();
22466 return {
22467 blinder: blinder,
22468 unblinder:r.invm(priv.modulus)
22469 };
22470}
22471function crt(msg, priv) {
22472 var blinds = blind(priv);
22473 var len = priv.modulus.byteLength();
22474 var mod = bn.mont(priv.modulus);
22475 var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
22476 var c1 = blinded.toRed(bn.mont(priv.prime1));
22477 var c2 = blinded.toRed(bn.mont(priv.prime2));
22478 var qinv = priv.coefficient;
22479 var p = priv.prime1;
22480 var q = priv.prime2;
22481 var m1 = c1.redPow(priv.exponent1);
22482 var m2 = c2.redPow(priv.exponent2);
22483 m1 = m1.fromRed();
22484 m2 = m2.fromRed();
22485 var h = m1.isub(m2).imul(qinv).umod(p);
22486 h.imul(q);
22487 m2.iadd(h);
22488 return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
22489}
22490crt.getr = getr;
22491function getr(priv) {
22492 var len = priv.modulus.byteLength();
22493 var r = new bn(randomBytes(len));
22494 while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
22495 r = new bn(randomBytes(len));
22496 }
22497 return r;
22498}
22499
22500}).call(this,require("buffer").Buffer)
22501},{"bn.js":80,"buffer":114,"randombytes":278}],104:[function(require,module,exports){
22502module.exports = require('./browser/algorithms.json')
22503
22504},{"./browser/algorithms.json":105}],105:[function(require,module,exports){
22505module.exports={
22506 "sha224WithRSAEncryption": {
22507 "sign": "rsa",
22508 "hash": "sha224",
22509 "id": "302d300d06096086480165030402040500041c"
22510 },
22511 "RSA-SHA224": {
22512 "sign": "ecdsa/rsa",
22513 "hash": "sha224",
22514 "id": "302d300d06096086480165030402040500041c"
22515 },
22516 "sha256WithRSAEncryption": {
22517 "sign": "rsa",
22518 "hash": "sha256",
22519 "id": "3031300d060960864801650304020105000420"
22520 },
22521 "RSA-SHA256": {
22522 "sign": "ecdsa/rsa",
22523 "hash": "sha256",
22524 "id": "3031300d060960864801650304020105000420"
22525 },
22526 "sha384WithRSAEncryption": {
22527 "sign": "rsa",
22528 "hash": "sha384",
22529 "id": "3041300d060960864801650304020205000430"
22530 },
22531 "RSA-SHA384": {
22532 "sign": "ecdsa/rsa",
22533 "hash": "sha384",
22534 "id": "3041300d060960864801650304020205000430"
22535 },
22536 "sha512WithRSAEncryption": {
22537 "sign": "rsa",
22538 "hash": "sha512",
22539 "id": "3051300d060960864801650304020305000440"
22540 },
22541 "RSA-SHA512": {
22542 "sign": "ecdsa/rsa",
22543 "hash": "sha512",
22544 "id": "3051300d060960864801650304020305000440"
22545 },
22546 "RSA-SHA1": {
22547 "sign": "rsa",
22548 "hash": "sha1",
22549 "id": "3021300906052b0e03021a05000414"
22550 },
22551 "ecdsa-with-SHA1": {
22552 "sign": "ecdsa",
22553 "hash": "sha1",
22554 "id": ""
22555 },
22556 "sha256": {
22557 "sign": "ecdsa",
22558 "hash": "sha256",
22559 "id": ""
22560 },
22561 "sha224": {
22562 "sign": "ecdsa",
22563 "hash": "sha224",
22564 "id": ""
22565 },
22566 "sha384": {
22567 "sign": "ecdsa",
22568 "hash": "sha384",
22569 "id": ""
22570 },
22571 "sha512": {
22572 "sign": "ecdsa",
22573 "hash": "sha512",
22574 "id": ""
22575 },
22576 "DSA-SHA": {
22577 "sign": "dsa",
22578 "hash": "sha1",
22579 "id": ""
22580 },
22581 "DSA-SHA1": {
22582 "sign": "dsa",
22583 "hash": "sha1",
22584 "id": ""
22585 },
22586 "DSA": {
22587 "sign": "dsa",
22588 "hash": "sha1",
22589 "id": ""
22590 },
22591 "DSA-WITH-SHA224": {
22592 "sign": "dsa",
22593 "hash": "sha224",
22594 "id": ""
22595 },
22596 "DSA-SHA224": {
22597 "sign": "dsa",
22598 "hash": "sha224",
22599 "id": ""
22600 },
22601 "DSA-WITH-SHA256": {
22602 "sign": "dsa",
22603 "hash": "sha256",
22604 "id": ""
22605 },
22606 "DSA-SHA256": {
22607 "sign": "dsa",
22608 "hash": "sha256",
22609 "id": ""
22610 },
22611 "DSA-WITH-SHA384": {
22612 "sign": "dsa",
22613 "hash": "sha384",
22614 "id": ""
22615 },
22616 "DSA-SHA384": {
22617 "sign": "dsa",
22618 "hash": "sha384",
22619 "id": ""
22620 },
22621 "DSA-WITH-SHA512": {
22622 "sign": "dsa",
22623 "hash": "sha512",
22624 "id": ""
22625 },
22626 "DSA-SHA512": {
22627 "sign": "dsa",
22628 "hash": "sha512",
22629 "id": ""
22630 },
22631 "DSA-RIPEMD160": {
22632 "sign": "dsa",
22633 "hash": "rmd160",
22634 "id": ""
22635 },
22636 "ripemd160WithRSA": {
22637 "sign": "rsa",
22638 "hash": "rmd160",
22639 "id": "3021300906052b2403020105000414"
22640 },
22641 "RSA-RIPEMD160": {
22642 "sign": "rsa",
22643 "hash": "rmd160",
22644 "id": "3021300906052b2403020105000414"
22645 },
22646 "md5WithRSAEncryption": {
22647 "sign": "rsa",
22648 "hash": "md5",
22649 "id": "3020300c06082a864886f70d020505000410"
22650 },
22651 "RSA-MD5": {
22652 "sign": "rsa",
22653 "hash": "md5",
22654 "id": "3020300c06082a864886f70d020505000410"
22655 }
22656}
22657
22658},{}],106:[function(require,module,exports){
22659module.exports={
22660 "1.3.132.0.10": "secp256k1",
22661 "1.3.132.0.33": "p224",
22662 "1.2.840.10045.3.1.1": "p192",
22663 "1.2.840.10045.3.1.7": "p256",
22664 "1.3.132.0.34": "p384",
22665 "1.3.132.0.35": "p521"
22666}
22667
22668},{}],107:[function(require,module,exports){
22669(function (Buffer){
22670var createHash = require('create-hash')
22671var stream = require('stream')
22672var inherits = require('inherits')
22673var sign = require('./sign')
22674var verify = require('./verify')
22675
22676var algorithms = require('./algorithms.json')
22677Object.keys(algorithms).forEach(function (key) {
22678 algorithms[key].id = new Buffer(algorithms[key].id, 'hex')
22679 algorithms[key.toLowerCase()] = algorithms[key]
22680})
22681
22682function Sign (algorithm) {
22683 stream.Writable.call(this)
22684
22685 var data = algorithms[algorithm]
22686 if (!data) throw new Error('Unknown message digest')
22687
22688 this._hashType = data.hash
22689 this._hash = createHash(data.hash)
22690 this._tag = data.id
22691 this._signType = data.sign
22692}
22693inherits(Sign, stream.Writable)
22694
22695Sign.prototype._write = function _write (data, _, done) {
22696 this._hash.update(data)
22697 done()
22698}
22699
22700Sign.prototype.update = function update (data, enc) {
22701 if (typeof data === 'string') data = new Buffer(data, enc)
22702
22703 this._hash.update(data)
22704 return this
22705}
22706
22707Sign.prototype.sign = function signMethod (key, enc) {
22708 this.end()
22709 var hash = this._hash.digest()
22710 var sig = sign(hash, key, this._hashType, this._signType, this._tag)
22711
22712 return enc ? sig.toString(enc) : sig
22713}
22714
22715function Verify (algorithm) {
22716 stream.Writable.call(this)
22717
22718 var data = algorithms[algorithm]
22719 if (!data) throw new Error('Unknown message digest')
22720
22721 this._hash = createHash(data.hash)
22722 this._tag = data.id
22723 this._signType = data.sign
22724}
22725inherits(Verify, stream.Writable)
22726
22727Verify.prototype._write = function _write (data, _, done) {
22728 this._hash.update(data)
22729 done()
22730}
22731
22732Verify.prototype.update = function update (data, enc) {
22733 if (typeof data === 'string') data = new Buffer(data, enc)
22734
22735 this._hash.update(data)
22736 return this
22737}
22738
22739Verify.prototype.verify = function verifyMethod (key, sig, enc) {
22740 if (typeof sig === 'string') sig = new Buffer(sig, enc)
22741
22742 this.end()
22743 var hash = this._hash.digest()
22744 return verify(sig, hash, key, this._signType, this._tag)
22745}
22746
22747function createSign (algorithm) {
22748 return new Sign(algorithm)
22749}
22750
22751function createVerify (algorithm) {
22752 return new Verify(algorithm)
22753}
22754
22755module.exports = {
22756 Sign: createSign,
22757 Verify: createVerify,
22758 createSign: createSign,
22759 createVerify: createVerify
22760}
22761
22762}).call(this,require("buffer").Buffer)
22763},{"./algorithms.json":105,"./sign":108,"./verify":109,"buffer":114,"create-hash":122,"inherits":210,"stream":361}],108:[function(require,module,exports){
22764(function (Buffer){
22765// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
22766var createHmac = require('create-hmac')
22767var crt = require('browserify-rsa')
22768var EC = require('elliptic').ec
22769var BN = require('bn.js')
22770var parseKeys = require('parse-asn1')
22771var curves = require('./curves.json')
22772
22773function sign (hash, key, hashType, signType, tag) {
22774 var priv = parseKeys(key)
22775 if (priv.curve) {
22776 // rsa keys can be interpreted as ecdsa ones in openssl
22777 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
22778 return ecSign(hash, priv)
22779 } else if (priv.type === 'dsa') {
22780 if (signType !== 'dsa') throw new Error('wrong private key type')
22781 return dsaSign(hash, priv, hashType)
22782 } else {
22783 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
22784 }
22785 hash = Buffer.concat([tag, hash])
22786 var len = priv.modulus.byteLength()
22787 var pad = [ 0, 1 ]
22788 while (hash.length + pad.length + 1 < len) pad.push(0xff)
22789 pad.push(0x00)
22790 var i = -1
22791 while (++i < hash.length) pad.push(hash[i])
22792
22793 var out = crt(pad, priv)
22794 return out
22795}
22796
22797function ecSign (hash, priv) {
22798 var curveId = curves[priv.curve.join('.')]
22799 if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
22800
22801 var curve = new EC(curveId)
22802 var key = curve.keyFromPrivate(priv.privateKey)
22803 var out = key.sign(hash)
22804
22805 return new Buffer(out.toDER())
22806}
22807
22808function dsaSign (hash, priv, algo) {
22809 var x = priv.params.priv_key
22810 var p = priv.params.p
22811 var q = priv.params.q
22812 var g = priv.params.g
22813 var r = new BN(0)
22814 var k
22815 var H = bits2int(hash, q).mod(q)
22816 var s = false
22817 var kv = getKey(x, q, hash, algo)
22818 while (s === false) {
22819 k = makeKey(q, kv, algo)
22820 r = makeR(g, k, p, q)
22821 s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
22822 if (s.cmpn(0) === 0) {
22823 s = false
22824 r = new BN(0)
22825 }
22826 }
22827 return toDER(r, s)
22828}
22829
22830function toDER (r, s) {
22831 r = r.toArray()
22832 s = s.toArray()
22833
22834 // Pad values
22835 if (r[0] & 0x80) r = [ 0 ].concat(r)
22836 if (s[0] & 0x80) s = [ 0 ].concat(s)
22837
22838 var total = r.length + s.length + 4
22839 var res = [ 0x30, total, 0x02, r.length ]
22840 res = res.concat(r, [ 0x02, s.length ], s)
22841 return new Buffer(res)
22842}
22843
22844function getKey (x, q, hash, algo) {
22845 x = new Buffer(x.toArray())
22846 if (x.length < q.byteLength()) {
22847 var zeros = new Buffer(q.byteLength() - x.length)
22848 zeros.fill(0)
22849 x = Buffer.concat([ zeros, x ])
22850 }
22851 var hlen = hash.length
22852 var hbits = bits2octets(hash, q)
22853 var v = new Buffer(hlen)
22854 v.fill(1)
22855 var k = new Buffer(hlen)
22856 k.fill(0)
22857 k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest()
22858 v = createHmac(algo, k).update(v).digest()
22859 k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest()
22860 v = createHmac(algo, k).update(v).digest()
22861 return { k: k, v: v }
22862}
22863
22864function bits2int (obits, q) {
22865 var bits = new BN(obits)
22866 var shift = (obits.length << 3) - q.bitLength()
22867 if (shift > 0) bits.ishrn(shift)
22868 return bits
22869}
22870
22871function bits2octets (bits, q) {
22872 bits = bits2int(bits, q)
22873 bits = bits.mod(q)
22874 var out = new Buffer(bits.toArray())
22875 if (out.length < q.byteLength()) {
22876 var zeros = new Buffer(q.byteLength() - out.length)
22877 zeros.fill(0)
22878 out = Buffer.concat([ zeros, out ])
22879 }
22880 return out
22881}
22882
22883function makeKey (q, kv, algo) {
22884 var t
22885 var k
22886
22887 do {
22888 t = new Buffer(0)
22889
22890 while (t.length * 8 < q.bitLength()) {
22891 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
22892 t = Buffer.concat([ t, kv.v ])
22893 }
22894
22895 k = bits2int(t, q)
22896 kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest()
22897 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
22898 } while (k.cmp(q) !== -1)
22899
22900 return k
22901}
22902
22903function makeR (g, k, p, q) {
22904 return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
22905}
22906
22907module.exports = sign
22908module.exports.getKey = getKey
22909module.exports.makeKey = makeKey
22910
22911}).call(this,require("buffer").Buffer)
22912},{"./curves.json":106,"bn.js":80,"browserify-rsa":103,"buffer":114,"create-hmac":124,"elliptic":142,"parse-asn1":256}],109:[function(require,module,exports){
22913(function (Buffer){
22914// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
22915var BN = require('bn.js')
22916var EC = require('elliptic').ec
22917var parseKeys = require('parse-asn1')
22918var curves = require('./curves.json')
22919
22920function verify (sig, hash, key, signType, tag) {
22921 var pub = parseKeys(key)
22922 if (pub.type === 'ec') {
22923 // rsa keys can be interpreted as ecdsa ones in openssl
22924 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
22925 return ecVerify(sig, hash, pub)
22926 } else if (pub.type === 'dsa') {
22927 if (signType !== 'dsa') throw new Error('wrong public key type')
22928 return dsaVerify(sig, hash, pub)
22929 } else {
22930 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
22931 }
22932 hash = Buffer.concat([tag, hash])
22933 var len = pub.modulus.byteLength()
22934 var pad = [ 1 ]
22935 var padNum = 0
22936 while (hash.length + pad.length + 2 < len) {
22937 pad.push(0xff)
22938 padNum++
22939 }
22940 pad.push(0x00)
22941 var i = -1
22942 while (++i < hash.length) {
22943 pad.push(hash[i])
22944 }
22945 pad = new Buffer(pad)
22946 var red = BN.mont(pub.modulus)
22947 sig = new BN(sig).toRed(red)
22948
22949 sig = sig.redPow(new BN(pub.publicExponent))
22950 sig = new Buffer(sig.fromRed().toArray())
22951 var out = padNum < 8 ? 1 : 0
22952 len = Math.min(sig.length, pad.length)
22953 if (sig.length !== pad.length) out = 1
22954
22955 i = -1
22956 while (++i < len) out |= sig[i] ^ pad[i]
22957 return out === 0
22958}
22959
22960function ecVerify (sig, hash, pub) {
22961 var curveId = curves[pub.data.algorithm.curve.join('.')]
22962 if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
22963
22964 var curve = new EC(curveId)
22965 var pubkey = pub.data.subjectPrivateKey.data
22966
22967 return curve.verify(hash, sig, pubkey)
22968}
22969
22970function dsaVerify (sig, hash, pub) {
22971 var p = pub.data.p
22972 var q = pub.data.q
22973 var g = pub.data.g
22974 var y = pub.data.pub_key
22975 var unpacked = parseKeys.signature.decode(sig, 'der')
22976 var s = unpacked.s
22977 var r = unpacked.r
22978 checkValue(s, q)
22979 checkValue(r, q)
22980 var montp = BN.mont(p)
22981 var w = s.invm(q)
22982 var v = g.toRed(montp)
22983 .redPow(new BN(hash).mul(w).mod(q))
22984 .fromRed()
22985 .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
22986 .mod(p)
22987 .mod(q)
22988 return v.cmp(r) === 0
22989}
22990
22991function checkValue (b, q) {
22992 if (b.cmpn(0) <= 0) throw new Error('invalid sig')
22993 if (b.cmp(q) >= q) throw new Error('invalid sig')
22994}
22995
22996module.exports = verify
22997
22998}).call(this,require("buffer").Buffer)
22999},{"./curves.json":106,"bn.js":80,"buffer":114,"elliptic":142,"parse-asn1":256}],110:[function(require,module,exports){
23000(function (process,Buffer){
23001'use strict';
23002/* eslint camelcase: "off" */
23003
23004var assert = require('assert');
23005
23006var Zstream = require('pako/lib/zlib/zstream');
23007var zlib_deflate = require('pako/lib/zlib/deflate.js');
23008var zlib_inflate = require('pako/lib/zlib/inflate.js');
23009var constants = require('pako/lib/zlib/constants');
23010
23011for (var key in constants) {
23012 exports[key] = constants[key];
23013}
23014
23015// zlib modes
23016exports.NONE = 0;
23017exports.DEFLATE = 1;
23018exports.INFLATE = 2;
23019exports.GZIP = 3;
23020exports.GUNZIP = 4;
23021exports.DEFLATERAW = 5;
23022exports.INFLATERAW = 6;
23023exports.UNZIP = 7;
23024
23025var GZIP_HEADER_ID1 = 0x1f;
23026var GZIP_HEADER_ID2 = 0x8b;
23027
23028/**
23029 * Emulate Node's zlib C++ layer for use by the JS layer in index.js
23030 */
23031function Zlib(mode) {
23032 if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
23033 throw new TypeError('Bad argument');
23034 }
23035
23036 this.dictionary = null;
23037 this.err = 0;
23038 this.flush = 0;
23039 this.init_done = false;
23040 this.level = 0;
23041 this.memLevel = 0;
23042 this.mode = mode;
23043 this.strategy = 0;
23044 this.windowBits = 0;
23045 this.write_in_progress = false;
23046 this.pending_close = false;
23047 this.gzip_id_bytes_read = 0;
23048}
23049
23050Zlib.prototype.close = function () {
23051 if (this.write_in_progress) {
23052 this.pending_close = true;
23053 return;
23054 }
23055
23056 this.pending_close = false;
23057
23058 assert(this.init_done, 'close before init');
23059 assert(this.mode <= exports.UNZIP);
23060
23061 if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
23062 zlib_deflate.deflateEnd(this.strm);
23063 } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
23064 zlib_inflate.inflateEnd(this.strm);
23065 }
23066
23067 this.mode = exports.NONE;
23068
23069 this.dictionary = null;
23070};
23071
23072Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
23073 return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
23074};
23075
23076Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
23077 return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
23078};
23079
23080Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
23081 assert.equal(arguments.length, 8);
23082
23083 assert(this.init_done, 'write before init');
23084 assert(this.mode !== exports.NONE, 'already finalized');
23085 assert.equal(false, this.write_in_progress, 'write already in progress');
23086 assert.equal(false, this.pending_close, 'close is pending');
23087
23088 this.write_in_progress = true;
23089
23090 assert.equal(false, flush === undefined, 'must provide flush value');
23091
23092 this.write_in_progress = true;
23093
23094 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) {
23095 throw new Error('Invalid flush value');
23096 }
23097
23098 if (input == null) {
23099 input = Buffer.alloc(0);
23100 in_len = 0;
23101 in_off = 0;
23102 }
23103
23104 this.strm.avail_in = in_len;
23105 this.strm.input = input;
23106 this.strm.next_in = in_off;
23107 this.strm.avail_out = out_len;
23108 this.strm.output = out;
23109 this.strm.next_out = out_off;
23110 this.flush = flush;
23111
23112 if (!async) {
23113 // sync version
23114 this._process();
23115
23116 if (this._checkError()) {
23117 return this._afterSync();
23118 }
23119 return;
23120 }
23121
23122 // async version
23123 var self = this;
23124 process.nextTick(function () {
23125 self._process();
23126 self._after();
23127 });
23128
23129 return this;
23130};
23131
23132Zlib.prototype._afterSync = function () {
23133 var avail_out = this.strm.avail_out;
23134 var avail_in = this.strm.avail_in;
23135
23136 this.write_in_progress = false;
23137
23138 return [avail_in, avail_out];
23139};
23140
23141Zlib.prototype._process = function () {
23142 var next_expected_header_byte = null;
23143
23144 // If the avail_out is left at 0, then it means that it ran out
23145 // of room. If there was avail_out left over, then it means
23146 // that all of the input was consumed.
23147 switch (this.mode) {
23148 case exports.DEFLATE:
23149 case exports.GZIP:
23150 case exports.DEFLATERAW:
23151 this.err = zlib_deflate.deflate(this.strm, this.flush);
23152 break;
23153 case exports.UNZIP:
23154 if (this.strm.avail_in > 0) {
23155 next_expected_header_byte = this.strm.next_in;
23156 }
23157
23158 switch (this.gzip_id_bytes_read) {
23159 case 0:
23160 if (next_expected_header_byte === null) {
23161 break;
23162 }
23163
23164 if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
23165 this.gzip_id_bytes_read = 1;
23166 next_expected_header_byte++;
23167
23168 if (this.strm.avail_in === 1) {
23169 // The only available byte was already read.
23170 break;
23171 }
23172 } else {
23173 this.mode = exports.INFLATE;
23174 break;
23175 }
23176
23177 // fallthrough
23178 case 1:
23179 if (next_expected_header_byte === null) {
23180 break;
23181 }
23182
23183 if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
23184 this.gzip_id_bytes_read = 2;
23185 this.mode = exports.GUNZIP;
23186 } else {
23187 // There is no actual difference between INFLATE and INFLATERAW
23188 // (after initialization).
23189 this.mode = exports.INFLATE;
23190 }
23191
23192 break;
23193 default:
23194 throw new Error('invalid number of gzip magic number bytes read');
23195 }
23196
23197 // fallthrough
23198 case exports.INFLATE:
23199 case exports.GUNZIP:
23200 case exports.INFLATERAW:
23201 this.err = zlib_inflate.inflate(this.strm, this.flush
23202
23203 // If data was encoded with dictionary
23204 );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
23205 // Load it
23206 this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
23207 if (this.err === exports.Z_OK) {
23208 // And try to decode again
23209 this.err = zlib_inflate.inflate(this.strm, this.flush);
23210 } else if (this.err === exports.Z_DATA_ERROR) {
23211 // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
23212 // Make it possible for After() to tell a bad dictionary from bad
23213 // input.
23214 this.err = exports.Z_NEED_DICT;
23215 }
23216 }
23217 while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
23218 // Bytes remain in input buffer. Perhaps this is another compressed
23219 // member in the same archive, or just trailing garbage.
23220 // Trailing zero bytes are okay, though, since they are frequently
23221 // used for padding.
23222
23223 this.reset();
23224 this.err = zlib_inflate.inflate(this.strm, this.flush);
23225 }
23226 break;
23227 default:
23228 throw new Error('Unknown mode ' + this.mode);
23229 }
23230};
23231
23232Zlib.prototype._checkError = function () {
23233 // Acceptable error states depend on the type of zlib stream.
23234 switch (this.err) {
23235 case exports.Z_OK:
23236 case exports.Z_BUF_ERROR:
23237 if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
23238 this._error('unexpected end of file');
23239 return false;
23240 }
23241 break;
23242 case exports.Z_STREAM_END:
23243 // normal statuses, not fatal
23244 break;
23245 case exports.Z_NEED_DICT:
23246 if (this.dictionary == null) {
23247 this._error('Missing dictionary');
23248 } else {
23249 this._error('Bad dictionary');
23250 }
23251 return false;
23252 default:
23253 // something else.
23254 this._error('Zlib error');
23255 return false;
23256 }
23257
23258 return true;
23259};
23260
23261Zlib.prototype._after = function () {
23262 if (!this._checkError()) {
23263 return;
23264 }
23265
23266 var avail_out = this.strm.avail_out;
23267 var avail_in = this.strm.avail_in;
23268
23269 this.write_in_progress = false;
23270
23271 // call the write() cb
23272 this.callback(avail_in, avail_out);
23273
23274 if (this.pending_close) {
23275 this.close();
23276 }
23277};
23278
23279Zlib.prototype._error = function (message) {
23280 if (this.strm.msg) {
23281 message = this.strm.msg;
23282 }
23283 this.onerror(message, this.err
23284
23285 // no hope of rescue.
23286 );this.write_in_progress = false;
23287 if (this.pending_close) {
23288 this.close();
23289 }
23290};
23291
23292Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
23293 assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
23294
23295 assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
23296 assert(level >= -1 && level <= 9, 'invalid compression level');
23297
23298 assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
23299
23300 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');
23301
23302 this._init(level, windowBits, memLevel, strategy, dictionary);
23303 this._setDictionary();
23304};
23305
23306Zlib.prototype.params = function () {
23307 throw new Error('deflateParams Not supported');
23308};
23309
23310Zlib.prototype.reset = function () {
23311 this._reset();
23312 this._setDictionary();
23313};
23314
23315Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
23316 this.level = level;
23317 this.windowBits = windowBits;
23318 this.memLevel = memLevel;
23319 this.strategy = strategy;
23320
23321 this.flush = exports.Z_NO_FLUSH;
23322
23323 this.err = exports.Z_OK;
23324
23325 if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
23326 this.windowBits += 16;
23327 }
23328
23329 if (this.mode === exports.UNZIP) {
23330 this.windowBits += 32;
23331 }
23332
23333 if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
23334 this.windowBits = -1 * this.windowBits;
23335 }
23336
23337 this.strm = new Zstream();
23338
23339 switch (this.mode) {
23340 case exports.DEFLATE:
23341 case exports.GZIP:
23342 case exports.DEFLATERAW:
23343 this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
23344 break;
23345 case exports.INFLATE:
23346 case exports.GUNZIP:
23347 case exports.INFLATERAW:
23348 case exports.UNZIP:
23349 this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
23350 break;
23351 default:
23352 throw new Error('Unknown mode ' + this.mode);
23353 }
23354
23355 if (this.err !== exports.Z_OK) {
23356 this._error('Init error');
23357 }
23358
23359 this.dictionary = dictionary;
23360
23361 this.write_in_progress = false;
23362 this.init_done = true;
23363};
23364
23365Zlib.prototype._setDictionary = function () {
23366 if (this.dictionary == null) {
23367 return;
23368 }
23369
23370 this.err = exports.Z_OK;
23371
23372 switch (this.mode) {
23373 case exports.DEFLATE:
23374 case exports.DEFLATERAW:
23375 this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
23376 break;
23377 default:
23378 break;
23379 }
23380
23381 if (this.err !== exports.Z_OK) {
23382 this._error('Failed to set dictionary');
23383 }
23384};
23385
23386Zlib.prototype._reset = function () {
23387 this.err = exports.Z_OK;
23388
23389 switch (this.mode) {
23390 case exports.DEFLATE:
23391 case exports.DEFLATERAW:
23392 case exports.GZIP:
23393 this.err = zlib_deflate.deflateReset(this.strm);
23394 break;
23395 case exports.INFLATE:
23396 case exports.INFLATERAW:
23397 case exports.GUNZIP:
23398 this.err = zlib_inflate.inflateReset(this.strm);
23399 break;
23400 default:
23401 break;
23402 }
23403
23404 if (this.err !== exports.Z_OK) {
23405 this._error('Failed to reset stream');
23406 }
23407};
23408
23409exports.Zlib = Zlib;
23410}).call(this,require('_process'),require("buffer").Buffer)
23411},{"_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){
23412(function (process){
23413'use strict';
23414
23415var Buffer = require('buffer').Buffer;
23416var Transform = require('stream').Transform;
23417var binding = require('./binding');
23418var util = require('util');
23419var assert = require('assert').ok;
23420var kMaxLength = require('buffer').kMaxLength;
23421var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
23422
23423// zlib doesn't provide these, so kludge them in following the same
23424// const naming scheme zlib uses.
23425binding.Z_MIN_WINDOWBITS = 8;
23426binding.Z_MAX_WINDOWBITS = 15;
23427binding.Z_DEFAULT_WINDOWBITS = 15;
23428
23429// fewer than 64 bytes per chunk is stupid.
23430// technically it could work with as few as 8, but even 64 bytes
23431// is absurdly low. Usually a MB or more is best.
23432binding.Z_MIN_CHUNK = 64;
23433binding.Z_MAX_CHUNK = Infinity;
23434binding.Z_DEFAULT_CHUNK = 16 * 1024;
23435
23436binding.Z_MIN_MEMLEVEL = 1;
23437binding.Z_MAX_MEMLEVEL = 9;
23438binding.Z_DEFAULT_MEMLEVEL = 8;
23439
23440binding.Z_MIN_LEVEL = -1;
23441binding.Z_MAX_LEVEL = 9;
23442binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
23443
23444// expose all the zlib constants
23445var bkeys = Object.keys(binding);
23446for (var bk = 0; bk < bkeys.length; bk++) {
23447 var bkey = bkeys[bk];
23448 if (bkey.match(/^Z/)) {
23449 Object.defineProperty(exports, bkey, {
23450 enumerable: true, value: binding[bkey], writable: false
23451 });
23452 }
23453}
23454
23455// translation table for return codes.
23456var codes = {
23457 Z_OK: binding.Z_OK,
23458 Z_STREAM_END: binding.Z_STREAM_END,
23459 Z_NEED_DICT: binding.Z_NEED_DICT,
23460 Z_ERRNO: binding.Z_ERRNO,
23461 Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
23462 Z_DATA_ERROR: binding.Z_DATA_ERROR,
23463 Z_MEM_ERROR: binding.Z_MEM_ERROR,
23464 Z_BUF_ERROR: binding.Z_BUF_ERROR,
23465 Z_VERSION_ERROR: binding.Z_VERSION_ERROR
23466};
23467
23468var ckeys = Object.keys(codes);
23469for (var ck = 0; ck < ckeys.length; ck++) {
23470 var ckey = ckeys[ck];
23471 codes[codes[ckey]] = ckey;
23472}
23473
23474Object.defineProperty(exports, 'codes', {
23475 enumerable: true, value: Object.freeze(codes), writable: false
23476});
23477
23478exports.Deflate = Deflate;
23479exports.Inflate = Inflate;
23480exports.Gzip = Gzip;
23481exports.Gunzip = Gunzip;
23482exports.DeflateRaw = DeflateRaw;
23483exports.InflateRaw = InflateRaw;
23484exports.Unzip = Unzip;
23485
23486exports.createDeflate = function (o) {
23487 return new Deflate(o);
23488};
23489
23490exports.createInflate = function (o) {
23491 return new Inflate(o);
23492};
23493
23494exports.createDeflateRaw = function (o) {
23495 return new DeflateRaw(o);
23496};
23497
23498exports.createInflateRaw = function (o) {
23499 return new InflateRaw(o);
23500};
23501
23502exports.createGzip = function (o) {
23503 return new Gzip(o);
23504};
23505
23506exports.createGunzip = function (o) {
23507 return new Gunzip(o);
23508};
23509
23510exports.createUnzip = function (o) {
23511 return new Unzip(o);
23512};
23513
23514// Convenience methods.
23515// compress/decompress a string or buffer in one step.
23516exports.deflate = function (buffer, opts, callback) {
23517 if (typeof opts === 'function') {
23518 callback = opts;
23519 opts = {};
23520 }
23521 return zlibBuffer(new Deflate(opts), buffer, callback);
23522};
23523
23524exports.deflateSync = function (buffer, opts) {
23525 return zlibBufferSync(new Deflate(opts), buffer);
23526};
23527
23528exports.gzip = function (buffer, opts, callback) {
23529 if (typeof opts === 'function') {
23530 callback = opts;
23531 opts = {};
23532 }
23533 return zlibBuffer(new Gzip(opts), buffer, callback);
23534};
23535
23536exports.gzipSync = function (buffer, opts) {
23537 return zlibBufferSync(new Gzip(opts), buffer);
23538};
23539
23540exports.deflateRaw = function (buffer, opts, callback) {
23541 if (typeof opts === 'function') {
23542 callback = opts;
23543 opts = {};
23544 }
23545 return zlibBuffer(new DeflateRaw(opts), buffer, callback);
23546};
23547
23548exports.deflateRawSync = function (buffer, opts) {
23549 return zlibBufferSync(new DeflateRaw(opts), buffer);
23550};
23551
23552exports.unzip = function (buffer, opts, callback) {
23553 if (typeof opts === 'function') {
23554 callback = opts;
23555 opts = {};
23556 }
23557 return zlibBuffer(new Unzip(opts), buffer, callback);
23558};
23559
23560exports.unzipSync = function (buffer, opts) {
23561 return zlibBufferSync(new Unzip(opts), buffer);
23562};
23563
23564exports.inflate = function (buffer, opts, callback) {
23565 if (typeof opts === 'function') {
23566 callback = opts;
23567 opts = {};
23568 }
23569 return zlibBuffer(new Inflate(opts), buffer, callback);
23570};
23571
23572exports.inflateSync = function (buffer, opts) {
23573 return zlibBufferSync(new Inflate(opts), buffer);
23574};
23575
23576exports.gunzip = function (buffer, opts, callback) {
23577 if (typeof opts === 'function') {
23578 callback = opts;
23579 opts = {};
23580 }
23581 return zlibBuffer(new Gunzip(opts), buffer, callback);
23582};
23583
23584exports.gunzipSync = function (buffer, opts) {
23585 return zlibBufferSync(new Gunzip(opts), buffer);
23586};
23587
23588exports.inflateRaw = function (buffer, opts, callback) {
23589 if (typeof opts === 'function') {
23590 callback = opts;
23591 opts = {};
23592 }
23593 return zlibBuffer(new InflateRaw(opts), buffer, callback);
23594};
23595
23596exports.inflateRawSync = function (buffer, opts) {
23597 return zlibBufferSync(new InflateRaw(opts), buffer);
23598};
23599
23600function zlibBuffer(engine, buffer, callback) {
23601 var buffers = [];
23602 var nread = 0;
23603
23604 engine.on('error', onError);
23605 engine.on('end', onEnd);
23606
23607 engine.end(buffer);
23608 flow();
23609
23610 function flow() {
23611 var chunk;
23612 while (null !== (chunk = engine.read())) {
23613 buffers.push(chunk);
23614 nread += chunk.length;
23615 }
23616 engine.once('readable', flow);
23617 }
23618
23619 function onError(err) {
23620 engine.removeListener('end', onEnd);
23621 engine.removeListener('readable', flow);
23622 callback(err);
23623 }
23624
23625 function onEnd() {
23626 var buf;
23627 var err = null;
23628
23629 if (nread >= kMaxLength) {
23630 err = new RangeError(kRangeErrorMessage);
23631 } else {
23632 buf = Buffer.concat(buffers, nread);
23633 }
23634
23635 buffers = [];
23636 engine.close();
23637 callback(err, buf);
23638 }
23639}
23640
23641function zlibBufferSync(engine, buffer) {
23642 if (typeof buffer === 'string') buffer = Buffer.from(buffer);
23643
23644 if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
23645
23646 var flushFlag = engine._finishFlushFlag;
23647
23648 return engine._processChunk(buffer, flushFlag);
23649}
23650
23651// generic zlib
23652// minimal 2-byte header
23653function Deflate(opts) {
23654 if (!(this instanceof Deflate)) return new Deflate(opts);
23655 Zlib.call(this, opts, binding.DEFLATE);
23656}
23657
23658function Inflate(opts) {
23659 if (!(this instanceof Inflate)) return new Inflate(opts);
23660 Zlib.call(this, opts, binding.INFLATE);
23661}
23662
23663// gzip - bigger header, same deflate compression
23664function Gzip(opts) {
23665 if (!(this instanceof Gzip)) return new Gzip(opts);
23666 Zlib.call(this, opts, binding.GZIP);
23667}
23668
23669function Gunzip(opts) {
23670 if (!(this instanceof Gunzip)) return new Gunzip(opts);
23671 Zlib.call(this, opts, binding.GUNZIP);
23672}
23673
23674// raw - no header
23675function DeflateRaw(opts) {
23676 if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
23677 Zlib.call(this, opts, binding.DEFLATERAW);
23678}
23679
23680function InflateRaw(opts) {
23681 if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
23682 Zlib.call(this, opts, binding.INFLATERAW);
23683}
23684
23685// auto-detect header.
23686function Unzip(opts) {
23687 if (!(this instanceof Unzip)) return new Unzip(opts);
23688 Zlib.call(this, opts, binding.UNZIP);
23689}
23690
23691function isValidFlushFlag(flag) {
23692 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;
23693}
23694
23695// the Zlib class they all inherit from
23696// This thing manages the queue of requests, and returns
23697// true or false if there is anything in the queue when
23698// you call the .write() method.
23699
23700function Zlib(opts, mode) {
23701 var _this = this;
23702
23703 this._opts = opts = opts || {};
23704 this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
23705
23706 Transform.call(this, opts);
23707
23708 if (opts.flush && !isValidFlushFlag(opts.flush)) {
23709 throw new Error('Invalid flush flag: ' + opts.flush);
23710 }
23711 if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
23712 throw new Error('Invalid flush flag: ' + opts.finishFlush);
23713 }
23714
23715 this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
23716 this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
23717
23718 if (opts.chunkSize) {
23719 if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
23720 throw new Error('Invalid chunk size: ' + opts.chunkSize);
23721 }
23722 }
23723
23724 if (opts.windowBits) {
23725 if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
23726 throw new Error('Invalid windowBits: ' + opts.windowBits);
23727 }
23728 }
23729
23730 if (opts.level) {
23731 if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
23732 throw new Error('Invalid compression level: ' + opts.level);
23733 }
23734 }
23735
23736 if (opts.memLevel) {
23737 if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
23738 throw new Error('Invalid memLevel: ' + opts.memLevel);
23739 }
23740 }
23741
23742 if (opts.strategy) {
23743 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) {
23744 throw new Error('Invalid strategy: ' + opts.strategy);
23745 }
23746 }
23747
23748 if (opts.dictionary) {
23749 if (!Buffer.isBuffer(opts.dictionary)) {
23750 throw new Error('Invalid dictionary: it should be a Buffer instance');
23751 }
23752 }
23753
23754 this._handle = new binding.Zlib(mode);
23755
23756 var self = this;
23757 this._hadError = false;
23758 this._handle.onerror = function (message, errno) {
23759 // there is no way to cleanly recover.
23760 // continuing only obscures problems.
23761 _close(self);
23762 self._hadError = true;
23763
23764 var error = new Error(message);
23765 error.errno = errno;
23766 error.code = exports.codes[errno];
23767 self.emit('error', error);
23768 };
23769
23770 var level = exports.Z_DEFAULT_COMPRESSION;
23771 if (typeof opts.level === 'number') level = opts.level;
23772
23773 var strategy = exports.Z_DEFAULT_STRATEGY;
23774 if (typeof opts.strategy === 'number') strategy = opts.strategy;
23775
23776 this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
23777
23778 this._buffer = Buffer.allocUnsafe(this._chunkSize);
23779 this._offset = 0;
23780 this._level = level;
23781 this._strategy = strategy;
23782
23783 this.once('end', this.close);
23784
23785 Object.defineProperty(this, '_closed', {
23786 get: function () {
23787 return !_this._handle;
23788 },
23789 configurable: true,
23790 enumerable: true
23791 });
23792}
23793
23794util.inherits(Zlib, Transform);
23795
23796Zlib.prototype.params = function (level, strategy, callback) {
23797 if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
23798 throw new RangeError('Invalid compression level: ' + level);
23799 }
23800 if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
23801 throw new TypeError('Invalid strategy: ' + strategy);
23802 }
23803
23804 if (this._level !== level || this._strategy !== strategy) {
23805 var self = this;
23806 this.flush(binding.Z_SYNC_FLUSH, function () {
23807 assert(self._handle, 'zlib binding closed');
23808 self._handle.params(level, strategy);
23809 if (!self._hadError) {
23810 self._level = level;
23811 self._strategy = strategy;
23812 if (callback) callback();
23813 }
23814 });
23815 } else {
23816 process.nextTick(callback);
23817 }
23818};
23819
23820Zlib.prototype.reset = function () {
23821 assert(this._handle, 'zlib binding closed');
23822 return this._handle.reset();
23823};
23824
23825// This is the _flush function called by the transform class,
23826// internally, when the last chunk has been written.
23827Zlib.prototype._flush = function (callback) {
23828 this._transform(Buffer.alloc(0), '', callback);
23829};
23830
23831Zlib.prototype.flush = function (kind, callback) {
23832 var _this2 = this;
23833
23834 var ws = this._writableState;
23835
23836 if (typeof kind === 'function' || kind === undefined && !callback) {
23837 callback = kind;
23838 kind = binding.Z_FULL_FLUSH;
23839 }
23840
23841 if (ws.ended) {
23842 if (callback) process.nextTick(callback);
23843 } else if (ws.ending) {
23844 if (callback) this.once('end', callback);
23845 } else if (ws.needDrain) {
23846 if (callback) {
23847 this.once('drain', function () {
23848 return _this2.flush(kind, callback);
23849 });
23850 }
23851 } else {
23852 this._flushFlag = kind;
23853 this.write(Buffer.alloc(0), '', callback);
23854 }
23855};
23856
23857Zlib.prototype.close = function (callback) {
23858 _close(this, callback);
23859 process.nextTick(emitCloseNT, this);
23860};
23861
23862function _close(engine, callback) {
23863 if (callback) process.nextTick(callback);
23864
23865 // Caller may invoke .close after a zlib error (which will null _handle).
23866 if (!engine._handle) return;
23867
23868 engine._handle.close();
23869 engine._handle = null;
23870}
23871
23872function emitCloseNT(self) {
23873 self.emit('close');
23874}
23875
23876Zlib.prototype._transform = function (chunk, encoding, cb) {
23877 var flushFlag;
23878 var ws = this._writableState;
23879 var ending = ws.ending || ws.ended;
23880 var last = ending && (!chunk || ws.length === chunk.length);
23881
23882 if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
23883
23884 if (!this._handle) return cb(new Error('zlib binding closed'));
23885
23886 // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
23887 // (or whatever flag was provided using opts.finishFlush).
23888 // If it's explicitly flushing at some other time, then we use
23889 // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
23890 // goodness.
23891 if (last) flushFlag = this._finishFlushFlag;else {
23892 flushFlag = this._flushFlag;
23893 // once we've flushed the last of the queue, stop flushing and
23894 // go back to the normal behavior.
23895 if (chunk.length >= ws.length) {
23896 this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
23897 }
23898 }
23899
23900 this._processChunk(chunk, flushFlag, cb);
23901};
23902
23903Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
23904 var availInBefore = chunk && chunk.length;
23905 var availOutBefore = this._chunkSize - this._offset;
23906 var inOff = 0;
23907
23908 var self = this;
23909
23910 var async = typeof cb === 'function';
23911
23912 if (!async) {
23913 var buffers = [];
23914 var nread = 0;
23915
23916 var error;
23917 this.on('error', function (er) {
23918 error = er;
23919 });
23920
23921 assert(this._handle, 'zlib binding closed');
23922 do {
23923 var res = this._handle.writeSync(flushFlag, chunk, // in
23924 inOff, // in_off
23925 availInBefore, // in_len
23926 this._buffer, // out
23927 this._offset, //out_off
23928 availOutBefore); // out_len
23929 } while (!this._hadError && callback(res[0], res[1]));
23930
23931 if (this._hadError) {
23932 throw error;
23933 }
23934
23935 if (nread >= kMaxLength) {
23936 _close(this);
23937 throw new RangeError(kRangeErrorMessage);
23938 }
23939
23940 var buf = Buffer.concat(buffers, nread);
23941 _close(this);
23942
23943 return buf;
23944 }
23945
23946 assert(this._handle, 'zlib binding closed');
23947 var req = this._handle.write(flushFlag, chunk, // in
23948 inOff, // in_off
23949 availInBefore, // in_len
23950 this._buffer, // out
23951 this._offset, //out_off
23952 availOutBefore); // out_len
23953
23954 req.buffer = chunk;
23955 req.callback = callback;
23956
23957 function callback(availInAfter, availOutAfter) {
23958 // When the callback is used in an async write, the callback's
23959 // context is the `req` object that was created. The req object
23960 // is === this._handle, and that's why it's important to null
23961 // out the values after they are done being used. `this._handle`
23962 // can stay in memory longer than the callback and buffer are needed.
23963 if (this) {
23964 this.buffer = null;
23965 this.callback = null;
23966 }
23967
23968 if (self._hadError) return;
23969
23970 var have = availOutBefore - availOutAfter;
23971 assert(have >= 0, 'have should not go down');
23972
23973 if (have > 0) {
23974 var out = self._buffer.slice(self._offset, self._offset + have);
23975 self._offset += have;
23976 // serve some output to the consumer.
23977 if (async) {
23978 self.push(out);
23979 } else {
23980 buffers.push(out);
23981 nread += out.length;
23982 }
23983 }
23984
23985 // exhausted the output buffer, or used all the input create a new one.
23986 if (availOutAfter === 0 || self._offset >= self._chunkSize) {
23987 availOutBefore = self._chunkSize;
23988 self._offset = 0;
23989 self._buffer = Buffer.allocUnsafe(self._chunkSize);
23990 }
23991
23992 if (availOutAfter === 0) {
23993 // Not actually done. Need to reprocess.
23994 // Also, update the availInBefore to the availInAfter value,
23995 // so that if we have to hit it a third (fourth, etc.) time,
23996 // it'll have the correct byte counts.
23997 inOff += availInBefore - availInAfter;
23998 availInBefore = availInAfter;
23999
24000 if (!async) return true;
24001
24002 var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
24003 newReq.callback = callback; // this same function
24004 newReq.buffer = chunk;
24005 return;
24006 }
24007
24008 if (!async) return false;
24009
24010 // finished with the chunk.
24011 cb();
24012 }
24013};
24014
24015util.inherits(Deflate, Zlib);
24016util.inherits(Inflate, Zlib);
24017util.inherits(Gzip, Zlib);
24018util.inherits(Gunzip, Zlib);
24019util.inherits(DeflateRaw, Zlib);
24020util.inherits(InflateRaw, Zlib);
24021util.inherits(Unzip, Zlib);
24022}).call(this,require('_process'))
24023},{"./binding":110,"_process":265,"assert":68,"buffer":114,"stream":361,"util":397}],112:[function(require,module,exports){
24024arguments[4][82][0].apply(exports,arguments)
24025},{"dup":82}],113:[function(require,module,exports){
24026(function (Buffer){
24027module.exports = function xor (a, b) {
24028 var length = Math.min(a.length, b.length)
24029 var buffer = new Buffer(length)
24030
24031 for (var i = 0; i < length; ++i) {
24032 buffer[i] = a[i] ^ b[i]
24033 }
24034
24035 return buffer
24036}
24037
24038}).call(this,require("buffer").Buffer)
24039},{"buffer":114}],114:[function(require,module,exports){
24040(function (Buffer){
24041/*!
24042 * The buffer module from node.js, for the browser.
24043 *
24044 * @author Feross Aboukhadijeh <https://feross.org>
24045 * @license MIT
24046 */
24047/* eslint-disable no-proto */
24048
24049'use strict'
24050
24051var base64 = require('base64-js')
24052var ieee754 = require('ieee754')
24053
24054exports.Buffer = Buffer
24055exports.SlowBuffer = SlowBuffer
24056exports.INSPECT_MAX_BYTES = 50
24057
24058var K_MAX_LENGTH = 0x7fffffff
24059exports.kMaxLength = K_MAX_LENGTH
24060
24061/**
24062 * If `Buffer.TYPED_ARRAY_SUPPORT`:
24063 * === true Use Uint8Array implementation (fastest)
24064 * === false Print warning and recommend using `buffer` v4.x which has an Object
24065 * implementation (most compatible, even IE6)
24066 *
24067 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
24068 * Opera 11.6+, iOS 4.2+.
24069 *
24070 * We report that the browser does not support typed arrays if the are not subclassable
24071 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
24072 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
24073 * for __proto__ and has a buggy typed array implementation.
24074 */
24075Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
24076
24077if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
24078 typeof console.error === 'function') {
24079 console.error(
24080 'This browser lacks typed array (Uint8Array) support which is required by ' +
24081 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
24082 )
24083}
24084
24085function typedArraySupport () {
24086 // Can typed array instances can be augmented?
24087 try {
24088 var arr = new Uint8Array(1)
24089 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
24090 return arr.foo() === 42
24091 } catch (e) {
24092 return false
24093 }
24094}
24095
24096Object.defineProperty(Buffer.prototype, 'parent', {
24097 enumerable: true,
24098 get: function () {
24099 if (!Buffer.isBuffer(this)) return undefined
24100 return this.buffer
24101 }
24102})
24103
24104Object.defineProperty(Buffer.prototype, 'offset', {
24105 enumerable: true,
24106 get: function () {
24107 if (!Buffer.isBuffer(this)) return undefined
24108 return this.byteOffset
24109 }
24110})
24111
24112function createBuffer (length) {
24113 if (length > K_MAX_LENGTH) {
24114 throw new RangeError('The value "' + length + '" is invalid for option "size"')
24115 }
24116 // Return an augmented `Uint8Array` instance
24117 var buf = new Uint8Array(length)
24118 buf.__proto__ = Buffer.prototype
24119 return buf
24120}
24121
24122/**
24123 * The Buffer constructor returns instances of `Uint8Array` that have their
24124 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
24125 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
24126 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
24127 * returns a single octet.
24128 *
24129 * The `Uint8Array` prototype remains unmodified.
24130 */
24131
24132function Buffer (arg, encodingOrOffset, length) {
24133 // Common case.
24134 if (typeof arg === 'number') {
24135 if (typeof encodingOrOffset === 'string') {
24136 throw new TypeError(
24137 'The "string" argument must be of type string. Received type number'
24138 )
24139 }
24140 return allocUnsafe(arg)
24141 }
24142 return from(arg, encodingOrOffset, length)
24143}
24144
24145// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
24146if (typeof Symbol !== 'undefined' && Symbol.species != null &&
24147 Buffer[Symbol.species] === Buffer) {
24148 Object.defineProperty(Buffer, Symbol.species, {
24149 value: null,
24150 configurable: true,
24151 enumerable: false,
24152 writable: false
24153 })
24154}
24155
24156Buffer.poolSize = 8192 // not used by this implementation
24157
24158function from (value, encodingOrOffset, length) {
24159 if (typeof value === 'string') {
24160 return fromString(value, encodingOrOffset)
24161 }
24162
24163 if (ArrayBuffer.isView(value)) {
24164 return fromArrayLike(value)
24165 }
24166
24167 if (value == null) {
24168 throw TypeError(
24169 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
24170 'or Array-like Object. Received type ' + (typeof value)
24171 )
24172 }
24173
24174 if (isInstance(value, ArrayBuffer) ||
24175 (value && isInstance(value.buffer, ArrayBuffer))) {
24176 return fromArrayBuffer(value, encodingOrOffset, length)
24177 }
24178
24179 if (typeof value === 'number') {
24180 throw new TypeError(
24181 'The "value" argument must not be of type number. Received type number'
24182 )
24183 }
24184
24185 var valueOf = value.valueOf && value.valueOf()
24186 if (valueOf != null && valueOf !== value) {
24187 return Buffer.from(valueOf, encodingOrOffset, length)
24188 }
24189
24190 var b = fromObject(value)
24191 if (b) return b
24192
24193 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
24194 typeof value[Symbol.toPrimitive] === 'function') {
24195 return Buffer.from(
24196 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
24197 )
24198 }
24199
24200 throw new TypeError(
24201 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
24202 'or Array-like Object. Received type ' + (typeof value)
24203 )
24204}
24205
24206/**
24207 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
24208 * if value is a number.
24209 * Buffer.from(str[, encoding])
24210 * Buffer.from(array)
24211 * Buffer.from(buffer)
24212 * Buffer.from(arrayBuffer[, byteOffset[, length]])
24213 **/
24214Buffer.from = function (value, encodingOrOffset, length) {
24215 return from(value, encodingOrOffset, length)
24216}
24217
24218// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
24219// https://github.com/feross/buffer/pull/148
24220Buffer.prototype.__proto__ = Uint8Array.prototype
24221Buffer.__proto__ = Uint8Array
24222
24223function assertSize (size) {
24224 if (typeof size !== 'number') {
24225 throw new TypeError('"size" argument must be of type number')
24226 } else if (size < 0) {
24227 throw new RangeError('The value "' + size + '" is invalid for option "size"')
24228 }
24229}
24230
24231function alloc (size, fill, encoding) {
24232 assertSize(size)
24233 if (size <= 0) {
24234 return createBuffer(size)
24235 }
24236 if (fill !== undefined) {
24237 // Only pay attention to encoding if it's a string. This
24238 // prevents accidentally sending in a number that would
24239 // be interpretted as a start offset.
24240 return typeof encoding === 'string'
24241 ? createBuffer(size).fill(fill, encoding)
24242 : createBuffer(size).fill(fill)
24243 }
24244 return createBuffer(size)
24245}
24246
24247/**
24248 * Creates a new filled Buffer instance.
24249 * alloc(size[, fill[, encoding]])
24250 **/
24251Buffer.alloc = function (size, fill, encoding) {
24252 return alloc(size, fill, encoding)
24253}
24254
24255function allocUnsafe (size) {
24256 assertSize(size)
24257 return createBuffer(size < 0 ? 0 : checked(size) | 0)
24258}
24259
24260/**
24261 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
24262 * */
24263Buffer.allocUnsafe = function (size) {
24264 return allocUnsafe(size)
24265}
24266/**
24267 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
24268 */
24269Buffer.allocUnsafeSlow = function (size) {
24270 return allocUnsafe(size)
24271}
24272
24273function fromString (string, encoding) {
24274 if (typeof encoding !== 'string' || encoding === '') {
24275 encoding = 'utf8'
24276 }
24277
24278 if (!Buffer.isEncoding(encoding)) {
24279 throw new TypeError('Unknown encoding: ' + encoding)
24280 }
24281
24282 var length = byteLength(string, encoding) | 0
24283 var buf = createBuffer(length)
24284
24285 var actual = buf.write(string, encoding)
24286
24287 if (actual !== length) {
24288 // Writing a hex string, for example, that contains invalid characters will
24289 // cause everything after the first invalid character to be ignored. (e.g.
24290 // 'abxxcd' will be treated as 'ab')
24291 buf = buf.slice(0, actual)
24292 }
24293
24294 return buf
24295}
24296
24297function fromArrayLike (array) {
24298 var length = array.length < 0 ? 0 : checked(array.length) | 0
24299 var buf = createBuffer(length)
24300 for (var i = 0; i < length; i += 1) {
24301 buf[i] = array[i] & 255
24302 }
24303 return buf
24304}
24305
24306function fromArrayBuffer (array, byteOffset, length) {
24307 if (byteOffset < 0 || array.byteLength < byteOffset) {
24308 throw new RangeError('"offset" is outside of buffer bounds')
24309 }
24310
24311 if (array.byteLength < byteOffset + (length || 0)) {
24312 throw new RangeError('"length" is outside of buffer bounds')
24313 }
24314
24315 var buf
24316 if (byteOffset === undefined && length === undefined) {
24317 buf = new Uint8Array(array)
24318 } else if (length === undefined) {
24319 buf = new Uint8Array(array, byteOffset)
24320 } else {
24321 buf = new Uint8Array(array, byteOffset, length)
24322 }
24323
24324 // Return an augmented `Uint8Array` instance
24325 buf.__proto__ = Buffer.prototype
24326 return buf
24327}
24328
24329function fromObject (obj) {
24330 if (Buffer.isBuffer(obj)) {
24331 var len = checked(obj.length) | 0
24332 var buf = createBuffer(len)
24333
24334 if (buf.length === 0) {
24335 return buf
24336 }
24337
24338 obj.copy(buf, 0, 0, len)
24339 return buf
24340 }
24341
24342 if (obj.length !== undefined) {
24343 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
24344 return createBuffer(0)
24345 }
24346 return fromArrayLike(obj)
24347 }
24348
24349 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
24350 return fromArrayLike(obj.data)
24351 }
24352}
24353
24354function checked (length) {
24355 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
24356 // length is NaN (which is otherwise coerced to zero.)
24357 if (length >= K_MAX_LENGTH) {
24358 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
24359 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
24360 }
24361 return length | 0
24362}
24363
24364function SlowBuffer (length) {
24365 if (+length != length) { // eslint-disable-line eqeqeq
24366 length = 0
24367 }
24368 return Buffer.alloc(+length)
24369}
24370
24371Buffer.isBuffer = function isBuffer (b) {
24372 return b != null && b._isBuffer === true &&
24373 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
24374}
24375
24376Buffer.compare = function compare (a, b) {
24377 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
24378 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
24379 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
24380 throw new TypeError(
24381 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
24382 )
24383 }
24384
24385 if (a === b) return 0
24386
24387 var x = a.length
24388 var y = b.length
24389
24390 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
24391 if (a[i] !== b[i]) {
24392 x = a[i]
24393 y = b[i]
24394 break
24395 }
24396 }
24397
24398 if (x < y) return -1
24399 if (y < x) return 1
24400 return 0
24401}
24402
24403Buffer.isEncoding = function isEncoding (encoding) {
24404 switch (String(encoding).toLowerCase()) {
24405 case 'hex':
24406 case 'utf8':
24407 case 'utf-8':
24408 case 'ascii':
24409 case 'latin1':
24410 case 'binary':
24411 case 'base64':
24412 case 'ucs2':
24413 case 'ucs-2':
24414 case 'utf16le':
24415 case 'utf-16le':
24416 return true
24417 default:
24418 return false
24419 }
24420}
24421
24422Buffer.concat = function concat (list, length) {
24423 if (!Array.isArray(list)) {
24424 throw new TypeError('"list" argument must be an Array of Buffers')
24425 }
24426
24427 if (list.length === 0) {
24428 return Buffer.alloc(0)
24429 }
24430
24431 var i
24432 if (length === undefined) {
24433 length = 0
24434 for (i = 0; i < list.length; ++i) {
24435 length += list[i].length
24436 }
24437 }
24438
24439 var buffer = Buffer.allocUnsafe(length)
24440 var pos = 0
24441 for (i = 0; i < list.length; ++i) {
24442 var buf = list[i]
24443 if (isInstance(buf, Uint8Array)) {
24444 buf = Buffer.from(buf)
24445 }
24446 if (!Buffer.isBuffer(buf)) {
24447 throw new TypeError('"list" argument must be an Array of Buffers')
24448 }
24449 buf.copy(buffer, pos)
24450 pos += buf.length
24451 }
24452 return buffer
24453}
24454
24455function byteLength (string, encoding) {
24456 if (Buffer.isBuffer(string)) {
24457 return string.length
24458 }
24459 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
24460 return string.byteLength
24461 }
24462 if (typeof string !== 'string') {
24463 throw new TypeError(
24464 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
24465 'Received type ' + typeof string
24466 )
24467 }
24468
24469 var len = string.length
24470 var mustMatch = (arguments.length > 2 && arguments[2] === true)
24471 if (!mustMatch && len === 0) return 0
24472
24473 // Use a for loop to avoid recursion
24474 var loweredCase = false
24475 for (;;) {
24476 switch (encoding) {
24477 case 'ascii':
24478 case 'latin1':
24479 case 'binary':
24480 return len
24481 case 'utf8':
24482 case 'utf-8':
24483 return utf8ToBytes(string).length
24484 case 'ucs2':
24485 case 'ucs-2':
24486 case 'utf16le':
24487 case 'utf-16le':
24488 return len * 2
24489 case 'hex':
24490 return len >>> 1
24491 case 'base64':
24492 return base64ToBytes(string).length
24493 default:
24494 if (loweredCase) {
24495 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
24496 }
24497 encoding = ('' + encoding).toLowerCase()
24498 loweredCase = true
24499 }
24500 }
24501}
24502Buffer.byteLength = byteLength
24503
24504function slowToString (encoding, start, end) {
24505 var loweredCase = false
24506
24507 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
24508 // property of a typed array.
24509
24510 // This behaves neither like String nor Uint8Array in that we set start/end
24511 // to their upper/lower bounds if the value passed is out of range.
24512 // undefined is handled specially as per ECMA-262 6th Edition,
24513 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
24514 if (start === undefined || start < 0) {
24515 start = 0
24516 }
24517 // Return early if start > this.length. Done here to prevent potential uint32
24518 // coercion fail below.
24519 if (start > this.length) {
24520 return ''
24521 }
24522
24523 if (end === undefined || end > this.length) {
24524 end = this.length
24525 }
24526
24527 if (end <= 0) {
24528 return ''
24529 }
24530
24531 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
24532 end >>>= 0
24533 start >>>= 0
24534
24535 if (end <= start) {
24536 return ''
24537 }
24538
24539 if (!encoding) encoding = 'utf8'
24540
24541 while (true) {
24542 switch (encoding) {
24543 case 'hex':
24544 return hexSlice(this, start, end)
24545
24546 case 'utf8':
24547 case 'utf-8':
24548 return utf8Slice(this, start, end)
24549
24550 case 'ascii':
24551 return asciiSlice(this, start, end)
24552
24553 case 'latin1':
24554 case 'binary':
24555 return latin1Slice(this, start, end)
24556
24557 case 'base64':
24558 return base64Slice(this, start, end)
24559
24560 case 'ucs2':
24561 case 'ucs-2':
24562 case 'utf16le':
24563 case 'utf-16le':
24564 return utf16leSlice(this, start, end)
24565
24566 default:
24567 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
24568 encoding = (encoding + '').toLowerCase()
24569 loweredCase = true
24570 }
24571 }
24572}
24573
24574// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
24575// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
24576// reliably in a browserify context because there could be multiple different
24577// copies of the 'buffer' package in use. This method works even for Buffer
24578// instances that were created from another copy of the `buffer` package.
24579// See: https://github.com/feross/buffer/issues/154
24580Buffer.prototype._isBuffer = true
24581
24582function swap (b, n, m) {
24583 var i = b[n]
24584 b[n] = b[m]
24585 b[m] = i
24586}
24587
24588Buffer.prototype.swap16 = function swap16 () {
24589 var len = this.length
24590 if (len % 2 !== 0) {
24591 throw new RangeError('Buffer size must be a multiple of 16-bits')
24592 }
24593 for (var i = 0; i < len; i += 2) {
24594 swap(this, i, i + 1)
24595 }
24596 return this
24597}
24598
24599Buffer.prototype.swap32 = function swap32 () {
24600 var len = this.length
24601 if (len % 4 !== 0) {
24602 throw new RangeError('Buffer size must be a multiple of 32-bits')
24603 }
24604 for (var i = 0; i < len; i += 4) {
24605 swap(this, i, i + 3)
24606 swap(this, i + 1, i + 2)
24607 }
24608 return this
24609}
24610
24611Buffer.prototype.swap64 = function swap64 () {
24612 var len = this.length
24613 if (len % 8 !== 0) {
24614 throw new RangeError('Buffer size must be a multiple of 64-bits')
24615 }
24616 for (var i = 0; i < len; i += 8) {
24617 swap(this, i, i + 7)
24618 swap(this, i + 1, i + 6)
24619 swap(this, i + 2, i + 5)
24620 swap(this, i + 3, i + 4)
24621 }
24622 return this
24623}
24624
24625Buffer.prototype.toString = function toString () {
24626 var length = this.length
24627 if (length === 0) return ''
24628 if (arguments.length === 0) return utf8Slice(this, 0, length)
24629 return slowToString.apply(this, arguments)
24630}
24631
24632Buffer.prototype.toLocaleString = Buffer.prototype.toString
24633
24634Buffer.prototype.equals = function equals (b) {
24635 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
24636 if (this === b) return true
24637 return Buffer.compare(this, b) === 0
24638}
24639
24640Buffer.prototype.inspect = function inspect () {
24641 var str = ''
24642 var max = exports.INSPECT_MAX_BYTES
24643 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
24644 if (this.length > max) str += ' ... '
24645 return '<Buffer ' + str + '>'
24646}
24647
24648Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
24649 if (isInstance(target, Uint8Array)) {
24650 target = Buffer.from(target, target.offset, target.byteLength)
24651 }
24652 if (!Buffer.isBuffer(target)) {
24653 throw new TypeError(
24654 'The "target" argument must be one of type Buffer or Uint8Array. ' +
24655 'Received type ' + (typeof target)
24656 )
24657 }
24658
24659 if (start === undefined) {
24660 start = 0
24661 }
24662 if (end === undefined) {
24663 end = target ? target.length : 0
24664 }
24665 if (thisStart === undefined) {
24666 thisStart = 0
24667 }
24668 if (thisEnd === undefined) {
24669 thisEnd = this.length
24670 }
24671
24672 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
24673 throw new RangeError('out of range index')
24674 }
24675
24676 if (thisStart >= thisEnd && start >= end) {
24677 return 0
24678 }
24679 if (thisStart >= thisEnd) {
24680 return -1
24681 }
24682 if (start >= end) {
24683 return 1
24684 }
24685
24686 start >>>= 0
24687 end >>>= 0
24688 thisStart >>>= 0
24689 thisEnd >>>= 0
24690
24691 if (this === target) return 0
24692
24693 var x = thisEnd - thisStart
24694 var y = end - start
24695 var len = Math.min(x, y)
24696
24697 var thisCopy = this.slice(thisStart, thisEnd)
24698 var targetCopy = target.slice(start, end)
24699
24700 for (var i = 0; i < len; ++i) {
24701 if (thisCopy[i] !== targetCopy[i]) {
24702 x = thisCopy[i]
24703 y = targetCopy[i]
24704 break
24705 }
24706 }
24707
24708 if (x < y) return -1
24709 if (y < x) return 1
24710 return 0
24711}
24712
24713// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
24714// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
24715//
24716// Arguments:
24717// - buffer - a Buffer to search
24718// - val - a string, Buffer, or number
24719// - byteOffset - an index into `buffer`; will be clamped to an int32
24720// - encoding - an optional encoding, relevant is val is a string
24721// - dir - true for indexOf, false for lastIndexOf
24722function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
24723 // Empty buffer means no match
24724 if (buffer.length === 0) return -1
24725
24726 // Normalize byteOffset
24727 if (typeof byteOffset === 'string') {
24728 encoding = byteOffset
24729 byteOffset = 0
24730 } else if (byteOffset > 0x7fffffff) {
24731 byteOffset = 0x7fffffff
24732 } else if (byteOffset < -0x80000000) {
24733 byteOffset = -0x80000000
24734 }
24735 byteOffset = +byteOffset // Coerce to Number.
24736 if (numberIsNaN(byteOffset)) {
24737 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
24738 byteOffset = dir ? 0 : (buffer.length - 1)
24739 }
24740
24741 // Normalize byteOffset: negative offsets start from the end of the buffer
24742 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
24743 if (byteOffset >= buffer.length) {
24744 if (dir) return -1
24745 else byteOffset = buffer.length - 1
24746 } else if (byteOffset < 0) {
24747 if (dir) byteOffset = 0
24748 else return -1
24749 }
24750
24751 // Normalize val
24752 if (typeof val === 'string') {
24753 val = Buffer.from(val, encoding)
24754 }
24755
24756 // Finally, search either indexOf (if dir is true) or lastIndexOf
24757 if (Buffer.isBuffer(val)) {
24758 // Special case: looking for empty string/buffer always fails
24759 if (val.length === 0) {
24760 return -1
24761 }
24762 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
24763 } else if (typeof val === 'number') {
24764 val = val & 0xFF // Search for a byte value [0-255]
24765 if (typeof Uint8Array.prototype.indexOf === 'function') {
24766 if (dir) {
24767 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
24768 } else {
24769 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
24770 }
24771 }
24772 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
24773 }
24774
24775 throw new TypeError('val must be string, number or Buffer')
24776}
24777
24778function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
24779 var indexSize = 1
24780 var arrLength = arr.length
24781 var valLength = val.length
24782
24783 if (encoding !== undefined) {
24784 encoding = String(encoding).toLowerCase()
24785 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
24786 encoding === 'utf16le' || encoding === 'utf-16le') {
24787 if (arr.length < 2 || val.length < 2) {
24788 return -1
24789 }
24790 indexSize = 2
24791 arrLength /= 2
24792 valLength /= 2
24793 byteOffset /= 2
24794 }
24795 }
24796
24797 function read (buf, i) {
24798 if (indexSize === 1) {
24799 return buf[i]
24800 } else {
24801 return buf.readUInt16BE(i * indexSize)
24802 }
24803 }
24804
24805 var i
24806 if (dir) {
24807 var foundIndex = -1
24808 for (i = byteOffset; i < arrLength; i++) {
24809 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
24810 if (foundIndex === -1) foundIndex = i
24811 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
24812 } else {
24813 if (foundIndex !== -1) i -= i - foundIndex
24814 foundIndex = -1
24815 }
24816 }
24817 } else {
24818 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
24819 for (i = byteOffset; i >= 0; i--) {
24820 var found = true
24821 for (var j = 0; j < valLength; j++) {
24822 if (read(arr, i + j) !== read(val, j)) {
24823 found = false
24824 break
24825 }
24826 }
24827 if (found) return i
24828 }
24829 }
24830
24831 return -1
24832}
24833
24834Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
24835 return this.indexOf(val, byteOffset, encoding) !== -1
24836}
24837
24838Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
24839 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
24840}
24841
24842Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
24843 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
24844}
24845
24846function hexWrite (buf, string, offset, length) {
24847 offset = Number(offset) || 0
24848 var remaining = buf.length - offset
24849 if (!length) {
24850 length = remaining
24851 } else {
24852 length = Number(length)
24853 if (length > remaining) {
24854 length = remaining
24855 }
24856 }
24857
24858 var strLen = string.length
24859
24860 if (length > strLen / 2) {
24861 length = strLen / 2
24862 }
24863 for (var i = 0; i < length; ++i) {
24864 var parsed = parseInt(string.substr(i * 2, 2), 16)
24865 if (numberIsNaN(parsed)) return i
24866 buf[offset + i] = parsed
24867 }
24868 return i
24869}
24870
24871function utf8Write (buf, string, offset, length) {
24872 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
24873}
24874
24875function asciiWrite (buf, string, offset, length) {
24876 return blitBuffer(asciiToBytes(string), buf, offset, length)
24877}
24878
24879function latin1Write (buf, string, offset, length) {
24880 return asciiWrite(buf, string, offset, length)
24881}
24882
24883function base64Write (buf, string, offset, length) {
24884 return blitBuffer(base64ToBytes(string), buf, offset, length)
24885}
24886
24887function ucs2Write (buf, string, offset, length) {
24888 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
24889}
24890
24891Buffer.prototype.write = function write (string, offset, length, encoding) {
24892 // Buffer#write(string)
24893 if (offset === undefined) {
24894 encoding = 'utf8'
24895 length = this.length
24896 offset = 0
24897 // Buffer#write(string, encoding)
24898 } else if (length === undefined && typeof offset === 'string') {
24899 encoding = offset
24900 length = this.length
24901 offset = 0
24902 // Buffer#write(string, offset[, length][, encoding])
24903 } else if (isFinite(offset)) {
24904 offset = offset >>> 0
24905 if (isFinite(length)) {
24906 length = length >>> 0
24907 if (encoding === undefined) encoding = 'utf8'
24908 } else {
24909 encoding = length
24910 length = undefined
24911 }
24912 } else {
24913 throw new Error(
24914 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
24915 )
24916 }
24917
24918 var remaining = this.length - offset
24919 if (length === undefined || length > remaining) length = remaining
24920
24921 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
24922 throw new RangeError('Attempt to write outside buffer bounds')
24923 }
24924
24925 if (!encoding) encoding = 'utf8'
24926
24927 var loweredCase = false
24928 for (;;) {
24929 switch (encoding) {
24930 case 'hex':
24931 return hexWrite(this, string, offset, length)
24932
24933 case 'utf8':
24934 case 'utf-8':
24935 return utf8Write(this, string, offset, length)
24936
24937 case 'ascii':
24938 return asciiWrite(this, string, offset, length)
24939
24940 case 'latin1':
24941 case 'binary':
24942 return latin1Write(this, string, offset, length)
24943
24944 case 'base64':
24945 // Warning: maxLength not taken into account in base64Write
24946 return base64Write(this, string, offset, length)
24947
24948 case 'ucs2':
24949 case 'ucs-2':
24950 case 'utf16le':
24951 case 'utf-16le':
24952 return ucs2Write(this, string, offset, length)
24953
24954 default:
24955 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
24956 encoding = ('' + encoding).toLowerCase()
24957 loweredCase = true
24958 }
24959 }
24960}
24961
24962Buffer.prototype.toJSON = function toJSON () {
24963 return {
24964 type: 'Buffer',
24965 data: Array.prototype.slice.call(this._arr || this, 0)
24966 }
24967}
24968
24969function base64Slice (buf, start, end) {
24970 if (start === 0 && end === buf.length) {
24971 return base64.fromByteArray(buf)
24972 } else {
24973 return base64.fromByteArray(buf.slice(start, end))
24974 }
24975}
24976
24977function utf8Slice (buf, start, end) {
24978 end = Math.min(buf.length, end)
24979 var res = []
24980
24981 var i = start
24982 while (i < end) {
24983 var firstByte = buf[i]
24984 var codePoint = null
24985 var bytesPerSequence = (firstByte > 0xEF) ? 4
24986 : (firstByte > 0xDF) ? 3
24987 : (firstByte > 0xBF) ? 2
24988 : 1
24989
24990 if (i + bytesPerSequence <= end) {
24991 var secondByte, thirdByte, fourthByte, tempCodePoint
24992
24993 switch (bytesPerSequence) {
24994 case 1:
24995 if (firstByte < 0x80) {
24996 codePoint = firstByte
24997 }
24998 break
24999 case 2:
25000 secondByte = buf[i + 1]
25001 if ((secondByte & 0xC0) === 0x80) {
25002 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
25003 if (tempCodePoint > 0x7F) {
25004 codePoint = tempCodePoint
25005 }
25006 }
25007 break
25008 case 3:
25009 secondByte = buf[i + 1]
25010 thirdByte = buf[i + 2]
25011 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
25012 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
25013 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
25014 codePoint = tempCodePoint
25015 }
25016 }
25017 break
25018 case 4:
25019 secondByte = buf[i + 1]
25020 thirdByte = buf[i + 2]
25021 fourthByte = buf[i + 3]
25022 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
25023 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
25024 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
25025 codePoint = tempCodePoint
25026 }
25027 }
25028 }
25029 }
25030
25031 if (codePoint === null) {
25032 // we did not generate a valid codePoint so insert a
25033 // replacement char (U+FFFD) and advance only 1 byte
25034 codePoint = 0xFFFD
25035 bytesPerSequence = 1
25036 } else if (codePoint > 0xFFFF) {
25037 // encode to utf16 (surrogate pair dance)
25038 codePoint -= 0x10000
25039 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
25040 codePoint = 0xDC00 | codePoint & 0x3FF
25041 }
25042
25043 res.push(codePoint)
25044 i += bytesPerSequence
25045 }
25046
25047 return decodeCodePointsArray(res)
25048}
25049
25050// Based on http://stackoverflow.com/a/22747272/680742, the browser with
25051// the lowest limit is Chrome, with 0x10000 args.
25052// We go 1 magnitude less, for safety
25053var MAX_ARGUMENTS_LENGTH = 0x1000
25054
25055function decodeCodePointsArray (codePoints) {
25056 var len = codePoints.length
25057 if (len <= MAX_ARGUMENTS_LENGTH) {
25058 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
25059 }
25060
25061 // Decode in chunks to avoid "call stack size exceeded".
25062 var res = ''
25063 var i = 0
25064 while (i < len) {
25065 res += String.fromCharCode.apply(
25066 String,
25067 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
25068 )
25069 }
25070 return res
25071}
25072
25073function asciiSlice (buf, start, end) {
25074 var ret = ''
25075 end = Math.min(buf.length, end)
25076
25077 for (var i = start; i < end; ++i) {
25078 ret += String.fromCharCode(buf[i] & 0x7F)
25079 }
25080 return ret
25081}
25082
25083function latin1Slice (buf, start, end) {
25084 var ret = ''
25085 end = Math.min(buf.length, end)
25086
25087 for (var i = start; i < end; ++i) {
25088 ret += String.fromCharCode(buf[i])
25089 }
25090 return ret
25091}
25092
25093function hexSlice (buf, start, end) {
25094 var len = buf.length
25095
25096 if (!start || start < 0) start = 0
25097 if (!end || end < 0 || end > len) end = len
25098
25099 var out = ''
25100 for (var i = start; i < end; ++i) {
25101 out += toHex(buf[i])
25102 }
25103 return out
25104}
25105
25106function utf16leSlice (buf, start, end) {
25107 var bytes = buf.slice(start, end)
25108 var res = ''
25109 for (var i = 0; i < bytes.length; i += 2) {
25110 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
25111 }
25112 return res
25113}
25114
25115Buffer.prototype.slice = function slice (start, end) {
25116 var len = this.length
25117 start = ~~start
25118 end = end === undefined ? len : ~~end
25119
25120 if (start < 0) {
25121 start += len
25122 if (start < 0) start = 0
25123 } else if (start > len) {
25124 start = len
25125 }
25126
25127 if (end < 0) {
25128 end += len
25129 if (end < 0) end = 0
25130 } else if (end > len) {
25131 end = len
25132 }
25133
25134 if (end < start) end = start
25135
25136 var newBuf = this.subarray(start, end)
25137 // Return an augmented `Uint8Array` instance
25138 newBuf.__proto__ = Buffer.prototype
25139 return newBuf
25140}
25141
25142/*
25143 * Need to make sure that buffer isn't trying to write out of bounds.
25144 */
25145function checkOffset (offset, ext, length) {
25146 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
25147 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
25148}
25149
25150Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
25151 offset = offset >>> 0
25152 byteLength = byteLength >>> 0
25153 if (!noAssert) checkOffset(offset, byteLength, this.length)
25154
25155 var val = this[offset]
25156 var mul = 1
25157 var i = 0
25158 while (++i < byteLength && (mul *= 0x100)) {
25159 val += this[offset + i] * mul
25160 }
25161
25162 return val
25163}
25164
25165Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
25166 offset = offset >>> 0
25167 byteLength = byteLength >>> 0
25168 if (!noAssert) {
25169 checkOffset(offset, byteLength, this.length)
25170 }
25171
25172 var val = this[offset + --byteLength]
25173 var mul = 1
25174 while (byteLength > 0 && (mul *= 0x100)) {
25175 val += this[offset + --byteLength] * mul
25176 }
25177
25178 return val
25179}
25180
25181Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
25182 offset = offset >>> 0
25183 if (!noAssert) checkOffset(offset, 1, this.length)
25184 return this[offset]
25185}
25186
25187Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
25188 offset = offset >>> 0
25189 if (!noAssert) checkOffset(offset, 2, this.length)
25190 return this[offset] | (this[offset + 1] << 8)
25191}
25192
25193Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
25194 offset = offset >>> 0
25195 if (!noAssert) checkOffset(offset, 2, this.length)
25196 return (this[offset] << 8) | this[offset + 1]
25197}
25198
25199Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
25200 offset = offset >>> 0
25201 if (!noAssert) checkOffset(offset, 4, this.length)
25202
25203 return ((this[offset]) |
25204 (this[offset + 1] << 8) |
25205 (this[offset + 2] << 16)) +
25206 (this[offset + 3] * 0x1000000)
25207}
25208
25209Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
25210 offset = offset >>> 0
25211 if (!noAssert) checkOffset(offset, 4, this.length)
25212
25213 return (this[offset] * 0x1000000) +
25214 ((this[offset + 1] << 16) |
25215 (this[offset + 2] << 8) |
25216 this[offset + 3])
25217}
25218
25219Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
25220 offset = offset >>> 0
25221 byteLength = byteLength >>> 0
25222 if (!noAssert) checkOffset(offset, byteLength, this.length)
25223
25224 var val = this[offset]
25225 var mul = 1
25226 var i = 0
25227 while (++i < byteLength && (mul *= 0x100)) {
25228 val += this[offset + i] * mul
25229 }
25230 mul *= 0x80
25231
25232 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
25233
25234 return val
25235}
25236
25237Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
25238 offset = offset >>> 0
25239 byteLength = byteLength >>> 0
25240 if (!noAssert) checkOffset(offset, byteLength, this.length)
25241
25242 var i = byteLength
25243 var mul = 1
25244 var val = this[offset + --i]
25245 while (i > 0 && (mul *= 0x100)) {
25246 val += this[offset + --i] * mul
25247 }
25248 mul *= 0x80
25249
25250 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
25251
25252 return val
25253}
25254
25255Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
25256 offset = offset >>> 0
25257 if (!noAssert) checkOffset(offset, 1, this.length)
25258 if (!(this[offset] & 0x80)) return (this[offset])
25259 return ((0xff - this[offset] + 1) * -1)
25260}
25261
25262Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
25263 offset = offset >>> 0
25264 if (!noAssert) checkOffset(offset, 2, this.length)
25265 var val = this[offset] | (this[offset + 1] << 8)
25266 return (val & 0x8000) ? val | 0xFFFF0000 : val
25267}
25268
25269Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
25270 offset = offset >>> 0
25271 if (!noAssert) checkOffset(offset, 2, this.length)
25272 var val = this[offset + 1] | (this[offset] << 8)
25273 return (val & 0x8000) ? val | 0xFFFF0000 : val
25274}
25275
25276Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
25277 offset = offset >>> 0
25278 if (!noAssert) checkOffset(offset, 4, this.length)
25279
25280 return (this[offset]) |
25281 (this[offset + 1] << 8) |
25282 (this[offset + 2] << 16) |
25283 (this[offset + 3] << 24)
25284}
25285
25286Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
25287 offset = offset >>> 0
25288 if (!noAssert) checkOffset(offset, 4, this.length)
25289
25290 return (this[offset] << 24) |
25291 (this[offset + 1] << 16) |
25292 (this[offset + 2] << 8) |
25293 (this[offset + 3])
25294}
25295
25296Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
25297 offset = offset >>> 0
25298 if (!noAssert) checkOffset(offset, 4, this.length)
25299 return ieee754.read(this, offset, true, 23, 4)
25300}
25301
25302Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
25303 offset = offset >>> 0
25304 if (!noAssert) checkOffset(offset, 4, this.length)
25305 return ieee754.read(this, offset, false, 23, 4)
25306}
25307
25308Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
25309 offset = offset >>> 0
25310 if (!noAssert) checkOffset(offset, 8, this.length)
25311 return ieee754.read(this, offset, true, 52, 8)
25312}
25313
25314Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
25315 offset = offset >>> 0
25316 if (!noAssert) checkOffset(offset, 8, this.length)
25317 return ieee754.read(this, offset, false, 52, 8)
25318}
25319
25320function checkInt (buf, value, offset, ext, max, min) {
25321 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
25322 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
25323 if (offset + ext > buf.length) throw new RangeError('Index out of range')
25324}
25325
25326Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
25327 value = +value
25328 offset = offset >>> 0
25329 byteLength = byteLength >>> 0
25330 if (!noAssert) {
25331 var maxBytes = Math.pow(2, 8 * byteLength) - 1
25332 checkInt(this, value, offset, byteLength, maxBytes, 0)
25333 }
25334
25335 var mul = 1
25336 var i = 0
25337 this[offset] = value & 0xFF
25338 while (++i < byteLength && (mul *= 0x100)) {
25339 this[offset + i] = (value / mul) & 0xFF
25340 }
25341
25342 return offset + byteLength
25343}
25344
25345Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
25346 value = +value
25347 offset = offset >>> 0
25348 byteLength = byteLength >>> 0
25349 if (!noAssert) {
25350 var maxBytes = Math.pow(2, 8 * byteLength) - 1
25351 checkInt(this, value, offset, byteLength, maxBytes, 0)
25352 }
25353
25354 var i = byteLength - 1
25355 var mul = 1
25356 this[offset + i] = value & 0xFF
25357 while (--i >= 0 && (mul *= 0x100)) {
25358 this[offset + i] = (value / mul) & 0xFF
25359 }
25360
25361 return offset + byteLength
25362}
25363
25364Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
25365 value = +value
25366 offset = offset >>> 0
25367 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
25368 this[offset] = (value & 0xff)
25369 return offset + 1
25370}
25371
25372Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
25373 value = +value
25374 offset = offset >>> 0
25375 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
25376 this[offset] = (value & 0xff)
25377 this[offset + 1] = (value >>> 8)
25378 return offset + 2
25379}
25380
25381Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
25382 value = +value
25383 offset = offset >>> 0
25384 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
25385 this[offset] = (value >>> 8)
25386 this[offset + 1] = (value & 0xff)
25387 return offset + 2
25388}
25389
25390Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
25391 value = +value
25392 offset = offset >>> 0
25393 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
25394 this[offset + 3] = (value >>> 24)
25395 this[offset + 2] = (value >>> 16)
25396 this[offset + 1] = (value >>> 8)
25397 this[offset] = (value & 0xff)
25398 return offset + 4
25399}
25400
25401Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
25402 value = +value
25403 offset = offset >>> 0
25404 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
25405 this[offset] = (value >>> 24)
25406 this[offset + 1] = (value >>> 16)
25407 this[offset + 2] = (value >>> 8)
25408 this[offset + 3] = (value & 0xff)
25409 return offset + 4
25410}
25411
25412Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
25413 value = +value
25414 offset = offset >>> 0
25415 if (!noAssert) {
25416 var limit = Math.pow(2, (8 * byteLength) - 1)
25417
25418 checkInt(this, value, offset, byteLength, limit - 1, -limit)
25419 }
25420
25421 var i = 0
25422 var mul = 1
25423 var sub = 0
25424 this[offset] = value & 0xFF
25425 while (++i < byteLength && (mul *= 0x100)) {
25426 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
25427 sub = 1
25428 }
25429 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
25430 }
25431
25432 return offset + byteLength
25433}
25434
25435Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
25436 value = +value
25437 offset = offset >>> 0
25438 if (!noAssert) {
25439 var limit = Math.pow(2, (8 * byteLength) - 1)
25440
25441 checkInt(this, value, offset, byteLength, limit - 1, -limit)
25442 }
25443
25444 var i = byteLength - 1
25445 var mul = 1
25446 var sub = 0
25447 this[offset + i] = value & 0xFF
25448 while (--i >= 0 && (mul *= 0x100)) {
25449 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
25450 sub = 1
25451 }
25452 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
25453 }
25454
25455 return offset + byteLength
25456}
25457
25458Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
25459 value = +value
25460 offset = offset >>> 0
25461 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
25462 if (value < 0) value = 0xff + value + 1
25463 this[offset] = (value & 0xff)
25464 return offset + 1
25465}
25466
25467Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
25468 value = +value
25469 offset = offset >>> 0
25470 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
25471 this[offset] = (value & 0xff)
25472 this[offset + 1] = (value >>> 8)
25473 return offset + 2
25474}
25475
25476Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
25477 value = +value
25478 offset = offset >>> 0
25479 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
25480 this[offset] = (value >>> 8)
25481 this[offset + 1] = (value & 0xff)
25482 return offset + 2
25483}
25484
25485Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
25486 value = +value
25487 offset = offset >>> 0
25488 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
25489 this[offset] = (value & 0xff)
25490 this[offset + 1] = (value >>> 8)
25491 this[offset + 2] = (value >>> 16)
25492 this[offset + 3] = (value >>> 24)
25493 return offset + 4
25494}
25495
25496Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
25497 value = +value
25498 offset = offset >>> 0
25499 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
25500 if (value < 0) value = 0xffffffff + value + 1
25501 this[offset] = (value >>> 24)
25502 this[offset + 1] = (value >>> 16)
25503 this[offset + 2] = (value >>> 8)
25504 this[offset + 3] = (value & 0xff)
25505 return offset + 4
25506}
25507
25508function checkIEEE754 (buf, value, offset, ext, max, min) {
25509 if (offset + ext > buf.length) throw new RangeError('Index out of range')
25510 if (offset < 0) throw new RangeError('Index out of range')
25511}
25512
25513function writeFloat (buf, value, offset, littleEndian, noAssert) {
25514 value = +value
25515 offset = offset >>> 0
25516 if (!noAssert) {
25517 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
25518 }
25519 ieee754.write(buf, value, offset, littleEndian, 23, 4)
25520 return offset + 4
25521}
25522
25523Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
25524 return writeFloat(this, value, offset, true, noAssert)
25525}
25526
25527Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
25528 return writeFloat(this, value, offset, false, noAssert)
25529}
25530
25531function writeDouble (buf, value, offset, littleEndian, noAssert) {
25532 value = +value
25533 offset = offset >>> 0
25534 if (!noAssert) {
25535 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
25536 }
25537 ieee754.write(buf, value, offset, littleEndian, 52, 8)
25538 return offset + 8
25539}
25540
25541Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
25542 return writeDouble(this, value, offset, true, noAssert)
25543}
25544
25545Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
25546 return writeDouble(this, value, offset, false, noAssert)
25547}
25548
25549// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
25550Buffer.prototype.copy = function copy (target, targetStart, start, end) {
25551 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
25552 if (!start) start = 0
25553 if (!end && end !== 0) end = this.length
25554 if (targetStart >= target.length) targetStart = target.length
25555 if (!targetStart) targetStart = 0
25556 if (end > 0 && end < start) end = start
25557
25558 // Copy 0 bytes; we're done
25559 if (end === start) return 0
25560 if (target.length === 0 || this.length === 0) return 0
25561
25562 // Fatal error conditions
25563 if (targetStart < 0) {
25564 throw new RangeError('targetStart out of bounds')
25565 }
25566 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
25567 if (end < 0) throw new RangeError('sourceEnd out of bounds')
25568
25569 // Are we oob?
25570 if (end > this.length) end = this.length
25571 if (target.length - targetStart < end - start) {
25572 end = target.length - targetStart + start
25573 }
25574
25575 var len = end - start
25576
25577 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
25578 // Use built-in when available, missing from IE11
25579 this.copyWithin(targetStart, start, end)
25580 } else if (this === target && start < targetStart && targetStart < end) {
25581 // descending copy from end
25582 for (var i = len - 1; i >= 0; --i) {
25583 target[i + targetStart] = this[i + start]
25584 }
25585 } else {
25586 Uint8Array.prototype.set.call(
25587 target,
25588 this.subarray(start, end),
25589 targetStart
25590 )
25591 }
25592
25593 return len
25594}
25595
25596// Usage:
25597// buffer.fill(number[, offset[, end]])
25598// buffer.fill(buffer[, offset[, end]])
25599// buffer.fill(string[, offset[, end]][, encoding])
25600Buffer.prototype.fill = function fill (val, start, end, encoding) {
25601 // Handle string cases:
25602 if (typeof val === 'string') {
25603 if (typeof start === 'string') {
25604 encoding = start
25605 start = 0
25606 end = this.length
25607 } else if (typeof end === 'string') {
25608 encoding = end
25609 end = this.length
25610 }
25611 if (encoding !== undefined && typeof encoding !== 'string') {
25612 throw new TypeError('encoding must be a string')
25613 }
25614 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
25615 throw new TypeError('Unknown encoding: ' + encoding)
25616 }
25617 if (val.length === 1) {
25618 var code = val.charCodeAt(0)
25619 if ((encoding === 'utf8' && code < 128) ||
25620 encoding === 'latin1') {
25621 // Fast path: If `val` fits into a single byte, use that numeric value.
25622 val = code
25623 }
25624 }
25625 } else if (typeof val === 'number') {
25626 val = val & 255
25627 }
25628
25629 // Invalid ranges are not set to a default, so can range check early.
25630 if (start < 0 || this.length < start || this.length < end) {
25631 throw new RangeError('Out of range index')
25632 }
25633
25634 if (end <= start) {
25635 return this
25636 }
25637
25638 start = start >>> 0
25639 end = end === undefined ? this.length : end >>> 0
25640
25641 if (!val) val = 0
25642
25643 var i
25644 if (typeof val === 'number') {
25645 for (i = start; i < end; ++i) {
25646 this[i] = val
25647 }
25648 } else {
25649 var bytes = Buffer.isBuffer(val)
25650 ? val
25651 : Buffer.from(val, encoding)
25652 var len = bytes.length
25653 if (len === 0) {
25654 throw new TypeError('The value "' + val +
25655 '" is invalid for argument "value"')
25656 }
25657 for (i = 0; i < end - start; ++i) {
25658 this[i + start] = bytes[i % len]
25659 }
25660 }
25661
25662 return this
25663}
25664
25665// HELPER FUNCTIONS
25666// ================
25667
25668var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
25669
25670function base64clean (str) {
25671 // Node takes equal signs as end of the Base64 encoding
25672 str = str.split('=')[0]
25673 // Node strips out invalid characters like \n and \t from the string, base64-js does not
25674 str = str.trim().replace(INVALID_BASE64_RE, '')
25675 // Node converts strings with length < 2 to ''
25676 if (str.length < 2) return ''
25677 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
25678 while (str.length % 4 !== 0) {
25679 str = str + '='
25680 }
25681 return str
25682}
25683
25684function toHex (n) {
25685 if (n < 16) return '0' + n.toString(16)
25686 return n.toString(16)
25687}
25688
25689function utf8ToBytes (string, units) {
25690 units = units || Infinity
25691 var codePoint
25692 var length = string.length
25693 var leadSurrogate = null
25694 var bytes = []
25695
25696 for (var i = 0; i < length; ++i) {
25697 codePoint = string.charCodeAt(i)
25698
25699 // is surrogate component
25700 if (codePoint > 0xD7FF && codePoint < 0xE000) {
25701 // last char was a lead
25702 if (!leadSurrogate) {
25703 // no lead yet
25704 if (codePoint > 0xDBFF) {
25705 // unexpected trail
25706 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
25707 continue
25708 } else if (i + 1 === length) {
25709 // unpaired lead
25710 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
25711 continue
25712 }
25713
25714 // valid lead
25715 leadSurrogate = codePoint
25716
25717 continue
25718 }
25719
25720 // 2 leads in a row
25721 if (codePoint < 0xDC00) {
25722 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
25723 leadSurrogate = codePoint
25724 continue
25725 }
25726
25727 // valid surrogate pair
25728 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
25729 } else if (leadSurrogate) {
25730 // valid bmp char, but last char was a lead
25731 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
25732 }
25733
25734 leadSurrogate = null
25735
25736 // encode utf8
25737 if (codePoint < 0x80) {
25738 if ((units -= 1) < 0) break
25739 bytes.push(codePoint)
25740 } else if (codePoint < 0x800) {
25741 if ((units -= 2) < 0) break
25742 bytes.push(
25743 codePoint >> 0x6 | 0xC0,
25744 codePoint & 0x3F | 0x80
25745 )
25746 } else if (codePoint < 0x10000) {
25747 if ((units -= 3) < 0) break
25748 bytes.push(
25749 codePoint >> 0xC | 0xE0,
25750 codePoint >> 0x6 & 0x3F | 0x80,
25751 codePoint & 0x3F | 0x80
25752 )
25753 } else if (codePoint < 0x110000) {
25754 if ((units -= 4) < 0) break
25755 bytes.push(
25756 codePoint >> 0x12 | 0xF0,
25757 codePoint >> 0xC & 0x3F | 0x80,
25758 codePoint >> 0x6 & 0x3F | 0x80,
25759 codePoint & 0x3F | 0x80
25760 )
25761 } else {
25762 throw new Error('Invalid code point')
25763 }
25764 }
25765
25766 return bytes
25767}
25768
25769function asciiToBytes (str) {
25770 var byteArray = []
25771 for (var i = 0; i < str.length; ++i) {
25772 // Node's code seems to be doing this and not & 0x7F..
25773 byteArray.push(str.charCodeAt(i) & 0xFF)
25774 }
25775 return byteArray
25776}
25777
25778function utf16leToBytes (str, units) {
25779 var c, hi, lo
25780 var byteArray = []
25781 for (var i = 0; i < str.length; ++i) {
25782 if ((units -= 2) < 0) break
25783
25784 c = str.charCodeAt(i)
25785 hi = c >> 8
25786 lo = c % 256
25787 byteArray.push(lo)
25788 byteArray.push(hi)
25789 }
25790
25791 return byteArray
25792}
25793
25794function base64ToBytes (str) {
25795 return base64.toByteArray(base64clean(str))
25796}
25797
25798function blitBuffer (src, dst, offset, length) {
25799 for (var i = 0; i < length; ++i) {
25800 if ((i + offset >= dst.length) || (i >= src.length)) break
25801 dst[i + offset] = src[i]
25802 }
25803 return i
25804}
25805
25806// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
25807// the `instanceof` check but they should be treated as of that type.
25808// See: https://github.com/feross/buffer/issues/166
25809function isInstance (obj, type) {
25810 return obj instanceof type ||
25811 (obj != null && obj.constructor != null && obj.constructor.name != null &&
25812 obj.constructor.name === type.name)
25813}
25814function numberIsNaN (obj) {
25815 // For IE11 support
25816 return obj !== obj // eslint-disable-line no-self-compare
25817}
25818
25819}).call(this,require("buffer").Buffer)
25820},{"base64-js":75,"buffer":114,"ieee754":209}],115:[function(require,module,exports){
25821module.exports = {
25822 "100": "Continue",
25823 "101": "Switching Protocols",
25824 "102": "Processing",
25825 "200": "OK",
25826 "201": "Created",
25827 "202": "Accepted",
25828 "203": "Non-Authoritative Information",
25829 "204": "No Content",
25830 "205": "Reset Content",
25831 "206": "Partial Content",
25832 "207": "Multi-Status",
25833 "208": "Already Reported",
25834 "226": "IM Used",
25835 "300": "Multiple Choices",
25836 "301": "Moved Permanently",
25837 "302": "Found",
25838 "303": "See Other",
25839 "304": "Not Modified",
25840 "305": "Use Proxy",
25841 "307": "Temporary Redirect",
25842 "308": "Permanent Redirect",
25843 "400": "Bad Request",
25844 "401": "Unauthorized",
25845 "402": "Payment Required",
25846 "403": "Forbidden",
25847 "404": "Not Found",
25848 "405": "Method Not Allowed",
25849 "406": "Not Acceptable",
25850 "407": "Proxy Authentication Required",
25851 "408": "Request Timeout",
25852 "409": "Conflict",
25853 "410": "Gone",
25854 "411": "Length Required",
25855 "412": "Precondition Failed",
25856 "413": "Payload Too Large",
25857 "414": "URI Too Long",
25858 "415": "Unsupported Media Type",
25859 "416": "Range Not Satisfiable",
25860 "417": "Expectation Failed",
25861 "418": "I'm a teapot",
25862 "421": "Misdirected Request",
25863 "422": "Unprocessable Entity",
25864 "423": "Locked",
25865 "424": "Failed Dependency",
25866 "425": "Unordered Collection",
25867 "426": "Upgrade Required",
25868 "428": "Precondition Required",
25869 "429": "Too Many Requests",
25870 "431": "Request Header Fields Too Large",
25871 "451": "Unavailable For Legal Reasons",
25872 "500": "Internal Server Error",
25873 "501": "Not Implemented",
25874 "502": "Bad Gateway",
25875 "503": "Service Unavailable",
25876 "504": "Gateway Timeout",
25877 "505": "HTTP Version Not Supported",
25878 "506": "Variant Also Negotiates",
25879 "507": "Insufficient Storage",
25880 "508": "Loop Detected",
25881 "509": "Bandwidth Limit Exceeded",
25882 "510": "Not Extended",
25883 "511": "Network Authentication Required"
25884}
25885
25886},{}],116:[function(require,module,exports){
25887function Caseless (dict) {
25888 this.dict = dict || {}
25889}
25890Caseless.prototype.set = function (name, value, clobber) {
25891 if (typeof name === 'object') {
25892 for (var i in name) {
25893 this.set(i, name[i], value)
25894 }
25895 } else {
25896 if (typeof clobber === 'undefined') clobber = true
25897 var has = this.has(name)
25898
25899 if (!clobber && has) this.dict[has] = this.dict[has] + ',' + value
25900 else this.dict[has || name] = value
25901 return has
25902 }
25903}
25904Caseless.prototype.has = function (name) {
25905 var keys = Object.keys(this.dict)
25906 , name = name.toLowerCase()
25907 ;
25908 for (var i=0;i<keys.length;i++) {
25909 if (keys[i].toLowerCase() === name) return keys[i]
25910 }
25911 return false
25912}
25913Caseless.prototype.get = function (name) {
25914 name = name.toLowerCase()
25915 var result, _key
25916 var headers = this.dict
25917 Object.keys(headers).forEach(function (key) {
25918 _key = key.toLowerCase()
25919 if (name === _key) result = headers[key]
25920 })
25921 return result
25922}
25923Caseless.prototype.swap = function (name) {
25924 var has = this.has(name)
25925 if (has === name) return
25926 if (!has) throw new Error('There is no header than matches "'+name+'"')
25927 this.dict[name] = this.dict[has]
25928 delete this.dict[has]
25929}
25930Caseless.prototype.del = function (name) {
25931 var has = this.has(name)
25932 return delete this.dict[has || name]
25933}
25934
25935module.exports = function (dict) {return new Caseless(dict)}
25936module.exports.httpify = function (resp, headers) {
25937 var c = new Caseless(headers)
25938 resp.setHeader = function (key, value, clobber) {
25939 if (typeof value === 'undefined') return
25940 return c.set(key, value, clobber)
25941 }
25942 resp.hasHeader = function (key) {
25943 return c.has(key)
25944 }
25945 resp.getHeader = function (key) {
25946 return c.get(key)
25947 }
25948 resp.removeHeader = function (key) {
25949 return c.del(key)
25950 }
25951 resp.headers = c.dict
25952 return c
25953}
25954
25955},{}],117:[function(require,module,exports){
25956var Buffer = require('safe-buffer').Buffer
25957var Transform = require('stream').Transform
25958var StringDecoder = require('string_decoder').StringDecoder
25959var inherits = require('inherits')
25960
25961function CipherBase (hashMode) {
25962 Transform.call(this)
25963 this.hashMode = typeof hashMode === 'string'
25964 if (this.hashMode) {
25965 this[hashMode] = this._finalOrDigest
25966 } else {
25967 this.final = this._finalOrDigest
25968 }
25969 if (this._final) {
25970 this.__final = this._final
25971 this._final = null
25972 }
25973 this._decoder = null
25974 this._encoding = null
25975}
25976inherits(CipherBase, Transform)
25977
25978CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
25979 if (typeof data === 'string') {
25980 data = Buffer.from(data, inputEnc)
25981 }
25982
25983 var outData = this._update(data)
25984 if (this.hashMode) return this
25985
25986 if (outputEnc) {
25987 outData = this._toString(outData, outputEnc)
25988 }
25989
25990 return outData
25991}
25992
25993CipherBase.prototype.setAutoPadding = function () {}
25994CipherBase.prototype.getAuthTag = function () {
25995 throw new Error('trying to get auth tag in unsupported state')
25996}
25997
25998CipherBase.prototype.setAuthTag = function () {
25999 throw new Error('trying to set auth tag in unsupported state')
26000}
26001
26002CipherBase.prototype.setAAD = function () {
26003 throw new Error('trying to set aad in unsupported state')
26004}
26005
26006CipherBase.prototype._transform = function (data, _, next) {
26007 var err
26008 try {
26009 if (this.hashMode) {
26010 this._update(data)
26011 } else {
26012 this.push(this._update(data))
26013 }
26014 } catch (e) {
26015 err = e
26016 } finally {
26017 next(err)
26018 }
26019}
26020CipherBase.prototype._flush = function (done) {
26021 var err
26022 try {
26023 this.push(this.__final())
26024 } catch (e) {
26025 err = e
26026 }
26027
26028 done(err)
26029}
26030CipherBase.prototype._finalOrDigest = function (outputEnc) {
26031 var outData = this.__final() || Buffer.alloc(0)
26032 if (outputEnc) {
26033 outData = this._toString(outData, outputEnc, true)
26034 }
26035 return outData
26036}
26037
26038CipherBase.prototype._toString = function (value, enc, fin) {
26039 if (!this._decoder) {
26040 this._decoder = new StringDecoder(enc)
26041 this._encoding = enc
26042 }
26043
26044 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
26045
26046 var out = this._decoder.write(value)
26047 if (fin) {
26048 out += this._decoder.end()
26049 }
26050
26051 return out
26052}
26053
26054module.exports = CipherBase
26055
26056},{"inherits":210,"safe-buffer":325,"stream":361,"string_decoder":381}],118:[function(require,module,exports){
26057(function (Buffer){
26058var util = require('util');
26059var Stream = require('stream').Stream;
26060var DelayedStream = require('delayed-stream');
26061var defer = require('./defer.js');
26062
26063module.exports = CombinedStream;
26064function CombinedStream() {
26065 this.writable = false;
26066 this.readable = true;
26067 this.dataSize = 0;
26068 this.maxDataSize = 2 * 1024 * 1024;
26069 this.pauseStreams = true;
26070
26071 this._released = false;
26072 this._streams = [];
26073 this._currentStream = null;
26074}
26075util.inherits(CombinedStream, Stream);
26076
26077CombinedStream.create = function(options) {
26078 var combinedStream = new this();
26079
26080 options = options || {};
26081 for (var option in options) {
26082 combinedStream[option] = options[option];
26083 }
26084
26085 return combinedStream;
26086};
26087
26088CombinedStream.isStreamLike = function(stream) {
26089 return (typeof stream !== 'function')
26090 && (typeof stream !== 'string')
26091 && (typeof stream !== 'boolean')
26092 && (typeof stream !== 'number')
26093 && (!Buffer.isBuffer(stream));
26094};
26095
26096CombinedStream.prototype.append = function(stream) {
26097 var isStreamLike = CombinedStream.isStreamLike(stream);
26098
26099 if (isStreamLike) {
26100 if (!(stream instanceof DelayedStream)) {
26101 var newStream = DelayedStream.create(stream, {
26102 maxDataSize: Infinity,
26103 pauseStream: this.pauseStreams,
26104 });
26105 stream.on('data', this._checkDataSize.bind(this));
26106 stream = newStream;
26107 }
26108
26109 this._handleErrors(stream);
26110
26111 if (this.pauseStreams) {
26112 stream.pause();
26113 }
26114 }
26115
26116 this._streams.push(stream);
26117 return this;
26118};
26119
26120CombinedStream.prototype.pipe = function(dest, options) {
26121 Stream.prototype.pipe.call(this, dest, options);
26122 this.resume();
26123 return dest;
26124};
26125
26126CombinedStream.prototype._getNext = function() {
26127 this._currentStream = null;
26128 var stream = this._streams.shift();
26129
26130
26131 if (typeof stream == 'undefined') {
26132 this.end();
26133 return;
26134 }
26135
26136 if (typeof stream !== 'function') {
26137 this._pipeNext(stream);
26138 return;
26139 }
26140
26141 var getStream = stream;
26142 getStream(function(stream) {
26143 var isStreamLike = CombinedStream.isStreamLike(stream);
26144 if (isStreamLike) {
26145 stream.on('data', this._checkDataSize.bind(this));
26146 this._handleErrors(stream);
26147 }
26148
26149 defer(this._pipeNext.bind(this, stream));
26150 }.bind(this));
26151};
26152
26153CombinedStream.prototype._pipeNext = function(stream) {
26154 this._currentStream = stream;
26155
26156 var isStreamLike = CombinedStream.isStreamLike(stream);
26157 if (isStreamLike) {
26158 stream.on('end', this._getNext.bind(this));
26159 stream.pipe(this, {end: false});
26160 return;
26161 }
26162
26163 var value = stream;
26164 this.write(value);
26165 this._getNext();
26166};
26167
26168CombinedStream.prototype._handleErrors = function(stream) {
26169 var self = this;
26170 stream.on('error', function(err) {
26171 self._emitError(err);
26172 });
26173};
26174
26175CombinedStream.prototype.write = function(data) {
26176 this.emit('data', data);
26177};
26178
26179CombinedStream.prototype.pause = function() {
26180 if (!this.pauseStreams) {
26181 return;
26182 }
26183
26184 if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause();
26185 this.emit('pause');
26186};
26187
26188CombinedStream.prototype.resume = function() {
26189 if (!this._released) {
26190 this._released = true;
26191 this.writable = true;
26192 this._getNext();
26193 }
26194
26195 if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume();
26196 this.emit('resume');
26197};
26198
26199CombinedStream.prototype.end = function() {
26200 this._reset();
26201 this.emit('end');
26202};
26203
26204CombinedStream.prototype.destroy = function() {
26205 this._reset();
26206 this.emit('close');
26207};
26208
26209CombinedStream.prototype._reset = function() {
26210 this.writable = false;
26211 this._streams = [];
26212 this._currentStream = null;
26213};
26214
26215CombinedStream.prototype._checkDataSize = function() {
26216 this._updateDataSize();
26217 if (this.dataSize <= this.maxDataSize) {
26218 return;
26219 }
26220
26221 var message =
26222 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.';
26223 this._emitError(new Error(message));
26224};
26225
26226CombinedStream.prototype._updateDataSize = function() {
26227 this.dataSize = 0;
26228
26229 var self = this;
26230 this._streams.forEach(function(stream) {
26231 if (!stream.dataSize) {
26232 return;
26233 }
26234
26235 self.dataSize += stream.dataSize;
26236 });
26237
26238 if (this._currentStream && this._currentStream.dataSize) {
26239 this.dataSize += this._currentStream.dataSize;
26240 }
26241};
26242
26243CombinedStream.prototype._emitError = function(err) {
26244 this._reset();
26245 this.emit('error', err);
26246};
26247
26248}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
26249},{"../../is-buffer/index.js":211,"./defer.js":119,"delayed-stream":127,"stream":361,"util":397}],119:[function(require,module,exports){
26250(function (process,setImmediate){
26251module.exports = defer;
26252
26253/**
26254 * Runs provided function on next iteration of the event loop
26255 *
26256 * @param {function} fn - function to run
26257 */
26258function defer(fn)
26259{
26260 var nextTick = typeof setImmediate == 'function'
26261 ? setImmediate
26262 : (
26263 typeof process == 'object' && typeof process.nextTick == 'function'
26264 ? process.nextTick
26265 : null
26266 );
26267
26268 if (nextTick)
26269 {
26270 nextTick(fn);
26271 }
26272 else
26273 {
26274 setTimeout(fn, 0);
26275 }
26276}
26277
26278}).call(this,require('_process'),require("timers").setImmediate)
26279},{"_process":265,"timers":382}],120:[function(require,module,exports){
26280(function (Buffer){
26281// Copyright Joyent, Inc. and other Node contributors.
26282//
26283// Permission is hereby granted, free of charge, to any person obtaining a
26284// copy of this software and associated documentation files (the
26285// "Software"), to deal in the Software without restriction, including
26286// without limitation the rights to use, copy, modify, merge, publish,
26287// distribute, sublicense, and/or sell copies of the Software, and to permit
26288// persons to whom the Software is furnished to do so, subject to the
26289// following conditions:
26290//
26291// The above copyright notice and this permission notice shall be included
26292// in all copies or substantial portions of the Software.
26293//
26294// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26295// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26296// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26297// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26298// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26299// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26300// USE OR OTHER DEALINGS IN THE SOFTWARE.
26301
26302// NOTE: These type checking functions intentionally don't use `instanceof`
26303// because it is fragile and can be easily faked with `Object.create()`.
26304
26305function isArray(arg) {
26306 if (Array.isArray) {
26307 return Array.isArray(arg);
26308 }
26309 return objectToString(arg) === '[object Array]';
26310}
26311exports.isArray = isArray;
26312
26313function isBoolean(arg) {
26314 return typeof arg === 'boolean';
26315}
26316exports.isBoolean = isBoolean;
26317
26318function isNull(arg) {
26319 return arg === null;
26320}
26321exports.isNull = isNull;
26322
26323function isNullOrUndefined(arg) {
26324 return arg == null;
26325}
26326exports.isNullOrUndefined = isNullOrUndefined;
26327
26328function isNumber(arg) {
26329 return typeof arg === 'number';
26330}
26331exports.isNumber = isNumber;
26332
26333function isString(arg) {
26334 return typeof arg === 'string';
26335}
26336exports.isString = isString;
26337
26338function isSymbol(arg) {
26339 return typeof arg === 'symbol';
26340}
26341exports.isSymbol = isSymbol;
26342
26343function isUndefined(arg) {
26344 return arg === void 0;
26345}
26346exports.isUndefined = isUndefined;
26347
26348function isRegExp(re) {
26349 return objectToString(re) === '[object RegExp]';
26350}
26351exports.isRegExp = isRegExp;
26352
26353function isObject(arg) {
26354 return typeof arg === 'object' && arg !== null;
26355}
26356exports.isObject = isObject;
26357
26358function isDate(d) {
26359 return objectToString(d) === '[object Date]';
26360}
26361exports.isDate = isDate;
26362
26363function isError(e) {
26364 return (objectToString(e) === '[object Error]' || e instanceof Error);
26365}
26366exports.isError = isError;
26367
26368function isFunction(arg) {
26369 return typeof arg === 'function';
26370}
26371exports.isFunction = isFunction;
26372
26373function isPrimitive(arg) {
26374 return arg === null ||
26375 typeof arg === 'boolean' ||
26376 typeof arg === 'number' ||
26377 typeof arg === 'string' ||
26378 typeof arg === 'symbol' || // ES6 symbol
26379 typeof arg === 'undefined';
26380}
26381exports.isPrimitive = isPrimitive;
26382
26383exports.isBuffer = Buffer.isBuffer;
26384
26385function objectToString(o) {
26386 return Object.prototype.toString.call(o);
26387}
26388
26389}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
26390},{"../../is-buffer/index.js":211}],121:[function(require,module,exports){
26391(function (Buffer){
26392var elliptic = require('elliptic')
26393var BN = require('bn.js')
26394
26395module.exports = function createECDH (curve) {
26396 return new ECDH(curve)
26397}
26398
26399var aliases = {
26400 secp256k1: {
26401 name: 'secp256k1',
26402 byteLength: 32
26403 },
26404 secp224r1: {
26405 name: 'p224',
26406 byteLength: 28
26407 },
26408 prime256v1: {
26409 name: 'p256',
26410 byteLength: 32
26411 },
26412 prime192v1: {
26413 name: 'p192',
26414 byteLength: 24
26415 },
26416 ed25519: {
26417 name: 'ed25519',
26418 byteLength: 32
26419 },
26420 secp384r1: {
26421 name: 'p384',
26422 byteLength: 48
26423 },
26424 secp521r1: {
26425 name: 'p521',
26426 byteLength: 66
26427 }
26428}
26429
26430aliases.p224 = aliases.secp224r1
26431aliases.p256 = aliases.secp256r1 = aliases.prime256v1
26432aliases.p192 = aliases.secp192r1 = aliases.prime192v1
26433aliases.p384 = aliases.secp384r1
26434aliases.p521 = aliases.secp521r1
26435
26436function ECDH (curve) {
26437 this.curveType = aliases[curve]
26438 if (!this.curveType) {
26439 this.curveType = {
26440 name: curve
26441 }
26442 }
26443 this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap
26444 this.keys = void 0
26445}
26446
26447ECDH.prototype.generateKeys = function (enc, format) {
26448 this.keys = this.curve.genKeyPair()
26449 return this.getPublicKey(enc, format)
26450}
26451
26452ECDH.prototype.computeSecret = function (other, inenc, enc) {
26453 inenc = inenc || 'utf8'
26454 if (!Buffer.isBuffer(other)) {
26455 other = new Buffer(other, inenc)
26456 }
26457 var otherPub = this.curve.keyFromPublic(other).getPublic()
26458 var out = otherPub.mul(this.keys.getPrivate()).getX()
26459 return formatReturnValue(out, enc, this.curveType.byteLength)
26460}
26461
26462ECDH.prototype.getPublicKey = function (enc, format) {
26463 var key = this.keys.getPublic(format === 'compressed', true)
26464 if (format === 'hybrid') {
26465 if (key[key.length - 1] % 2) {
26466 key[0] = 7
26467 } else {
26468 key[0] = 6
26469 }
26470 }
26471 return formatReturnValue(key, enc)
26472}
26473
26474ECDH.prototype.getPrivateKey = function (enc) {
26475 return formatReturnValue(this.keys.getPrivate(), enc)
26476}
26477
26478ECDH.prototype.setPublicKey = function (pub, enc) {
26479 enc = enc || 'utf8'
26480 if (!Buffer.isBuffer(pub)) {
26481 pub = new Buffer(pub, enc)
26482 }
26483 this.keys._importPublic(pub)
26484 return this
26485}
26486
26487ECDH.prototype.setPrivateKey = function (priv, enc) {
26488 enc = enc || 'utf8'
26489 if (!Buffer.isBuffer(priv)) {
26490 priv = new Buffer(priv, enc)
26491 }
26492
26493 var _priv = new BN(priv)
26494 _priv = _priv.toString(16)
26495 this.keys = this.curve.genKeyPair()
26496 this.keys._importPrivate(_priv)
26497 return this
26498}
26499
26500function formatReturnValue (bn, enc, len) {
26501 if (!Array.isArray(bn)) {
26502 bn = bn.toArray()
26503 }
26504 var buf = new Buffer(bn)
26505 if (len && buf.length < len) {
26506 var zeros = new Buffer(len - buf.length)
26507 zeros.fill(0)
26508 buf = Buffer.concat([zeros, buf])
26509 }
26510 if (!enc) {
26511 return buf
26512 } else {
26513 return buf.toString(enc)
26514 }
26515}
26516
26517}).call(this,require("buffer").Buffer)
26518},{"bn.js":80,"buffer":114,"elliptic":142}],122:[function(require,module,exports){
26519'use strict'
26520var inherits = require('inherits')
26521var MD5 = require('md5.js')
26522var RIPEMD160 = require('ripemd160')
26523var sha = require('sha.js')
26524var Base = require('cipher-base')
26525
26526function Hash (hash) {
26527 Base.call(this, 'digest')
26528
26529 this._hash = hash
26530}
26531
26532inherits(Hash, Base)
26533
26534Hash.prototype._update = function (data) {
26535 this._hash.update(data)
26536}
26537
26538Hash.prototype._final = function () {
26539 return this._hash.digest()
26540}
26541
26542module.exports = function createHash (alg) {
26543 alg = alg.toLowerCase()
26544 if (alg === 'md5') return new MD5()
26545 if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()
26546
26547 return new Hash(sha(alg))
26548}
26549
26550},{"cipher-base":117,"inherits":210,"md5.js":232,"ripemd160":324,"sha.js":328}],123:[function(require,module,exports){
26551var MD5 = require('md5.js')
26552
26553module.exports = function (buffer) {
26554 return new MD5().update(buffer).digest()
26555}
26556
26557},{"md5.js":232}],124:[function(require,module,exports){
26558'use strict'
26559var inherits = require('inherits')
26560var Legacy = require('./legacy')
26561var Base = require('cipher-base')
26562var Buffer = require('safe-buffer').Buffer
26563var md5 = require('create-hash/md5')
26564var RIPEMD160 = require('ripemd160')
26565
26566var sha = require('sha.js')
26567
26568var ZEROS = Buffer.alloc(128)
26569
26570function Hmac (alg, key) {
26571 Base.call(this, 'digest')
26572 if (typeof key === 'string') {
26573 key = Buffer.from(key)
26574 }
26575
26576 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
26577
26578 this._alg = alg
26579 this._key = key
26580 if (key.length > blocksize) {
26581 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
26582 key = hash.update(key).digest()
26583 } else if (key.length < blocksize) {
26584 key = Buffer.concat([key, ZEROS], blocksize)
26585 }
26586
26587 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
26588 var opad = this._opad = Buffer.allocUnsafe(blocksize)
26589
26590 for (var i = 0; i < blocksize; i++) {
26591 ipad[i] = key[i] ^ 0x36
26592 opad[i] = key[i] ^ 0x5C
26593 }
26594 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
26595 this._hash.update(ipad)
26596}
26597
26598inherits(Hmac, Base)
26599
26600Hmac.prototype._update = function (data) {
26601 this._hash.update(data)
26602}
26603
26604Hmac.prototype._final = function () {
26605 var h = this._hash.digest()
26606 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
26607 return hash.update(this._opad).update(h).digest()
26608}
26609
26610module.exports = function createHmac (alg, key) {
26611 alg = alg.toLowerCase()
26612 if (alg === 'rmd160' || alg === 'ripemd160') {
26613 return new Hmac('rmd160', key)
26614 }
26615 if (alg === 'md5') {
26616 return new Legacy(md5, key)
26617 }
26618 return new Hmac(alg, key)
26619}
26620
26621},{"./legacy":125,"cipher-base":117,"create-hash/md5":123,"inherits":210,"ripemd160":324,"safe-buffer":325,"sha.js":328}],125:[function(require,module,exports){
26622'use strict'
26623var inherits = require('inherits')
26624var Buffer = require('safe-buffer').Buffer
26625
26626var Base = require('cipher-base')
26627
26628var ZEROS = Buffer.alloc(128)
26629var blocksize = 64
26630
26631function Hmac (alg, key) {
26632 Base.call(this, 'digest')
26633 if (typeof key === 'string') {
26634 key = Buffer.from(key)
26635 }
26636
26637 this._alg = alg
26638 this._key = key
26639
26640 if (key.length > blocksize) {
26641 key = alg(key)
26642 } else if (key.length < blocksize) {
26643 key = Buffer.concat([key, ZEROS], blocksize)
26644 }
26645
26646 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
26647 var opad = this._opad = Buffer.allocUnsafe(blocksize)
26648
26649 for (var i = 0; i < blocksize; i++) {
26650 ipad[i] = key[i] ^ 0x36
26651 opad[i] = key[i] ^ 0x5C
26652 }
26653
26654 this._hash = [ipad]
26655}
26656
26657inherits(Hmac, Base)
26658
26659Hmac.prototype._update = function (data) {
26660 this._hash.push(data)
26661}
26662
26663Hmac.prototype._final = function () {
26664 var h = this._alg(Buffer.concat(this._hash))
26665 return this._alg(Buffer.concat([this._opad, h]))
26666}
26667module.exports = Hmac
26668
26669},{"cipher-base":117,"inherits":210,"safe-buffer":325}],126:[function(require,module,exports){
26670'use strict'
26671
26672exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
26673exports.createHash = exports.Hash = require('create-hash')
26674exports.createHmac = exports.Hmac = require('create-hmac')
26675
26676var algos = require('browserify-sign/algos')
26677var algoKeys = Object.keys(algos)
26678var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
26679exports.getHashes = function () {
26680 return hashes
26681}
26682
26683var p = require('pbkdf2')
26684exports.pbkdf2 = p.pbkdf2
26685exports.pbkdf2Sync = p.pbkdf2Sync
26686
26687var aes = require('browserify-cipher')
26688
26689exports.Cipher = aes.Cipher
26690exports.createCipher = aes.createCipher
26691exports.Cipheriv = aes.Cipheriv
26692exports.createCipheriv = aes.createCipheriv
26693exports.Decipher = aes.Decipher
26694exports.createDecipher = aes.createDecipher
26695exports.Decipheriv = aes.Decipheriv
26696exports.createDecipheriv = aes.createDecipheriv
26697exports.getCiphers = aes.getCiphers
26698exports.listCiphers = aes.listCiphers
26699
26700var dh = require('diffie-hellman')
26701
26702exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
26703exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
26704exports.getDiffieHellman = dh.getDiffieHellman
26705exports.createDiffieHellman = dh.createDiffieHellman
26706exports.DiffieHellman = dh.DiffieHellman
26707
26708var sign = require('browserify-sign')
26709
26710exports.createSign = sign.createSign
26711exports.Sign = sign.Sign
26712exports.createVerify = sign.createVerify
26713exports.Verify = sign.Verify
26714
26715exports.createECDH = require('create-ecdh')
26716
26717var publicEncrypt = require('public-encrypt')
26718
26719exports.publicEncrypt = publicEncrypt.publicEncrypt
26720exports.privateEncrypt = publicEncrypt.privateEncrypt
26721exports.publicDecrypt = publicEncrypt.publicDecrypt
26722exports.privateDecrypt = publicEncrypt.privateDecrypt
26723
26724// the least I can do is make error messages for the rest of the node.js/crypto api.
26725// ;[
26726// 'createCredentials'
26727// ].forEach(function (name) {
26728// exports[name] = function () {
26729// throw new Error([
26730// 'sorry, ' + name + ' is not implemented yet',
26731// 'we accept pull requests',
26732// 'https://github.com/crypto-browserify/crypto-browserify'
26733// ].join('\n'))
26734// }
26735// })
26736
26737var rf = require('randomfill')
26738
26739exports.randomFill = rf.randomFill
26740exports.randomFillSync = rf.randomFillSync
26741
26742exports.createCredentials = function () {
26743 throw new Error([
26744 'sorry, createCredentials is not implemented yet',
26745 'we accept pull requests',
26746 'https://github.com/crypto-browserify/crypto-browserify'
26747 ].join('\n'))
26748}
26749
26750exports.constants = {
26751 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
26752 'DH_CHECK_P_NOT_PRIME': 1,
26753 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
26754 'DH_NOT_SUITABLE_GENERATOR': 8,
26755 'NPN_ENABLED': 1,
26756 'ALPN_ENABLED': 1,
26757 'RSA_PKCS1_PADDING': 1,
26758 'RSA_SSLV23_PADDING': 2,
26759 'RSA_NO_PADDING': 3,
26760 'RSA_PKCS1_OAEP_PADDING': 4,
26761 'RSA_X931_PADDING': 5,
26762 'RSA_PKCS1_PSS_PADDING': 6,
26763 'POINT_CONVERSION_COMPRESSED': 2,
26764 'POINT_CONVERSION_UNCOMPRESSED': 4,
26765 'POINT_CONVERSION_HYBRID': 6
26766}
26767
26768},{"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){
26769var Stream = require('stream').Stream;
26770var util = require('util');
26771
26772module.exports = DelayedStream;
26773function DelayedStream() {
26774 this.source = null;
26775 this.dataSize = 0;
26776 this.maxDataSize = 1024 * 1024;
26777 this.pauseStream = true;
26778
26779 this._maxDataSizeExceeded = false;
26780 this._released = false;
26781 this._bufferedEvents = [];
26782}
26783util.inherits(DelayedStream, Stream);
26784
26785DelayedStream.create = function(source, options) {
26786 var delayedStream = new this();
26787
26788 options = options || {};
26789 for (var option in options) {
26790 delayedStream[option] = options[option];
26791 }
26792
26793 delayedStream.source = source;
26794
26795 var realEmit = source.emit;
26796 source.emit = function() {
26797 delayedStream._handleEmit(arguments);
26798 return realEmit.apply(source, arguments);
26799 };
26800
26801 source.on('error', function() {});
26802 if (delayedStream.pauseStream) {
26803 source.pause();
26804 }
26805
26806 return delayedStream;
26807};
26808
26809Object.defineProperty(DelayedStream.prototype, 'readable', {
26810 configurable: true,
26811 enumerable: true,
26812 get: function() {
26813 return this.source.readable;
26814 }
26815});
26816
26817DelayedStream.prototype.setEncoding = function() {
26818 return this.source.setEncoding.apply(this.source, arguments);
26819};
26820
26821DelayedStream.prototype.resume = function() {
26822 if (!this._released) {
26823 this.release();
26824 }
26825
26826 this.source.resume();
26827};
26828
26829DelayedStream.prototype.pause = function() {
26830 this.source.pause();
26831};
26832
26833DelayedStream.prototype.release = function() {
26834 this._released = true;
26835
26836 this._bufferedEvents.forEach(function(args) {
26837 this.emit.apply(this, args);
26838 }.bind(this));
26839 this._bufferedEvents = [];
26840};
26841
26842DelayedStream.prototype.pipe = function() {
26843 var r = Stream.prototype.pipe.apply(this, arguments);
26844 this.resume();
26845 return r;
26846};
26847
26848DelayedStream.prototype._handleEmit = function(args) {
26849 if (this._released) {
26850 this.emit.apply(this, args);
26851 return;
26852 }
26853
26854 if (args[0] === 'data') {
26855 this.dataSize += args[1].length;
26856 this._checkIfMaxDataSizeExceeded();
26857 }
26858
26859 this._bufferedEvents.push(args);
26860};
26861
26862DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
26863 if (this._maxDataSizeExceeded) {
26864 return;
26865 }
26866
26867 if (this.dataSize <= this.maxDataSize) {
26868 return;
26869 }
26870
26871 this._maxDataSizeExceeded = true;
26872 var message =
26873 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
26874 this.emit('error', new Error(message));
26875};
26876
26877},{"stream":361,"util":397}],128:[function(require,module,exports){
26878'use strict';
26879
26880exports.utils = require('./des/utils');
26881exports.Cipher = require('./des/cipher');
26882exports.DES = require('./des/des');
26883exports.CBC = require('./des/cbc');
26884exports.EDE = require('./des/ede');
26885
26886},{"./des/cbc":129,"./des/cipher":130,"./des/des":131,"./des/ede":132,"./des/utils":133}],129:[function(require,module,exports){
26887'use strict';
26888
26889var assert = require('minimalistic-assert');
26890var inherits = require('inherits');
26891
26892var proto = {};
26893
26894function CBCState(iv) {
26895 assert.equal(iv.length, 8, 'Invalid IV length');
26896
26897 this.iv = new Array(8);
26898 for (var i = 0; i < this.iv.length; i++)
26899 this.iv[i] = iv[i];
26900}
26901
26902function instantiate(Base) {
26903 function CBC(options) {
26904 Base.call(this, options);
26905 this._cbcInit();
26906 }
26907 inherits(CBC, Base);
26908
26909 var keys = Object.keys(proto);
26910 for (var i = 0; i < keys.length; i++) {
26911 var key = keys[i];
26912 CBC.prototype[key] = proto[key];
26913 }
26914
26915 CBC.create = function create(options) {
26916 return new CBC(options);
26917 };
26918
26919 return CBC;
26920}
26921
26922exports.instantiate = instantiate;
26923
26924proto._cbcInit = function _cbcInit() {
26925 var state = new CBCState(this.options.iv);
26926 this._cbcState = state;
26927};
26928
26929proto._update = function _update(inp, inOff, out, outOff) {
26930 var state = this._cbcState;
26931 var superProto = this.constructor.super_.prototype;
26932
26933 var iv = state.iv;
26934 if (this.type === 'encrypt') {
26935 for (var i = 0; i < this.blockSize; i++)
26936 iv[i] ^= inp[inOff + i];
26937
26938 superProto._update.call(this, iv, 0, out, outOff);
26939
26940 for (var i = 0; i < this.blockSize; i++)
26941 iv[i] = out[outOff + i];
26942 } else {
26943 superProto._update.call(this, inp, inOff, out, outOff);
26944
26945 for (var i = 0; i < this.blockSize; i++)
26946 out[outOff + i] ^= iv[i];
26947
26948 for (var i = 0; i < this.blockSize; i++)
26949 iv[i] = inp[inOff + i];
26950 }
26951};
26952
26953},{"inherits":210,"minimalistic-assert":237}],130:[function(require,module,exports){
26954'use strict';
26955
26956var assert = require('minimalistic-assert');
26957
26958function Cipher(options) {
26959 this.options = options;
26960
26961 this.type = this.options.type;
26962 this.blockSize = 8;
26963 this._init();
26964
26965 this.buffer = new Array(this.blockSize);
26966 this.bufferOff = 0;
26967}
26968module.exports = Cipher;
26969
26970Cipher.prototype._init = function _init() {
26971 // Might be overrided
26972};
26973
26974Cipher.prototype.update = function update(data) {
26975 if (data.length === 0)
26976 return [];
26977
26978 if (this.type === 'decrypt')
26979 return this._updateDecrypt(data);
26980 else
26981 return this._updateEncrypt(data);
26982};
26983
26984Cipher.prototype._buffer = function _buffer(data, off) {
26985 // Append data to buffer
26986 var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
26987 for (var i = 0; i < min; i++)
26988 this.buffer[this.bufferOff + i] = data[off + i];
26989 this.bufferOff += min;
26990
26991 // Shift next
26992 return min;
26993};
26994
26995Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
26996 this._update(this.buffer, 0, out, off);
26997 this.bufferOff = 0;
26998 return this.blockSize;
26999};
27000
27001Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
27002 var inputOff = 0;
27003 var outputOff = 0;
27004
27005 var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
27006 var out = new Array(count * this.blockSize);
27007
27008 if (this.bufferOff !== 0) {
27009 inputOff += this._buffer(data, inputOff);
27010
27011 if (this.bufferOff === this.buffer.length)
27012 outputOff += this._flushBuffer(out, outputOff);
27013 }
27014
27015 // Write blocks
27016 var max = data.length - ((data.length - inputOff) % this.blockSize);
27017 for (; inputOff < max; inputOff += this.blockSize) {
27018 this._update(data, inputOff, out, outputOff);
27019 outputOff += this.blockSize;
27020 }
27021
27022 // Queue rest
27023 for (; inputOff < data.length; inputOff++, this.bufferOff++)
27024 this.buffer[this.bufferOff] = data[inputOff];
27025
27026 return out;
27027};
27028
27029Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
27030 var inputOff = 0;
27031 var outputOff = 0;
27032
27033 var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
27034 var out = new Array(count * this.blockSize);
27035
27036 // TODO(indutny): optimize it, this is far from optimal
27037 for (; count > 0; count--) {
27038 inputOff += this._buffer(data, inputOff);
27039 outputOff += this._flushBuffer(out, outputOff);
27040 }
27041
27042 // Buffer rest of the input
27043 inputOff += this._buffer(data, inputOff);
27044
27045 return out;
27046};
27047
27048Cipher.prototype.final = function final(buffer) {
27049 var first;
27050 if (buffer)
27051 first = this.update(buffer);
27052
27053 var last;
27054 if (this.type === 'encrypt')
27055 last = this._finalEncrypt();
27056 else
27057 last = this._finalDecrypt();
27058
27059 if (first)
27060 return first.concat(last);
27061 else
27062 return last;
27063};
27064
27065Cipher.prototype._pad = function _pad(buffer, off) {
27066 if (off === 0)
27067 return false;
27068
27069 while (off < buffer.length)
27070 buffer[off++] = 0;
27071
27072 return true;
27073};
27074
27075Cipher.prototype._finalEncrypt = function _finalEncrypt() {
27076 if (!this._pad(this.buffer, this.bufferOff))
27077 return [];
27078
27079 var out = new Array(this.blockSize);
27080 this._update(this.buffer, 0, out, 0);
27081 return out;
27082};
27083
27084Cipher.prototype._unpad = function _unpad(buffer) {
27085 return buffer;
27086};
27087
27088Cipher.prototype._finalDecrypt = function _finalDecrypt() {
27089 assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
27090 var out = new Array(this.blockSize);
27091 this._flushBuffer(out, 0);
27092
27093 return this._unpad(out);
27094};
27095
27096},{"minimalistic-assert":237}],131:[function(require,module,exports){
27097'use strict';
27098
27099var assert = require('minimalistic-assert');
27100var inherits = require('inherits');
27101
27102var des = require('../des');
27103var utils = des.utils;
27104var Cipher = des.Cipher;
27105
27106function DESState() {
27107 this.tmp = new Array(2);
27108 this.keys = null;
27109}
27110
27111function DES(options) {
27112 Cipher.call(this, options);
27113
27114 var state = new DESState();
27115 this._desState = state;
27116
27117 this.deriveKeys(state, options.key);
27118}
27119inherits(DES, Cipher);
27120module.exports = DES;
27121
27122DES.create = function create(options) {
27123 return new DES(options);
27124};
27125
27126var shiftTable = [
27127 1, 1, 2, 2, 2, 2, 2, 2,
27128 1, 2, 2, 2, 2, 2, 2, 1
27129];
27130
27131DES.prototype.deriveKeys = function deriveKeys(state, key) {
27132 state.keys = new Array(16 * 2);
27133
27134 assert.equal(key.length, this.blockSize, 'Invalid key length');
27135
27136 var kL = utils.readUInt32BE(key, 0);
27137 var kR = utils.readUInt32BE(key, 4);
27138
27139 utils.pc1(kL, kR, state.tmp, 0);
27140 kL = state.tmp[0];
27141 kR = state.tmp[1];
27142 for (var i = 0; i < state.keys.length; i += 2) {
27143 var shift = shiftTable[i >>> 1];
27144 kL = utils.r28shl(kL, shift);
27145 kR = utils.r28shl(kR, shift);
27146 utils.pc2(kL, kR, state.keys, i);
27147 }
27148};
27149
27150DES.prototype._update = function _update(inp, inOff, out, outOff) {
27151 var state = this._desState;
27152
27153 var l = utils.readUInt32BE(inp, inOff);
27154 var r = utils.readUInt32BE(inp, inOff + 4);
27155
27156 // Initial Permutation
27157 utils.ip(l, r, state.tmp, 0);
27158 l = state.tmp[0];
27159 r = state.tmp[1];
27160
27161 if (this.type === 'encrypt')
27162 this._encrypt(state, l, r, state.tmp, 0);
27163 else
27164 this._decrypt(state, l, r, state.tmp, 0);
27165
27166 l = state.tmp[0];
27167 r = state.tmp[1];
27168
27169 utils.writeUInt32BE(out, l, outOff);
27170 utils.writeUInt32BE(out, r, outOff + 4);
27171};
27172
27173DES.prototype._pad = function _pad(buffer, off) {
27174 var value = buffer.length - off;
27175 for (var i = off; i < buffer.length; i++)
27176 buffer[i] = value;
27177
27178 return true;
27179};
27180
27181DES.prototype._unpad = function _unpad(buffer) {
27182 var pad = buffer[buffer.length - 1];
27183 for (var i = buffer.length - pad; i < buffer.length; i++)
27184 assert.equal(buffer[i], pad);
27185
27186 return buffer.slice(0, buffer.length - pad);
27187};
27188
27189DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
27190 var l = lStart;
27191 var r = rStart;
27192
27193 // Apply f() x16 times
27194 for (var i = 0; i < state.keys.length; i += 2) {
27195 var keyL = state.keys[i];
27196 var keyR = state.keys[i + 1];
27197
27198 // f(r, k)
27199 utils.expand(r, state.tmp, 0);
27200
27201 keyL ^= state.tmp[0];
27202 keyR ^= state.tmp[1];
27203 var s = utils.substitute(keyL, keyR);
27204 var f = utils.permute(s);
27205
27206 var t = r;
27207 r = (l ^ f) >>> 0;
27208 l = t;
27209 }
27210
27211 // Reverse Initial Permutation
27212 utils.rip(r, l, out, off);
27213};
27214
27215DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
27216 var l = rStart;
27217 var r = lStart;
27218
27219 // Apply f() x16 times
27220 for (var i = state.keys.length - 2; i >= 0; i -= 2) {
27221 var keyL = state.keys[i];
27222 var keyR = state.keys[i + 1];
27223
27224 // f(r, k)
27225 utils.expand(l, state.tmp, 0);
27226
27227 keyL ^= state.tmp[0];
27228 keyR ^= state.tmp[1];
27229 var s = utils.substitute(keyL, keyR);
27230 var f = utils.permute(s);
27231
27232 var t = l;
27233 l = (r ^ f) >>> 0;
27234 r = t;
27235 }
27236
27237 // Reverse Initial Permutation
27238 utils.rip(l, r, out, off);
27239};
27240
27241},{"../des":128,"inherits":210,"minimalistic-assert":237}],132:[function(require,module,exports){
27242'use strict';
27243
27244var assert = require('minimalistic-assert');
27245var inherits = require('inherits');
27246
27247var des = require('../des');
27248var Cipher = des.Cipher;
27249var DES = des.DES;
27250
27251function EDEState(type, key) {
27252 assert.equal(key.length, 24, 'Invalid key length');
27253
27254 var k1 = key.slice(0, 8);
27255 var k2 = key.slice(8, 16);
27256 var k3 = key.slice(16, 24);
27257
27258 if (type === 'encrypt') {
27259 this.ciphers = [
27260 DES.create({ type: 'encrypt', key: k1 }),
27261 DES.create({ type: 'decrypt', key: k2 }),
27262 DES.create({ type: 'encrypt', key: k3 })
27263 ];
27264 } else {
27265 this.ciphers = [
27266 DES.create({ type: 'decrypt', key: k3 }),
27267 DES.create({ type: 'encrypt', key: k2 }),
27268 DES.create({ type: 'decrypt', key: k1 })
27269 ];
27270 }
27271}
27272
27273function EDE(options) {
27274 Cipher.call(this, options);
27275
27276 var state = new EDEState(this.type, this.options.key);
27277 this._edeState = state;
27278}
27279inherits(EDE, Cipher);
27280
27281module.exports = EDE;
27282
27283EDE.create = function create(options) {
27284 return new EDE(options);
27285};
27286
27287EDE.prototype._update = function _update(inp, inOff, out, outOff) {
27288 var state = this._edeState;
27289
27290 state.ciphers[0]._update(inp, inOff, out, outOff);
27291 state.ciphers[1]._update(out, outOff, out, outOff);
27292 state.ciphers[2]._update(out, outOff, out, outOff);
27293};
27294
27295EDE.prototype._pad = DES.prototype._pad;
27296EDE.prototype._unpad = DES.prototype._unpad;
27297
27298},{"../des":128,"inherits":210,"minimalistic-assert":237}],133:[function(require,module,exports){
27299'use strict';
27300
27301exports.readUInt32BE = function readUInt32BE(bytes, off) {
27302 var res = (bytes[0 + off] << 24) |
27303 (bytes[1 + off] << 16) |
27304 (bytes[2 + off] << 8) |
27305 bytes[3 + off];
27306 return res >>> 0;
27307};
27308
27309exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
27310 bytes[0 + off] = value >>> 24;
27311 bytes[1 + off] = (value >>> 16) & 0xff;
27312 bytes[2 + off] = (value >>> 8) & 0xff;
27313 bytes[3 + off] = value & 0xff;
27314};
27315
27316exports.ip = function ip(inL, inR, out, off) {
27317 var outL = 0;
27318 var outR = 0;
27319
27320 for (var i = 6; i >= 0; i -= 2) {
27321 for (var j = 0; j <= 24; j += 8) {
27322 outL <<= 1;
27323 outL |= (inR >>> (j + i)) & 1;
27324 }
27325 for (var j = 0; j <= 24; j += 8) {
27326 outL <<= 1;
27327 outL |= (inL >>> (j + i)) & 1;
27328 }
27329 }
27330
27331 for (var i = 6; i >= 0; i -= 2) {
27332 for (var j = 1; j <= 25; j += 8) {
27333 outR <<= 1;
27334 outR |= (inR >>> (j + i)) & 1;
27335 }
27336 for (var j = 1; j <= 25; j += 8) {
27337 outR <<= 1;
27338 outR |= (inL >>> (j + i)) & 1;
27339 }
27340 }
27341
27342 out[off + 0] = outL >>> 0;
27343 out[off + 1] = outR >>> 0;
27344};
27345
27346exports.rip = function rip(inL, inR, out, off) {
27347 var outL = 0;
27348 var outR = 0;
27349
27350 for (var i = 0; i < 4; i++) {
27351 for (var j = 24; j >= 0; j -= 8) {
27352 outL <<= 1;
27353 outL |= (inR >>> (j + i)) & 1;
27354 outL <<= 1;
27355 outL |= (inL >>> (j + i)) & 1;
27356 }
27357 }
27358 for (var i = 4; i < 8; i++) {
27359 for (var j = 24; j >= 0; j -= 8) {
27360 outR <<= 1;
27361 outR |= (inR >>> (j + i)) & 1;
27362 outR <<= 1;
27363 outR |= (inL >>> (j + i)) & 1;
27364 }
27365 }
27366
27367 out[off + 0] = outL >>> 0;
27368 out[off + 1] = outR >>> 0;
27369};
27370
27371exports.pc1 = function pc1(inL, inR, out, off) {
27372 var outL = 0;
27373 var outR = 0;
27374
27375 // 7, 15, 23, 31, 39, 47, 55, 63
27376 // 6, 14, 22, 30, 39, 47, 55, 63
27377 // 5, 13, 21, 29, 39, 47, 55, 63
27378 // 4, 12, 20, 28
27379 for (var i = 7; i >= 5; i--) {
27380 for (var j = 0; j <= 24; j += 8) {
27381 outL <<= 1;
27382 outL |= (inR >> (j + i)) & 1;
27383 }
27384 for (var j = 0; j <= 24; j += 8) {
27385 outL <<= 1;
27386 outL |= (inL >> (j + i)) & 1;
27387 }
27388 }
27389 for (var j = 0; j <= 24; j += 8) {
27390 outL <<= 1;
27391 outL |= (inR >> (j + i)) & 1;
27392 }
27393
27394 // 1, 9, 17, 25, 33, 41, 49, 57
27395 // 2, 10, 18, 26, 34, 42, 50, 58
27396 // 3, 11, 19, 27, 35, 43, 51, 59
27397 // 36, 44, 52, 60
27398 for (var i = 1; i <= 3; i++) {
27399 for (var j = 0; j <= 24; j += 8) {
27400 outR <<= 1;
27401 outR |= (inR >> (j + i)) & 1;
27402 }
27403 for (var j = 0; j <= 24; j += 8) {
27404 outR <<= 1;
27405 outR |= (inL >> (j + i)) & 1;
27406 }
27407 }
27408 for (var j = 0; j <= 24; j += 8) {
27409 outR <<= 1;
27410 outR |= (inL >> (j + i)) & 1;
27411 }
27412
27413 out[off + 0] = outL >>> 0;
27414 out[off + 1] = outR >>> 0;
27415};
27416
27417exports.r28shl = function r28shl(num, shift) {
27418 return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
27419};
27420
27421var pc2table = [
27422 // inL => outL
27423 14, 11, 17, 4, 27, 23, 25, 0,
27424 13, 22, 7, 18, 5, 9, 16, 24,
27425 2, 20, 12, 21, 1, 8, 15, 26,
27426
27427 // inR => outR
27428 15, 4, 25, 19, 9, 1, 26, 16,
27429 5, 11, 23, 8, 12, 7, 17, 0,
27430 22, 3, 10, 14, 6, 20, 27, 24
27431];
27432
27433exports.pc2 = function pc2(inL, inR, out, off) {
27434 var outL = 0;
27435 var outR = 0;
27436
27437 var len = pc2table.length >>> 1;
27438 for (var i = 0; i < len; i++) {
27439 outL <<= 1;
27440 outL |= (inL >>> pc2table[i]) & 0x1;
27441 }
27442 for (var i = len; i < pc2table.length; i++) {
27443 outR <<= 1;
27444 outR |= (inR >>> pc2table[i]) & 0x1;
27445 }
27446
27447 out[off + 0] = outL >>> 0;
27448 out[off + 1] = outR >>> 0;
27449};
27450
27451exports.expand = function expand(r, out, off) {
27452 var outL = 0;
27453 var outR = 0;
27454
27455 outL = ((r & 1) << 5) | (r >>> 27);
27456 for (var i = 23; i >= 15; i -= 4) {
27457 outL <<= 6;
27458 outL |= (r >>> i) & 0x3f;
27459 }
27460 for (var i = 11; i >= 3; i -= 4) {
27461 outR |= (r >>> i) & 0x3f;
27462 outR <<= 6;
27463 }
27464 outR |= ((r & 0x1f) << 1) | (r >>> 31);
27465
27466 out[off + 0] = outL >>> 0;
27467 out[off + 1] = outR >>> 0;
27468};
27469
27470var sTable = [
27471 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
27472 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
27473 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
27474 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
27475
27476 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
27477 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
27478 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
27479 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
27480
27481 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
27482 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
27483 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
27484 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
27485
27486 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
27487 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
27488 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
27489 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
27490
27491 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
27492 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
27493 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
27494 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
27495
27496 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
27497 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
27498 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
27499 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
27500
27501 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
27502 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
27503 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
27504 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
27505
27506 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
27507 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
27508 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
27509 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
27510];
27511
27512exports.substitute = function substitute(inL, inR) {
27513 var out = 0;
27514 for (var i = 0; i < 4; i++) {
27515 var b = (inL >>> (18 - i * 6)) & 0x3f;
27516 var sb = sTable[i * 0x40 + b];
27517
27518 out <<= 4;
27519 out |= sb;
27520 }
27521 for (var i = 0; i < 4; i++) {
27522 var b = (inR >>> (18 - i * 6)) & 0x3f;
27523 var sb = sTable[4 * 0x40 + i * 0x40 + b];
27524
27525 out <<= 4;
27526 out |= sb;
27527 }
27528 return out >>> 0;
27529};
27530
27531var permuteTable = [
27532 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
27533 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
27534];
27535
27536exports.permute = function permute(num) {
27537 var out = 0;
27538 for (var i = 0; i < permuteTable.length; i++) {
27539 out <<= 1;
27540 out |= (num >>> permuteTable[i]) & 0x1;
27541 }
27542 return out >>> 0;
27543};
27544
27545exports.padSplit = function padSplit(num, size, group) {
27546 var str = num.toString(2);
27547 while (str.length < size)
27548 str = '0' + str;
27549
27550 var out = [];
27551 for (var i = 0; i < size; i += group)
27552 out.push(str.slice(i, i + group));
27553 return out.join(' ');
27554};
27555
27556},{}],134:[function(require,module,exports){
27557(function (Buffer){
27558var generatePrime = require('./lib/generatePrime')
27559var primes = require('./lib/primes.json')
27560
27561var DH = require('./lib/dh')
27562
27563function getDiffieHellman (mod) {
27564 var prime = new Buffer(primes[mod].prime, 'hex')
27565 var gen = new Buffer(primes[mod].gen, 'hex')
27566
27567 return new DH(prime, gen)
27568}
27569
27570var ENCODINGS = {
27571 'binary': true, 'hex': true, 'base64': true
27572}
27573
27574function createDiffieHellman (prime, enc, generator, genc) {
27575 if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
27576 return createDiffieHellman(prime, 'binary', enc, generator)
27577 }
27578
27579 enc = enc || 'binary'
27580 genc = genc || 'binary'
27581 generator = generator || new Buffer([2])
27582
27583 if (!Buffer.isBuffer(generator)) {
27584 generator = new Buffer(generator, genc)
27585 }
27586
27587 if (typeof prime === 'number') {
27588 return new DH(generatePrime(prime, generator), generator, true)
27589 }
27590
27591 if (!Buffer.isBuffer(prime)) {
27592 prime = new Buffer(prime, enc)
27593 }
27594
27595 return new DH(prime, generator, true)
27596}
27597
27598exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
27599exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
27600
27601}).call(this,require("buffer").Buffer)
27602},{"./lib/dh":135,"./lib/generatePrime":136,"./lib/primes.json":137,"buffer":114}],135:[function(require,module,exports){
27603(function (Buffer){
27604var BN = require('bn.js');
27605var MillerRabin = require('miller-rabin');
27606var millerRabin = new MillerRabin();
27607var TWENTYFOUR = new BN(24);
27608var ELEVEN = new BN(11);
27609var TEN = new BN(10);
27610var THREE = new BN(3);
27611var SEVEN = new BN(7);
27612var primes = require('./generatePrime');
27613var randomBytes = require('randombytes');
27614module.exports = DH;
27615
27616function setPublicKey(pub, enc) {
27617 enc = enc || 'utf8';
27618 if (!Buffer.isBuffer(pub)) {
27619 pub = new Buffer(pub, enc);
27620 }
27621 this._pub = new BN(pub);
27622 return this;
27623}
27624
27625function setPrivateKey(priv, enc) {
27626 enc = enc || 'utf8';
27627 if (!Buffer.isBuffer(priv)) {
27628 priv = new Buffer(priv, enc);
27629 }
27630 this._priv = new BN(priv);
27631 return this;
27632}
27633
27634var primeCache = {};
27635function checkPrime(prime, generator) {
27636 var gen = generator.toString('hex');
27637 var hex = [gen, prime.toString(16)].join('_');
27638 if (hex in primeCache) {
27639 return primeCache[hex];
27640 }
27641 var error = 0;
27642
27643 if (prime.isEven() ||
27644 !primes.simpleSieve ||
27645 !primes.fermatTest(prime) ||
27646 !millerRabin.test(prime)) {
27647 //not a prime so +1
27648 error += 1;
27649
27650 if (gen === '02' || gen === '05') {
27651 // we'd be able to check the generator
27652 // it would fail so +8
27653 error += 8;
27654 } else {
27655 //we wouldn't be able to test the generator
27656 // so +4
27657 error += 4;
27658 }
27659 primeCache[hex] = error;
27660 return error;
27661 }
27662 if (!millerRabin.test(prime.shrn(1))) {
27663 //not a safe prime
27664 error += 2;
27665 }
27666 var rem;
27667 switch (gen) {
27668 case '02':
27669 if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
27670 // unsuidable generator
27671 error += 8;
27672 }
27673 break;
27674 case '05':
27675 rem = prime.mod(TEN);
27676 if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
27677 // prime mod 10 needs to equal 3 or 7
27678 error += 8;
27679 }
27680 break;
27681 default:
27682 error += 4;
27683 }
27684 primeCache[hex] = error;
27685 return error;
27686}
27687
27688function DH(prime, generator, malleable) {
27689 this.setGenerator(generator);
27690 this.__prime = new BN(prime);
27691 this._prime = BN.mont(this.__prime);
27692 this._primeLen = prime.length;
27693 this._pub = undefined;
27694 this._priv = undefined;
27695 this._primeCode = undefined;
27696 if (malleable) {
27697 this.setPublicKey = setPublicKey;
27698 this.setPrivateKey = setPrivateKey;
27699 } else {
27700 this._primeCode = 8;
27701 }
27702}
27703Object.defineProperty(DH.prototype, 'verifyError', {
27704 enumerable: true,
27705 get: function () {
27706 if (typeof this._primeCode !== 'number') {
27707 this._primeCode = checkPrime(this.__prime, this.__gen);
27708 }
27709 return this._primeCode;
27710 }
27711});
27712DH.prototype.generateKeys = function () {
27713 if (!this._priv) {
27714 this._priv = new BN(randomBytes(this._primeLen));
27715 }
27716 this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
27717 return this.getPublicKey();
27718};
27719
27720DH.prototype.computeSecret = function (other) {
27721 other = new BN(other);
27722 other = other.toRed(this._prime);
27723 var secret = other.redPow(this._priv).fromRed();
27724 var out = new Buffer(secret.toArray());
27725 var prime = this.getPrime();
27726 if (out.length < prime.length) {
27727 var front = new Buffer(prime.length - out.length);
27728 front.fill(0);
27729 out = Buffer.concat([front, out]);
27730 }
27731 return out;
27732};
27733
27734DH.prototype.getPublicKey = function getPublicKey(enc) {
27735 return formatReturnValue(this._pub, enc);
27736};
27737
27738DH.prototype.getPrivateKey = function getPrivateKey(enc) {
27739 return formatReturnValue(this._priv, enc);
27740};
27741
27742DH.prototype.getPrime = function (enc) {
27743 return formatReturnValue(this.__prime, enc);
27744};
27745
27746DH.prototype.getGenerator = function (enc) {
27747 return formatReturnValue(this._gen, enc);
27748};
27749
27750DH.prototype.setGenerator = function (gen, enc) {
27751 enc = enc || 'utf8';
27752 if (!Buffer.isBuffer(gen)) {
27753 gen = new Buffer(gen, enc);
27754 }
27755 this.__gen = gen;
27756 this._gen = new BN(gen);
27757 return this;
27758};
27759
27760function formatReturnValue(bn, enc) {
27761 var buf = new Buffer(bn.toArray());
27762 if (!enc) {
27763 return buf;
27764 } else {
27765 return buf.toString(enc);
27766 }
27767}
27768
27769}).call(this,require("buffer").Buffer)
27770},{"./generatePrime":136,"bn.js":80,"buffer":114,"miller-rabin":233,"randombytes":278}],136:[function(require,module,exports){
27771var randomBytes = require('randombytes');
27772module.exports = findPrime;
27773findPrime.simpleSieve = simpleSieve;
27774findPrime.fermatTest = fermatTest;
27775var BN = require('bn.js');
27776var TWENTYFOUR = new BN(24);
27777var MillerRabin = require('miller-rabin');
27778var millerRabin = new MillerRabin();
27779var ONE = new BN(1);
27780var TWO = new BN(2);
27781var FIVE = new BN(5);
27782var SIXTEEN = new BN(16);
27783var EIGHT = new BN(8);
27784var TEN = new BN(10);
27785var THREE = new BN(3);
27786var SEVEN = new BN(7);
27787var ELEVEN = new BN(11);
27788var FOUR = new BN(4);
27789var TWELVE = new BN(12);
27790var primes = null;
27791
27792function _getPrimes() {
27793 if (primes !== null)
27794 return primes;
27795
27796 var limit = 0x100000;
27797 var res = [];
27798 res[0] = 2;
27799 for (var i = 1, k = 3; k < limit; k += 2) {
27800 var sqrt = Math.ceil(Math.sqrt(k));
27801 for (var j = 0; j < i && res[j] <= sqrt; j++)
27802 if (k % res[j] === 0)
27803 break;
27804
27805 if (i !== j && res[j] <= sqrt)
27806 continue;
27807
27808 res[i++] = k;
27809 }
27810 primes = res;
27811 return res;
27812}
27813
27814function simpleSieve(p) {
27815 var primes = _getPrimes();
27816
27817 for (var i = 0; i < primes.length; i++)
27818 if (p.modn(primes[i]) === 0) {
27819 if (p.cmpn(primes[i]) === 0) {
27820 return true;
27821 } else {
27822 return false;
27823 }
27824 }
27825
27826 return true;
27827}
27828
27829function fermatTest(p) {
27830 var red = BN.mont(p);
27831 return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
27832}
27833
27834function findPrime(bits, gen) {
27835 if (bits < 16) {
27836 // this is what openssl does
27837 if (gen === 2 || gen === 5) {
27838 return new BN([0x8c, 0x7b]);
27839 } else {
27840 return new BN([0x8c, 0x27]);
27841 }
27842 }
27843 gen = new BN(gen);
27844
27845 var num, n2;
27846
27847 while (true) {
27848 num = new BN(randomBytes(Math.ceil(bits / 8)));
27849 while (num.bitLength() > bits) {
27850 num.ishrn(1);
27851 }
27852 if (num.isEven()) {
27853 num.iadd(ONE);
27854 }
27855 if (!num.testn(1)) {
27856 num.iadd(TWO);
27857 }
27858 if (!gen.cmp(TWO)) {
27859 while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
27860 num.iadd(FOUR);
27861 }
27862 } else if (!gen.cmp(FIVE)) {
27863 while (num.mod(TEN).cmp(THREE)) {
27864 num.iadd(FOUR);
27865 }
27866 }
27867 n2 = num.shrn(1);
27868 if (simpleSieve(n2) && simpleSieve(num) &&
27869 fermatTest(n2) && fermatTest(num) &&
27870 millerRabin.test(n2) && millerRabin.test(num)) {
27871 return num;
27872 }
27873 }
27874
27875}
27876
27877},{"bn.js":80,"miller-rabin":233,"randombytes":278}],137:[function(require,module,exports){
27878module.exports={
27879 "modp1": {
27880 "gen": "02",
27881 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
27882 },
27883 "modp2": {
27884 "gen": "02",
27885 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
27886 },
27887 "modp5": {
27888 "gen": "02",
27889 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
27890 },
27891 "modp14": {
27892 "gen": "02",
27893 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
27894 },
27895 "modp15": {
27896 "gen": "02",
27897 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
27898 },
27899 "modp16": {
27900 "gen": "02",
27901 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
27902 },
27903 "modp17": {
27904 "gen": "02",
27905 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
27906 },
27907 "modp18": {
27908 "gen": "02",
27909 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
27910 }
27911}
27912},{}],138:[function(require,module,exports){
27913(function (process){
27914/* @flow */
27915/*::
27916
27917type DotenvParseOptions = {
27918 debug?: boolean
27919}
27920
27921// keys and values from src
27922type DotenvParseOutput = { [string]: string }
27923
27924type DotenvConfigOptions = {
27925 path?: string, // path to .env file
27926 encoding?: string, // encoding of .env file
27927 debug?: string // turn on logging for debugging purposes
27928}
27929
27930type DotenvConfigOutput = {
27931 parsed?: DotenvParseOutput,
27932 error?: Error
27933}
27934
27935*/
27936
27937const fs = require('fs')
27938const path = require('path')
27939
27940function log (message /*: string */) {
27941 console.log(`[dotenv][DEBUG] ${message}`)
27942}
27943
27944const NEWLINE = '\n'
27945const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/
27946const RE_NEWLINES = /\\n/g
27947const NEWLINES_MATCH = /\n|\r|\r\n/
27948
27949// Parses src into an Object
27950function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ {
27951 const debug = Boolean(options && options.debug)
27952 const obj = {}
27953
27954 // convert Buffers before splitting into lines and processing
27955 src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) {
27956 // matching "KEY' and 'VAL' in 'KEY=VAL'
27957 const keyValueArr = line.match(RE_INI_KEY_VAL)
27958 // matched?
27959 if (keyValueArr != null) {
27960 const key = keyValueArr[1]
27961 // default undefined or missing values to empty string
27962 let val = (keyValueArr[2] || '')
27963 const end = val.length - 1
27964 const isDoubleQuoted = val[0] === '"' && val[end] === '"'
27965 const isSingleQuoted = val[0] === "'" && val[end] === "'"
27966
27967 // if single or double quoted, remove quotes
27968 if (isSingleQuoted || isDoubleQuoted) {
27969 val = val.substring(1, end)
27970
27971 // if double quoted, expand newlines
27972 if (isDoubleQuoted) {
27973 val = val.replace(RE_NEWLINES, NEWLINE)
27974 }
27975 } else {
27976 // remove surrounding whitespace
27977 val = val.trim()
27978 }
27979
27980 obj[key] = val
27981 } else if (debug) {
27982 log(`did not match key and value when parsing line ${idx + 1}: ${line}`)
27983 }
27984 })
27985
27986 return obj
27987}
27988
27989// Populates process.env from .env file
27990function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ {
27991 let dotenvPath = path.resolve(process.cwd(), '.env')
27992 let encoding /*: string */ = 'utf8'
27993 let debug = false
27994
27995 if (options) {
27996 if (options.path != null) {
27997 dotenvPath = options.path
27998 }
27999 if (options.encoding != null) {
28000 encoding = options.encoding
28001 }
28002 if (options.debug != null) {
28003 debug = true
28004 }
28005 }
28006
28007 try {
28008 // specifying an encoding returns a string instead of a buffer
28009 const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug })
28010
28011 Object.keys(parsed).forEach(function (key) {
28012 if (!Object.prototype.hasOwnProperty.call(process.env, key)) {
28013 process.env[key] = parsed[key]
28014 } else if (debug) {
28015 log(`"${key}" is already defined in \`process.env\` and will not be overwritten`)
28016 }
28017 })
28018
28019 return { parsed }
28020 } catch (e) {
28021 return { error: e }
28022 }
28023}
28024
28025module.exports.config = config
28026module.exports.parse = parse
28027
28028}).call(this,require('_process'))
28029},{"_process":265,"fs":112,"path":257}],139:[function(require,module,exports){
28030var crypto = require("crypto");
28031var BigInteger = require("jsbn").BigInteger;
28032var ECPointFp = require("./lib/ec.js").ECPointFp;
28033var Buffer = require("safer-buffer").Buffer;
28034exports.ECCurves = require("./lib/sec.js");
28035
28036// zero prepad
28037function unstupid(hex,len)
28038{
28039 return (hex.length >= len) ? hex : unstupid("0"+hex,len);
28040}
28041
28042exports.ECKey = function(curve, key, isPublic)
28043{
28044 var priv;
28045 var c = curve();
28046 var n = c.getN();
28047 var bytes = Math.floor(n.bitLength()/8);
28048
28049 if(key)
28050 {
28051 if(isPublic)
28052 {
28053 var curve = c.getCurve();
28054// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format
28055// var y = key.slice(bytes+1);
28056// this.P = new ECPointFp(curve,
28057// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)),
28058// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16)));
28059 this.P = curve.decodePointHex(key.toString("hex"));
28060 }else{
28061 if(key.length != bytes) return false;
28062 priv = new BigInteger(key.toString("hex"), 16);
28063 }
28064 }else{
28065 var n1 = n.subtract(BigInteger.ONE);
28066 var r = new BigInteger(crypto.randomBytes(n.bitLength()));
28067 priv = r.mod(n1).add(BigInteger.ONE);
28068 this.P = c.getG().multiply(priv);
28069 }
28070 if(this.P)
28071 {
28072// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2);
28073// this.PublicKey = Buffer.from("04"+pubhex,"hex");
28074 this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex");
28075 }
28076 if(priv)
28077 {
28078 this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex");
28079 this.deriveSharedSecret = function(key)
28080 {
28081 if(!key || !key.P) return false;
28082 var S = key.P.multiply(priv);
28083 return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex");
28084 }
28085 }
28086}
28087
28088
28089},{"./lib/ec.js":140,"./lib/sec.js":141,"crypto":126,"jsbn":215,"safer-buffer":326}],140:[function(require,module,exports){
28090// Basic Javascript Elliptic Curve implementation
28091// Ported loosely from BouncyCastle's Java EC code
28092// Only Fp curves implemented for now
28093
28094// Requires jsbn.js and jsbn2.js
28095var BigInteger = require('jsbn').BigInteger
28096var Barrett = BigInteger.prototype.Barrett
28097
28098// ----------------
28099// ECFieldElementFp
28100
28101// constructor
28102function ECFieldElementFp(q,x) {
28103 this.x = x;
28104 // TODO if(x.compareTo(q) >= 0) error
28105 this.q = q;
28106}
28107
28108function feFpEquals(other) {
28109 if(other == this) return true;
28110 return (this.q.equals(other.q) && this.x.equals(other.x));
28111}
28112
28113function feFpToBigInteger() {
28114 return this.x;
28115}
28116
28117function feFpNegate() {
28118 return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
28119}
28120
28121function feFpAdd(b) {
28122 return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
28123}
28124
28125function feFpSubtract(b) {
28126 return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
28127}
28128
28129function feFpMultiply(b) {
28130 return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
28131}
28132
28133function feFpSquare() {
28134 return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
28135}
28136
28137function feFpDivide(b) {
28138 return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
28139}
28140
28141ECFieldElementFp.prototype.equals = feFpEquals;
28142ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger;
28143ECFieldElementFp.prototype.negate = feFpNegate;
28144ECFieldElementFp.prototype.add = feFpAdd;
28145ECFieldElementFp.prototype.subtract = feFpSubtract;
28146ECFieldElementFp.prototype.multiply = feFpMultiply;
28147ECFieldElementFp.prototype.square = feFpSquare;
28148ECFieldElementFp.prototype.divide = feFpDivide;
28149
28150// ----------------
28151// ECPointFp
28152
28153// constructor
28154function ECPointFp(curve,x,y,z) {
28155 this.curve = curve;
28156 this.x = x;
28157 this.y = y;
28158 // Projective coordinates: either zinv == null or z * zinv == 1
28159 // z and zinv are just BigIntegers, not fieldElements
28160 if(z == null) {
28161 this.z = BigInteger.ONE;
28162 }
28163 else {
28164 this.z = z;
28165 }
28166 this.zinv = null;
28167 //TODO: compression flag
28168}
28169
28170function pointFpGetX() {
28171 if(this.zinv == null) {
28172 this.zinv = this.z.modInverse(this.curve.q);
28173 }
28174 var r = this.x.toBigInteger().multiply(this.zinv);
28175 this.curve.reduce(r);
28176 return this.curve.fromBigInteger(r);
28177}
28178
28179function pointFpGetY() {
28180 if(this.zinv == null) {
28181 this.zinv = this.z.modInverse(this.curve.q);
28182 }
28183 var r = this.y.toBigInteger().multiply(this.zinv);
28184 this.curve.reduce(r);
28185 return this.curve.fromBigInteger(r);
28186}
28187
28188function pointFpEquals(other) {
28189 if(other == this) return true;
28190 if(this.isInfinity()) return other.isInfinity();
28191 if(other.isInfinity()) return this.isInfinity();
28192 var u, v;
28193 // u = Y2 * Z1 - Y1 * Z2
28194 u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
28195 if(!u.equals(BigInteger.ZERO)) return false;
28196 // v = X2 * Z1 - X1 * Z2
28197 v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
28198 return v.equals(BigInteger.ZERO);
28199}
28200
28201function pointFpIsInfinity() {
28202 if((this.x == null) && (this.y == null)) return true;
28203 return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
28204}
28205
28206function pointFpNegate() {
28207 return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
28208}
28209
28210function pointFpAdd(b) {
28211 if(this.isInfinity()) return b;
28212 if(b.isInfinity()) return this;
28213
28214 // u = Y2 * Z1 - Y1 * Z2
28215 var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q);
28216 // v = X2 * Z1 - X1 * Z2
28217 var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q);
28218
28219 if(BigInteger.ZERO.equals(v)) {
28220 if(BigInteger.ZERO.equals(u)) {
28221 return this.twice(); // this == b, so double
28222 }
28223 return this.curve.getInfinity(); // this = -b, so infinity
28224 }
28225
28226 var THREE = new BigInteger("3");
28227 var x1 = this.x.toBigInteger();
28228 var y1 = this.y.toBigInteger();
28229 var x2 = b.x.toBigInteger();
28230 var y2 = b.y.toBigInteger();
28231
28232 var v2 = v.square();
28233 var v3 = v2.multiply(v);
28234 var x1v2 = x1.multiply(v2);
28235 var zu2 = u.square().multiply(this.z);
28236
28237 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
28238 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q);
28239 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
28240 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);
28241 // z3 = v^3 * z1 * z2
28242 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q);
28243
28244 return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
28245}
28246
28247function pointFpTwice() {
28248 if(this.isInfinity()) return this;
28249 if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity();
28250
28251 // TODO: optimized handling of constants
28252 var THREE = new BigInteger("3");
28253 var x1 = this.x.toBigInteger();
28254 var y1 = this.y.toBigInteger();
28255
28256 var y1z1 = y1.multiply(this.z);
28257 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q);
28258 var a = this.curve.a.toBigInteger();
28259
28260 // w = 3 * x1^2 + a * z1^2
28261 var w = x1.square().multiply(THREE);
28262 if(!BigInteger.ZERO.equals(a)) {
28263 w = w.add(this.z.square().multiply(a));
28264 }
28265 w = w.mod(this.curve.q);
28266 //this.curve.reduce(w);
28267 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
28268 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q);
28269 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
28270 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q);
28271 // z3 = 8 * (y1 * z1)^3
28272 var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q);
28273
28274 return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
28275}
28276
28277// Simple NAF (Non-Adjacent Form) multiplication algorithm
28278// TODO: modularize the multiplication algorithm
28279function pointFpMultiply(k) {
28280 if(this.isInfinity()) return this;
28281 if(k.signum() == 0) return this.curve.getInfinity();
28282
28283 var e = k;
28284 var h = e.multiply(new BigInteger("3"));
28285
28286 var neg = this.negate();
28287 var R = this;
28288
28289 var i;
28290 for(i = h.bitLength() - 2; i > 0; --i) {
28291 R = R.twice();
28292
28293 var hBit = h.testBit(i);
28294 var eBit = e.testBit(i);
28295
28296 if (hBit != eBit) {
28297 R = R.add(hBit ? this : neg);
28298 }
28299 }
28300
28301 return R;
28302}
28303
28304// Compute this*j + x*k (simultaneous multiplication)
28305function pointFpMultiplyTwo(j,x,k) {
28306 var i;
28307 if(j.bitLength() > k.bitLength())
28308 i = j.bitLength() - 1;
28309 else
28310 i = k.bitLength() - 1;
28311
28312 var R = this.curve.getInfinity();
28313 var both = this.add(x);
28314 while(i >= 0) {
28315 R = R.twice();
28316 if(j.testBit(i)) {
28317 if(k.testBit(i)) {
28318 R = R.add(both);
28319 }
28320 else {
28321 R = R.add(this);
28322 }
28323 }
28324 else {
28325 if(k.testBit(i)) {
28326 R = R.add(x);
28327 }
28328 }
28329 --i;
28330 }
28331
28332 return R;
28333}
28334
28335ECPointFp.prototype.getX = pointFpGetX;
28336ECPointFp.prototype.getY = pointFpGetY;
28337ECPointFp.prototype.equals = pointFpEquals;
28338ECPointFp.prototype.isInfinity = pointFpIsInfinity;
28339ECPointFp.prototype.negate = pointFpNegate;
28340ECPointFp.prototype.add = pointFpAdd;
28341ECPointFp.prototype.twice = pointFpTwice;
28342ECPointFp.prototype.multiply = pointFpMultiply;
28343ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo;
28344
28345// ----------------
28346// ECCurveFp
28347
28348// constructor
28349function ECCurveFp(q,a,b) {
28350 this.q = q;
28351 this.a = this.fromBigInteger(a);
28352 this.b = this.fromBigInteger(b);
28353 this.infinity = new ECPointFp(this, null, null);
28354 this.reducer = new Barrett(this.q);
28355}
28356
28357function curveFpGetQ() {
28358 return this.q;
28359}
28360
28361function curveFpGetA() {
28362 return this.a;
28363}
28364
28365function curveFpGetB() {
28366 return this.b;
28367}
28368
28369function curveFpEquals(other) {
28370 if(other == this) return true;
28371 return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b));
28372}
28373
28374function curveFpGetInfinity() {
28375 return this.infinity;
28376}
28377
28378function curveFpFromBigInteger(x) {
28379 return new ECFieldElementFp(this.q, x);
28380}
28381
28382function curveReduce(x) {
28383 this.reducer.reduce(x);
28384}
28385
28386// for now, work with hex strings because they're easier in JS
28387function curveFpDecodePointHex(s) {
28388 switch(parseInt(s.substr(0,2), 16)) { // first byte
28389 case 0:
28390 return this.infinity;
28391 case 2:
28392 case 3:
28393 // point compression not supported yet
28394 return null;
28395 case 4:
28396 case 6:
28397 case 7:
28398 var len = (s.length - 2) / 2;
28399 var xHex = s.substr(2, len);
28400 var yHex = s.substr(len+2, len);
28401
28402 return new ECPointFp(this,
28403 this.fromBigInteger(new BigInteger(xHex, 16)),
28404 this.fromBigInteger(new BigInteger(yHex, 16)));
28405
28406 default: // unsupported
28407 return null;
28408 }
28409}
28410
28411function curveFpEncodePointHex(p) {
28412 if (p.isInfinity()) return "00";
28413 var xHex = p.getX().toBigInteger().toString(16);
28414 var yHex = p.getY().toBigInteger().toString(16);
28415 var oLen = this.getQ().toString(16).length;
28416 if ((oLen % 2) != 0) oLen++;
28417 while (xHex.length < oLen) {
28418 xHex = "0" + xHex;
28419 }
28420 while (yHex.length < oLen) {
28421 yHex = "0" + yHex;
28422 }
28423 return "04" + xHex + yHex;
28424}
28425
28426ECCurveFp.prototype.getQ = curveFpGetQ;
28427ECCurveFp.prototype.getA = curveFpGetA;
28428ECCurveFp.prototype.getB = curveFpGetB;
28429ECCurveFp.prototype.equals = curveFpEquals;
28430ECCurveFp.prototype.getInfinity = curveFpGetInfinity;
28431ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger;
28432ECCurveFp.prototype.reduce = curveReduce;
28433//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex;
28434ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex;
28435
28436// from: https://github.com/kaielvin/jsbn-ec-point-compression
28437ECCurveFp.prototype.decodePointHex = function(s)
28438{
28439 var yIsEven;
28440 switch(parseInt(s.substr(0,2), 16)) { // first byte
28441 case 0:
28442 return this.infinity;
28443 case 2:
28444 yIsEven = false;
28445 case 3:
28446 if(yIsEven == undefined) yIsEven = true;
28447 var len = s.length - 2;
28448 var xHex = s.substr(2, len);
28449 var x = this.fromBigInteger(new BigInteger(xHex,16));
28450 var alpha = x.multiply(x.square().add(this.getA())).add(this.getB());
28451 var beta = alpha.sqrt();
28452
28453 if (beta == null) throw "Invalid point compression";
28454
28455 var betaValue = beta.toBigInteger();
28456 if (betaValue.testBit(0) != yIsEven)
28457 {
28458 // Use the other root
28459 beta = this.fromBigInteger(this.getQ().subtract(betaValue));
28460 }
28461 return new ECPointFp(this,x,beta);
28462 case 4:
28463 case 6:
28464 case 7:
28465 var len = (s.length - 2) / 2;
28466 var xHex = s.substr(2, len);
28467 var yHex = s.substr(len+2, len);
28468
28469 return new ECPointFp(this,
28470 this.fromBigInteger(new BigInteger(xHex, 16)),
28471 this.fromBigInteger(new BigInteger(yHex, 16)));
28472
28473 default: // unsupported
28474 return null;
28475 }
28476}
28477ECCurveFp.prototype.encodeCompressedPointHex = function(p)
28478{
28479 if (p.isInfinity()) return "00";
28480 var xHex = p.getX().toBigInteger().toString(16);
28481 var oLen = this.getQ().toString(16).length;
28482 if ((oLen % 2) != 0) oLen++;
28483 while (xHex.length < oLen)
28484 xHex = "0" + xHex;
28485 var yPrefix;
28486 if(p.getY().toBigInteger().isEven()) yPrefix = "02";
28487 else yPrefix = "03";
28488
28489 return yPrefix + xHex;
28490}
28491
28492
28493ECFieldElementFp.prototype.getR = function()
28494{
28495 if(this.r != undefined) return this.r;
28496
28497 this.r = null;
28498 var bitLength = this.q.bitLength();
28499 if (bitLength > 128)
28500 {
28501 var firstWord = this.q.shiftRight(bitLength - 64);
28502 if (firstWord.intValue() == -1)
28503 {
28504 this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q);
28505 }
28506 }
28507 return this.r;
28508}
28509ECFieldElementFp.prototype.modMult = function(x1,x2)
28510{
28511 return this.modReduce(x1.multiply(x2));
28512}
28513ECFieldElementFp.prototype.modReduce = function(x)
28514{
28515 if (this.getR() != null)
28516 {
28517 var qLen = q.bitLength();
28518 while (x.bitLength() > (qLen + 1))
28519 {
28520 var u = x.shiftRight(qLen);
28521 var v = x.subtract(u.shiftLeft(qLen));
28522 if (!this.getR().equals(BigInteger.ONE))
28523 {
28524 u = u.multiply(this.getR());
28525 }
28526 x = u.add(v);
28527 }
28528 while (x.compareTo(q) >= 0)
28529 {
28530 x = x.subtract(q);
28531 }
28532 }
28533 else
28534 {
28535 x = x.mod(q);
28536 }
28537 return x;
28538}
28539ECFieldElementFp.prototype.sqrt = function()
28540{
28541 if (!this.q.testBit(0)) throw "unsupported";
28542
28543 // p mod 4 == 3
28544 if (this.q.testBit(1))
28545 {
28546 var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q));
28547 return z.square().equals(this) ? z : null;
28548 }
28549
28550 // p mod 4 == 1
28551 var qMinusOne = this.q.subtract(BigInteger.ONE);
28552
28553 var legendreExponent = qMinusOne.shiftRight(1);
28554 if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE)))
28555 {
28556 return null;
28557 }
28558
28559 var u = qMinusOne.shiftRight(2);
28560 var k = u.shiftLeft(1).add(BigInteger.ONE);
28561
28562 var Q = this.x;
28563 var fourQ = modDouble(modDouble(Q));
28564
28565 var U, V;
28566 do
28567 {
28568 var P;
28569 do
28570 {
28571 P = new BigInteger(this.q.bitLength(), new SecureRandom());
28572 }
28573 while (P.compareTo(this.q) >= 0
28574 || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne)));
28575
28576 var result = this.lucasSequence(P, Q, k);
28577 U = result[0];
28578 V = result[1];
28579
28580 if (this.modMult(V, V).equals(fourQ))
28581 {
28582 // Integer division by 2, mod q
28583 if (V.testBit(0))
28584 {
28585 V = V.add(q);
28586 }
28587
28588 V = V.shiftRight(1);
28589
28590 return new ECFieldElementFp(q,V);
28591 }
28592 }
28593 while (U.equals(BigInteger.ONE) || U.equals(qMinusOne));
28594
28595 return null;
28596}
28597ECFieldElementFp.prototype.lucasSequence = function(P,Q,k)
28598{
28599 var n = k.bitLength();
28600 var s = k.getLowestSetBit();
28601
28602 var Uh = BigInteger.ONE;
28603 var Vl = BigInteger.TWO;
28604 var Vh = P;
28605 var Ql = BigInteger.ONE;
28606 var Qh = BigInteger.ONE;
28607
28608 for (var j = n - 1; j >= s + 1; --j)
28609 {
28610 Ql = this.modMult(Ql, Qh);
28611
28612 if (k.testBit(j))
28613 {
28614 Qh = this.modMult(Ql, Q);
28615 Uh = this.modMult(Uh, Vh);
28616 Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
28617 Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)));
28618 }
28619 else
28620 {
28621 Qh = Ql;
28622 Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
28623 Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
28624 Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
28625 }
28626 }
28627
28628 Ql = this.modMult(Ql, Qh);
28629 Qh = this.modMult(Ql, Q);
28630 Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
28631 Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
28632 Ql = this.modMult(Ql, Qh);
28633
28634 for (var j = 1; j <= s; ++j)
28635 {
28636 Uh = this.modMult(Uh, Vl);
28637 Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
28638 Ql = this.modMult(Ql, Ql);
28639 }
28640
28641 return [ Uh, Vl ];
28642}
28643
28644var exports = {
28645 ECCurveFp: ECCurveFp,
28646 ECPointFp: ECPointFp,
28647 ECFieldElementFp: ECFieldElementFp
28648}
28649
28650module.exports = exports
28651
28652},{"jsbn":215}],141:[function(require,module,exports){
28653// Named EC curves
28654
28655// Requires ec.js, jsbn.js, and jsbn2.js
28656var BigInteger = require('jsbn').BigInteger
28657var ECCurveFp = require('./ec.js').ECCurveFp
28658
28659
28660// ----------------
28661// X9ECParameters
28662
28663// constructor
28664function X9ECParameters(curve,g,n,h) {
28665 this.curve = curve;
28666 this.g = g;
28667 this.n = n;
28668 this.h = h;
28669}
28670
28671function x9getCurve() {
28672 return this.curve;
28673}
28674
28675function x9getG() {
28676 return this.g;
28677}
28678
28679function x9getN() {
28680 return this.n;
28681}
28682
28683function x9getH() {
28684 return this.h;
28685}
28686
28687X9ECParameters.prototype.getCurve = x9getCurve;
28688X9ECParameters.prototype.getG = x9getG;
28689X9ECParameters.prototype.getN = x9getN;
28690X9ECParameters.prototype.getH = x9getH;
28691
28692// ----------------
28693// SECNamedCurves
28694
28695function fromHex(s) { return new BigInteger(s, 16); }
28696
28697function secp128r1() {
28698 // p = 2^128 - 2^97 - 1
28699 var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
28700 var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
28701 var b = fromHex("E87579C11079F43DD824993C2CEE5ED3");
28702 //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679");
28703 var n = fromHex("FFFFFFFE0000000075A30D1B9038A115");
28704 var h = BigInteger.ONE;
28705 var curve = new ECCurveFp(p, a, b);
28706 var G = curve.decodePointHex("04"
28707 + "161FF7528B899B2D0C28607CA52C5B86"
28708 + "CF5AC8395BAFEB13C02DA292DDED7A83");
28709 return new X9ECParameters(curve, G, n, h);
28710}
28711
28712function secp160k1() {
28713 // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
28714 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
28715 var a = BigInteger.ZERO;
28716 var b = fromHex("7");
28717 //byte[] S = null;
28718 var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
28719 var h = BigInteger.ONE;
28720 var curve = new ECCurveFp(p, a, b);
28721 var G = curve.decodePointHex("04"
28722 + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
28723 + "938CF935318FDCED6BC28286531733C3F03C4FEE");
28724 return new X9ECParameters(curve, G, n, h);
28725}
28726
28727function secp160r1() {
28728 // p = 2^160 - 2^31 - 1
28729 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
28730 var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
28731 var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
28732 //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345");
28733 var n = fromHex("0100000000000000000001F4C8F927AED3CA752257");
28734 var h = BigInteger.ONE;
28735 var curve = new ECCurveFp(p, a, b);
28736 var G = curve.decodePointHex("04"
28737 + "4A96B5688EF573284664698968C38BB913CBFC82"
28738 + "23A628553168947D59DCC912042351377AC5FB32");
28739 return new X9ECParameters(curve, G, n, h);
28740}
28741
28742function secp192k1() {
28743 // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
28744 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
28745 var a = BigInteger.ZERO;
28746 var b = fromHex("3");
28747 //byte[] S = null;
28748 var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
28749 var h = BigInteger.ONE;
28750 var curve = new ECCurveFp(p, a, b);
28751 var G = curve.decodePointHex("04"
28752 + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
28753 + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");
28754 return new X9ECParameters(curve, G, n, h);
28755}
28756
28757function secp192r1() {
28758 // p = 2^192 - 2^64 - 1
28759 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
28760 var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
28761 var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
28762 //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
28763 var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
28764 var h = BigInteger.ONE;
28765 var curve = new ECCurveFp(p, a, b);
28766 var G = curve.decodePointHex("04"
28767 + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
28768 + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
28769 return new X9ECParameters(curve, G, n, h);
28770}
28771
28772function secp224r1() {
28773 // p = 2^224 - 2^96 + 1
28774 var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
28775 var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
28776 var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
28777 //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
28778 var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
28779 var h = BigInteger.ONE;
28780 var curve = new ECCurveFp(p, a, b);
28781 var G = curve.decodePointHex("04"
28782 + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
28783 + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");
28784 return new X9ECParameters(curve, G, n, h);
28785}
28786
28787function secp256r1() {
28788 // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
28789 var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
28790 var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
28791 var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
28792 //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90");
28793 var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
28794 var h = BigInteger.ONE;
28795 var curve = new ECCurveFp(p, a, b);
28796 var G = curve.decodePointHex("04"
28797 + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
28798 + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
28799 return new X9ECParameters(curve, G, n, h);
28800}
28801
28802// TODO: make this into a proper hashtable
28803function getSECCurveByName(name) {
28804 if(name == "secp128r1") return secp128r1();
28805 if(name == "secp160k1") return secp160k1();
28806 if(name == "secp160r1") return secp160r1();
28807 if(name == "secp192k1") return secp192k1();
28808 if(name == "secp192r1") return secp192r1();
28809 if(name == "secp224r1") return secp224r1();
28810 if(name == "secp256r1") return secp256r1();
28811 return null;
28812}
28813
28814module.exports = {
28815 "secp128r1":secp128r1,
28816 "secp160k1":secp160k1,
28817 "secp160r1":secp160r1,
28818 "secp192k1":secp192k1,
28819 "secp192r1":secp192r1,
28820 "secp224r1":secp224r1,
28821 "secp256r1":secp256r1
28822}
28823
28824},{"./ec.js":140,"jsbn":215}],142:[function(require,module,exports){
28825'use strict';
28826
28827var elliptic = exports;
28828
28829elliptic.version = require('../package.json').version;
28830elliptic.utils = require('./elliptic/utils');
28831elliptic.rand = require('brorand');
28832elliptic.curve = require('./elliptic/curve');
28833elliptic.curves = require('./elliptic/curves');
28834
28835// Protocols
28836elliptic.ec = require('./elliptic/ec');
28837elliptic.eddsa = require('./elliptic/eddsa');
28838
28839},{"../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){
28840'use strict';
28841
28842var BN = require('bn.js');
28843var elliptic = require('../../elliptic');
28844var utils = elliptic.utils;
28845var getNAF = utils.getNAF;
28846var getJSF = utils.getJSF;
28847var assert = utils.assert;
28848
28849function BaseCurve(type, conf) {
28850 this.type = type;
28851 this.p = new BN(conf.p, 16);
28852
28853 // Use Montgomery, when there is no fast reduction for the prime
28854 this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
28855
28856 // Useful for many curves
28857 this.zero = new BN(0).toRed(this.red);
28858 this.one = new BN(1).toRed(this.red);
28859 this.two = new BN(2).toRed(this.red);
28860
28861 // Curve configuration, optional
28862 this.n = conf.n && new BN(conf.n, 16);
28863 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
28864
28865 // Temporary arrays
28866 this._wnafT1 = new Array(4);
28867 this._wnafT2 = new Array(4);
28868 this._wnafT3 = new Array(4);
28869 this._wnafT4 = new Array(4);
28870
28871 // Generalized Greg Maxwell's trick
28872 var adjustCount = this.n && this.p.div(this.n);
28873 if (!adjustCount || adjustCount.cmpn(100) > 0) {
28874 this.redN = null;
28875 } else {
28876 this._maxwellTrick = true;
28877 this.redN = this.n.toRed(this.red);
28878 }
28879}
28880module.exports = BaseCurve;
28881
28882BaseCurve.prototype.point = function point() {
28883 throw new Error('Not implemented');
28884};
28885
28886BaseCurve.prototype.validate = function validate() {
28887 throw new Error('Not implemented');
28888};
28889
28890BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
28891 assert(p.precomputed);
28892 var doubles = p._getDoubles();
28893
28894 var naf = getNAF(k, 1);
28895 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
28896 I /= 3;
28897
28898 // Translate into more windowed form
28899 var repr = [];
28900 for (var j = 0; j < naf.length; j += doubles.step) {
28901 var nafW = 0;
28902 for (var k = j + doubles.step - 1; k >= j; k--)
28903 nafW = (nafW << 1) + naf[k];
28904 repr.push(nafW);
28905 }
28906
28907 var a = this.jpoint(null, null, null);
28908 var b = this.jpoint(null, null, null);
28909 for (var i = I; i > 0; i--) {
28910 for (var j = 0; j < repr.length; j++) {
28911 var nafW = repr[j];
28912 if (nafW === i)
28913 b = b.mixedAdd(doubles.points[j]);
28914 else if (nafW === -i)
28915 b = b.mixedAdd(doubles.points[j].neg());
28916 }
28917 a = a.add(b);
28918 }
28919 return a.toP();
28920};
28921
28922BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
28923 var w = 4;
28924
28925 // Precompute window
28926 var nafPoints = p._getNAFPoints(w);
28927 w = nafPoints.wnd;
28928 var wnd = nafPoints.points;
28929
28930 // Get NAF form
28931 var naf = getNAF(k, w);
28932
28933 // Add `this`*(N+1) for every w-NAF index
28934 var acc = this.jpoint(null, null, null);
28935 for (var i = naf.length - 1; i >= 0; i--) {
28936 // Count zeroes
28937 for (var k = 0; i >= 0 && naf[i] === 0; i--)
28938 k++;
28939 if (i >= 0)
28940 k++;
28941 acc = acc.dblp(k);
28942
28943 if (i < 0)
28944 break;
28945 var z = naf[i];
28946 assert(z !== 0);
28947 if (p.type === 'affine') {
28948 // J +- P
28949 if (z > 0)
28950 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
28951 else
28952 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
28953 } else {
28954 // J +- J
28955 if (z > 0)
28956 acc = acc.add(wnd[(z - 1) >> 1]);
28957 else
28958 acc = acc.add(wnd[(-z - 1) >> 1].neg());
28959 }
28960 }
28961 return p.type === 'affine' ? acc.toP() : acc;
28962};
28963
28964BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
28965 points,
28966 coeffs,
28967 len,
28968 jacobianResult) {
28969 var wndWidth = this._wnafT1;
28970 var wnd = this._wnafT2;
28971 var naf = this._wnafT3;
28972
28973 // Fill all arrays
28974 var max = 0;
28975 for (var i = 0; i < len; i++) {
28976 var p = points[i];
28977 var nafPoints = p._getNAFPoints(defW);
28978 wndWidth[i] = nafPoints.wnd;
28979 wnd[i] = nafPoints.points;
28980 }
28981
28982 // Comb small window NAFs
28983 for (var i = len - 1; i >= 1; i -= 2) {
28984 var a = i - 1;
28985 var b = i;
28986 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
28987 naf[a] = getNAF(coeffs[a], wndWidth[a]);
28988 naf[b] = getNAF(coeffs[b], wndWidth[b]);
28989 max = Math.max(naf[a].length, max);
28990 max = Math.max(naf[b].length, max);
28991 continue;
28992 }
28993
28994 var comb = [
28995 points[a], /* 1 */
28996 null, /* 3 */
28997 null, /* 5 */
28998 points[b] /* 7 */
28999 ];
29000
29001 // Try to avoid Projective points, if possible
29002 if (points[a].y.cmp(points[b].y) === 0) {
29003 comb[1] = points[a].add(points[b]);
29004 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
29005 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
29006 comb[1] = points[a].toJ().mixedAdd(points[b]);
29007 comb[2] = points[a].add(points[b].neg());
29008 } else {
29009 comb[1] = points[a].toJ().mixedAdd(points[b]);
29010 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
29011 }
29012
29013 var index = [
29014 -3, /* -1 -1 */
29015 -1, /* -1 0 */
29016 -5, /* -1 1 */
29017 -7, /* 0 -1 */
29018 0, /* 0 0 */
29019 7, /* 0 1 */
29020 5, /* 1 -1 */
29021 1, /* 1 0 */
29022 3 /* 1 1 */
29023 ];
29024
29025 var jsf = getJSF(coeffs[a], coeffs[b]);
29026 max = Math.max(jsf[0].length, max);
29027 naf[a] = new Array(max);
29028 naf[b] = new Array(max);
29029 for (var j = 0; j < max; j++) {
29030 var ja = jsf[0][j] | 0;
29031 var jb = jsf[1][j] | 0;
29032
29033 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
29034 naf[b][j] = 0;
29035 wnd[a] = comb;
29036 }
29037 }
29038
29039 var acc = this.jpoint(null, null, null);
29040 var tmp = this._wnafT4;
29041 for (var i = max; i >= 0; i--) {
29042 var k = 0;
29043
29044 while (i >= 0) {
29045 var zero = true;
29046 for (var j = 0; j < len; j++) {
29047 tmp[j] = naf[j][i] | 0;
29048 if (tmp[j] !== 0)
29049 zero = false;
29050 }
29051 if (!zero)
29052 break;
29053 k++;
29054 i--;
29055 }
29056 if (i >= 0)
29057 k++;
29058 acc = acc.dblp(k);
29059 if (i < 0)
29060 break;
29061
29062 for (var j = 0; j < len; j++) {
29063 var z = tmp[j];
29064 var p;
29065 if (z === 0)
29066 continue;
29067 else if (z > 0)
29068 p = wnd[j][(z - 1) >> 1];
29069 else if (z < 0)
29070 p = wnd[j][(-z - 1) >> 1].neg();
29071
29072 if (p.type === 'affine')
29073 acc = acc.mixedAdd(p);
29074 else
29075 acc = acc.add(p);
29076 }
29077 }
29078 // Zeroify references
29079 for (var i = 0; i < len; i++)
29080 wnd[i] = null;
29081
29082 if (jacobianResult)
29083 return acc;
29084 else
29085 return acc.toP();
29086};
29087
29088function BasePoint(curve, type) {
29089 this.curve = curve;
29090 this.type = type;
29091 this.precomputed = null;
29092}
29093BaseCurve.BasePoint = BasePoint;
29094
29095BasePoint.prototype.eq = function eq(/*other*/) {
29096 throw new Error('Not implemented');
29097};
29098
29099BasePoint.prototype.validate = function validate() {
29100 return this.curve.validate(this);
29101};
29102
29103BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
29104 bytes = utils.toArray(bytes, enc);
29105
29106 var len = this.p.byteLength();
29107
29108 // uncompressed, hybrid-odd, hybrid-even
29109 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
29110 bytes.length - 1 === 2 * len) {
29111 if (bytes[0] === 0x06)
29112 assert(bytes[bytes.length - 1] % 2 === 0);
29113 else if (bytes[0] === 0x07)
29114 assert(bytes[bytes.length - 1] % 2 === 1);
29115
29116 var res = this.point(bytes.slice(1, 1 + len),
29117 bytes.slice(1 + len, 1 + 2 * len));
29118
29119 return res;
29120 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
29121 bytes.length - 1 === len) {
29122 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
29123 }
29124 throw new Error('Unknown point format');
29125};
29126
29127BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
29128 return this.encode(enc, true);
29129};
29130
29131BasePoint.prototype._encode = function _encode(compact) {
29132 var len = this.curve.p.byteLength();
29133 var x = this.getX().toArray('be', len);
29134
29135 if (compact)
29136 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
29137
29138 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
29139};
29140
29141BasePoint.prototype.encode = function encode(enc, compact) {
29142 return utils.encode(this._encode(compact), enc);
29143};
29144
29145BasePoint.prototype.precompute = function precompute(power) {
29146 if (this.precomputed)
29147 return this;
29148
29149 var precomputed = {
29150 doubles: null,
29151 naf: null,
29152 beta: null
29153 };
29154 precomputed.naf = this._getNAFPoints(8);
29155 precomputed.doubles = this._getDoubles(4, power);
29156 precomputed.beta = this._getBeta();
29157 this.precomputed = precomputed;
29158
29159 return this;
29160};
29161
29162BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
29163 if (!this.precomputed)
29164 return false;
29165
29166 var doubles = this.precomputed.doubles;
29167 if (!doubles)
29168 return false;
29169
29170 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
29171};
29172
29173BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
29174 if (this.precomputed && this.precomputed.doubles)
29175 return this.precomputed.doubles;
29176
29177 var doubles = [ this ];
29178 var acc = this;
29179 for (var i = 0; i < power; i += step) {
29180 for (var j = 0; j < step; j++)
29181 acc = acc.dbl();
29182 doubles.push(acc);
29183 }
29184 return {
29185 step: step,
29186 points: doubles
29187 };
29188};
29189
29190BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
29191 if (this.precomputed && this.precomputed.naf)
29192 return this.precomputed.naf;
29193
29194 var res = [ this ];
29195 var max = (1 << wnd) - 1;
29196 var dbl = max === 1 ? null : this.dbl();
29197 for (var i = 1; i < max; i++)
29198 res[i] = res[i - 1].add(dbl);
29199 return {
29200 wnd: wnd,
29201 points: res
29202 };
29203};
29204
29205BasePoint.prototype._getBeta = function _getBeta() {
29206 return null;
29207};
29208
29209BasePoint.prototype.dblp = function dblp(k) {
29210 var r = this;
29211 for (var i = 0; i < k; i++)
29212 r = r.dbl();
29213 return r;
29214};
29215
29216},{"../../elliptic":142,"bn.js":80}],144:[function(require,module,exports){
29217'use strict';
29218
29219var curve = require('../curve');
29220var elliptic = require('../../elliptic');
29221var BN = require('bn.js');
29222var inherits = require('inherits');
29223var Base = curve.base;
29224
29225var assert = elliptic.utils.assert;
29226
29227function EdwardsCurve(conf) {
29228 // NOTE: Important as we are creating point in Base.call()
29229 this.twisted = (conf.a | 0) !== 1;
29230 this.mOneA = this.twisted && (conf.a | 0) === -1;
29231 this.extended = this.mOneA;
29232
29233 Base.call(this, 'edwards', conf);
29234
29235 this.a = new BN(conf.a, 16).umod(this.red.m);
29236 this.a = this.a.toRed(this.red);
29237 this.c = new BN(conf.c, 16).toRed(this.red);
29238 this.c2 = this.c.redSqr();
29239 this.d = new BN(conf.d, 16).toRed(this.red);
29240 this.dd = this.d.redAdd(this.d);
29241
29242 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
29243 this.oneC = (conf.c | 0) === 1;
29244}
29245inherits(EdwardsCurve, Base);
29246module.exports = EdwardsCurve;
29247
29248EdwardsCurve.prototype._mulA = function _mulA(num) {
29249 if (this.mOneA)
29250 return num.redNeg();
29251 else
29252 return this.a.redMul(num);
29253};
29254
29255EdwardsCurve.prototype._mulC = function _mulC(num) {
29256 if (this.oneC)
29257 return num;
29258 else
29259 return this.c.redMul(num);
29260};
29261
29262// Just for compatibility with Short curve
29263EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
29264 return this.point(x, y, z, t);
29265};
29266
29267EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
29268 x = new BN(x, 16);
29269 if (!x.red)
29270 x = x.toRed(this.red);
29271
29272 var x2 = x.redSqr();
29273 var rhs = this.c2.redSub(this.a.redMul(x2));
29274 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
29275
29276 var y2 = rhs.redMul(lhs.redInvm());
29277 var y = y2.redSqrt();
29278 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
29279 throw new Error('invalid point');
29280
29281 var isOdd = y.fromRed().isOdd();
29282 if (odd && !isOdd || !odd && isOdd)
29283 y = y.redNeg();
29284
29285 return this.point(x, y);
29286};
29287
29288EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
29289 y = new BN(y, 16);
29290 if (!y.red)
29291 y = y.toRed(this.red);
29292
29293 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
29294 var y2 = y.redSqr();
29295 var lhs = y2.redSub(this.c2);
29296 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
29297 var x2 = lhs.redMul(rhs.redInvm());
29298
29299 if (x2.cmp(this.zero) === 0) {
29300 if (odd)
29301 throw new Error('invalid point');
29302 else
29303 return this.point(this.zero, y);
29304 }
29305
29306 var x = x2.redSqrt();
29307 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
29308 throw new Error('invalid point');
29309
29310 if (x.fromRed().isOdd() !== odd)
29311 x = x.redNeg();
29312
29313 return this.point(x, y);
29314};
29315
29316EdwardsCurve.prototype.validate = function validate(point) {
29317 if (point.isInfinity())
29318 return true;
29319
29320 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
29321 point.normalize();
29322
29323 var x2 = point.x.redSqr();
29324 var y2 = point.y.redSqr();
29325 var lhs = x2.redMul(this.a).redAdd(y2);
29326 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
29327
29328 return lhs.cmp(rhs) === 0;
29329};
29330
29331function Point(curve, x, y, z, t) {
29332 Base.BasePoint.call(this, curve, 'projective');
29333 if (x === null && y === null && z === null) {
29334 this.x = this.curve.zero;
29335 this.y = this.curve.one;
29336 this.z = this.curve.one;
29337 this.t = this.curve.zero;
29338 this.zOne = true;
29339 } else {
29340 this.x = new BN(x, 16);
29341 this.y = new BN(y, 16);
29342 this.z = z ? new BN(z, 16) : this.curve.one;
29343 this.t = t && new BN(t, 16);
29344 if (!this.x.red)
29345 this.x = this.x.toRed(this.curve.red);
29346 if (!this.y.red)
29347 this.y = this.y.toRed(this.curve.red);
29348 if (!this.z.red)
29349 this.z = this.z.toRed(this.curve.red);
29350 if (this.t && !this.t.red)
29351 this.t = this.t.toRed(this.curve.red);
29352 this.zOne = this.z === this.curve.one;
29353
29354 // Use extended coordinates
29355 if (this.curve.extended && !this.t) {
29356 this.t = this.x.redMul(this.y);
29357 if (!this.zOne)
29358 this.t = this.t.redMul(this.z.redInvm());
29359 }
29360 }
29361}
29362inherits(Point, Base.BasePoint);
29363
29364EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
29365 return Point.fromJSON(this, obj);
29366};
29367
29368EdwardsCurve.prototype.point = function point(x, y, z, t) {
29369 return new Point(this, x, y, z, t);
29370};
29371
29372Point.fromJSON = function fromJSON(curve, obj) {
29373 return new Point(curve, obj[0], obj[1], obj[2]);
29374};
29375
29376Point.prototype.inspect = function inspect() {
29377 if (this.isInfinity())
29378 return '<EC Point Infinity>';
29379 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
29380 ' y: ' + this.y.fromRed().toString(16, 2) +
29381 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
29382};
29383
29384Point.prototype.isInfinity = function isInfinity() {
29385 // XXX This code assumes that zero is always zero in red
29386 return this.x.cmpn(0) === 0 &&
29387 (this.y.cmp(this.z) === 0 ||
29388 (this.zOne && this.y.cmp(this.curve.c) === 0));
29389};
29390
29391Point.prototype._extDbl = function _extDbl() {
29392 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
29393 // #doubling-dbl-2008-hwcd
29394 // 4M + 4S
29395
29396 // A = X1^2
29397 var a = this.x.redSqr();
29398 // B = Y1^2
29399 var b = this.y.redSqr();
29400 // C = 2 * Z1^2
29401 var c = this.z.redSqr();
29402 c = c.redIAdd(c);
29403 // D = a * A
29404 var d = this.curve._mulA(a);
29405 // E = (X1 + Y1)^2 - A - B
29406 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
29407 // G = D + B
29408 var g = d.redAdd(b);
29409 // F = G - C
29410 var f = g.redSub(c);
29411 // H = D - B
29412 var h = d.redSub(b);
29413 // X3 = E * F
29414 var nx = e.redMul(f);
29415 // Y3 = G * H
29416 var ny = g.redMul(h);
29417 // T3 = E * H
29418 var nt = e.redMul(h);
29419 // Z3 = F * G
29420 var nz = f.redMul(g);
29421 return this.curve.point(nx, ny, nz, nt);
29422};
29423
29424Point.prototype._projDbl = function _projDbl() {
29425 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
29426 // #doubling-dbl-2008-bbjlp
29427 // #doubling-dbl-2007-bl
29428 // and others
29429 // Generally 3M + 4S or 2M + 4S
29430
29431 // B = (X1 + Y1)^2
29432 var b = this.x.redAdd(this.y).redSqr();
29433 // C = X1^2
29434 var c = this.x.redSqr();
29435 // D = Y1^2
29436 var d = this.y.redSqr();
29437
29438 var nx;
29439 var ny;
29440 var nz;
29441 if (this.curve.twisted) {
29442 // E = a * C
29443 var e = this.curve._mulA(c);
29444 // F = E + D
29445 var f = e.redAdd(d);
29446 if (this.zOne) {
29447 // X3 = (B - C - D) * (F - 2)
29448 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
29449 // Y3 = F * (E - D)
29450 ny = f.redMul(e.redSub(d));
29451 // Z3 = F^2 - 2 * F
29452 nz = f.redSqr().redSub(f).redSub(f);
29453 } else {
29454 // H = Z1^2
29455 var h = this.z.redSqr();
29456 // J = F - 2 * H
29457 var j = f.redSub(h).redISub(h);
29458 // X3 = (B-C-D)*J
29459 nx = b.redSub(c).redISub(d).redMul(j);
29460 // Y3 = F * (E - D)
29461 ny = f.redMul(e.redSub(d));
29462 // Z3 = F * J
29463 nz = f.redMul(j);
29464 }
29465 } else {
29466 // E = C + D
29467 var e = c.redAdd(d);
29468 // H = (c * Z1)^2
29469 var h = this.curve._mulC(this.z).redSqr();
29470 // J = E - 2 * H
29471 var j = e.redSub(h).redSub(h);
29472 // X3 = c * (B - E) * J
29473 nx = this.curve._mulC(b.redISub(e)).redMul(j);
29474 // Y3 = c * E * (C - D)
29475 ny = this.curve._mulC(e).redMul(c.redISub(d));
29476 // Z3 = E * J
29477 nz = e.redMul(j);
29478 }
29479 return this.curve.point(nx, ny, nz);
29480};
29481
29482Point.prototype.dbl = function dbl() {
29483 if (this.isInfinity())
29484 return this;
29485
29486 // Double in extended coordinates
29487 if (this.curve.extended)
29488 return this._extDbl();
29489 else
29490 return this._projDbl();
29491};
29492
29493Point.prototype._extAdd = function _extAdd(p) {
29494 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
29495 // #addition-add-2008-hwcd-3
29496 // 8M
29497
29498 // A = (Y1 - X1) * (Y2 - X2)
29499 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
29500 // B = (Y1 + X1) * (Y2 + X2)
29501 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
29502 // C = T1 * k * T2
29503 var c = this.t.redMul(this.curve.dd).redMul(p.t);
29504 // D = Z1 * 2 * Z2
29505 var d = this.z.redMul(p.z.redAdd(p.z));
29506 // E = B - A
29507 var e = b.redSub(a);
29508 // F = D - C
29509 var f = d.redSub(c);
29510 // G = D + C
29511 var g = d.redAdd(c);
29512 // H = B + A
29513 var h = b.redAdd(a);
29514 // X3 = E * F
29515 var nx = e.redMul(f);
29516 // Y3 = G * H
29517 var ny = g.redMul(h);
29518 // T3 = E * H
29519 var nt = e.redMul(h);
29520 // Z3 = F * G
29521 var nz = f.redMul(g);
29522 return this.curve.point(nx, ny, nz, nt);
29523};
29524
29525Point.prototype._projAdd = function _projAdd(p) {
29526 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
29527 // #addition-add-2008-bbjlp
29528 // #addition-add-2007-bl
29529 // 10M + 1S
29530
29531 // A = Z1 * Z2
29532 var a = this.z.redMul(p.z);
29533 // B = A^2
29534 var b = a.redSqr();
29535 // C = X1 * X2
29536 var c = this.x.redMul(p.x);
29537 // D = Y1 * Y2
29538 var d = this.y.redMul(p.y);
29539 // E = d * C * D
29540 var e = this.curve.d.redMul(c).redMul(d);
29541 // F = B - E
29542 var f = b.redSub(e);
29543 // G = B + E
29544 var g = b.redAdd(e);
29545 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
29546 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
29547 var nx = a.redMul(f).redMul(tmp);
29548 var ny;
29549 var nz;
29550 if (this.curve.twisted) {
29551 // Y3 = A * G * (D - a * C)
29552 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
29553 // Z3 = F * G
29554 nz = f.redMul(g);
29555 } else {
29556 // Y3 = A * G * (D - C)
29557 ny = a.redMul(g).redMul(d.redSub(c));
29558 // Z3 = c * F * G
29559 nz = this.curve._mulC(f).redMul(g);
29560 }
29561 return this.curve.point(nx, ny, nz);
29562};
29563
29564Point.prototype.add = function add(p) {
29565 if (this.isInfinity())
29566 return p;
29567 if (p.isInfinity())
29568 return this;
29569
29570 if (this.curve.extended)
29571 return this._extAdd(p);
29572 else
29573 return this._projAdd(p);
29574};
29575
29576Point.prototype.mul = function mul(k) {
29577 if (this._hasDoubles(k))
29578 return this.curve._fixedNafMul(this, k);
29579 else
29580 return this.curve._wnafMul(this, k);
29581};
29582
29583Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
29584 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
29585};
29586
29587Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
29588 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
29589};
29590
29591Point.prototype.normalize = function normalize() {
29592 if (this.zOne)
29593 return this;
29594
29595 // Normalize coordinates
29596 var zi = this.z.redInvm();
29597 this.x = this.x.redMul(zi);
29598 this.y = this.y.redMul(zi);
29599 if (this.t)
29600 this.t = this.t.redMul(zi);
29601 this.z = this.curve.one;
29602 this.zOne = true;
29603 return this;
29604};
29605
29606Point.prototype.neg = function neg() {
29607 return this.curve.point(this.x.redNeg(),
29608 this.y,
29609 this.z,
29610 this.t && this.t.redNeg());
29611};
29612
29613Point.prototype.getX = function getX() {
29614 this.normalize();
29615 return this.x.fromRed();
29616};
29617
29618Point.prototype.getY = function getY() {
29619 this.normalize();
29620 return this.y.fromRed();
29621};
29622
29623Point.prototype.eq = function eq(other) {
29624 return this === other ||
29625 this.getX().cmp(other.getX()) === 0 &&
29626 this.getY().cmp(other.getY()) === 0;
29627};
29628
29629Point.prototype.eqXToP = function eqXToP(x) {
29630 var rx = x.toRed(this.curve.red).redMul(this.z);
29631 if (this.x.cmp(rx) === 0)
29632 return true;
29633
29634 var xc = x.clone();
29635 var t = this.curve.redN.redMul(this.z);
29636 for (;;) {
29637 xc.iadd(this.curve.n);
29638 if (xc.cmp(this.curve.p) >= 0)
29639 return false;
29640
29641 rx.redIAdd(t);
29642 if (this.x.cmp(rx) === 0)
29643 return true;
29644 }
29645};
29646
29647// Compatibility with BaseCurve
29648Point.prototype.toP = Point.prototype.normalize;
29649Point.prototype.mixedAdd = Point.prototype.add;
29650
29651},{"../../elliptic":142,"../curve":145,"bn.js":80,"inherits":210}],145:[function(require,module,exports){
29652'use strict';
29653
29654var curve = exports;
29655
29656curve.base = require('./base');
29657curve.short = require('./short');
29658curve.mont = require('./mont');
29659curve.edwards = require('./edwards');
29660
29661},{"./base":143,"./edwards":144,"./mont":146,"./short":147}],146:[function(require,module,exports){
29662'use strict';
29663
29664var curve = require('../curve');
29665var BN = require('bn.js');
29666var inherits = require('inherits');
29667var Base = curve.base;
29668
29669var elliptic = require('../../elliptic');
29670var utils = elliptic.utils;
29671
29672function MontCurve(conf) {
29673 Base.call(this, 'mont', conf);
29674
29675 this.a = new BN(conf.a, 16).toRed(this.red);
29676 this.b = new BN(conf.b, 16).toRed(this.red);
29677 this.i4 = new BN(4).toRed(this.red).redInvm();
29678 this.two = new BN(2).toRed(this.red);
29679 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
29680}
29681inherits(MontCurve, Base);
29682module.exports = MontCurve;
29683
29684MontCurve.prototype.validate = function validate(point) {
29685 var x = point.normalize().x;
29686 var x2 = x.redSqr();
29687 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
29688 var y = rhs.redSqrt();
29689
29690 return y.redSqr().cmp(rhs) === 0;
29691};
29692
29693function Point(curve, x, z) {
29694 Base.BasePoint.call(this, curve, 'projective');
29695 if (x === null && z === null) {
29696 this.x = this.curve.one;
29697 this.z = this.curve.zero;
29698 } else {
29699 this.x = new BN(x, 16);
29700 this.z = new BN(z, 16);
29701 if (!this.x.red)
29702 this.x = this.x.toRed(this.curve.red);
29703 if (!this.z.red)
29704 this.z = this.z.toRed(this.curve.red);
29705 }
29706}
29707inherits(Point, Base.BasePoint);
29708
29709MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
29710 return this.point(utils.toArray(bytes, enc), 1);
29711};
29712
29713MontCurve.prototype.point = function point(x, z) {
29714 return new Point(this, x, z);
29715};
29716
29717MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
29718 return Point.fromJSON(this, obj);
29719};
29720
29721Point.prototype.precompute = function precompute() {
29722 // No-op
29723};
29724
29725Point.prototype._encode = function _encode() {
29726 return this.getX().toArray('be', this.curve.p.byteLength());
29727};
29728
29729Point.fromJSON = function fromJSON(curve, obj) {
29730 return new Point(curve, obj[0], obj[1] || curve.one);
29731};
29732
29733Point.prototype.inspect = function inspect() {
29734 if (this.isInfinity())
29735 return '<EC Point Infinity>';
29736 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
29737 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
29738};
29739
29740Point.prototype.isInfinity = function isInfinity() {
29741 // XXX This code assumes that zero is always zero in red
29742 return this.z.cmpn(0) === 0;
29743};
29744
29745Point.prototype.dbl = function dbl() {
29746 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
29747 // 2M + 2S + 4A
29748
29749 // A = X1 + Z1
29750 var a = this.x.redAdd(this.z);
29751 // AA = A^2
29752 var aa = a.redSqr();
29753 // B = X1 - Z1
29754 var b = this.x.redSub(this.z);
29755 // BB = B^2
29756 var bb = b.redSqr();
29757 // C = AA - BB
29758 var c = aa.redSub(bb);
29759 // X3 = AA * BB
29760 var nx = aa.redMul(bb);
29761 // Z3 = C * (BB + A24 * C)
29762 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
29763 return this.curve.point(nx, nz);
29764};
29765
29766Point.prototype.add = function add() {
29767 throw new Error('Not supported on Montgomery curve');
29768};
29769
29770Point.prototype.diffAdd = function diffAdd(p, diff) {
29771 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
29772 // 4M + 2S + 6A
29773
29774 // A = X2 + Z2
29775 var a = this.x.redAdd(this.z);
29776 // B = X2 - Z2
29777 var b = this.x.redSub(this.z);
29778 // C = X3 + Z3
29779 var c = p.x.redAdd(p.z);
29780 // D = X3 - Z3
29781 var d = p.x.redSub(p.z);
29782 // DA = D * A
29783 var da = d.redMul(a);
29784 // CB = C * B
29785 var cb = c.redMul(b);
29786 // X5 = Z1 * (DA + CB)^2
29787 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
29788 // Z5 = X1 * (DA - CB)^2
29789 var nz = diff.x.redMul(da.redISub(cb).redSqr());
29790 return this.curve.point(nx, nz);
29791};
29792
29793Point.prototype.mul = function mul(k) {
29794 var t = k.clone();
29795 var a = this; // (N / 2) * Q + Q
29796 var b = this.curve.point(null, null); // (N / 2) * Q
29797 var c = this; // Q
29798
29799 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
29800 bits.push(t.andln(1));
29801
29802 for (var i = bits.length - 1; i >= 0; i--) {
29803 if (bits[i] === 0) {
29804 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
29805 a = a.diffAdd(b, c);
29806 // N * Q = 2 * ((N / 2) * Q + Q))
29807 b = b.dbl();
29808 } else {
29809 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
29810 b = a.diffAdd(b, c);
29811 // N * Q + Q = 2 * ((N / 2) * Q + Q)
29812 a = a.dbl();
29813 }
29814 }
29815 return b;
29816};
29817
29818Point.prototype.mulAdd = function mulAdd() {
29819 throw new Error('Not supported on Montgomery curve');
29820};
29821
29822Point.prototype.jumlAdd = function jumlAdd() {
29823 throw new Error('Not supported on Montgomery curve');
29824};
29825
29826Point.prototype.eq = function eq(other) {
29827 return this.getX().cmp(other.getX()) === 0;
29828};
29829
29830Point.prototype.normalize = function normalize() {
29831 this.x = this.x.redMul(this.z.redInvm());
29832 this.z = this.curve.one;
29833 return this;
29834};
29835
29836Point.prototype.getX = function getX() {
29837 // Normalize coordinates
29838 this.normalize();
29839
29840 return this.x.fromRed();
29841};
29842
29843},{"../../elliptic":142,"../curve":145,"bn.js":80,"inherits":210}],147:[function(require,module,exports){
29844'use strict';
29845
29846var curve = require('../curve');
29847var elliptic = require('../../elliptic');
29848var BN = require('bn.js');
29849var inherits = require('inherits');
29850var Base = curve.base;
29851
29852var assert = elliptic.utils.assert;
29853
29854function ShortCurve(conf) {
29855 Base.call(this, 'short', conf);
29856
29857 this.a = new BN(conf.a, 16).toRed(this.red);
29858 this.b = new BN(conf.b, 16).toRed(this.red);
29859 this.tinv = this.two.redInvm();
29860
29861 this.zeroA = this.a.fromRed().cmpn(0) === 0;
29862 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
29863
29864 // If the curve is endomorphic, precalculate beta and lambda
29865 this.endo = this._getEndomorphism(conf);
29866 this._endoWnafT1 = new Array(4);
29867 this._endoWnafT2 = new Array(4);
29868}
29869inherits(ShortCurve, Base);
29870module.exports = ShortCurve;
29871
29872ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
29873 // No efficient endomorphism
29874 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
29875 return;
29876
29877 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
29878 var beta;
29879 var lambda;
29880 if (conf.beta) {
29881 beta = new BN(conf.beta, 16).toRed(this.red);
29882 } else {
29883 var betas = this._getEndoRoots(this.p);
29884 // Choose the smallest beta
29885 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
29886 beta = beta.toRed(this.red);
29887 }
29888 if (conf.lambda) {
29889 lambda = new BN(conf.lambda, 16);
29890 } else {
29891 // Choose the lambda that is matching selected beta
29892 var lambdas = this._getEndoRoots(this.n);
29893 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
29894 lambda = lambdas[0];
29895 } else {
29896 lambda = lambdas[1];
29897 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
29898 }
29899 }
29900
29901 // Get basis vectors, used for balanced length-two representation
29902 var basis;
29903 if (conf.basis) {
29904 basis = conf.basis.map(function(vec) {
29905 return {
29906 a: new BN(vec.a, 16),
29907 b: new BN(vec.b, 16)
29908 };
29909 });
29910 } else {
29911 basis = this._getEndoBasis(lambda);
29912 }
29913
29914 return {
29915 beta: beta,
29916 lambda: lambda,
29917 basis: basis
29918 };
29919};
29920
29921ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
29922 // Find roots of for x^2 + x + 1 in F
29923 // Root = (-1 +- Sqrt(-3)) / 2
29924 //
29925 var red = num === this.p ? this.red : BN.mont(num);
29926 var tinv = new BN(2).toRed(red).redInvm();
29927 var ntinv = tinv.redNeg();
29928
29929 var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
29930
29931 var l1 = ntinv.redAdd(s).fromRed();
29932 var l2 = ntinv.redSub(s).fromRed();
29933 return [ l1, l2 ];
29934};
29935
29936ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
29937 // aprxSqrt >= sqrt(this.n)
29938 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
29939
29940 // 3.74
29941 // Run EGCD, until r(L + 1) < aprxSqrt
29942 var u = lambda;
29943 var v = this.n.clone();
29944 var x1 = new BN(1);
29945 var y1 = new BN(0);
29946 var x2 = new BN(0);
29947 var y2 = new BN(1);
29948
29949 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
29950 var a0;
29951 var b0;
29952 // First vector
29953 var a1;
29954 var b1;
29955 // Second vector
29956 var a2;
29957 var b2;
29958
29959 var prevR;
29960 var i = 0;
29961 var r;
29962 var x;
29963 while (u.cmpn(0) !== 0) {
29964 var q = v.div(u);
29965 r = v.sub(q.mul(u));
29966 x = x2.sub(q.mul(x1));
29967 var y = y2.sub(q.mul(y1));
29968
29969 if (!a1 && r.cmp(aprxSqrt) < 0) {
29970 a0 = prevR.neg();
29971 b0 = x1;
29972 a1 = r.neg();
29973 b1 = x;
29974 } else if (a1 && ++i === 2) {
29975 break;
29976 }
29977 prevR = r;
29978
29979 v = u;
29980 u = r;
29981 x2 = x1;
29982 x1 = x;
29983 y2 = y1;
29984 y1 = y;
29985 }
29986 a2 = r.neg();
29987 b2 = x;
29988
29989 var len1 = a1.sqr().add(b1.sqr());
29990 var len2 = a2.sqr().add(b2.sqr());
29991 if (len2.cmp(len1) >= 0) {
29992 a2 = a0;
29993 b2 = b0;
29994 }
29995
29996 // Normalize signs
29997 if (a1.negative) {
29998 a1 = a1.neg();
29999 b1 = b1.neg();
30000 }
30001 if (a2.negative) {
30002 a2 = a2.neg();
30003 b2 = b2.neg();
30004 }
30005
30006 return [
30007 { a: a1, b: b1 },
30008 { a: a2, b: b2 }
30009 ];
30010};
30011
30012ShortCurve.prototype._endoSplit = function _endoSplit(k) {
30013 var basis = this.endo.basis;
30014 var v1 = basis[0];
30015 var v2 = basis[1];
30016
30017 var c1 = v2.b.mul(k).divRound(this.n);
30018 var c2 = v1.b.neg().mul(k).divRound(this.n);
30019
30020 var p1 = c1.mul(v1.a);
30021 var p2 = c2.mul(v2.a);
30022 var q1 = c1.mul(v1.b);
30023 var q2 = c2.mul(v2.b);
30024
30025 // Calculate answer
30026 var k1 = k.sub(p1).sub(p2);
30027 var k2 = q1.add(q2).neg();
30028 return { k1: k1, k2: k2 };
30029};
30030
30031ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
30032 x = new BN(x, 16);
30033 if (!x.red)
30034 x = x.toRed(this.red);
30035
30036 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
30037 var y = y2.redSqrt();
30038 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
30039 throw new Error('invalid point');
30040
30041 // XXX Is there any way to tell if the number is odd without converting it
30042 // to non-red form?
30043 var isOdd = y.fromRed().isOdd();
30044 if (odd && !isOdd || !odd && isOdd)
30045 y = y.redNeg();
30046
30047 return this.point(x, y);
30048};
30049
30050ShortCurve.prototype.validate = function validate(point) {
30051 if (point.inf)
30052 return true;
30053
30054 var x = point.x;
30055 var y = point.y;
30056
30057 var ax = this.a.redMul(x);
30058 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
30059 return y.redSqr().redISub(rhs).cmpn(0) === 0;
30060};
30061
30062ShortCurve.prototype._endoWnafMulAdd =
30063 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
30064 var npoints = this._endoWnafT1;
30065 var ncoeffs = this._endoWnafT2;
30066 for (var i = 0; i < points.length; i++) {
30067 var split = this._endoSplit(coeffs[i]);
30068 var p = points[i];
30069 var beta = p._getBeta();
30070
30071 if (split.k1.negative) {
30072 split.k1.ineg();
30073 p = p.neg(true);
30074 }
30075 if (split.k2.negative) {
30076 split.k2.ineg();
30077 beta = beta.neg(true);
30078 }
30079
30080 npoints[i * 2] = p;
30081 npoints[i * 2 + 1] = beta;
30082 ncoeffs[i * 2] = split.k1;
30083 ncoeffs[i * 2 + 1] = split.k2;
30084 }
30085 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
30086
30087 // Clean-up references to points and coefficients
30088 for (var j = 0; j < i * 2; j++) {
30089 npoints[j] = null;
30090 ncoeffs[j] = null;
30091 }
30092 return res;
30093};
30094
30095function Point(curve, x, y, isRed) {
30096 Base.BasePoint.call(this, curve, 'affine');
30097 if (x === null && y === null) {
30098 this.x = null;
30099 this.y = null;
30100 this.inf = true;
30101 } else {
30102 this.x = new BN(x, 16);
30103 this.y = new BN(y, 16);
30104 // Force redgomery representation when loading from JSON
30105 if (isRed) {
30106 this.x.forceRed(this.curve.red);
30107 this.y.forceRed(this.curve.red);
30108 }
30109 if (!this.x.red)
30110 this.x = this.x.toRed(this.curve.red);
30111 if (!this.y.red)
30112 this.y = this.y.toRed(this.curve.red);
30113 this.inf = false;
30114 }
30115}
30116inherits(Point, Base.BasePoint);
30117
30118ShortCurve.prototype.point = function point(x, y, isRed) {
30119 return new Point(this, x, y, isRed);
30120};
30121
30122ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
30123 return Point.fromJSON(this, obj, red);
30124};
30125
30126Point.prototype._getBeta = function _getBeta() {
30127 if (!this.curve.endo)
30128 return;
30129
30130 var pre = this.precomputed;
30131 if (pre && pre.beta)
30132 return pre.beta;
30133
30134 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
30135 if (pre) {
30136 var curve = this.curve;
30137 var endoMul = function(p) {
30138 return curve.point(p.x.redMul(curve.endo.beta), p.y);
30139 };
30140 pre.beta = beta;
30141 beta.precomputed = {
30142 beta: null,
30143 naf: pre.naf && {
30144 wnd: pre.naf.wnd,
30145 points: pre.naf.points.map(endoMul)
30146 },
30147 doubles: pre.doubles && {
30148 step: pre.doubles.step,
30149 points: pre.doubles.points.map(endoMul)
30150 }
30151 };
30152 }
30153 return beta;
30154};
30155
30156Point.prototype.toJSON = function toJSON() {
30157 if (!this.precomputed)
30158 return [ this.x, this.y ];
30159
30160 return [ this.x, this.y, this.precomputed && {
30161 doubles: this.precomputed.doubles && {
30162 step: this.precomputed.doubles.step,
30163 points: this.precomputed.doubles.points.slice(1)
30164 },
30165 naf: this.precomputed.naf && {
30166 wnd: this.precomputed.naf.wnd,
30167 points: this.precomputed.naf.points.slice(1)
30168 }
30169 } ];
30170};
30171
30172Point.fromJSON = function fromJSON(curve, obj, red) {
30173 if (typeof obj === 'string')
30174 obj = JSON.parse(obj);
30175 var res = curve.point(obj[0], obj[1], red);
30176 if (!obj[2])
30177 return res;
30178
30179 function obj2point(obj) {
30180 return curve.point(obj[0], obj[1], red);
30181 }
30182
30183 var pre = obj[2];
30184 res.precomputed = {
30185 beta: null,
30186 doubles: pre.doubles && {
30187 step: pre.doubles.step,
30188 points: [ res ].concat(pre.doubles.points.map(obj2point))
30189 },
30190 naf: pre.naf && {
30191 wnd: pre.naf.wnd,
30192 points: [ res ].concat(pre.naf.points.map(obj2point))
30193 }
30194 };
30195 return res;
30196};
30197
30198Point.prototype.inspect = function inspect() {
30199 if (this.isInfinity())
30200 return '<EC Point Infinity>';
30201 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
30202 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
30203};
30204
30205Point.prototype.isInfinity = function isInfinity() {
30206 return this.inf;
30207};
30208
30209Point.prototype.add = function add(p) {
30210 // O + P = P
30211 if (this.inf)
30212 return p;
30213
30214 // P + O = P
30215 if (p.inf)
30216 return this;
30217
30218 // P + P = 2P
30219 if (this.eq(p))
30220 return this.dbl();
30221
30222 // P + (-P) = O
30223 if (this.neg().eq(p))
30224 return this.curve.point(null, null);
30225
30226 // P + Q = O
30227 if (this.x.cmp(p.x) === 0)
30228 return this.curve.point(null, null);
30229
30230 var c = this.y.redSub(p.y);
30231 if (c.cmpn(0) !== 0)
30232 c = c.redMul(this.x.redSub(p.x).redInvm());
30233 var nx = c.redSqr().redISub(this.x).redISub(p.x);
30234 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
30235 return this.curve.point(nx, ny);
30236};
30237
30238Point.prototype.dbl = function dbl() {
30239 if (this.inf)
30240 return this;
30241
30242 // 2P = O
30243 var ys1 = this.y.redAdd(this.y);
30244 if (ys1.cmpn(0) === 0)
30245 return this.curve.point(null, null);
30246
30247 var a = this.curve.a;
30248
30249 var x2 = this.x.redSqr();
30250 var dyinv = ys1.redInvm();
30251 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
30252
30253 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
30254 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
30255 return this.curve.point(nx, ny);
30256};
30257
30258Point.prototype.getX = function getX() {
30259 return this.x.fromRed();
30260};
30261
30262Point.prototype.getY = function getY() {
30263 return this.y.fromRed();
30264};
30265
30266Point.prototype.mul = function mul(k) {
30267 k = new BN(k, 16);
30268
30269 if (this._hasDoubles(k))
30270 return this.curve._fixedNafMul(this, k);
30271 else if (this.curve.endo)
30272 return this.curve._endoWnafMulAdd([ this ], [ k ]);
30273 else
30274 return this.curve._wnafMul(this, k);
30275};
30276
30277Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
30278 var points = [ this, p2 ];
30279 var coeffs = [ k1, k2 ];
30280 if (this.curve.endo)
30281 return this.curve._endoWnafMulAdd(points, coeffs);
30282 else
30283 return this.curve._wnafMulAdd(1, points, coeffs, 2);
30284};
30285
30286Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
30287 var points = [ this, p2 ];
30288 var coeffs = [ k1, k2 ];
30289 if (this.curve.endo)
30290 return this.curve._endoWnafMulAdd(points, coeffs, true);
30291 else
30292 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
30293};
30294
30295Point.prototype.eq = function eq(p) {
30296 return this === p ||
30297 this.inf === p.inf &&
30298 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
30299};
30300
30301Point.prototype.neg = function neg(_precompute) {
30302 if (this.inf)
30303 return this;
30304
30305 var res = this.curve.point(this.x, this.y.redNeg());
30306 if (_precompute && this.precomputed) {
30307 var pre = this.precomputed;
30308 var negate = function(p) {
30309 return p.neg();
30310 };
30311 res.precomputed = {
30312 naf: pre.naf && {
30313 wnd: pre.naf.wnd,
30314 points: pre.naf.points.map(negate)
30315 },
30316 doubles: pre.doubles && {
30317 step: pre.doubles.step,
30318 points: pre.doubles.points.map(negate)
30319 }
30320 };
30321 }
30322 return res;
30323};
30324
30325Point.prototype.toJ = function toJ() {
30326 if (this.inf)
30327 return this.curve.jpoint(null, null, null);
30328
30329 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
30330 return res;
30331};
30332
30333function JPoint(curve, x, y, z) {
30334 Base.BasePoint.call(this, curve, 'jacobian');
30335 if (x === null && y === null && z === null) {
30336 this.x = this.curve.one;
30337 this.y = this.curve.one;
30338 this.z = new BN(0);
30339 } else {
30340 this.x = new BN(x, 16);
30341 this.y = new BN(y, 16);
30342 this.z = new BN(z, 16);
30343 }
30344 if (!this.x.red)
30345 this.x = this.x.toRed(this.curve.red);
30346 if (!this.y.red)
30347 this.y = this.y.toRed(this.curve.red);
30348 if (!this.z.red)
30349 this.z = this.z.toRed(this.curve.red);
30350
30351 this.zOne = this.z === this.curve.one;
30352}
30353inherits(JPoint, Base.BasePoint);
30354
30355ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
30356 return new JPoint(this, x, y, z);
30357};
30358
30359JPoint.prototype.toP = function toP() {
30360 if (this.isInfinity())
30361 return this.curve.point(null, null);
30362
30363 var zinv = this.z.redInvm();
30364 var zinv2 = zinv.redSqr();
30365 var ax = this.x.redMul(zinv2);
30366 var ay = this.y.redMul(zinv2).redMul(zinv);
30367
30368 return this.curve.point(ax, ay);
30369};
30370
30371JPoint.prototype.neg = function neg() {
30372 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
30373};
30374
30375JPoint.prototype.add = function add(p) {
30376 // O + P = P
30377 if (this.isInfinity())
30378 return p;
30379
30380 // P + O = P
30381 if (p.isInfinity())
30382 return this;
30383
30384 // 12M + 4S + 7A
30385 var pz2 = p.z.redSqr();
30386 var z2 = this.z.redSqr();
30387 var u1 = this.x.redMul(pz2);
30388 var u2 = p.x.redMul(z2);
30389 var s1 = this.y.redMul(pz2.redMul(p.z));
30390 var s2 = p.y.redMul(z2.redMul(this.z));
30391
30392 var h = u1.redSub(u2);
30393 var r = s1.redSub(s2);
30394 if (h.cmpn(0) === 0) {
30395 if (r.cmpn(0) !== 0)
30396 return this.curve.jpoint(null, null, null);
30397 else
30398 return this.dbl();
30399 }
30400
30401 var h2 = h.redSqr();
30402 var h3 = h2.redMul(h);
30403 var v = u1.redMul(h2);
30404
30405 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
30406 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
30407 var nz = this.z.redMul(p.z).redMul(h);
30408
30409 return this.curve.jpoint(nx, ny, nz);
30410};
30411
30412JPoint.prototype.mixedAdd = function mixedAdd(p) {
30413 // O + P = P
30414 if (this.isInfinity())
30415 return p.toJ();
30416
30417 // P + O = P
30418 if (p.isInfinity())
30419 return this;
30420
30421 // 8M + 3S + 7A
30422 var z2 = this.z.redSqr();
30423 var u1 = this.x;
30424 var u2 = p.x.redMul(z2);
30425 var s1 = this.y;
30426 var s2 = p.y.redMul(z2).redMul(this.z);
30427
30428 var h = u1.redSub(u2);
30429 var r = s1.redSub(s2);
30430 if (h.cmpn(0) === 0) {
30431 if (r.cmpn(0) !== 0)
30432 return this.curve.jpoint(null, null, null);
30433 else
30434 return this.dbl();
30435 }
30436
30437 var h2 = h.redSqr();
30438 var h3 = h2.redMul(h);
30439 var v = u1.redMul(h2);
30440
30441 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
30442 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
30443 var nz = this.z.redMul(h);
30444
30445 return this.curve.jpoint(nx, ny, nz);
30446};
30447
30448JPoint.prototype.dblp = function dblp(pow) {
30449 if (pow === 0)
30450 return this;
30451 if (this.isInfinity())
30452 return this;
30453 if (!pow)
30454 return this.dbl();
30455
30456 if (this.curve.zeroA || this.curve.threeA) {
30457 var r = this;
30458 for (var i = 0; i < pow; i++)
30459 r = r.dbl();
30460 return r;
30461 }
30462
30463 // 1M + 2S + 1A + N * (4S + 5M + 8A)
30464 // N = 1 => 6M + 6S + 9A
30465 var a = this.curve.a;
30466 var tinv = this.curve.tinv;
30467
30468 var jx = this.x;
30469 var jy = this.y;
30470 var jz = this.z;
30471 var jz4 = jz.redSqr().redSqr();
30472
30473 // Reuse results
30474 var jyd = jy.redAdd(jy);
30475 for (var i = 0; i < pow; i++) {
30476 var jx2 = jx.redSqr();
30477 var jyd2 = jyd.redSqr();
30478 var jyd4 = jyd2.redSqr();
30479 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
30480
30481 var t1 = jx.redMul(jyd2);
30482 var nx = c.redSqr().redISub(t1.redAdd(t1));
30483 var t2 = t1.redISub(nx);
30484 var dny = c.redMul(t2);
30485 dny = dny.redIAdd(dny).redISub(jyd4);
30486 var nz = jyd.redMul(jz);
30487 if (i + 1 < pow)
30488 jz4 = jz4.redMul(jyd4);
30489
30490 jx = nx;
30491 jz = nz;
30492 jyd = dny;
30493 }
30494
30495 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
30496};
30497
30498JPoint.prototype.dbl = function dbl() {
30499 if (this.isInfinity())
30500 return this;
30501
30502 if (this.curve.zeroA)
30503 return this._zeroDbl();
30504 else if (this.curve.threeA)
30505 return this._threeDbl();
30506 else
30507 return this._dbl();
30508};
30509
30510JPoint.prototype._zeroDbl = function _zeroDbl() {
30511 var nx;
30512 var ny;
30513 var nz;
30514 // Z = 1
30515 if (this.zOne) {
30516 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
30517 // #doubling-mdbl-2007-bl
30518 // 1M + 5S + 14A
30519
30520 // XX = X1^2
30521 var xx = this.x.redSqr();
30522 // YY = Y1^2
30523 var yy = this.y.redSqr();
30524 // YYYY = YY^2
30525 var yyyy = yy.redSqr();
30526 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
30527 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
30528 s = s.redIAdd(s);
30529 // M = 3 * XX + a; a = 0
30530 var m = xx.redAdd(xx).redIAdd(xx);
30531 // T = M ^ 2 - 2*S
30532 var t = m.redSqr().redISub(s).redISub(s);
30533
30534 // 8 * YYYY
30535 var yyyy8 = yyyy.redIAdd(yyyy);
30536 yyyy8 = yyyy8.redIAdd(yyyy8);
30537 yyyy8 = yyyy8.redIAdd(yyyy8);
30538
30539 // X3 = T
30540 nx = t;
30541 // Y3 = M * (S - T) - 8 * YYYY
30542 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
30543 // Z3 = 2*Y1
30544 nz = this.y.redAdd(this.y);
30545 } else {
30546 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
30547 // #doubling-dbl-2009-l
30548 // 2M + 5S + 13A
30549
30550 // A = X1^2
30551 var a = this.x.redSqr();
30552 // B = Y1^2
30553 var b = this.y.redSqr();
30554 // C = B^2
30555 var c = b.redSqr();
30556 // D = 2 * ((X1 + B)^2 - A - C)
30557 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
30558 d = d.redIAdd(d);
30559 // E = 3 * A
30560 var e = a.redAdd(a).redIAdd(a);
30561 // F = E^2
30562 var f = e.redSqr();
30563
30564 // 8 * C
30565 var c8 = c.redIAdd(c);
30566 c8 = c8.redIAdd(c8);
30567 c8 = c8.redIAdd(c8);
30568
30569 // X3 = F - 2 * D
30570 nx = f.redISub(d).redISub(d);
30571 // Y3 = E * (D - X3) - 8 * C
30572 ny = e.redMul(d.redISub(nx)).redISub(c8);
30573 // Z3 = 2 * Y1 * Z1
30574 nz = this.y.redMul(this.z);
30575 nz = nz.redIAdd(nz);
30576 }
30577
30578 return this.curve.jpoint(nx, ny, nz);
30579};
30580
30581JPoint.prototype._threeDbl = function _threeDbl() {
30582 var nx;
30583 var ny;
30584 var nz;
30585 // Z = 1
30586 if (this.zOne) {
30587 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
30588 // #doubling-mdbl-2007-bl
30589 // 1M + 5S + 15A
30590
30591 // XX = X1^2
30592 var xx = this.x.redSqr();
30593 // YY = Y1^2
30594 var yy = this.y.redSqr();
30595 // YYYY = YY^2
30596 var yyyy = yy.redSqr();
30597 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
30598 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
30599 s = s.redIAdd(s);
30600 // M = 3 * XX + a
30601 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
30602 // T = M^2 - 2 * S
30603 var t = m.redSqr().redISub(s).redISub(s);
30604 // X3 = T
30605 nx = t;
30606 // Y3 = M * (S - T) - 8 * YYYY
30607 var yyyy8 = yyyy.redIAdd(yyyy);
30608 yyyy8 = yyyy8.redIAdd(yyyy8);
30609 yyyy8 = yyyy8.redIAdd(yyyy8);
30610 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
30611 // Z3 = 2 * Y1
30612 nz = this.y.redAdd(this.y);
30613 } else {
30614 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
30615 // 3M + 5S
30616
30617 // delta = Z1^2
30618 var delta = this.z.redSqr();
30619 // gamma = Y1^2
30620 var gamma = this.y.redSqr();
30621 // beta = X1 * gamma
30622 var beta = this.x.redMul(gamma);
30623 // alpha = 3 * (X1 - delta) * (X1 + delta)
30624 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
30625 alpha = alpha.redAdd(alpha).redIAdd(alpha);
30626 // X3 = alpha^2 - 8 * beta
30627 var beta4 = beta.redIAdd(beta);
30628 beta4 = beta4.redIAdd(beta4);
30629 var beta8 = beta4.redAdd(beta4);
30630 nx = alpha.redSqr().redISub(beta8);
30631 // Z3 = (Y1 + Z1)^2 - gamma - delta
30632 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
30633 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
30634 var ggamma8 = gamma.redSqr();
30635 ggamma8 = ggamma8.redIAdd(ggamma8);
30636 ggamma8 = ggamma8.redIAdd(ggamma8);
30637 ggamma8 = ggamma8.redIAdd(ggamma8);
30638 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
30639 }
30640
30641 return this.curve.jpoint(nx, ny, nz);
30642};
30643
30644JPoint.prototype._dbl = function _dbl() {
30645 var a = this.curve.a;
30646
30647 // 4M + 6S + 10A
30648 var jx = this.x;
30649 var jy = this.y;
30650 var jz = this.z;
30651 var jz4 = jz.redSqr().redSqr();
30652
30653 var jx2 = jx.redSqr();
30654 var jy2 = jy.redSqr();
30655
30656 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
30657
30658 var jxd4 = jx.redAdd(jx);
30659 jxd4 = jxd4.redIAdd(jxd4);
30660 var t1 = jxd4.redMul(jy2);
30661 var nx = c.redSqr().redISub(t1.redAdd(t1));
30662 var t2 = t1.redISub(nx);
30663
30664 var jyd8 = jy2.redSqr();
30665 jyd8 = jyd8.redIAdd(jyd8);
30666 jyd8 = jyd8.redIAdd(jyd8);
30667 jyd8 = jyd8.redIAdd(jyd8);
30668 var ny = c.redMul(t2).redISub(jyd8);
30669 var nz = jy.redAdd(jy).redMul(jz);
30670
30671 return this.curve.jpoint(nx, ny, nz);
30672};
30673
30674JPoint.prototype.trpl = function trpl() {
30675 if (!this.curve.zeroA)
30676 return this.dbl().add(this);
30677
30678 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
30679 // 5M + 10S + ...
30680
30681 // XX = X1^2
30682 var xx = this.x.redSqr();
30683 // YY = Y1^2
30684 var yy = this.y.redSqr();
30685 // ZZ = Z1^2
30686 var zz = this.z.redSqr();
30687 // YYYY = YY^2
30688 var yyyy = yy.redSqr();
30689 // M = 3 * XX + a * ZZ2; a = 0
30690 var m = xx.redAdd(xx).redIAdd(xx);
30691 // MM = M^2
30692 var mm = m.redSqr();
30693 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
30694 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
30695 e = e.redIAdd(e);
30696 e = e.redAdd(e).redIAdd(e);
30697 e = e.redISub(mm);
30698 // EE = E^2
30699 var ee = e.redSqr();
30700 // T = 16*YYYY
30701 var t = yyyy.redIAdd(yyyy);
30702 t = t.redIAdd(t);
30703 t = t.redIAdd(t);
30704 t = t.redIAdd(t);
30705 // U = (M + E)^2 - MM - EE - T
30706 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
30707 // X3 = 4 * (X1 * EE - 4 * YY * U)
30708 var yyu4 = yy.redMul(u);
30709 yyu4 = yyu4.redIAdd(yyu4);
30710 yyu4 = yyu4.redIAdd(yyu4);
30711 var nx = this.x.redMul(ee).redISub(yyu4);
30712 nx = nx.redIAdd(nx);
30713 nx = nx.redIAdd(nx);
30714 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
30715 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
30716 ny = ny.redIAdd(ny);
30717 ny = ny.redIAdd(ny);
30718 ny = ny.redIAdd(ny);
30719 // Z3 = (Z1 + E)^2 - ZZ - EE
30720 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
30721
30722 return this.curve.jpoint(nx, ny, nz);
30723};
30724
30725JPoint.prototype.mul = function mul(k, kbase) {
30726 k = new BN(k, kbase);
30727
30728 return this.curve._wnafMul(this, k);
30729};
30730
30731JPoint.prototype.eq = function eq(p) {
30732 if (p.type === 'affine')
30733 return this.eq(p.toJ());
30734
30735 if (this === p)
30736 return true;
30737
30738 // x1 * z2^2 == x2 * z1^2
30739 var z2 = this.z.redSqr();
30740 var pz2 = p.z.redSqr();
30741 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
30742 return false;
30743
30744 // y1 * z2^3 == y2 * z1^3
30745 var z3 = z2.redMul(this.z);
30746 var pz3 = pz2.redMul(p.z);
30747 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
30748};
30749
30750JPoint.prototype.eqXToP = function eqXToP(x) {
30751 var zs = this.z.redSqr();
30752 var rx = x.toRed(this.curve.red).redMul(zs);
30753 if (this.x.cmp(rx) === 0)
30754 return true;
30755
30756 var xc = x.clone();
30757 var t = this.curve.redN.redMul(zs);
30758 for (;;) {
30759 xc.iadd(this.curve.n);
30760 if (xc.cmp(this.curve.p) >= 0)
30761 return false;
30762
30763 rx.redIAdd(t);
30764 if (this.x.cmp(rx) === 0)
30765 return true;
30766 }
30767};
30768
30769JPoint.prototype.inspect = function inspect() {
30770 if (this.isInfinity())
30771 return '<EC JPoint Infinity>';
30772 return '<EC JPoint x: ' + this.x.toString(16, 2) +
30773 ' y: ' + this.y.toString(16, 2) +
30774 ' z: ' + this.z.toString(16, 2) + '>';
30775};
30776
30777JPoint.prototype.isInfinity = function isInfinity() {
30778 // XXX This code assumes that zero is always zero in red
30779 return this.z.cmpn(0) === 0;
30780};
30781
30782},{"../../elliptic":142,"../curve":145,"bn.js":80,"inherits":210}],148:[function(require,module,exports){
30783'use strict';
30784
30785var curves = exports;
30786
30787var hash = require('hash.js');
30788var elliptic = require('../elliptic');
30789
30790var assert = elliptic.utils.assert;
30791
30792function PresetCurve(options) {
30793 if (options.type === 'short')
30794 this.curve = new elliptic.curve.short(options);
30795 else if (options.type === 'edwards')
30796 this.curve = new elliptic.curve.edwards(options);
30797 else
30798 this.curve = new elliptic.curve.mont(options);
30799 this.g = this.curve.g;
30800 this.n = this.curve.n;
30801 this.hash = options.hash;
30802
30803 assert(this.g.validate(), 'Invalid curve');
30804 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
30805}
30806curves.PresetCurve = PresetCurve;
30807
30808function defineCurve(name, options) {
30809 Object.defineProperty(curves, name, {
30810 configurable: true,
30811 enumerable: true,
30812 get: function() {
30813 var curve = new PresetCurve(options);
30814 Object.defineProperty(curves, name, {
30815 configurable: true,
30816 enumerable: true,
30817 value: curve
30818 });
30819 return curve;
30820 }
30821 });
30822}
30823
30824defineCurve('p192', {
30825 type: 'short',
30826 prime: 'p192',
30827 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
30828 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
30829 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
30830 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
30831 hash: hash.sha256,
30832 gRed: false,
30833 g: [
30834 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
30835 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
30836 ]
30837});
30838
30839defineCurve('p224', {
30840 type: 'short',
30841 prime: 'p224',
30842 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
30843 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
30844 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
30845 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
30846 hash: hash.sha256,
30847 gRed: false,
30848 g: [
30849 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
30850 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
30851 ]
30852});
30853
30854defineCurve('p256', {
30855 type: 'short',
30856 prime: null,
30857 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
30858 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
30859 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
30860 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
30861 hash: hash.sha256,
30862 gRed: false,
30863 g: [
30864 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
30865 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
30866 ]
30867});
30868
30869defineCurve('p384', {
30870 type: 'short',
30871 prime: null,
30872 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30873 'fffffffe ffffffff 00000000 00000000 ffffffff',
30874 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30875 'fffffffe ffffffff 00000000 00000000 fffffffc',
30876 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
30877 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
30878 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
30879 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
30880 hash: hash.sha384,
30881 gRed: false,
30882 g: [
30883 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
30884 '5502f25d bf55296c 3a545e38 72760ab7',
30885 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
30886 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
30887 ]
30888});
30889
30890defineCurve('p521', {
30891 type: 'short',
30892 prime: null,
30893 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30894 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30895 'ffffffff ffffffff ffffffff ffffffff ffffffff',
30896 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30897 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30898 'ffffffff ffffffff ffffffff ffffffff fffffffc',
30899 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
30900 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
30901 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
30902 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
30903 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
30904 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
30905 hash: hash.sha512,
30906 gRed: false,
30907 g: [
30908 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
30909 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
30910 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
30911 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
30912 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
30913 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
30914 ]
30915});
30916
30917defineCurve('curve25519', {
30918 type: 'mont',
30919 prime: 'p25519',
30920 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
30921 a: '76d06',
30922 b: '1',
30923 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
30924 hash: hash.sha256,
30925 gRed: false,
30926 g: [
30927 '9'
30928 ]
30929});
30930
30931defineCurve('ed25519', {
30932 type: 'edwards',
30933 prime: 'p25519',
30934 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
30935 a: '-1',
30936 c: '1',
30937 // -121665 * (121666^(-1)) (mod P)
30938 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
30939 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
30940 hash: hash.sha256,
30941 gRed: false,
30942 g: [
30943 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
30944
30945 // 4/5
30946 '6666666666666666666666666666666666666666666666666666666666666658'
30947 ]
30948});
30949
30950var pre;
30951try {
30952 pre = require('./precomputed/secp256k1');
30953} catch (e) {
30954 pre = undefined;
30955}
30956
30957defineCurve('secp256k1', {
30958 type: 'short',
30959 prime: 'k256',
30960 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
30961 a: '0',
30962 b: '7',
30963 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
30964 h: '1',
30965 hash: hash.sha256,
30966
30967 // Precomputed endomorphism
30968 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
30969 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
30970 basis: [
30971 {
30972 a: '3086d221a7d46bcde86c90e49284eb15',
30973 b: '-e4437ed6010e88286f547fa90abfe4c3'
30974 },
30975 {
30976 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
30977 b: '3086d221a7d46bcde86c90e49284eb15'
30978 }
30979 ],
30980
30981 gRed: false,
30982 g: [
30983 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
30984 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
30985 pre
30986 ]
30987});
30988
30989},{"../elliptic":142,"./precomputed/secp256k1":155,"hash.js":190}],149:[function(require,module,exports){
30990'use strict';
30991
30992var BN = require('bn.js');
30993var HmacDRBG = require('hmac-drbg');
30994var elliptic = require('../../elliptic');
30995var utils = elliptic.utils;
30996var assert = utils.assert;
30997
30998var KeyPair = require('./key');
30999var Signature = require('./signature');
31000
31001function EC(options) {
31002 if (!(this instanceof EC))
31003 return new EC(options);
31004
31005 // Shortcut `elliptic.ec(curve-name)`
31006 if (typeof options === 'string') {
31007 assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
31008
31009 options = elliptic.curves[options];
31010 }
31011
31012 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
31013 if (options instanceof elliptic.curves.PresetCurve)
31014 options = { curve: options };
31015
31016 this.curve = options.curve.curve;
31017 this.n = this.curve.n;
31018 this.nh = this.n.ushrn(1);
31019 this.g = this.curve.g;
31020
31021 // Point on curve
31022 this.g = options.curve.g;
31023 this.g.precompute(options.curve.n.bitLength() + 1);
31024
31025 // Hash for function for DRBG
31026 this.hash = options.hash || options.curve.hash;
31027}
31028module.exports = EC;
31029
31030EC.prototype.keyPair = function keyPair(options) {
31031 return new KeyPair(this, options);
31032};
31033
31034EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
31035 return KeyPair.fromPrivate(this, priv, enc);
31036};
31037
31038EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
31039 return KeyPair.fromPublic(this, pub, enc);
31040};
31041
31042EC.prototype.genKeyPair = function genKeyPair(options) {
31043 if (!options)
31044 options = {};
31045
31046 // Instantiate Hmac_DRBG
31047 var drbg = new HmacDRBG({
31048 hash: this.hash,
31049 pers: options.pers,
31050 persEnc: options.persEnc || 'utf8',
31051 entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
31052 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
31053 nonce: this.n.toArray()
31054 });
31055
31056 var bytes = this.n.byteLength();
31057 var ns2 = this.n.sub(new BN(2));
31058 do {
31059 var priv = new BN(drbg.generate(bytes));
31060 if (priv.cmp(ns2) > 0)
31061 continue;
31062
31063 priv.iaddn(1);
31064 return this.keyFromPrivate(priv);
31065 } while (true);
31066};
31067
31068EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
31069 var delta = msg.byteLength() * 8 - this.n.bitLength();
31070 if (delta > 0)
31071 msg = msg.ushrn(delta);
31072 if (!truncOnly && msg.cmp(this.n) >= 0)
31073 return msg.sub(this.n);
31074 else
31075 return msg;
31076};
31077
31078EC.prototype.sign = function sign(msg, key, enc, options) {
31079 if (typeof enc === 'object') {
31080 options = enc;
31081 enc = null;
31082 }
31083 if (!options)
31084 options = {};
31085
31086 key = this.keyFromPrivate(key, enc);
31087 msg = this._truncateToN(new BN(msg, 16));
31088
31089 // Zero-extend key to provide enough entropy
31090 var bytes = this.n.byteLength();
31091 var bkey = key.getPrivate().toArray('be', bytes);
31092
31093 // Zero-extend nonce to have the same byte size as N
31094 var nonce = msg.toArray('be', bytes);
31095
31096 // Instantiate Hmac_DRBG
31097 var drbg = new HmacDRBG({
31098 hash: this.hash,
31099 entropy: bkey,
31100 nonce: nonce,
31101 pers: options.pers,
31102 persEnc: options.persEnc || 'utf8'
31103 });
31104
31105 // Number of bytes to generate
31106 var ns1 = this.n.sub(new BN(1));
31107
31108 for (var iter = 0; true; iter++) {
31109 var k = options.k ?
31110 options.k(iter) :
31111 new BN(drbg.generate(this.n.byteLength()));
31112 k = this._truncateToN(k, true);
31113 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
31114 continue;
31115
31116 var kp = this.g.mul(k);
31117 if (kp.isInfinity())
31118 continue;
31119
31120 var kpX = kp.getX();
31121 var r = kpX.umod(this.n);
31122 if (r.cmpn(0) === 0)
31123 continue;
31124
31125 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
31126 s = s.umod(this.n);
31127 if (s.cmpn(0) === 0)
31128 continue;
31129
31130 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
31131 (kpX.cmp(r) !== 0 ? 2 : 0);
31132
31133 // Use complement of `s`, if it is > `n / 2`
31134 if (options.canonical && s.cmp(this.nh) > 0) {
31135 s = this.n.sub(s);
31136 recoveryParam ^= 1;
31137 }
31138
31139 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
31140 }
31141};
31142
31143EC.prototype.verify = function verify(msg, signature, key, enc) {
31144 msg = this._truncateToN(new BN(msg, 16));
31145 key = this.keyFromPublic(key, enc);
31146 signature = new Signature(signature, 'hex');
31147
31148 // Perform primitive values validation
31149 var r = signature.r;
31150 var s = signature.s;
31151 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
31152 return false;
31153 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
31154 return false;
31155
31156 // Validate signature
31157 var sinv = s.invm(this.n);
31158 var u1 = sinv.mul(msg).umod(this.n);
31159 var u2 = sinv.mul(r).umod(this.n);
31160
31161 if (!this.curve._maxwellTrick) {
31162 var p = this.g.mulAdd(u1, key.getPublic(), u2);
31163 if (p.isInfinity())
31164 return false;
31165
31166 return p.getX().umod(this.n).cmp(r) === 0;
31167 }
31168
31169 // NOTE: Greg Maxwell's trick, inspired by:
31170 // https://git.io/vad3K
31171
31172 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
31173 if (p.isInfinity())
31174 return false;
31175
31176 // Compare `p.x` of Jacobian point with `r`,
31177 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
31178 // inverse of `p.z^2`
31179 return p.eqXToP(r);
31180};
31181
31182EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
31183 assert((3 & j) === j, 'The recovery param is more than two bits');
31184 signature = new Signature(signature, enc);
31185
31186 var n = this.n;
31187 var e = new BN(msg);
31188 var r = signature.r;
31189 var s = signature.s;
31190
31191 // A set LSB signifies that the y-coordinate is odd
31192 var isYOdd = j & 1;
31193 var isSecondKey = j >> 1;
31194 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
31195 throw new Error('Unable to find sencond key candinate');
31196
31197 // 1.1. Let x = r + jn.
31198 if (isSecondKey)
31199 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
31200 else
31201 r = this.curve.pointFromX(r, isYOdd);
31202
31203 var rInv = signature.r.invm(n);
31204 var s1 = n.sub(e).mul(rInv).umod(n);
31205 var s2 = s.mul(rInv).umod(n);
31206
31207 // 1.6.1 Compute Q = r^-1 (sR - eG)
31208 // Q = r^-1 (sR + -eG)
31209 return this.g.mulAdd(s1, r, s2);
31210};
31211
31212EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
31213 signature = new Signature(signature, enc);
31214 if (signature.recoveryParam !== null)
31215 return signature.recoveryParam;
31216
31217 for (var i = 0; i < 4; i++) {
31218 var Qprime;
31219 try {
31220 Qprime = this.recoverPubKey(e, signature, i);
31221 } catch (e) {
31222 continue;
31223 }
31224
31225 if (Qprime.eq(Q))
31226 return i;
31227 }
31228 throw new Error('Unable to find valid recovery factor');
31229};
31230
31231},{"../../elliptic":142,"./key":150,"./signature":151,"bn.js":80,"hmac-drbg":202}],150:[function(require,module,exports){
31232'use strict';
31233
31234var BN = require('bn.js');
31235var elliptic = require('../../elliptic');
31236var utils = elliptic.utils;
31237var assert = utils.assert;
31238
31239function KeyPair(ec, options) {
31240 this.ec = ec;
31241 this.priv = null;
31242 this.pub = null;
31243
31244 // KeyPair(ec, { priv: ..., pub: ... })
31245 if (options.priv)
31246 this._importPrivate(options.priv, options.privEnc);
31247 if (options.pub)
31248 this._importPublic(options.pub, options.pubEnc);
31249}
31250module.exports = KeyPair;
31251
31252KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
31253 if (pub instanceof KeyPair)
31254 return pub;
31255
31256 return new KeyPair(ec, {
31257 pub: pub,
31258 pubEnc: enc
31259 });
31260};
31261
31262KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
31263 if (priv instanceof KeyPair)
31264 return priv;
31265
31266 return new KeyPair(ec, {
31267 priv: priv,
31268 privEnc: enc
31269 });
31270};
31271
31272KeyPair.prototype.validate = function validate() {
31273 var pub = this.getPublic();
31274
31275 if (pub.isInfinity())
31276 return { result: false, reason: 'Invalid public key' };
31277 if (!pub.validate())
31278 return { result: false, reason: 'Public key is not a point' };
31279 if (!pub.mul(this.ec.curve.n).isInfinity())
31280 return { result: false, reason: 'Public key * N != O' };
31281
31282 return { result: true, reason: null };
31283};
31284
31285KeyPair.prototype.getPublic = function getPublic(compact, enc) {
31286 // compact is optional argument
31287 if (typeof compact === 'string') {
31288 enc = compact;
31289 compact = null;
31290 }
31291
31292 if (!this.pub)
31293 this.pub = this.ec.g.mul(this.priv);
31294
31295 if (!enc)
31296 return this.pub;
31297
31298 return this.pub.encode(enc, compact);
31299};
31300
31301KeyPair.prototype.getPrivate = function getPrivate(enc) {
31302 if (enc === 'hex')
31303 return this.priv.toString(16, 2);
31304 else
31305 return this.priv;
31306};
31307
31308KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
31309 this.priv = new BN(key, enc || 16);
31310
31311 // Ensure that the priv won't be bigger than n, otherwise we may fail
31312 // in fixed multiplication method
31313 this.priv = this.priv.umod(this.ec.curve.n);
31314};
31315
31316KeyPair.prototype._importPublic = function _importPublic(key, enc) {
31317 if (key.x || key.y) {
31318 // Montgomery points only have an `x` coordinate.
31319 // Weierstrass/Edwards points on the other hand have both `x` and
31320 // `y` coordinates.
31321 if (this.ec.curve.type === 'mont') {
31322 assert(key.x, 'Need x coordinate');
31323 } else if (this.ec.curve.type === 'short' ||
31324 this.ec.curve.type === 'edwards') {
31325 assert(key.x && key.y, 'Need both x and y coordinate');
31326 }
31327 this.pub = this.ec.curve.point(key.x, key.y);
31328 return;
31329 }
31330 this.pub = this.ec.curve.decodePoint(key, enc);
31331};
31332
31333// ECDH
31334KeyPair.prototype.derive = function derive(pub) {
31335 return pub.mul(this.priv).getX();
31336};
31337
31338// ECDSA
31339KeyPair.prototype.sign = function sign(msg, enc, options) {
31340 return this.ec.sign(msg, this, enc, options);
31341};
31342
31343KeyPair.prototype.verify = function verify(msg, signature) {
31344 return this.ec.verify(msg, signature, this);
31345};
31346
31347KeyPair.prototype.inspect = function inspect() {
31348 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
31349 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
31350};
31351
31352},{"../../elliptic":142,"bn.js":80}],151:[function(require,module,exports){
31353'use strict';
31354
31355var BN = require('bn.js');
31356
31357var elliptic = require('../../elliptic');
31358var utils = elliptic.utils;
31359var assert = utils.assert;
31360
31361function Signature(options, enc) {
31362 if (options instanceof Signature)
31363 return options;
31364
31365 if (this._importDER(options, enc))
31366 return;
31367
31368 assert(options.r && options.s, 'Signature without r or s');
31369 this.r = new BN(options.r, 16);
31370 this.s = new BN(options.s, 16);
31371 if (options.recoveryParam === undefined)
31372 this.recoveryParam = null;
31373 else
31374 this.recoveryParam = options.recoveryParam;
31375}
31376module.exports = Signature;
31377
31378function Position() {
31379 this.place = 0;
31380}
31381
31382function getLength(buf, p) {
31383 var initial = buf[p.place++];
31384 if (!(initial & 0x80)) {
31385 return initial;
31386 }
31387 var octetLen = initial & 0xf;
31388 var val = 0;
31389 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
31390 val <<= 8;
31391 val |= buf[off];
31392 }
31393 p.place = off;
31394 return val;
31395}
31396
31397function rmPadding(buf) {
31398 var i = 0;
31399 var len = buf.length - 1;
31400 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
31401 i++;
31402 }
31403 if (i === 0) {
31404 return buf;
31405 }
31406 return buf.slice(i);
31407}
31408
31409Signature.prototype._importDER = function _importDER(data, enc) {
31410 data = utils.toArray(data, enc);
31411 var p = new Position();
31412 if (data[p.place++] !== 0x30) {
31413 return false;
31414 }
31415 var len = getLength(data, p);
31416 if ((len + p.place) !== data.length) {
31417 return false;
31418 }
31419 if (data[p.place++] !== 0x02) {
31420 return false;
31421 }
31422 var rlen = getLength(data, p);
31423 var r = data.slice(p.place, rlen + p.place);
31424 p.place += rlen;
31425 if (data[p.place++] !== 0x02) {
31426 return false;
31427 }
31428 var slen = getLength(data, p);
31429 if (data.length !== slen + p.place) {
31430 return false;
31431 }
31432 var s = data.slice(p.place, slen + p.place);
31433 if (r[0] === 0 && (r[1] & 0x80)) {
31434 r = r.slice(1);
31435 }
31436 if (s[0] === 0 && (s[1] & 0x80)) {
31437 s = s.slice(1);
31438 }
31439
31440 this.r = new BN(r);
31441 this.s = new BN(s);
31442 this.recoveryParam = null;
31443
31444 return true;
31445};
31446
31447function constructLength(arr, len) {
31448 if (len < 0x80) {
31449 arr.push(len);
31450 return;
31451 }
31452 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
31453 arr.push(octets | 0x80);
31454 while (--octets) {
31455 arr.push((len >>> (octets << 3)) & 0xff);
31456 }
31457 arr.push(len);
31458}
31459
31460Signature.prototype.toDER = function toDER(enc) {
31461 var r = this.r.toArray();
31462 var s = this.s.toArray();
31463
31464 // Pad values
31465 if (r[0] & 0x80)
31466 r = [ 0 ].concat(r);
31467 // Pad values
31468 if (s[0] & 0x80)
31469 s = [ 0 ].concat(s);
31470
31471 r = rmPadding(r);
31472 s = rmPadding(s);
31473
31474 while (!s[0] && !(s[1] & 0x80)) {
31475 s = s.slice(1);
31476 }
31477 var arr = [ 0x02 ];
31478 constructLength(arr, r.length);
31479 arr = arr.concat(r);
31480 arr.push(0x02);
31481 constructLength(arr, s.length);
31482 var backHalf = arr.concat(s);
31483 var res = [ 0x30 ];
31484 constructLength(res, backHalf.length);
31485 res = res.concat(backHalf);
31486 return utils.encode(res, enc);
31487};
31488
31489},{"../../elliptic":142,"bn.js":80}],152:[function(require,module,exports){
31490'use strict';
31491
31492var hash = require('hash.js');
31493var elliptic = require('../../elliptic');
31494var utils = elliptic.utils;
31495var assert = utils.assert;
31496var parseBytes = utils.parseBytes;
31497var KeyPair = require('./key');
31498var Signature = require('./signature');
31499
31500function EDDSA(curve) {
31501 assert(curve === 'ed25519', 'only tested with ed25519 so far');
31502
31503 if (!(this instanceof EDDSA))
31504 return new EDDSA(curve);
31505
31506 var curve = elliptic.curves[curve].curve;
31507 this.curve = curve;
31508 this.g = curve.g;
31509 this.g.precompute(curve.n.bitLength() + 1);
31510
31511 this.pointClass = curve.point().constructor;
31512 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
31513 this.hash = hash.sha512;
31514}
31515
31516module.exports = EDDSA;
31517
31518/**
31519* @param {Array|String} message - message bytes
31520* @param {Array|String|KeyPair} secret - secret bytes or a keypair
31521* @returns {Signature} - signature
31522*/
31523EDDSA.prototype.sign = function sign(message, secret) {
31524 message = parseBytes(message);
31525 var key = this.keyFromSecret(secret);
31526 var r = this.hashInt(key.messagePrefix(), message);
31527 var R = this.g.mul(r);
31528 var Rencoded = this.encodePoint(R);
31529 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
31530 .mul(key.priv());
31531 var S = r.add(s_).umod(this.curve.n);
31532 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
31533};
31534
31535/**
31536* @param {Array} message - message bytes
31537* @param {Array|String|Signature} sig - sig bytes
31538* @param {Array|String|Point|KeyPair} pub - public key
31539* @returns {Boolean} - true if public key matches sig of message
31540*/
31541EDDSA.prototype.verify = function verify(message, sig, pub) {
31542 message = parseBytes(message);
31543 sig = this.makeSignature(sig);
31544 var key = this.keyFromPublic(pub);
31545 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
31546 var SG = this.g.mul(sig.S());
31547 var RplusAh = sig.R().add(key.pub().mul(h));
31548 return RplusAh.eq(SG);
31549};
31550
31551EDDSA.prototype.hashInt = function hashInt() {
31552 var hash = this.hash();
31553 for (var i = 0; i < arguments.length; i++)
31554 hash.update(arguments[i]);
31555 return utils.intFromLE(hash.digest()).umod(this.curve.n);
31556};
31557
31558EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
31559 return KeyPair.fromPublic(this, pub);
31560};
31561
31562EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
31563 return KeyPair.fromSecret(this, secret);
31564};
31565
31566EDDSA.prototype.makeSignature = function makeSignature(sig) {
31567 if (sig instanceof Signature)
31568 return sig;
31569 return new Signature(this, sig);
31570};
31571
31572/**
31573* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
31574*
31575* EDDSA defines methods for encoding and decoding points and integers. These are
31576* helper convenience methods, that pass along to utility functions implied
31577* parameters.
31578*
31579*/
31580EDDSA.prototype.encodePoint = function encodePoint(point) {
31581 var enc = point.getY().toArray('le', this.encodingLength);
31582 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
31583 return enc;
31584};
31585
31586EDDSA.prototype.decodePoint = function decodePoint(bytes) {
31587 bytes = utils.parseBytes(bytes);
31588
31589 var lastIx = bytes.length - 1;
31590 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
31591 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
31592
31593 var y = utils.intFromLE(normed);
31594 return this.curve.pointFromY(y, xIsOdd);
31595};
31596
31597EDDSA.prototype.encodeInt = function encodeInt(num) {
31598 return num.toArray('le', this.encodingLength);
31599};
31600
31601EDDSA.prototype.decodeInt = function decodeInt(bytes) {
31602 return utils.intFromLE(bytes);
31603};
31604
31605EDDSA.prototype.isPoint = function isPoint(val) {
31606 return val instanceof this.pointClass;
31607};
31608
31609},{"../../elliptic":142,"./key":153,"./signature":154,"hash.js":190}],153:[function(require,module,exports){
31610'use strict';
31611
31612var elliptic = require('../../elliptic');
31613var utils = elliptic.utils;
31614var assert = utils.assert;
31615var parseBytes = utils.parseBytes;
31616var cachedProperty = utils.cachedProperty;
31617
31618/**
31619* @param {EDDSA} eddsa - instance
31620* @param {Object} params - public/private key parameters
31621*
31622* @param {Array<Byte>} [params.secret] - secret seed bytes
31623* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
31624* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
31625*
31626*/
31627function KeyPair(eddsa, params) {
31628 this.eddsa = eddsa;
31629 this._secret = parseBytes(params.secret);
31630 if (eddsa.isPoint(params.pub))
31631 this._pub = params.pub;
31632 else
31633 this._pubBytes = parseBytes(params.pub);
31634}
31635
31636KeyPair.fromPublic = function fromPublic(eddsa, pub) {
31637 if (pub instanceof KeyPair)
31638 return pub;
31639 return new KeyPair(eddsa, { pub: pub });
31640};
31641
31642KeyPair.fromSecret = function fromSecret(eddsa, secret) {
31643 if (secret instanceof KeyPair)
31644 return secret;
31645 return new KeyPair(eddsa, { secret: secret });
31646};
31647
31648KeyPair.prototype.secret = function secret() {
31649 return this._secret;
31650};
31651
31652cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
31653 return this.eddsa.encodePoint(this.pub());
31654});
31655
31656cachedProperty(KeyPair, 'pub', function pub() {
31657 if (this._pubBytes)
31658 return this.eddsa.decodePoint(this._pubBytes);
31659 return this.eddsa.g.mul(this.priv());
31660});
31661
31662cachedProperty(KeyPair, 'privBytes', function privBytes() {
31663 var eddsa = this.eddsa;
31664 var hash = this.hash();
31665 var lastIx = eddsa.encodingLength - 1;
31666
31667 var a = hash.slice(0, eddsa.encodingLength);
31668 a[0] &= 248;
31669 a[lastIx] &= 127;
31670 a[lastIx] |= 64;
31671
31672 return a;
31673});
31674
31675cachedProperty(KeyPair, 'priv', function priv() {
31676 return this.eddsa.decodeInt(this.privBytes());
31677});
31678
31679cachedProperty(KeyPair, 'hash', function hash() {
31680 return this.eddsa.hash().update(this.secret()).digest();
31681});
31682
31683cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
31684 return this.hash().slice(this.eddsa.encodingLength);
31685});
31686
31687KeyPair.prototype.sign = function sign(message) {
31688 assert(this._secret, 'KeyPair can only verify');
31689 return this.eddsa.sign(message, this);
31690};
31691
31692KeyPair.prototype.verify = function verify(message, sig) {
31693 return this.eddsa.verify(message, sig, this);
31694};
31695
31696KeyPair.prototype.getSecret = function getSecret(enc) {
31697 assert(this._secret, 'KeyPair is public only');
31698 return utils.encode(this.secret(), enc);
31699};
31700
31701KeyPair.prototype.getPublic = function getPublic(enc) {
31702 return utils.encode(this.pubBytes(), enc);
31703};
31704
31705module.exports = KeyPair;
31706
31707},{"../../elliptic":142}],154:[function(require,module,exports){
31708'use strict';
31709
31710var BN = require('bn.js');
31711var elliptic = require('../../elliptic');
31712var utils = elliptic.utils;
31713var assert = utils.assert;
31714var cachedProperty = utils.cachedProperty;
31715var parseBytes = utils.parseBytes;
31716
31717/**
31718* @param {EDDSA} eddsa - eddsa instance
31719* @param {Array<Bytes>|Object} sig -
31720* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
31721* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
31722* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
31723* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
31724*/
31725function Signature(eddsa, sig) {
31726 this.eddsa = eddsa;
31727
31728 if (typeof sig !== 'object')
31729 sig = parseBytes(sig);
31730
31731 if (Array.isArray(sig)) {
31732 sig = {
31733 R: sig.slice(0, eddsa.encodingLength),
31734 S: sig.slice(eddsa.encodingLength)
31735 };
31736 }
31737
31738 assert(sig.R && sig.S, 'Signature without R or S');
31739
31740 if (eddsa.isPoint(sig.R))
31741 this._R = sig.R;
31742 if (sig.S instanceof BN)
31743 this._S = sig.S;
31744
31745 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
31746 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
31747}
31748
31749cachedProperty(Signature, 'S', function S() {
31750 return this.eddsa.decodeInt(this.Sencoded());
31751});
31752
31753cachedProperty(Signature, 'R', function R() {
31754 return this.eddsa.decodePoint(this.Rencoded());
31755});
31756
31757cachedProperty(Signature, 'Rencoded', function Rencoded() {
31758 return this.eddsa.encodePoint(this.R());
31759});
31760
31761cachedProperty(Signature, 'Sencoded', function Sencoded() {
31762 return this.eddsa.encodeInt(this.S());
31763});
31764
31765Signature.prototype.toBytes = function toBytes() {
31766 return this.Rencoded().concat(this.Sencoded());
31767};
31768
31769Signature.prototype.toHex = function toHex() {
31770 return utils.encode(this.toBytes(), 'hex').toUpperCase();
31771};
31772
31773module.exports = Signature;
31774
31775},{"../../elliptic":142,"bn.js":80}],155:[function(require,module,exports){
31776module.exports = {
31777 doubles: {
31778 step: 4,
31779 points: [
31780 [
31781 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
31782 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
31783 ],
31784 [
31785 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
31786 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
31787 ],
31788 [
31789 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
31790 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
31791 ],
31792 [
31793 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
31794 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
31795 ],
31796 [
31797 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
31798 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
31799 ],
31800 [
31801 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
31802 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
31803 ],
31804 [
31805 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
31806 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
31807 ],
31808 [
31809 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
31810 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
31811 ],
31812 [
31813 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
31814 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
31815 ],
31816 [
31817 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
31818 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
31819 ],
31820 [
31821 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
31822 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
31823 ],
31824 [
31825 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
31826 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
31827 ],
31828 [
31829 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
31830 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
31831 ],
31832 [
31833 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
31834 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
31835 ],
31836 [
31837 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
31838 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
31839 ],
31840 [
31841 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
31842 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
31843 ],
31844 [
31845 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
31846 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
31847 ],
31848 [
31849 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
31850 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
31851 ],
31852 [
31853 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
31854 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
31855 ],
31856 [
31857 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
31858 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
31859 ],
31860 [
31861 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
31862 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
31863 ],
31864 [
31865 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
31866 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
31867 ],
31868 [
31869 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
31870 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
31871 ],
31872 [
31873 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
31874 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
31875 ],
31876 [
31877 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
31878 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
31879 ],
31880 [
31881 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
31882 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
31883 ],
31884 [
31885 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
31886 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
31887 ],
31888 [
31889 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
31890 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
31891 ],
31892 [
31893 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
31894 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
31895 ],
31896 [
31897 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
31898 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
31899 ],
31900 [
31901 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
31902 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
31903 ],
31904 [
31905 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
31906 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
31907 ],
31908 [
31909 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
31910 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
31911 ],
31912 [
31913 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
31914 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
31915 ],
31916 [
31917 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
31918 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
31919 ],
31920 [
31921 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
31922 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
31923 ],
31924 [
31925 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
31926 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
31927 ],
31928 [
31929 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
31930 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
31931 ],
31932 [
31933 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
31934 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
31935 ],
31936 [
31937 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
31938 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
31939 ],
31940 [
31941 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
31942 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
31943 ],
31944 [
31945 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
31946 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
31947 ],
31948 [
31949 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
31950 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
31951 ],
31952 [
31953 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
31954 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
31955 ],
31956 [
31957 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
31958 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
31959 ],
31960 [
31961 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
31962 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
31963 ],
31964 [
31965 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
31966 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
31967 ],
31968 [
31969 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
31970 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
31971 ],
31972 [
31973 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
31974 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
31975 ],
31976 [
31977 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
31978 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
31979 ],
31980 [
31981 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
31982 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
31983 ],
31984 [
31985 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
31986 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
31987 ],
31988 [
31989 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
31990 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
31991 ],
31992 [
31993 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
31994 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
31995 ],
31996 [
31997 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
31998 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
31999 ],
32000 [
32001 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
32002 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
32003 ],
32004 [
32005 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
32006 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
32007 ],
32008 [
32009 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
32010 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
32011 ],
32012 [
32013 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
32014 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
32015 ],
32016 [
32017 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
32018 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
32019 ],
32020 [
32021 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
32022 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
32023 ],
32024 [
32025 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
32026 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
32027 ],
32028 [
32029 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
32030 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
32031 ],
32032 [
32033 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
32034 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
32035 ],
32036 [
32037 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
32038 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
32039 ]
32040 ]
32041 },
32042 naf: {
32043 wnd: 7,
32044 points: [
32045 [
32046 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
32047 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
32048 ],
32049 [
32050 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
32051 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
32052 ],
32053 [
32054 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
32055 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
32056 ],
32057 [
32058 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
32059 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
32060 ],
32061 [
32062 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
32063 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
32064 ],
32065 [
32066 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
32067 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
32068 ],
32069 [
32070 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
32071 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
32072 ],
32073 [
32074 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
32075 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
32076 ],
32077 [
32078 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
32079 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
32080 ],
32081 [
32082 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
32083 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
32084 ],
32085 [
32086 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
32087 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
32088 ],
32089 [
32090 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
32091 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
32092 ],
32093 [
32094 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
32095 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
32096 ],
32097 [
32098 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
32099 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
32100 ],
32101 [
32102 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
32103 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
32104 ],
32105 [
32106 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
32107 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
32108 ],
32109 [
32110 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
32111 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
32112 ],
32113 [
32114 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
32115 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
32116 ],
32117 [
32118 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
32119 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
32120 ],
32121 [
32122 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
32123 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
32124 ],
32125 [
32126 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
32127 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
32128 ],
32129 [
32130 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
32131 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
32132 ],
32133 [
32134 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
32135 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
32136 ],
32137 [
32138 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
32139 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
32140 ],
32141 [
32142 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
32143 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
32144 ],
32145 [
32146 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
32147 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
32148 ],
32149 [
32150 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
32151 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
32152 ],
32153 [
32154 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
32155 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
32156 ],
32157 [
32158 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
32159 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
32160 ],
32161 [
32162 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
32163 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
32164 ],
32165 [
32166 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
32167 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
32168 ],
32169 [
32170 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
32171 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
32172 ],
32173 [
32174 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
32175 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
32176 ],
32177 [
32178 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
32179 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
32180 ],
32181 [
32182 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
32183 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
32184 ],
32185 [
32186 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
32187 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
32188 ],
32189 [
32190 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
32191 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
32192 ],
32193 [
32194 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
32195 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
32196 ],
32197 [
32198 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
32199 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
32200 ],
32201 [
32202 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
32203 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
32204 ],
32205 [
32206 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
32207 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
32208 ],
32209 [
32210 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
32211 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
32212 ],
32213 [
32214 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
32215 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
32216 ],
32217 [
32218 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
32219 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
32220 ],
32221 [
32222 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
32223 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
32224 ],
32225 [
32226 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
32227 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
32228 ],
32229 [
32230 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
32231 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
32232 ],
32233 [
32234 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
32235 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
32236 ],
32237 [
32238 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
32239 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
32240 ],
32241 [
32242 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
32243 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
32244 ],
32245 [
32246 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
32247 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
32248 ],
32249 [
32250 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
32251 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
32252 ],
32253 [
32254 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
32255 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
32256 ],
32257 [
32258 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
32259 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
32260 ],
32261 [
32262 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
32263 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
32264 ],
32265 [
32266 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
32267 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
32268 ],
32269 [
32270 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
32271 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
32272 ],
32273 [
32274 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
32275 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
32276 ],
32277 [
32278 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
32279 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
32280 ],
32281 [
32282 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
32283 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
32284 ],
32285 [
32286 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
32287 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
32288 ],
32289 [
32290 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
32291 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
32292 ],
32293 [
32294 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
32295 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
32296 ],
32297 [
32298 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
32299 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
32300 ],
32301 [
32302 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
32303 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
32304 ],
32305 [
32306 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
32307 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
32308 ],
32309 [
32310 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
32311 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
32312 ],
32313 [
32314 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
32315 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
32316 ],
32317 [
32318 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
32319 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
32320 ],
32321 [
32322 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
32323 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
32324 ],
32325 [
32326 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
32327 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
32328 ],
32329 [
32330 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
32331 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
32332 ],
32333 [
32334 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
32335 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
32336 ],
32337 [
32338 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
32339 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
32340 ],
32341 [
32342 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
32343 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
32344 ],
32345 [
32346 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
32347 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
32348 ],
32349 [
32350 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
32351 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
32352 ],
32353 [
32354 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
32355 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
32356 ],
32357 [
32358 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
32359 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
32360 ],
32361 [
32362 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
32363 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
32364 ],
32365 [
32366 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
32367 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
32368 ],
32369 [
32370 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
32371 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
32372 ],
32373 [
32374 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
32375 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
32376 ],
32377 [
32378 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
32379 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
32380 ],
32381 [
32382 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
32383 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
32384 ],
32385 [
32386 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
32387 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
32388 ],
32389 [
32390 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
32391 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
32392 ],
32393 [
32394 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
32395 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
32396 ],
32397 [
32398 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
32399 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
32400 ],
32401 [
32402 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
32403 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
32404 ],
32405 [
32406 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
32407 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
32408 ],
32409 [
32410 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
32411 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
32412 ],
32413 [
32414 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
32415 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
32416 ],
32417 [
32418 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
32419 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
32420 ],
32421 [
32422 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
32423 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
32424 ],
32425 [
32426 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
32427 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
32428 ],
32429 [
32430 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
32431 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
32432 ],
32433 [
32434 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
32435 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
32436 ],
32437 [
32438 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
32439 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
32440 ],
32441 [
32442 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
32443 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
32444 ],
32445 [
32446 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
32447 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
32448 ],
32449 [
32450 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
32451 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
32452 ],
32453 [
32454 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
32455 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
32456 ],
32457 [
32458 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
32459 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
32460 ],
32461 [
32462 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
32463 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
32464 ],
32465 [
32466 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
32467 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
32468 ],
32469 [
32470 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
32471 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
32472 ],
32473 [
32474 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
32475 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
32476 ],
32477 [
32478 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
32479 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
32480 ],
32481 [
32482 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
32483 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
32484 ],
32485 [
32486 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
32487 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
32488 ],
32489 [
32490 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
32491 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
32492 ],
32493 [
32494 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
32495 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
32496 ],
32497 [
32498 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
32499 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
32500 ],
32501 [
32502 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
32503 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
32504 ],
32505 [
32506 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
32507 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
32508 ],
32509 [
32510 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
32511 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
32512 ],
32513 [
32514 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
32515 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
32516 ],
32517 [
32518 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
32519 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
32520 ],
32521 [
32522 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
32523 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
32524 ],
32525 [
32526 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
32527 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
32528 ],
32529 [
32530 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
32531 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
32532 ],
32533 [
32534 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
32535 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
32536 ],
32537 [
32538 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
32539 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
32540 ],
32541 [
32542 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
32543 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
32544 ],
32545 [
32546 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
32547 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
32548 ],
32549 [
32550 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
32551 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
32552 ]
32553 ]
32554 }
32555};
32556
32557},{}],156:[function(require,module,exports){
32558'use strict';
32559
32560var utils = exports;
32561var BN = require('bn.js');
32562var minAssert = require('minimalistic-assert');
32563var minUtils = require('minimalistic-crypto-utils');
32564
32565utils.assert = minAssert;
32566utils.toArray = minUtils.toArray;
32567utils.zero2 = minUtils.zero2;
32568utils.toHex = minUtils.toHex;
32569utils.encode = minUtils.encode;
32570
32571// Represent num in a w-NAF form
32572function getNAF(num, w) {
32573 var naf = [];
32574 var ws = 1 << (w + 1);
32575 var k = num.clone();
32576 while (k.cmpn(1) >= 0) {
32577 var z;
32578 if (k.isOdd()) {
32579 var mod = k.andln(ws - 1);
32580 if (mod > (ws >> 1) - 1)
32581 z = (ws >> 1) - mod;
32582 else
32583 z = mod;
32584 k.isubn(z);
32585 } else {
32586 z = 0;
32587 }
32588 naf.push(z);
32589
32590 // Optimization, shift by word if possible
32591 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
32592 for (var i = 1; i < shift; i++)
32593 naf.push(0);
32594 k.iushrn(shift);
32595 }
32596
32597 return naf;
32598}
32599utils.getNAF = getNAF;
32600
32601// Represent k1, k2 in a Joint Sparse Form
32602function getJSF(k1, k2) {
32603 var jsf = [
32604 [],
32605 []
32606 ];
32607
32608 k1 = k1.clone();
32609 k2 = k2.clone();
32610 var d1 = 0;
32611 var d2 = 0;
32612 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
32613
32614 // First phase
32615 var m14 = (k1.andln(3) + d1) & 3;
32616 var m24 = (k2.andln(3) + d2) & 3;
32617 if (m14 === 3)
32618 m14 = -1;
32619 if (m24 === 3)
32620 m24 = -1;
32621 var u1;
32622 if ((m14 & 1) === 0) {
32623 u1 = 0;
32624 } else {
32625 var m8 = (k1.andln(7) + d1) & 7;
32626 if ((m8 === 3 || m8 === 5) && m24 === 2)
32627 u1 = -m14;
32628 else
32629 u1 = m14;
32630 }
32631 jsf[0].push(u1);
32632
32633 var u2;
32634 if ((m24 & 1) === 0) {
32635 u2 = 0;
32636 } else {
32637 var m8 = (k2.andln(7) + d2) & 7;
32638 if ((m8 === 3 || m8 === 5) && m14 === 2)
32639 u2 = -m24;
32640 else
32641 u2 = m24;
32642 }
32643 jsf[1].push(u2);
32644
32645 // Second phase
32646 if (2 * d1 === u1 + 1)
32647 d1 = 1 - d1;
32648 if (2 * d2 === u2 + 1)
32649 d2 = 1 - d2;
32650 k1.iushrn(1);
32651 k2.iushrn(1);
32652 }
32653
32654 return jsf;
32655}
32656utils.getJSF = getJSF;
32657
32658function cachedProperty(obj, name, computer) {
32659 var key = '_' + name;
32660 obj.prototype[name] = function cachedProperty() {
32661 return this[key] !== undefined ? this[key] :
32662 this[key] = computer.call(this);
32663 };
32664}
32665utils.cachedProperty = cachedProperty;
32666
32667function parseBytes(bytes) {
32668 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
32669 bytes;
32670}
32671utils.parseBytes = parseBytes;
32672
32673function intFromLE(bytes) {
32674 return new BN(bytes, 'hex', 'le');
32675}
32676utils.intFromLE = intFromLE;
32677
32678
32679},{"bn.js":80,"minimalistic-assert":237,"minimalistic-crypto-utils":238}],157:[function(require,module,exports){
32680module.exports={
32681 "name": "elliptic",
32682 "version": "6.4.1",
32683 "description": "EC cryptography",
32684 "main": "lib/elliptic.js",
32685 "files": [
32686 "lib"
32687 ],
32688 "scripts": {
32689 "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
32690 "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
32691 "lint": "npm run jscs && npm run jshint",
32692 "unit": "istanbul test _mocha --reporter=spec test/index.js",
32693 "test": "npm run lint && npm run unit",
32694 "version": "grunt dist && git add dist/"
32695 },
32696 "repository": {
32697 "type": "git",
32698 "url": "git@github.com:indutny/elliptic"
32699 },
32700 "keywords": [
32701 "EC",
32702 "Elliptic",
32703 "curve",
32704 "Cryptography"
32705 ],
32706 "author": "Fedor Indutny <fedor@indutny.com>",
32707 "license": "MIT",
32708 "bugs": {
32709 "url": "https://github.com/indutny/elliptic/issues"
32710 },
32711 "homepage": "https://github.com/indutny/elliptic",
32712 "devDependencies": {
32713 "brfs": "^1.4.3",
32714 "coveralls": "^2.11.3",
32715 "grunt": "^0.4.5",
32716 "grunt-browserify": "^5.0.0",
32717 "grunt-cli": "^1.2.0",
32718 "grunt-contrib-connect": "^1.0.0",
32719 "grunt-contrib-copy": "^1.0.0",
32720 "grunt-contrib-uglify": "^1.0.1",
32721 "grunt-mocha-istanbul": "^3.0.1",
32722 "grunt-saucelabs": "^8.6.2",
32723 "istanbul": "^0.4.2",
32724 "jscs": "^2.9.0",
32725 "jshint": "^2.6.0",
32726 "mocha": "^2.1.0"
32727 },
32728 "dependencies": {
32729 "bn.js": "^4.4.0",
32730 "brorand": "^1.0.1",
32731 "hash.js": "^1.0.0",
32732 "hmac-drbg": "^1.0.0",
32733 "inherits": "^2.0.1",
32734 "minimalistic-assert": "^1.0.0",
32735 "minimalistic-crypto-utils": "^1.0.0"
32736 }
32737}
32738
32739},{}],158:[function(require,module,exports){
32740(function (root, factory) {
32741 /* istanbul ignore next */
32742 if (typeof define === 'function' && define.amd) {
32743 define([], factory)
32744 } else if (typeof exports === 'object') {
32745 module.exports = factory()
32746 } else {
32747 root.PromisePool = factory()
32748 // Legacy API
32749 root.promisePool = root.PromisePool
32750 }
32751})(this, function () {
32752 'use strict'
32753
32754 var EventTarget = function () {
32755 this._listeners = {}
32756 }
32757
32758 EventTarget.prototype.addEventListener = function (type, listener) {
32759 this._listeners[type] = this._listeners[type] || []
32760 if (this._listeners[type].indexOf(listener) < 0) {
32761 this._listeners[type].push(listener)
32762 }
32763 }
32764
32765 EventTarget.prototype.removeEventListener = function (type, listener) {
32766 if (this._listeners[type]) {
32767 var p = this._listeners[type].indexOf(listener)
32768 if (p >= 0) {
32769 this._listeners[type].splice(p, 1)
32770 }
32771 }
32772 }
32773
32774 EventTarget.prototype.dispatchEvent = function (evt) {
32775 if (this._listeners[evt.type] && this._listeners[evt.type].length) {
32776 var listeners = this._listeners[evt.type].slice()
32777 for (var i = 0, l = listeners.length; i < l; ++i) {
32778 listeners[i].call(this, evt)
32779 }
32780 }
32781 }
32782
32783 var isGenerator = function (func) {
32784 return (typeof func.constructor === 'function' &&
32785 func.constructor.name === 'GeneratorFunction')
32786 }
32787
32788 var functionToIterator = function (func) {
32789 return {
32790 next: function () {
32791 var promise = func()
32792 return promise ? {value: promise} : {done: true}
32793 }
32794 }
32795 }
32796
32797 var promiseToIterator = function (promise) {
32798 var called = false
32799 return {
32800 next: function () {
32801 if (called) {
32802 return {done: true}
32803 }
32804 called = true
32805 return {value: promise}
32806 }
32807 }
32808 }
32809
32810 var toIterator = function (obj, Promise) {
32811 var type = typeof obj
32812 if (type === 'object') {
32813 if (typeof obj.next === 'function') {
32814 return obj
32815 }
32816 /* istanbul ignore else */
32817 if (typeof obj.then === 'function') {
32818 return promiseToIterator(obj)
32819 }
32820 }
32821 if (type === 'function') {
32822 return isGenerator(obj) ? obj() : functionToIterator(obj)
32823 }
32824 return promiseToIterator(Promise.resolve(obj))
32825 }
32826
32827 var PromisePoolEvent = function (target, type, data) {
32828 this.target = target
32829 this.type = type
32830 this.data = data
32831 }
32832
32833 var PromisePool = function (source, concurrency, options) {
32834 EventTarget.call(this)
32835 if (typeof concurrency !== 'number' ||
32836 Math.floor(concurrency) !== concurrency ||
32837 concurrency < 1) {
32838 throw new Error('Invalid concurrency')
32839 }
32840 this._concurrency = concurrency
32841 this._options = options || {}
32842 this._options.promise = this._options.promise || Promise
32843 this._iterator = toIterator(source, this._options.promise)
32844 this._done = false
32845 this._size = 0
32846 this._promise = null
32847 this._callbacks = null
32848 }
32849 PromisePool.prototype = new EventTarget()
32850 PromisePool.prototype.constructor = PromisePool
32851
32852 PromisePool.prototype.concurrency = function (value) {
32853 if (typeof value !== 'undefined') {
32854 this._concurrency = value
32855 if (this.active()) {
32856 this._proceed()
32857 }
32858 }
32859 return this._concurrency
32860 }
32861
32862 PromisePool.prototype.size = function () {
32863 return this._size
32864 }
32865
32866 PromisePool.prototype.active = function () {
32867 return !!this._promise
32868 }
32869
32870 PromisePool.prototype.promise = function () {
32871 return this._promise
32872 }
32873
32874 PromisePool.prototype.start = function () {
32875 var that = this
32876 var Promise = this._options.promise
32877 this._promise = new Promise(function (resolve, reject) {
32878 that._callbacks = {
32879 reject: reject,
32880 resolve: resolve
32881 }
32882 that._proceed()
32883 })
32884 return this._promise
32885 }
32886
32887 PromisePool.prototype._fireEvent = function (type, data) {
32888 this.dispatchEvent(new PromisePoolEvent(this, type, data))
32889 }
32890
32891 PromisePool.prototype._settle = function (error) {
32892 if (error) {
32893 this._callbacks.reject(error)
32894 } else {
32895 this._callbacks.resolve()
32896 }
32897 this._promise = null
32898 this._callbacks = null
32899 }
32900
32901 PromisePool.prototype._onPooledPromiseFulfilled = function (promise, result) {
32902 this._size--
32903 if (this.active()) {
32904 this._fireEvent('fulfilled', {
32905 promise: promise,
32906 result: result
32907 })
32908 this._proceed()
32909 }
32910 }
32911
32912 PromisePool.prototype._onPooledPromiseRejected = function (promise, error) {
32913 this._size--
32914 if (this.active()) {
32915 this._fireEvent('rejected', {
32916 promise: promise,
32917 error: error
32918 })
32919 this._settle(error || new Error('Unknown error'))
32920 }
32921 }
32922
32923 PromisePool.prototype._trackPromise = function (promise) {
32924 var that = this
32925 promise
32926 .then(function (result) {
32927 that._onPooledPromiseFulfilled(promise, result)
32928 }, function (error) {
32929 that._onPooledPromiseRejected(promise, error)
32930 })['catch'](function (err) {
32931 that._settle(new Error('Promise processing failed: ' + err))
32932 })
32933 }
32934
32935 PromisePool.prototype._proceed = function () {
32936 if (!this._done) {
32937 var result = { done: false }
32938 while (this._size < this._concurrency &&
32939 !(result = this._iterator.next()).done) {
32940 this._size++
32941 this._trackPromise(result.value)
32942 }
32943 this._done = (result === null || !!result.done)
32944 }
32945 if (this._done && this._size === 0) {
32946 this._settle()
32947 }
32948 }
32949
32950 PromisePool.PromisePoolEvent = PromisePoolEvent
32951 // Legacy API
32952 PromisePool.PromisePool = PromisePool
32953
32954 return PromisePool
32955})
32956
32957},{}],159:[function(require,module,exports){
32958// Copyright Joyent, Inc. and other Node contributors.
32959//
32960// Permission is hereby granted, free of charge, to any person obtaining a
32961// copy of this software and associated documentation files (the
32962// "Software"), to deal in the Software without restriction, including
32963// without limitation the rights to use, copy, modify, merge, publish,
32964// distribute, sublicense, and/or sell copies of the Software, and to permit
32965// persons to whom the Software is furnished to do so, subject to the
32966// following conditions:
32967//
32968// The above copyright notice and this permission notice shall be included
32969// in all copies or substantial portions of the Software.
32970//
32971// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
32972// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32973// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
32974// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
32975// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
32976// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
32977// USE OR OTHER DEALINGS IN THE SOFTWARE.
32978
32979var objectCreate = Object.create || objectCreatePolyfill
32980var objectKeys = Object.keys || objectKeysPolyfill
32981var bind = Function.prototype.bind || functionBindPolyfill
32982
32983function EventEmitter() {
32984 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
32985 this._events = objectCreate(null);
32986 this._eventsCount = 0;
32987 }
32988
32989 this._maxListeners = this._maxListeners || undefined;
32990}
32991module.exports = EventEmitter;
32992
32993// Backwards-compat with node 0.10.x
32994EventEmitter.EventEmitter = EventEmitter;
32995
32996EventEmitter.prototype._events = undefined;
32997EventEmitter.prototype._maxListeners = undefined;
32998
32999// By default EventEmitters will print a warning if more than 10 listeners are
33000// added to it. This is a useful default which helps finding memory leaks.
33001var defaultMaxListeners = 10;
33002
33003var hasDefineProperty;
33004try {
33005 var o = {};
33006 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
33007 hasDefineProperty = o.x === 0;
33008} catch (err) { hasDefineProperty = false }
33009if (hasDefineProperty) {
33010 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
33011 enumerable: true,
33012 get: function() {
33013 return defaultMaxListeners;
33014 },
33015 set: function(arg) {
33016 // check whether the input is a positive number (whose value is zero or
33017 // greater and not a NaN).
33018 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
33019 throw new TypeError('"defaultMaxListeners" must be a positive number');
33020 defaultMaxListeners = arg;
33021 }
33022 });
33023} else {
33024 EventEmitter.defaultMaxListeners = defaultMaxListeners;
33025}
33026
33027// Obviously not all Emitters should be limited to 10. This function allows
33028// that to be increased. Set to zero for unlimited.
33029EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
33030 if (typeof n !== 'number' || n < 0 || isNaN(n))
33031 throw new TypeError('"n" argument must be a positive number');
33032 this._maxListeners = n;
33033 return this;
33034};
33035
33036function $getMaxListeners(that) {
33037 if (that._maxListeners === undefined)
33038 return EventEmitter.defaultMaxListeners;
33039 return that._maxListeners;
33040}
33041
33042EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
33043 return $getMaxListeners(this);
33044};
33045
33046// These standalone emit* functions are used to optimize calling of event
33047// handlers for fast cases because emit() itself often has a variable number of
33048// arguments and can be deoptimized because of that. These functions always have
33049// the same number of arguments and thus do not get deoptimized, so the code
33050// inside them can execute faster.
33051function emitNone(handler, isFn, self) {
33052 if (isFn)
33053 handler.call(self);
33054 else {
33055 var len = handler.length;
33056 var listeners = arrayClone(handler, len);
33057 for (var i = 0; i < len; ++i)
33058 listeners[i].call(self);
33059 }
33060}
33061function emitOne(handler, isFn, self, arg1) {
33062 if (isFn)
33063 handler.call(self, arg1);
33064 else {
33065 var len = handler.length;
33066 var listeners = arrayClone(handler, len);
33067 for (var i = 0; i < len; ++i)
33068 listeners[i].call(self, arg1);
33069 }
33070}
33071function emitTwo(handler, isFn, self, arg1, arg2) {
33072 if (isFn)
33073 handler.call(self, arg1, arg2);
33074 else {
33075 var len = handler.length;
33076 var listeners = arrayClone(handler, len);
33077 for (var i = 0; i < len; ++i)
33078 listeners[i].call(self, arg1, arg2);
33079 }
33080}
33081function emitThree(handler, isFn, self, arg1, arg2, arg3) {
33082 if (isFn)
33083 handler.call(self, arg1, arg2, arg3);
33084 else {
33085 var len = handler.length;
33086 var listeners = arrayClone(handler, len);
33087 for (var i = 0; i < len; ++i)
33088 listeners[i].call(self, arg1, arg2, arg3);
33089 }
33090}
33091
33092function emitMany(handler, isFn, self, args) {
33093 if (isFn)
33094 handler.apply(self, args);
33095 else {
33096 var len = handler.length;
33097 var listeners = arrayClone(handler, len);
33098 for (var i = 0; i < len; ++i)
33099 listeners[i].apply(self, args);
33100 }
33101}
33102
33103EventEmitter.prototype.emit = function emit(type) {
33104 var er, handler, len, args, i, events;
33105 var doError = (type === 'error');
33106
33107 events = this._events;
33108 if (events)
33109 doError = (doError && events.error == null);
33110 else if (!doError)
33111 return false;
33112
33113 // If there is no 'error' event listener then throw.
33114 if (doError) {
33115 if (arguments.length > 1)
33116 er = arguments[1];
33117 if (er instanceof Error) {
33118 throw er; // Unhandled 'error' event
33119 } else {
33120 // At least give some kind of context to the user
33121 var err = new Error('Unhandled "error" event. (' + er + ')');
33122 err.context = er;
33123 throw err;
33124 }
33125 return false;
33126 }
33127
33128 handler = events[type];
33129
33130 if (!handler)
33131 return false;
33132
33133 var isFn = typeof handler === 'function';
33134 len = arguments.length;
33135 switch (len) {
33136 // fast cases
33137 case 1:
33138 emitNone(handler, isFn, this);
33139 break;
33140 case 2:
33141 emitOne(handler, isFn, this, arguments[1]);
33142 break;
33143 case 3:
33144 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
33145 break;
33146 case 4:
33147 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
33148 break;
33149 // slower
33150 default:
33151 args = new Array(len - 1);
33152 for (i = 1; i < len; i++)
33153 args[i - 1] = arguments[i];
33154 emitMany(handler, isFn, this, args);
33155 }
33156
33157 return true;
33158};
33159
33160function _addListener(target, type, listener, prepend) {
33161 var m;
33162 var events;
33163 var existing;
33164
33165 if (typeof listener !== 'function')
33166 throw new TypeError('"listener" argument must be a function');
33167
33168 events = target._events;
33169 if (!events) {
33170 events = target._events = objectCreate(null);
33171 target._eventsCount = 0;
33172 } else {
33173 // To avoid recursion in the case that type === "newListener"! Before
33174 // adding it to the listeners, first emit "newListener".
33175 if (events.newListener) {
33176 target.emit('newListener', type,
33177 listener.listener ? listener.listener : listener);
33178
33179 // Re-assign `events` because a newListener handler could have caused the
33180 // this._events to be assigned to a new object
33181 events = target._events;
33182 }
33183 existing = events[type];
33184 }
33185
33186 if (!existing) {
33187 // Optimize the case of one listener. Don't need the extra array object.
33188 existing = events[type] = listener;
33189 ++target._eventsCount;
33190 } else {
33191 if (typeof existing === 'function') {
33192 // Adding the second element, need to change to array.
33193 existing = events[type] =
33194 prepend ? [listener, existing] : [existing, listener];
33195 } else {
33196 // If we've already got an array, just append.
33197 if (prepend) {
33198 existing.unshift(listener);
33199 } else {
33200 existing.push(listener);
33201 }
33202 }
33203
33204 // Check for listener leak
33205 if (!existing.warned) {
33206 m = $getMaxListeners(target);
33207 if (m && m > 0 && existing.length > m) {
33208 existing.warned = true;
33209 var w = new Error('Possible EventEmitter memory leak detected. ' +
33210 existing.length + ' "' + String(type) + '" listeners ' +
33211 'added. Use emitter.setMaxListeners() to ' +
33212 'increase limit.');
33213 w.name = 'MaxListenersExceededWarning';
33214 w.emitter = target;
33215 w.type = type;
33216 w.count = existing.length;
33217 if (typeof console === 'object' && console.warn) {
33218 console.warn('%s: %s', w.name, w.message);
33219 }
33220 }
33221 }
33222 }
33223
33224 return target;
33225}
33226
33227EventEmitter.prototype.addListener = function addListener(type, listener) {
33228 return _addListener(this, type, listener, false);
33229};
33230
33231EventEmitter.prototype.on = EventEmitter.prototype.addListener;
33232
33233EventEmitter.prototype.prependListener =
33234 function prependListener(type, listener) {
33235 return _addListener(this, type, listener, true);
33236 };
33237
33238function onceWrapper() {
33239 if (!this.fired) {
33240 this.target.removeListener(this.type, this.wrapFn);
33241 this.fired = true;
33242 switch (arguments.length) {
33243 case 0:
33244 return this.listener.call(this.target);
33245 case 1:
33246 return this.listener.call(this.target, arguments[0]);
33247 case 2:
33248 return this.listener.call(this.target, arguments[0], arguments[1]);
33249 case 3:
33250 return this.listener.call(this.target, arguments[0], arguments[1],
33251 arguments[2]);
33252 default:
33253 var args = new Array(arguments.length);
33254 for (var i = 0; i < args.length; ++i)
33255 args[i] = arguments[i];
33256 this.listener.apply(this.target, args);
33257 }
33258 }
33259}
33260
33261function _onceWrap(target, type, listener) {
33262 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
33263 var wrapped = bind.call(onceWrapper, state);
33264 wrapped.listener = listener;
33265 state.wrapFn = wrapped;
33266 return wrapped;
33267}
33268
33269EventEmitter.prototype.once = function once(type, listener) {
33270 if (typeof listener !== 'function')
33271 throw new TypeError('"listener" argument must be a function');
33272 this.on(type, _onceWrap(this, type, listener));
33273 return this;
33274};
33275
33276EventEmitter.prototype.prependOnceListener =
33277 function prependOnceListener(type, listener) {
33278 if (typeof listener !== 'function')
33279 throw new TypeError('"listener" argument must be a function');
33280 this.prependListener(type, _onceWrap(this, type, listener));
33281 return this;
33282 };
33283
33284// Emits a 'removeListener' event if and only if the listener was removed.
33285EventEmitter.prototype.removeListener =
33286 function removeListener(type, listener) {
33287 var list, events, position, i, originalListener;
33288
33289 if (typeof listener !== 'function')
33290 throw new TypeError('"listener" argument must be a function');
33291
33292 events = this._events;
33293 if (!events)
33294 return this;
33295
33296 list = events[type];
33297 if (!list)
33298 return this;
33299
33300 if (list === listener || list.listener === listener) {
33301 if (--this._eventsCount === 0)
33302 this._events = objectCreate(null);
33303 else {
33304 delete events[type];
33305 if (events.removeListener)
33306 this.emit('removeListener', type, list.listener || listener);
33307 }
33308 } else if (typeof list !== 'function') {
33309 position = -1;
33310
33311 for (i = list.length - 1; i >= 0; i--) {
33312 if (list[i] === listener || list[i].listener === listener) {
33313 originalListener = list[i].listener;
33314 position = i;
33315 break;
33316 }
33317 }
33318
33319 if (position < 0)
33320 return this;
33321
33322 if (position === 0)
33323 list.shift();
33324 else
33325 spliceOne(list, position);
33326
33327 if (list.length === 1)
33328 events[type] = list[0];
33329
33330 if (events.removeListener)
33331 this.emit('removeListener', type, originalListener || listener);
33332 }
33333
33334 return this;
33335 };
33336
33337EventEmitter.prototype.removeAllListeners =
33338 function removeAllListeners(type) {
33339 var listeners, events, i;
33340
33341 events = this._events;
33342 if (!events)
33343 return this;
33344
33345 // not listening for removeListener, no need to emit
33346 if (!events.removeListener) {
33347 if (arguments.length === 0) {
33348 this._events = objectCreate(null);
33349 this._eventsCount = 0;
33350 } else if (events[type]) {
33351 if (--this._eventsCount === 0)
33352 this._events = objectCreate(null);
33353 else
33354 delete events[type];
33355 }
33356 return this;
33357 }
33358
33359 // emit removeListener for all listeners on all events
33360 if (arguments.length === 0) {
33361 var keys = objectKeys(events);
33362 var key;
33363 for (i = 0; i < keys.length; ++i) {
33364 key = keys[i];
33365 if (key === 'removeListener') continue;
33366 this.removeAllListeners(key);
33367 }
33368 this.removeAllListeners('removeListener');
33369 this._events = objectCreate(null);
33370 this._eventsCount = 0;
33371 return this;
33372 }
33373
33374 listeners = events[type];
33375
33376 if (typeof listeners === 'function') {
33377 this.removeListener(type, listeners);
33378 } else if (listeners) {
33379 // LIFO order
33380 for (i = listeners.length - 1; i >= 0; i--) {
33381 this.removeListener(type, listeners[i]);
33382 }
33383 }
33384
33385 return this;
33386 };
33387
33388function _listeners(target, type, unwrap) {
33389 var events = target._events;
33390
33391 if (!events)
33392 return [];
33393
33394 var evlistener = events[type];
33395 if (!evlistener)
33396 return [];
33397
33398 if (typeof evlistener === 'function')
33399 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
33400
33401 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
33402}
33403
33404EventEmitter.prototype.listeners = function listeners(type) {
33405 return _listeners(this, type, true);
33406};
33407
33408EventEmitter.prototype.rawListeners = function rawListeners(type) {
33409 return _listeners(this, type, false);
33410};
33411
33412EventEmitter.listenerCount = function(emitter, type) {
33413 if (typeof emitter.listenerCount === 'function') {
33414 return emitter.listenerCount(type);
33415 } else {
33416 return listenerCount.call(emitter, type);
33417 }
33418};
33419
33420EventEmitter.prototype.listenerCount = listenerCount;
33421function listenerCount(type) {
33422 var events = this._events;
33423
33424 if (events) {
33425 var evlistener = events[type];
33426
33427 if (typeof evlistener === 'function') {
33428 return 1;
33429 } else if (evlistener) {
33430 return evlistener.length;
33431 }
33432 }
33433
33434 return 0;
33435}
33436
33437EventEmitter.prototype.eventNames = function eventNames() {
33438 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
33439};
33440
33441// About 1.5x faster than the two-arg version of Array#splice().
33442function spliceOne(list, index) {
33443 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
33444 list[i] = list[k];
33445 list.pop();
33446}
33447
33448function arrayClone(arr, n) {
33449 var copy = new Array(n);
33450 for (var i = 0; i < n; ++i)
33451 copy[i] = arr[i];
33452 return copy;
33453}
33454
33455function unwrapListeners(arr) {
33456 var ret = new Array(arr.length);
33457 for (var i = 0; i < ret.length; ++i) {
33458 ret[i] = arr[i].listener || arr[i];
33459 }
33460 return ret;
33461}
33462
33463function objectCreatePolyfill(proto) {
33464 var F = function() {};
33465 F.prototype = proto;
33466 return new F;
33467}
33468function objectKeysPolyfill(obj) {
33469 var keys = [];
33470 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
33471 keys.push(k);
33472 }
33473 return k;
33474}
33475function functionBindPolyfill(context) {
33476 var fn = this;
33477 return function () {
33478 return fn.apply(context, arguments);
33479 };
33480}
33481
33482},{}],160:[function(require,module,exports){
33483var Buffer = require('safe-buffer').Buffer
33484var MD5 = require('md5.js')
33485
33486/* eslint-disable camelcase */
33487function EVP_BytesToKey (password, salt, keyBits, ivLen) {
33488 if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
33489 if (salt) {
33490 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
33491 if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
33492 }
33493
33494 var keyLen = keyBits / 8
33495 var key = Buffer.alloc(keyLen)
33496 var iv = Buffer.alloc(ivLen || 0)
33497 var tmp = Buffer.alloc(0)
33498
33499 while (keyLen > 0 || ivLen > 0) {
33500 var hash = new MD5()
33501 hash.update(tmp)
33502 hash.update(password)
33503 if (salt) hash.update(salt)
33504 tmp = hash.digest()
33505
33506 var used = 0
33507
33508 if (keyLen > 0) {
33509 var keyStart = key.length - keyLen
33510 used = Math.min(keyLen, tmp.length)
33511 tmp.copy(key, keyStart, 0, used)
33512 keyLen -= used
33513 }
33514
33515 if (used < tmp.length && ivLen > 0) {
33516 var ivStart = iv.length - ivLen
33517 var length = Math.min(ivLen, tmp.length - used)
33518 tmp.copy(iv, ivStart, used, used + length)
33519 ivLen -= length
33520 }
33521 }
33522
33523 tmp.fill(0)
33524 return { key: key, iv: iv }
33525}
33526
33527module.exports = EVP_BytesToKey
33528
33529},{"md5.js":232,"safe-buffer":325}],161:[function(require,module,exports){
33530'use strict';
33531
33532var hasOwn = Object.prototype.hasOwnProperty;
33533var toStr = Object.prototype.toString;
33534var defineProperty = Object.defineProperty;
33535var gOPD = Object.getOwnPropertyDescriptor;
33536
33537var isArray = function isArray(arr) {
33538 if (typeof Array.isArray === 'function') {
33539 return Array.isArray(arr);
33540 }
33541
33542 return toStr.call(arr) === '[object Array]';
33543};
33544
33545var isPlainObject = function isPlainObject(obj) {
33546 if (!obj || toStr.call(obj) !== '[object Object]') {
33547 return false;
33548 }
33549
33550 var hasOwnConstructor = hasOwn.call(obj, 'constructor');
33551 var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
33552 // Not own constructor property must be Object
33553 if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
33554 return false;
33555 }
33556
33557 // Own properties are enumerated firstly, so to speed up,
33558 // if last one is own, then all properties are own.
33559 var key;
33560 for (key in obj) { /**/ }
33561
33562 return typeof key === 'undefined' || hasOwn.call(obj, key);
33563};
33564
33565// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
33566var setProperty = function setProperty(target, options) {
33567 if (defineProperty && options.name === '__proto__') {
33568 defineProperty(target, options.name, {
33569 enumerable: true,
33570 configurable: true,
33571 value: options.newValue,
33572 writable: true
33573 });
33574 } else {
33575 target[options.name] = options.newValue;
33576 }
33577};
33578
33579// Return undefined instead of __proto__ if '__proto__' is not an own property
33580var getProperty = function getProperty(obj, name) {
33581 if (name === '__proto__') {
33582 if (!hasOwn.call(obj, name)) {
33583 return void 0;
33584 } else if (gOPD) {
33585 // In early versions of node, obj['__proto__'] is buggy when obj has
33586 // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
33587 return gOPD(obj, name).value;
33588 }
33589 }
33590
33591 return obj[name];
33592};
33593
33594module.exports = function extend() {
33595 var options, name, src, copy, copyIsArray, clone;
33596 var target = arguments[0];
33597 var i = 1;
33598 var length = arguments.length;
33599 var deep = false;
33600
33601 // Handle a deep copy situation
33602 if (typeof target === 'boolean') {
33603 deep = target;
33604 target = arguments[1] || {};
33605 // skip the boolean and the target
33606 i = 2;
33607 }
33608 if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
33609 target = {};
33610 }
33611
33612 for (; i < length; ++i) {
33613 options = arguments[i];
33614 // Only deal with non-null/undefined values
33615 if (options != null) {
33616 // Extend the base object
33617 for (name in options) {
33618 src = getProperty(target, name);
33619 copy = getProperty(options, name);
33620
33621 // Prevent never-ending loop
33622 if (target !== copy) {
33623 // Recurse if we're merging plain objects or arrays
33624 if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
33625 if (copyIsArray) {
33626 copyIsArray = false;
33627 clone = src && isArray(src) ? src : [];
33628 } else {
33629 clone = src && isPlainObject(src) ? src : {};
33630 }
33631
33632 // Never move original objects, clone them
33633 setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
33634
33635 // Don't bring in undefined values
33636 } else if (typeof copy !== 'undefined') {
33637 setProperty(target, { name: name, newValue: copy });
33638 }
33639 }
33640 }
33641 }
33642 }
33643
33644 // Return the modified object
33645 return target;
33646};
33647
33648},{}],162:[function(require,module,exports){
33649(function (process){
33650/*
33651 * extsprintf.js: extended POSIX-style sprintf
33652 */
33653
33654var mod_assert = require('assert');
33655var mod_util = require('util');
33656
33657/*
33658 * Public interface
33659 */
33660exports.sprintf = jsSprintf;
33661exports.printf = jsPrintf;
33662exports.fprintf = jsFprintf;
33663
33664/*
33665 * Stripped down version of s[n]printf(3c). We make a best effort to throw an
33666 * exception when given a format string we don't understand, rather than
33667 * ignoring it, so that we won't break existing programs if/when we go implement
33668 * the rest of this.
33669 *
33670 * This implementation currently supports specifying
33671 * - field alignment ('-' flag),
33672 * - zero-pad ('0' flag)
33673 * - always show numeric sign ('+' flag),
33674 * - field width
33675 * - conversions for strings, decimal integers, and floats (numbers).
33676 * - argument size specifiers. These are all accepted but ignored, since
33677 * Javascript has no notion of the physical size of an argument.
33678 *
33679 * Everything else is currently unsupported, most notably precision, unsigned
33680 * numbers, non-decimal numbers, and characters.
33681 */
33682function jsSprintf(fmt)
33683{
33684 var regex = [
33685 '([^%]*)', /* normal text */
33686 '%', /* start of format */
33687 '([\'\\-+ #0]*?)', /* flags (optional) */
33688 '([1-9]\\d*)?', /* width (optional) */
33689 '(\\.([1-9]\\d*))?', /* precision (optional) */
33690 '[lhjztL]*?', /* length mods (ignored) */
33691 '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
33692 ].join('');
33693
33694 var re = new RegExp(regex);
33695 var args = Array.prototype.slice.call(arguments, 1);
33696 var flags, width, precision, conversion;
33697 var left, pad, sign, arg, match;
33698 var ret = '';
33699 var argn = 1;
33700
33701 mod_assert.equal('string', typeof (fmt));
33702
33703 while ((match = re.exec(fmt)) !== null) {
33704 ret += match[1];
33705 fmt = fmt.substring(match[0].length);
33706
33707 flags = match[2] || '';
33708 width = match[3] || 0;
33709 precision = match[4] || '';
33710 conversion = match[6];
33711 left = false;
33712 sign = false;
33713 pad = ' ';
33714
33715 if (conversion == '%') {
33716 ret += '%';
33717 continue;
33718 }
33719
33720 if (args.length === 0)
33721 throw (new Error('too few args to sprintf'));
33722
33723 arg = args.shift();
33724 argn++;
33725
33726 if (flags.match(/[\' #]/))
33727 throw (new Error(
33728 'unsupported flags: ' + flags));
33729
33730 if (precision.length > 0)
33731 throw (new Error(
33732 'non-zero precision not supported'));
33733
33734 if (flags.match(/-/))
33735 left = true;
33736
33737 if (flags.match(/0/))
33738 pad = '0';
33739
33740 if (flags.match(/\+/))
33741 sign = true;
33742
33743 switch (conversion) {
33744 case 's':
33745 if (arg === undefined || arg === null)
33746 throw (new Error('argument ' + argn +
33747 ': attempted to print undefined or null ' +
33748 'as a string'));
33749 ret += doPad(pad, width, left, arg.toString());
33750 break;
33751
33752 case 'd':
33753 arg = Math.floor(arg);
33754 /*jsl:fallthru*/
33755 case 'f':
33756 sign = sign && arg > 0 ? '+' : '';
33757 ret += sign + doPad(pad, width, left,
33758 arg.toString());
33759 break;
33760
33761 case 'x':
33762 ret += doPad(pad, width, left, arg.toString(16));
33763 break;
33764
33765 case 'j': /* non-standard */
33766 if (width === 0)
33767 width = 10;
33768 ret += mod_util.inspect(arg, false, width);
33769 break;
33770
33771 case 'r': /* non-standard */
33772 ret += dumpException(arg);
33773 break;
33774
33775 default:
33776 throw (new Error('unsupported conversion: ' +
33777 conversion));
33778 }
33779 }
33780
33781 ret += fmt;
33782 return (ret);
33783}
33784
33785function jsPrintf() {
33786 var args = Array.prototype.slice.call(arguments);
33787 args.unshift(process.stdout);
33788 jsFprintf.apply(null, args);
33789}
33790
33791function jsFprintf(stream) {
33792 var args = Array.prototype.slice.call(arguments, 1);
33793 return (stream.write(jsSprintf.apply(this, args)));
33794}
33795
33796function doPad(chr, width, left, str)
33797{
33798 var ret = str;
33799
33800 while (ret.length < width) {
33801 if (left)
33802 ret += chr;
33803 else
33804 ret = chr + ret;
33805 }
33806
33807 return (ret);
33808}
33809
33810/*
33811 * This function dumps long stack traces for exceptions having a cause() method.
33812 * See node-verror for an example.
33813 */
33814function dumpException(ex)
33815{
33816 var ret;
33817
33818 if (!(ex instanceof Error))
33819 throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
33820
33821 /* Note that V8 prepends "ex.stack" with ex.toString(). */
33822 ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
33823
33824 if (ex.cause && typeof (ex.cause) === 'function') {
33825 var cex = ex.cause();
33826 if (cex) {
33827 ret += '\nCaused by: ' + dumpException(cex);
33828 }
33829 }
33830
33831 return (ret);
33832}
33833
33834}).call(this,require('_process'))
33835},{"_process":265,"assert":68,"util":397}],163:[function(require,module,exports){
33836'use strict';
33837
33838var isArray = Array.isArray;
33839var keyList = Object.keys;
33840var hasProp = Object.prototype.hasOwnProperty;
33841
33842module.exports = function equal(a, b) {
33843 if (a === b) return true;
33844
33845 if (a && b && typeof a == 'object' && typeof b == 'object') {
33846 var arrA = isArray(a)
33847 , arrB = isArray(b)
33848 , i
33849 , length
33850 , key;
33851
33852 if (arrA && arrB) {
33853 length = a.length;
33854 if (length != b.length) return false;
33855 for (i = length; i-- !== 0;)
33856 if (!equal(a[i], b[i])) return false;
33857 return true;
33858 }
33859
33860 if (arrA != arrB) return false;
33861
33862 var dateA = a instanceof Date
33863 , dateB = b instanceof Date;
33864 if (dateA != dateB) return false;
33865 if (dateA && dateB) return a.getTime() == b.getTime();
33866
33867 var regexpA = a instanceof RegExp
33868 , regexpB = b instanceof RegExp;
33869 if (regexpA != regexpB) return false;
33870 if (regexpA && regexpB) return a.toString() == b.toString();
33871
33872 var keys = keyList(a);
33873 length = keys.length;
33874
33875 if (length !== keyList(b).length)
33876 return false;
33877
33878 for (i = length; i-- !== 0;)
33879 if (!hasProp.call(b, keys[i])) return false;
33880
33881 for (i = length; i-- !== 0;) {
33882 key = keys[i];
33883 if (!equal(a[key], b[key])) return false;
33884 }
33885
33886 return true;
33887 }
33888
33889 return a!==a && b!==b;
33890};
33891
33892},{}],164:[function(require,module,exports){
33893'use strict';
33894
33895module.exports = function (data, opts) {
33896 if (!opts) opts = {};
33897 if (typeof opts === 'function') opts = { cmp: opts };
33898 var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
33899
33900 var cmp = opts.cmp && (function (f) {
33901 return function (node) {
33902 return function (a, b) {
33903 var aobj = { key: a, value: node[a] };
33904 var bobj = { key: b, value: node[b] };
33905 return f(aobj, bobj);
33906 };
33907 };
33908 })(opts.cmp);
33909
33910 var seen = [];
33911 return (function stringify (node) {
33912 if (node && node.toJSON && typeof node.toJSON === 'function') {
33913 node = node.toJSON();
33914 }
33915
33916 if (node === undefined) return;
33917 if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
33918 if (typeof node !== 'object') return JSON.stringify(node);
33919
33920 var i, out;
33921 if (Array.isArray(node)) {
33922 out = '[';
33923 for (i = 0; i < node.length; i++) {
33924 if (i) out += ',';
33925 out += stringify(node[i]) || 'null';
33926 }
33927 return out + ']';
33928 }
33929
33930 if (node === null) return 'null';
33931
33932 if (seen.indexOf(node) !== -1) {
33933 if (cycles) return JSON.stringify('__cycle__');
33934 throw new TypeError('Converting circular structure to JSON');
33935 }
33936
33937 var seenIndex = seen.push(node) - 1;
33938 var keys = Object.keys(node).sort(cmp && cmp(node));
33939 out = '';
33940 for (i = 0; i < keys.length; i++) {
33941 var key = keys[i];
33942 var value = stringify(node[key]);
33943
33944 if (!value) continue;
33945 if (out) out += ',';
33946 out += JSON.stringify(key) + ':' + value;
33947 }
33948 seen.splice(seenIndex, 1);
33949 return '{' + out + '}';
33950 })(data);
33951};
33952
33953},{}],165:[function(require,module,exports){
33954/*jshint -W054 */
33955;(function (exports) {
33956 'use strict';
33957
33958 function forEachAsync(arr, fn, thisArg) {
33959 var dones = []
33960 , index = -1
33961 ;
33962
33963 function next(BREAK, result) {
33964 index += 1;
33965
33966 if (index === arr.length || BREAK === forEachAsync.__BREAK) {
33967 dones.forEach(function (done) {
33968 done.call(thisArg, result);
33969 });
33970 return;
33971 }
33972
33973 fn.call(thisArg, next, arr[index], index, arr);
33974 }
33975
33976 setTimeout(next, 4);
33977
33978 return {
33979 then: function (_done) {
33980 dones.push(_done);
33981 return this;
33982 }
33983 };
33984 }
33985 forEachAsync.__BREAK = {};
33986
33987 exports.forEachAsync = forEachAsync;
33988}('undefined' !== typeof exports && exports || new Function('return this')()));
33989
33990},{}],166:[function(require,module,exports){
33991module.exports = ForeverAgent
33992ForeverAgent.SSL = ForeverAgentSSL
33993
33994var util = require('util')
33995 , Agent = require('http').Agent
33996 , net = require('net')
33997 , tls = require('tls')
33998 , AgentSSL = require('https').Agent
33999
34000function getConnectionName(host, port) {
34001 var name = ''
34002 if (typeof host === 'string') {
34003 name = host + ':' + port
34004 } else {
34005 // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name.
34006 name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':')
34007 }
34008 return name
34009}
34010
34011function ForeverAgent(options) {
34012 var self = this
34013 self.options = options || {}
34014 self.requests = {}
34015 self.sockets = {}
34016 self.freeSockets = {}
34017 self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets
34018 self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets
34019 self.on('free', function(socket, host, port) {
34020 var name = getConnectionName(host, port)
34021
34022 if (self.requests[name] && self.requests[name].length) {
34023 self.requests[name].shift().onSocket(socket)
34024 } else if (self.sockets[name].length < self.minSockets) {
34025 if (!self.freeSockets[name]) self.freeSockets[name] = []
34026 self.freeSockets[name].push(socket)
34027
34028 // if an error happens while we don't use the socket anyway, meh, throw the socket away
34029 var onIdleError = function() {
34030 socket.destroy()
34031 }
34032 socket._onIdleError = onIdleError
34033 socket.on('error', onIdleError)
34034 } else {
34035 // If there are no pending requests just destroy the
34036 // socket and it will get removed from the pool. This
34037 // gets us out of timeout issues and allows us to
34038 // default to Connection:keep-alive.
34039 socket.destroy()
34040 }
34041 })
34042
34043}
34044util.inherits(ForeverAgent, Agent)
34045
34046ForeverAgent.defaultMinSockets = 5
34047
34048
34049ForeverAgent.prototype.createConnection = net.createConnection
34050ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest
34051ForeverAgent.prototype.addRequest = function(req, host, port) {
34052 var name = getConnectionName(host, port)
34053
34054 if (typeof host !== 'string') {
34055 var options = host
34056 port = options.port
34057 host = options.host
34058 }
34059
34060 if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
34061 var idleSocket = this.freeSockets[name].pop()
34062 idleSocket.removeListener('error', idleSocket._onIdleError)
34063 delete idleSocket._onIdleError
34064 req._reusedSocket = true
34065 req.onSocket(idleSocket)
34066 } else {
34067 this.addRequestNoreuse(req, host, port)
34068 }
34069}
34070
34071ForeverAgent.prototype.removeSocket = function(s, name, host, port) {
34072 if (this.sockets[name]) {
34073 var index = this.sockets[name].indexOf(s)
34074 if (index !== -1) {
34075 this.sockets[name].splice(index, 1)
34076 }
34077 } else if (this.sockets[name] && this.sockets[name].length === 0) {
34078 // don't leak
34079 delete this.sockets[name]
34080 delete this.requests[name]
34081 }
34082
34083 if (this.freeSockets[name]) {
34084 var index = this.freeSockets[name].indexOf(s)
34085 if (index !== -1) {
34086 this.freeSockets[name].splice(index, 1)
34087 if (this.freeSockets[name].length === 0) {
34088 delete this.freeSockets[name]
34089 }
34090 }
34091 }
34092
34093 if (this.requests[name] && this.requests[name].length) {
34094 // If we have pending requests and a socket gets closed a new one
34095 // needs to be created to take over in the pool for the one that closed.
34096 this.createSocket(name, host, port).emit('free')
34097 }
34098}
34099
34100function ForeverAgentSSL (options) {
34101 ForeverAgent.call(this, options)
34102}
34103util.inherits(ForeverAgentSSL, ForeverAgent)
34104
34105ForeverAgentSSL.prototype.createConnection = createConnectionSSL
34106ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest
34107
34108function createConnectionSSL (port, host, options) {
34109 if (typeof port === 'object') {
34110 options = port;
34111 } else if (typeof host === 'object') {
34112 options = host;
34113 } else if (typeof options === 'object') {
34114 options = options;
34115 } else {
34116 options = {};
34117 }
34118
34119 if (typeof port === 'number') {
34120 options.port = port;
34121 }
34122
34123 if (typeof host === 'string') {
34124 options.host = host;
34125 }
34126
34127 return tls.connect(options);
34128}
34129
34130},{"http":362,"https":208,"net":112,"tls":112,"util":397}],167:[function(require,module,exports){
34131/* eslint-env browser */
34132module.exports = typeof self == 'object' ? self.FormData : window.FormData;
34133
34134},{}],168:[function(require,module,exports){
34135module.exports={
34136 "$id": "afterRequest.json#",
34137 "$schema": "http://json-schema.org/draft-06/schema#",
34138 "type": "object",
34139 "optional": true,
34140 "required": [
34141 "lastAccess",
34142 "eTag",
34143 "hitCount"
34144 ],
34145 "properties": {
34146 "expires": {
34147 "type": "string",
34148 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
34149 },
34150 "lastAccess": {
34151 "type": "string",
34152 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
34153 },
34154 "eTag": {
34155 "type": "string"
34156 },
34157 "hitCount": {
34158 "type": "integer"
34159 },
34160 "comment": {
34161 "type": "string"
34162 }
34163 }
34164}
34165
34166},{}],169:[function(require,module,exports){
34167module.exports={
34168 "$id": "beforeRequest.json#",
34169 "$schema": "http://json-schema.org/draft-06/schema#",
34170 "type": "object",
34171 "optional": true,
34172 "required": [
34173 "lastAccess",
34174 "eTag",
34175 "hitCount"
34176 ],
34177 "properties": {
34178 "expires": {
34179 "type": "string",
34180 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
34181 },
34182 "lastAccess": {
34183 "type": "string",
34184 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
34185 },
34186 "eTag": {
34187 "type": "string"
34188 },
34189 "hitCount": {
34190 "type": "integer"
34191 },
34192 "comment": {
34193 "type": "string"
34194 }
34195 }
34196}
34197
34198},{}],170:[function(require,module,exports){
34199module.exports={
34200 "$id": "browser.json#",
34201 "$schema": "http://json-schema.org/draft-06/schema#",
34202 "type": "object",
34203 "required": [
34204 "name",
34205 "version"
34206 ],
34207 "properties": {
34208 "name": {
34209 "type": "string"
34210 },
34211 "version": {
34212 "type": "string"
34213 },
34214 "comment": {
34215 "type": "string"
34216 }
34217 }
34218}
34219
34220},{}],171:[function(require,module,exports){
34221module.exports={
34222 "$id": "cache.json#",
34223 "$schema": "http://json-schema.org/draft-06/schema#",
34224 "properties": {
34225 "beforeRequest": {
34226 "oneOf": [
34227 { "type": "null" },
34228 { "$ref": "beforeRequest.json#" }
34229 ]
34230 },
34231 "afterRequest": {
34232 "oneOf": [
34233 { "type": "null" },
34234 { "$ref": "afterRequest.json#" }
34235 ]
34236 },
34237 "comment": {
34238 "type": "string"
34239 }
34240 }
34241}
34242
34243},{}],172:[function(require,module,exports){
34244module.exports={
34245 "$id": "content.json#",
34246 "$schema": "http://json-schema.org/draft-06/schema#",
34247 "type": "object",
34248 "required": [
34249 "size",
34250 "mimeType"
34251 ],
34252 "properties": {
34253 "size": {
34254 "type": "integer"
34255 },
34256 "compression": {
34257 "type": "integer"
34258 },
34259 "mimeType": {
34260 "type": "string"
34261 },
34262 "text": {
34263 "type": "string"
34264 },
34265 "encoding": {
34266 "type": "string"
34267 },
34268 "comment": {
34269 "type": "string"
34270 }
34271 }
34272}
34273
34274},{}],173:[function(require,module,exports){
34275module.exports={
34276 "$id": "cookie.json#",
34277 "$schema": "http://json-schema.org/draft-06/schema#",
34278 "type": "object",
34279 "required": [
34280 "name",
34281 "value"
34282 ],
34283 "properties": {
34284 "name": {
34285 "type": "string"
34286 },
34287 "value": {
34288 "type": "string"
34289 },
34290 "path": {
34291 "type": "string"
34292 },
34293 "domain": {
34294 "type": "string"
34295 },
34296 "expires": {
34297 "type": ["string", "null"],
34298 "format": "date-time"
34299 },
34300 "httpOnly": {
34301 "type": "boolean"
34302 },
34303 "secure": {
34304 "type": "boolean"
34305 },
34306 "comment": {
34307 "type": "string"
34308 }
34309 }
34310}
34311
34312},{}],174:[function(require,module,exports){
34313module.exports={
34314 "$id": "creator.json#",
34315 "$schema": "http://json-schema.org/draft-06/schema#",
34316 "type": "object",
34317 "required": [
34318 "name",
34319 "version"
34320 ],
34321 "properties": {
34322 "name": {
34323 "type": "string"
34324 },
34325 "version": {
34326 "type": "string"
34327 },
34328 "comment": {
34329 "type": "string"
34330 }
34331 }
34332}
34333
34334},{}],175:[function(require,module,exports){
34335module.exports={
34336 "$id": "entry.json#",
34337 "$schema": "http://json-schema.org/draft-06/schema#",
34338 "type": "object",
34339 "optional": true,
34340 "required": [
34341 "startedDateTime",
34342 "time",
34343 "request",
34344 "response",
34345 "cache",
34346 "timings"
34347 ],
34348 "properties": {
34349 "pageref": {
34350 "type": "string"
34351 },
34352 "startedDateTime": {
34353 "type": "string",
34354 "format": "date-time",
34355 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"
34356 },
34357 "time": {
34358 "type": "number",
34359 "min": 0
34360 },
34361 "request": {
34362 "$ref": "request.json#"
34363 },
34364 "response": {
34365 "$ref": "response.json#"
34366 },
34367 "cache": {
34368 "$ref": "cache.json#"
34369 },
34370 "timings": {
34371 "$ref": "timings.json#"
34372 },
34373 "serverIPAddress": {
34374 "type": "string",
34375 "oneOf": [
34376 { "format": "ipv4" },
34377 { "format": "ipv6" }
34378 ]
34379 },
34380 "connection": {
34381 "type": "string"
34382 },
34383 "comment": {
34384 "type": "string"
34385 }
34386 }
34387}
34388
34389},{}],176:[function(require,module,exports){
34390module.exports={
34391 "$id": "har.json#",
34392 "$schema": "http://json-schema.org/draft-06/schema#",
34393 "type": "object",
34394 "required": [
34395 "log"
34396 ],
34397 "properties": {
34398 "log": {
34399 "$ref": "log.json#"
34400 }
34401 }
34402}
34403
34404},{}],177:[function(require,module,exports){
34405module.exports={
34406 "$id": "header.json#",
34407 "$schema": "http://json-schema.org/draft-06/schema#",
34408 "type": "object",
34409 "required": [
34410 "name",
34411 "value"
34412 ],
34413 "properties": {
34414 "name": {
34415 "type": "string"
34416 },
34417 "value": {
34418 "type": "string"
34419 },
34420 "comment": {
34421 "type": "string"
34422 }
34423 }
34424}
34425
34426},{}],178:[function(require,module,exports){
34427'use strict'
34428
34429module.exports = {
34430 afterRequest: require('./afterRequest.json'),
34431 beforeRequest: require('./beforeRequest.json'),
34432 browser: require('./browser.json'),
34433 cache: require('./cache.json'),
34434 content: require('./content.json'),
34435 cookie: require('./cookie.json'),
34436 creator: require('./creator.json'),
34437 entry: require('./entry.json'),
34438 har: require('./har.json'),
34439 header: require('./header.json'),
34440 log: require('./log.json'),
34441 page: require('./page.json'),
34442 pageTimings: require('./pageTimings.json'),
34443 postData: require('./postData.json'),
34444 query: require('./query.json'),
34445 request: require('./request.json'),
34446 response: require('./response.json'),
34447 timings: require('./timings.json')
34448}
34449
34450},{"./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){
34451module.exports={
34452 "$id": "log.json#",
34453 "$schema": "http://json-schema.org/draft-06/schema#",
34454 "type": "object",
34455 "required": [
34456 "version",
34457 "creator",
34458 "entries"
34459 ],
34460 "properties": {
34461 "version": {
34462 "type": "string"
34463 },
34464 "creator": {
34465 "$ref": "creator.json#"
34466 },
34467 "browser": {
34468 "$ref": "browser.json#"
34469 },
34470 "pages": {
34471 "type": "array",
34472 "items": {
34473 "$ref": "page.json#"
34474 }
34475 },
34476 "entries": {
34477 "type": "array",
34478 "items": {
34479 "$ref": "entry.json#"
34480 }
34481 },
34482 "comment": {
34483 "type": "string"
34484 }
34485 }
34486}
34487
34488},{}],180:[function(require,module,exports){
34489module.exports={
34490 "$id": "page.json#",
34491 "$schema": "http://json-schema.org/draft-06/schema#",
34492 "type": "object",
34493 "optional": true,
34494 "required": [
34495 "startedDateTime",
34496 "id",
34497 "title",
34498 "pageTimings"
34499 ],
34500 "properties": {
34501 "startedDateTime": {
34502 "type": "string",
34503 "format": "date-time",
34504 "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"
34505 },
34506 "id": {
34507 "type": "string",
34508 "unique": true
34509 },
34510 "title": {
34511 "type": "string"
34512 },
34513 "pageTimings": {
34514 "$ref": "pageTimings.json#"
34515 },
34516 "comment": {
34517 "type": "string"
34518 }
34519 }
34520}
34521
34522},{}],181:[function(require,module,exports){
34523module.exports={
34524 "$id": "pageTimings.json#",
34525 "$schema": "http://json-schema.org/draft-06/schema#",
34526 "type": "object",
34527 "properties": {
34528 "onContentLoad": {
34529 "type": "number",
34530 "min": -1
34531 },
34532 "onLoad": {
34533 "type": "number",
34534 "min": -1
34535 },
34536 "comment": {
34537 "type": "string"
34538 }
34539 }
34540}
34541
34542},{}],182:[function(require,module,exports){
34543module.exports={
34544 "$id": "postData.json#",
34545 "$schema": "http://json-schema.org/draft-06/schema#",
34546 "type": "object",
34547 "optional": true,
34548 "required": [
34549 "mimeType"
34550 ],
34551 "properties": {
34552 "mimeType": {
34553 "type": "string"
34554 },
34555 "text": {
34556 "type": "string"
34557 },
34558 "params": {
34559 "type": "array",
34560 "required": [
34561 "name"
34562 ],
34563 "properties": {
34564 "name": {
34565 "type": "string"
34566 },
34567 "value": {
34568 "type": "string"
34569 },
34570 "fileName": {
34571 "type": "string"
34572 },
34573 "contentType": {
34574 "type": "string"
34575 },
34576 "comment": {
34577 "type": "string"
34578 }
34579 }
34580 },
34581 "comment": {
34582 "type": "string"
34583 }
34584 }
34585}
34586
34587},{}],183:[function(require,module,exports){
34588module.exports={
34589 "$id": "query.json#",
34590 "$schema": "http://json-schema.org/draft-06/schema#",
34591 "type": "object",
34592 "required": [
34593 "name",
34594 "value"
34595 ],
34596 "properties": {
34597 "name": {
34598 "type": "string"
34599 },
34600 "value": {
34601 "type": "string"
34602 },
34603 "comment": {
34604 "type": "string"
34605 }
34606 }
34607}
34608
34609},{}],184:[function(require,module,exports){
34610module.exports={
34611 "$id": "request.json#",
34612 "$schema": "http://json-schema.org/draft-06/schema#",
34613 "type": "object",
34614 "required": [
34615 "method",
34616 "url",
34617 "httpVersion",
34618 "cookies",
34619 "headers",
34620 "queryString",
34621 "headersSize",
34622 "bodySize"
34623 ],
34624 "properties": {
34625 "method": {
34626 "type": "string"
34627 },
34628 "url": {
34629 "type": "string",
34630 "format": "uri"
34631 },
34632 "httpVersion": {
34633 "type": "string"
34634 },
34635 "cookies": {
34636 "type": "array",
34637 "items": {
34638 "$ref": "cookie.json#"
34639 }
34640 },
34641 "headers": {
34642 "type": "array",
34643 "items": {
34644 "$ref": "header.json#"
34645 }
34646 },
34647 "queryString": {
34648 "type": "array",
34649 "items": {
34650 "$ref": "query.json#"
34651 }
34652 },
34653 "postData": {
34654 "$ref": "postData.json#"
34655 },
34656 "headersSize": {
34657 "type": "integer"
34658 },
34659 "bodySize": {
34660 "type": "integer"
34661 },
34662 "comment": {
34663 "type": "string"
34664 }
34665 }
34666}
34667
34668},{}],185:[function(require,module,exports){
34669module.exports={
34670 "$id": "response.json#",
34671 "$schema": "http://json-schema.org/draft-06/schema#",
34672 "type": "object",
34673 "required": [
34674 "status",
34675 "statusText",
34676 "httpVersion",
34677 "cookies",
34678 "headers",
34679 "content",
34680 "redirectURL",
34681 "headersSize",
34682 "bodySize"
34683 ],
34684 "properties": {
34685 "status": {
34686 "type": "integer"
34687 },
34688 "statusText": {
34689 "type": "string"
34690 },
34691 "httpVersion": {
34692 "type": "string"
34693 },
34694 "cookies": {
34695 "type": "array",
34696 "items": {
34697 "$ref": "cookie.json#"
34698 }
34699 },
34700 "headers": {
34701 "type": "array",
34702 "items": {
34703 "$ref": "header.json#"
34704 }
34705 },
34706 "content": {
34707 "$ref": "content.json#"
34708 },
34709 "redirectURL": {
34710 "type": "string"
34711 },
34712 "headersSize": {
34713 "type": "integer"
34714 },
34715 "bodySize": {
34716 "type": "integer"
34717 },
34718 "comment": {
34719 "type": "string"
34720 }
34721 }
34722}
34723
34724},{}],186:[function(require,module,exports){
34725module.exports={
34726 "$id": "timings.json#",
34727 "$schema": "http://json-schema.org/draft-06/schema#",
34728 "required": [
34729 "send",
34730 "wait",
34731 "receive"
34732 ],
34733 "properties": {
34734 "dns": {
34735 "type": "number",
34736 "min": -1
34737 },
34738 "connect": {
34739 "type": "number",
34740 "min": -1
34741 },
34742 "blocked": {
34743 "type": "number",
34744 "min": -1
34745 },
34746 "send": {
34747 "type": "number",
34748 "min": -1
34749 },
34750 "wait": {
34751 "type": "number",
34752 "min": -1
34753 },
34754 "receive": {
34755 "type": "number",
34756 "min": -1
34757 },
34758 "ssl": {
34759 "type": "number",
34760 "min": -1
34761 },
34762 "comment": {
34763 "type": "string"
34764 }
34765 }
34766}
34767
34768},{}],187:[function(require,module,exports){
34769function HARError (errors) {
34770 var message = 'validation failed'
34771
34772 this.name = 'HARError'
34773 this.message = message
34774 this.errors = errors
34775
34776 if (typeof Error.captureStackTrace === 'function') {
34777 Error.captureStackTrace(this, this.constructor)
34778 } else {
34779 this.stack = (new Error(message)).stack
34780 }
34781}
34782
34783HARError.prototype = Error.prototype
34784
34785module.exports = HARError
34786
34787},{}],188:[function(require,module,exports){
34788var Ajv = require('ajv')
34789var HARError = require('./error')
34790var schemas = require('har-schema')
34791
34792var ajv
34793
34794function createAjvInstance () {
34795 var ajv = new Ajv({
34796 allErrors: true
34797 })
34798 ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))
34799 ajv.addSchema(schemas)
34800
34801 return ajv
34802}
34803
34804function validate (name, data) {
34805 data = data || {}
34806
34807 // validator config
34808 ajv = ajv || createAjvInstance()
34809
34810 var validate = ajv.getSchema(name + '.json')
34811
34812 return new Promise(function (resolve, reject) {
34813 var valid = validate(data)
34814
34815 !valid ? reject(new HARError(validate.errors)) : resolve(data)
34816 })
34817}
34818
34819exports.afterRequest = function (data) {
34820 return validate('afterRequest', data)
34821}
34822
34823exports.beforeRequest = function (data) {
34824 return validate('beforeRequest', data)
34825}
34826
34827exports.browser = function (data) {
34828 return validate('browser', data)
34829}
34830
34831exports.cache = function (data) {
34832 return validate('cache', data)
34833}
34834
34835exports.content = function (data) {
34836 return validate('content', data)
34837}
34838
34839exports.cookie = function (data) {
34840 return validate('cookie', data)
34841}
34842
34843exports.creator = function (data) {
34844 return validate('creator', data)
34845}
34846
34847exports.entry = function (data) {
34848 return validate('entry', data)
34849}
34850
34851exports.har = function (data) {
34852 return validate('har', data)
34853}
34854
34855exports.header = function (data) {
34856 return validate('header', data)
34857}
34858
34859exports.log = function (data) {
34860 return validate('log', data)
34861}
34862
34863exports.page = function (data) {
34864 return validate('page', data)
34865}
34866
34867exports.pageTimings = function (data) {
34868 return validate('pageTimings', data)
34869}
34870
34871exports.postData = function (data) {
34872 return validate('postData', data)
34873}
34874
34875exports.query = function (data) {
34876 return validate('query', data)
34877}
34878
34879exports.request = function (data) {
34880 return validate('request', data)
34881}
34882
34883exports.response = function (data) {
34884 return validate('response', data)
34885}
34886
34887exports.timings = function (data) {
34888 return validate('timings', data)
34889}
34890
34891},{"./error":187,"ajv":5,"ajv/lib/refs/json-schema-draft-06.json":45,"har-schema":178}],189:[function(require,module,exports){
34892'use strict'
34893var Buffer = require('safe-buffer').Buffer
34894var Transform = require('stream').Transform
34895var inherits = require('inherits')
34896
34897function throwIfNotStringOrBuffer (val, prefix) {
34898 if (!Buffer.isBuffer(val) && typeof val !== 'string') {
34899 throw new TypeError(prefix + ' must be a string or a buffer')
34900 }
34901}
34902
34903function HashBase (blockSize) {
34904 Transform.call(this)
34905
34906 this._block = Buffer.allocUnsafe(blockSize)
34907 this._blockSize = blockSize
34908 this._blockOffset = 0
34909 this._length = [0, 0, 0, 0]
34910
34911 this._finalized = false
34912}
34913
34914inherits(HashBase, Transform)
34915
34916HashBase.prototype._transform = function (chunk, encoding, callback) {
34917 var error = null
34918 try {
34919 this.update(chunk, encoding)
34920 } catch (err) {
34921 error = err
34922 }
34923
34924 callback(error)
34925}
34926
34927HashBase.prototype._flush = function (callback) {
34928 var error = null
34929 try {
34930 this.push(this.digest())
34931 } catch (err) {
34932 error = err
34933 }
34934
34935 callback(error)
34936}
34937
34938HashBase.prototype.update = function (data, encoding) {
34939 throwIfNotStringOrBuffer(data, 'Data')
34940 if (this._finalized) throw new Error('Digest already called')
34941 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
34942
34943 // consume data
34944 var block = this._block
34945 var offset = 0
34946 while (this._blockOffset + data.length - offset >= this._blockSize) {
34947 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
34948 this._update()
34949 this._blockOffset = 0
34950 }
34951 while (offset < data.length) block[this._blockOffset++] = data[offset++]
34952
34953 // update length
34954 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
34955 this._length[j] += carry
34956 carry = (this._length[j] / 0x0100000000) | 0
34957 if (carry > 0) this._length[j] -= 0x0100000000 * carry
34958 }
34959
34960 return this
34961}
34962
34963HashBase.prototype._update = function () {
34964 throw new Error('_update is not implemented')
34965}
34966
34967HashBase.prototype.digest = function (encoding) {
34968 if (this._finalized) throw new Error('Digest already called')
34969 this._finalized = true
34970
34971 var digest = this._digest()
34972 if (encoding !== undefined) digest = digest.toString(encoding)
34973
34974 // reset state
34975 this._block.fill(0)
34976 this._blockOffset = 0
34977 for (var i = 0; i < 4; ++i) this._length[i] = 0
34978
34979 return digest
34980}
34981
34982HashBase.prototype._digest = function () {
34983 throw new Error('_digest is not implemented')
34984}
34985
34986module.exports = HashBase
34987
34988},{"inherits":210,"safe-buffer":325,"stream":361}],190:[function(require,module,exports){
34989var hash = exports;
34990
34991hash.utils = require('./hash/utils');
34992hash.common = require('./hash/common');
34993hash.sha = require('./hash/sha');
34994hash.ripemd = require('./hash/ripemd');
34995hash.hmac = require('./hash/hmac');
34996
34997// Proxy hash functions to the main object
34998hash.sha1 = hash.sha.sha1;
34999hash.sha256 = hash.sha.sha256;
35000hash.sha224 = hash.sha.sha224;
35001hash.sha384 = hash.sha.sha384;
35002hash.sha512 = hash.sha.sha512;
35003hash.ripemd160 = hash.ripemd.ripemd160;
35004
35005},{"./hash/common":191,"./hash/hmac":192,"./hash/ripemd":193,"./hash/sha":194,"./hash/utils":201}],191:[function(require,module,exports){
35006'use strict';
35007
35008var utils = require('./utils');
35009var assert = require('minimalistic-assert');
35010
35011function BlockHash() {
35012 this.pending = null;
35013 this.pendingTotal = 0;
35014 this.blockSize = this.constructor.blockSize;
35015 this.outSize = this.constructor.outSize;
35016 this.hmacStrength = this.constructor.hmacStrength;
35017 this.padLength = this.constructor.padLength / 8;
35018 this.endian = 'big';
35019
35020 this._delta8 = this.blockSize / 8;
35021 this._delta32 = this.blockSize / 32;
35022}
35023exports.BlockHash = BlockHash;
35024
35025BlockHash.prototype.update = function update(msg, enc) {
35026 // Convert message to array, pad it, and join into 32bit blocks
35027 msg = utils.toArray(msg, enc);
35028 if (!this.pending)
35029 this.pending = msg;
35030 else
35031 this.pending = this.pending.concat(msg);
35032 this.pendingTotal += msg.length;
35033
35034 // Enough data, try updating
35035 if (this.pending.length >= this._delta8) {
35036 msg = this.pending;
35037
35038 // Process pending data in blocks
35039 var r = msg.length % this._delta8;
35040 this.pending = msg.slice(msg.length - r, msg.length);
35041 if (this.pending.length === 0)
35042 this.pending = null;
35043
35044 msg = utils.join32(msg, 0, msg.length - r, this.endian);
35045 for (var i = 0; i < msg.length; i += this._delta32)
35046 this._update(msg, i, i + this._delta32);
35047 }
35048
35049 return this;
35050};
35051
35052BlockHash.prototype.digest = function digest(enc) {
35053 this.update(this._pad());
35054 assert(this.pending === null);
35055
35056 return this._digest(enc);
35057};
35058
35059BlockHash.prototype._pad = function pad() {
35060 var len = this.pendingTotal;
35061 var bytes = this._delta8;
35062 var k = bytes - ((len + this.padLength) % bytes);
35063 var res = new Array(k + this.padLength);
35064 res[0] = 0x80;
35065 for (var i = 1; i < k; i++)
35066 res[i] = 0;
35067
35068 // Append length
35069 len <<= 3;
35070 if (this.endian === 'big') {
35071 for (var t = 8; t < this.padLength; t++)
35072 res[i++] = 0;
35073
35074 res[i++] = 0;
35075 res[i++] = 0;
35076 res[i++] = 0;
35077 res[i++] = 0;
35078 res[i++] = (len >>> 24) & 0xff;
35079 res[i++] = (len >>> 16) & 0xff;
35080 res[i++] = (len >>> 8) & 0xff;
35081 res[i++] = len & 0xff;
35082 } else {
35083 res[i++] = len & 0xff;
35084 res[i++] = (len >>> 8) & 0xff;
35085 res[i++] = (len >>> 16) & 0xff;
35086 res[i++] = (len >>> 24) & 0xff;
35087 res[i++] = 0;
35088 res[i++] = 0;
35089 res[i++] = 0;
35090 res[i++] = 0;
35091
35092 for (t = 8; t < this.padLength; t++)
35093 res[i++] = 0;
35094 }
35095
35096 return res;
35097};
35098
35099},{"./utils":201,"minimalistic-assert":237}],192:[function(require,module,exports){
35100'use strict';
35101
35102var utils = require('./utils');
35103var assert = require('minimalistic-assert');
35104
35105function Hmac(hash, key, enc) {
35106 if (!(this instanceof Hmac))
35107 return new Hmac(hash, key, enc);
35108 this.Hash = hash;
35109 this.blockSize = hash.blockSize / 8;
35110 this.outSize = hash.outSize / 8;
35111 this.inner = null;
35112 this.outer = null;
35113
35114 this._init(utils.toArray(key, enc));
35115}
35116module.exports = Hmac;
35117
35118Hmac.prototype._init = function init(key) {
35119 // Shorten key, if needed
35120 if (key.length > this.blockSize)
35121 key = new this.Hash().update(key).digest();
35122 assert(key.length <= this.blockSize);
35123
35124 // Add padding to key
35125 for (var i = key.length; i < this.blockSize; i++)
35126 key.push(0);
35127
35128 for (i = 0; i < key.length; i++)
35129 key[i] ^= 0x36;
35130 this.inner = new this.Hash().update(key);
35131
35132 // 0x36 ^ 0x5c = 0x6a
35133 for (i = 0; i < key.length; i++)
35134 key[i] ^= 0x6a;
35135 this.outer = new this.Hash().update(key);
35136};
35137
35138Hmac.prototype.update = function update(msg, enc) {
35139 this.inner.update(msg, enc);
35140 return this;
35141};
35142
35143Hmac.prototype.digest = function digest(enc) {
35144 this.outer.update(this.inner.digest());
35145 return this.outer.digest(enc);
35146};
35147
35148},{"./utils":201,"minimalistic-assert":237}],193:[function(require,module,exports){
35149'use strict';
35150
35151var utils = require('./utils');
35152var common = require('./common');
35153
35154var rotl32 = utils.rotl32;
35155var sum32 = utils.sum32;
35156var sum32_3 = utils.sum32_3;
35157var sum32_4 = utils.sum32_4;
35158var BlockHash = common.BlockHash;
35159
35160function RIPEMD160() {
35161 if (!(this instanceof RIPEMD160))
35162 return new RIPEMD160();
35163
35164 BlockHash.call(this);
35165
35166 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
35167 this.endian = 'little';
35168}
35169utils.inherits(RIPEMD160, BlockHash);
35170exports.ripemd160 = RIPEMD160;
35171
35172RIPEMD160.blockSize = 512;
35173RIPEMD160.outSize = 160;
35174RIPEMD160.hmacStrength = 192;
35175RIPEMD160.padLength = 64;
35176
35177RIPEMD160.prototype._update = function update(msg, start) {
35178 var A = this.h[0];
35179 var B = this.h[1];
35180 var C = this.h[2];
35181 var D = this.h[3];
35182 var E = this.h[4];
35183 var Ah = A;
35184 var Bh = B;
35185 var Ch = C;
35186 var Dh = D;
35187 var Eh = E;
35188 for (var j = 0; j < 80; j++) {
35189 var T = sum32(
35190 rotl32(
35191 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
35192 s[j]),
35193 E);
35194 A = E;
35195 E = D;
35196 D = rotl32(C, 10);
35197 C = B;
35198 B = T;
35199 T = sum32(
35200 rotl32(
35201 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
35202 sh[j]),
35203 Eh);
35204 Ah = Eh;
35205 Eh = Dh;
35206 Dh = rotl32(Ch, 10);
35207 Ch = Bh;
35208 Bh = T;
35209 }
35210 T = sum32_3(this.h[1], C, Dh);
35211 this.h[1] = sum32_3(this.h[2], D, Eh);
35212 this.h[2] = sum32_3(this.h[3], E, Ah);
35213 this.h[3] = sum32_3(this.h[4], A, Bh);
35214 this.h[4] = sum32_3(this.h[0], B, Ch);
35215 this.h[0] = T;
35216};
35217
35218RIPEMD160.prototype._digest = function digest(enc) {
35219 if (enc === 'hex')
35220 return utils.toHex32(this.h, 'little');
35221 else
35222 return utils.split32(this.h, 'little');
35223};
35224
35225function f(j, x, y, z) {
35226 if (j <= 15)
35227 return x ^ y ^ z;
35228 else if (j <= 31)
35229 return (x & y) | ((~x) & z);
35230 else if (j <= 47)
35231 return (x | (~y)) ^ z;
35232 else if (j <= 63)
35233 return (x & z) | (y & (~z));
35234 else
35235 return x ^ (y | (~z));
35236}
35237
35238function K(j) {
35239 if (j <= 15)
35240 return 0x00000000;
35241 else if (j <= 31)
35242 return 0x5a827999;
35243 else if (j <= 47)
35244 return 0x6ed9eba1;
35245 else if (j <= 63)
35246 return 0x8f1bbcdc;
35247 else
35248 return 0xa953fd4e;
35249}
35250
35251function Kh(j) {
35252 if (j <= 15)
35253 return 0x50a28be6;
35254 else if (j <= 31)
35255 return 0x5c4dd124;
35256 else if (j <= 47)
35257 return 0x6d703ef3;
35258 else if (j <= 63)
35259 return 0x7a6d76e9;
35260 else
35261 return 0x00000000;
35262}
35263
35264var r = [
35265 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
35266 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
35267 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
35268 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
35269 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
35270];
35271
35272var rh = [
35273 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
35274 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
35275 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
35276 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
35277 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
35278];
35279
35280var s = [
35281 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
35282 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
35283 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
35284 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
35285 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
35286];
35287
35288var sh = [
35289 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
35290 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
35291 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
35292 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
35293 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
35294];
35295
35296},{"./common":191,"./utils":201}],194:[function(require,module,exports){
35297'use strict';
35298
35299exports.sha1 = require('./sha/1');
35300exports.sha224 = require('./sha/224');
35301exports.sha256 = require('./sha/256');
35302exports.sha384 = require('./sha/384');
35303exports.sha512 = require('./sha/512');
35304
35305},{"./sha/1":195,"./sha/224":196,"./sha/256":197,"./sha/384":198,"./sha/512":199}],195:[function(require,module,exports){
35306'use strict';
35307
35308var utils = require('../utils');
35309var common = require('../common');
35310var shaCommon = require('./common');
35311
35312var rotl32 = utils.rotl32;
35313var sum32 = utils.sum32;
35314var sum32_5 = utils.sum32_5;
35315var ft_1 = shaCommon.ft_1;
35316var BlockHash = common.BlockHash;
35317
35318var sha1_K = [
35319 0x5A827999, 0x6ED9EBA1,
35320 0x8F1BBCDC, 0xCA62C1D6
35321];
35322
35323function SHA1() {
35324 if (!(this instanceof SHA1))
35325 return new SHA1();
35326
35327 BlockHash.call(this);
35328 this.h = [
35329 0x67452301, 0xefcdab89, 0x98badcfe,
35330 0x10325476, 0xc3d2e1f0 ];
35331 this.W = new Array(80);
35332}
35333
35334utils.inherits(SHA1, BlockHash);
35335module.exports = SHA1;
35336
35337SHA1.blockSize = 512;
35338SHA1.outSize = 160;
35339SHA1.hmacStrength = 80;
35340SHA1.padLength = 64;
35341
35342SHA1.prototype._update = function _update(msg, start) {
35343 var W = this.W;
35344
35345 for (var i = 0; i < 16; i++)
35346 W[i] = msg[start + i];
35347
35348 for(; i < W.length; i++)
35349 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
35350
35351 var a = this.h[0];
35352 var b = this.h[1];
35353 var c = this.h[2];
35354 var d = this.h[3];
35355 var e = this.h[4];
35356
35357 for (i = 0; i < W.length; i++) {
35358 var s = ~~(i / 20);
35359 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
35360 e = d;
35361 d = c;
35362 c = rotl32(b, 30);
35363 b = a;
35364 a = t;
35365 }
35366
35367 this.h[0] = sum32(this.h[0], a);
35368 this.h[1] = sum32(this.h[1], b);
35369 this.h[2] = sum32(this.h[2], c);
35370 this.h[3] = sum32(this.h[3], d);
35371 this.h[4] = sum32(this.h[4], e);
35372};
35373
35374SHA1.prototype._digest = function digest(enc) {
35375 if (enc === 'hex')
35376 return utils.toHex32(this.h, 'big');
35377 else
35378 return utils.split32(this.h, 'big');
35379};
35380
35381},{"../common":191,"../utils":201,"./common":200}],196:[function(require,module,exports){
35382'use strict';
35383
35384var utils = require('../utils');
35385var SHA256 = require('./256');
35386
35387function SHA224() {
35388 if (!(this instanceof SHA224))
35389 return new SHA224();
35390
35391 SHA256.call(this);
35392 this.h = [
35393 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
35394 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
35395}
35396utils.inherits(SHA224, SHA256);
35397module.exports = SHA224;
35398
35399SHA224.blockSize = 512;
35400SHA224.outSize = 224;
35401SHA224.hmacStrength = 192;
35402SHA224.padLength = 64;
35403
35404SHA224.prototype._digest = function digest(enc) {
35405 // Just truncate output
35406 if (enc === 'hex')
35407 return utils.toHex32(this.h.slice(0, 7), 'big');
35408 else
35409 return utils.split32(this.h.slice(0, 7), 'big');
35410};
35411
35412
35413},{"../utils":201,"./256":197}],197:[function(require,module,exports){
35414'use strict';
35415
35416var utils = require('../utils');
35417var common = require('../common');
35418var shaCommon = require('./common');
35419var assert = require('minimalistic-assert');
35420
35421var sum32 = utils.sum32;
35422var sum32_4 = utils.sum32_4;
35423var sum32_5 = utils.sum32_5;
35424var ch32 = shaCommon.ch32;
35425var maj32 = shaCommon.maj32;
35426var s0_256 = shaCommon.s0_256;
35427var s1_256 = shaCommon.s1_256;
35428var g0_256 = shaCommon.g0_256;
35429var g1_256 = shaCommon.g1_256;
35430
35431var BlockHash = common.BlockHash;
35432
35433var sha256_K = [
35434 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
35435 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
35436 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
35437 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
35438 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
35439 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
35440 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
35441 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
35442 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
35443 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
35444 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
35445 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
35446 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
35447 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
35448 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
35449 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
35450];
35451
35452function SHA256() {
35453 if (!(this instanceof SHA256))
35454 return new SHA256();
35455
35456 BlockHash.call(this);
35457 this.h = [
35458 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
35459 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
35460 ];
35461 this.k = sha256_K;
35462 this.W = new Array(64);
35463}
35464utils.inherits(SHA256, BlockHash);
35465module.exports = SHA256;
35466
35467SHA256.blockSize = 512;
35468SHA256.outSize = 256;
35469SHA256.hmacStrength = 192;
35470SHA256.padLength = 64;
35471
35472SHA256.prototype._update = function _update(msg, start) {
35473 var W = this.W;
35474
35475 for (var i = 0; i < 16; i++)
35476 W[i] = msg[start + i];
35477 for (; i < W.length; i++)
35478 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
35479
35480 var a = this.h[0];
35481 var b = this.h[1];
35482 var c = this.h[2];
35483 var d = this.h[3];
35484 var e = this.h[4];
35485 var f = this.h[5];
35486 var g = this.h[6];
35487 var h = this.h[7];
35488
35489 assert(this.k.length === W.length);
35490 for (i = 0; i < W.length; i++) {
35491 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
35492 var T2 = sum32(s0_256(a), maj32(a, b, c));
35493 h = g;
35494 g = f;
35495 f = e;
35496 e = sum32(d, T1);
35497 d = c;
35498 c = b;
35499 b = a;
35500 a = sum32(T1, T2);
35501 }
35502
35503 this.h[0] = sum32(this.h[0], a);
35504 this.h[1] = sum32(this.h[1], b);
35505 this.h[2] = sum32(this.h[2], c);
35506 this.h[3] = sum32(this.h[3], d);
35507 this.h[4] = sum32(this.h[4], e);
35508 this.h[5] = sum32(this.h[5], f);
35509 this.h[6] = sum32(this.h[6], g);
35510 this.h[7] = sum32(this.h[7], h);
35511};
35512
35513SHA256.prototype._digest = function digest(enc) {
35514 if (enc === 'hex')
35515 return utils.toHex32(this.h, 'big');
35516 else
35517 return utils.split32(this.h, 'big');
35518};
35519
35520},{"../common":191,"../utils":201,"./common":200,"minimalistic-assert":237}],198:[function(require,module,exports){
35521'use strict';
35522
35523var utils = require('../utils');
35524
35525var SHA512 = require('./512');
35526
35527function SHA384() {
35528 if (!(this instanceof SHA384))
35529 return new SHA384();
35530
35531 SHA512.call(this);
35532 this.h = [
35533 0xcbbb9d5d, 0xc1059ed8,
35534 0x629a292a, 0x367cd507,
35535 0x9159015a, 0x3070dd17,
35536 0x152fecd8, 0xf70e5939,
35537 0x67332667, 0xffc00b31,
35538 0x8eb44a87, 0x68581511,
35539 0xdb0c2e0d, 0x64f98fa7,
35540 0x47b5481d, 0xbefa4fa4 ];
35541}
35542utils.inherits(SHA384, SHA512);
35543module.exports = SHA384;
35544
35545SHA384.blockSize = 1024;
35546SHA384.outSize = 384;
35547SHA384.hmacStrength = 192;
35548SHA384.padLength = 128;
35549
35550SHA384.prototype._digest = function digest(enc) {
35551 if (enc === 'hex')
35552 return utils.toHex32(this.h.slice(0, 12), 'big');
35553 else
35554 return utils.split32(this.h.slice(0, 12), 'big');
35555};
35556
35557},{"../utils":201,"./512":199}],199:[function(require,module,exports){
35558'use strict';
35559
35560var utils = require('../utils');
35561var common = require('../common');
35562var assert = require('minimalistic-assert');
35563
35564var rotr64_hi = utils.rotr64_hi;
35565var rotr64_lo = utils.rotr64_lo;
35566var shr64_hi = utils.shr64_hi;
35567var shr64_lo = utils.shr64_lo;
35568var sum64 = utils.sum64;
35569var sum64_hi = utils.sum64_hi;
35570var sum64_lo = utils.sum64_lo;
35571var sum64_4_hi = utils.sum64_4_hi;
35572var sum64_4_lo = utils.sum64_4_lo;
35573var sum64_5_hi = utils.sum64_5_hi;
35574var sum64_5_lo = utils.sum64_5_lo;
35575
35576var BlockHash = common.BlockHash;
35577
35578var sha512_K = [
35579 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
35580 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
35581 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
35582 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
35583 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
35584 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
35585 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
35586 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
35587 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
35588 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
35589 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
35590 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
35591 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
35592 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
35593 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
35594 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
35595 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
35596 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
35597 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
35598 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
35599 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
35600 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
35601 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
35602 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
35603 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
35604 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
35605 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
35606 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
35607 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
35608 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
35609 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
35610 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
35611 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
35612 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
35613 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
35614 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
35615 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
35616 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
35617 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
35618 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
35619];
35620
35621function SHA512() {
35622 if (!(this instanceof SHA512))
35623 return new SHA512();
35624
35625 BlockHash.call(this);
35626 this.h = [
35627 0x6a09e667, 0xf3bcc908,
35628 0xbb67ae85, 0x84caa73b,
35629 0x3c6ef372, 0xfe94f82b,
35630 0xa54ff53a, 0x5f1d36f1,
35631 0x510e527f, 0xade682d1,
35632 0x9b05688c, 0x2b3e6c1f,
35633 0x1f83d9ab, 0xfb41bd6b,
35634 0x5be0cd19, 0x137e2179 ];
35635 this.k = sha512_K;
35636 this.W = new Array(160);
35637}
35638utils.inherits(SHA512, BlockHash);
35639module.exports = SHA512;
35640
35641SHA512.blockSize = 1024;
35642SHA512.outSize = 512;
35643SHA512.hmacStrength = 192;
35644SHA512.padLength = 128;
35645
35646SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
35647 var W = this.W;
35648
35649 // 32 x 32bit words
35650 for (var i = 0; i < 32; i++)
35651 W[i] = msg[start + i];
35652 for (; i < W.length; i += 2) {
35653 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
35654 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
35655 var c1_hi = W[i - 14]; // i - 7
35656 var c1_lo = W[i - 13];
35657 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
35658 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
35659 var c3_hi = W[i - 32]; // i - 16
35660 var c3_lo = W[i - 31];
35661
35662 W[i] = sum64_4_hi(
35663 c0_hi, c0_lo,
35664 c1_hi, c1_lo,
35665 c2_hi, c2_lo,
35666 c3_hi, c3_lo);
35667 W[i + 1] = sum64_4_lo(
35668 c0_hi, c0_lo,
35669 c1_hi, c1_lo,
35670 c2_hi, c2_lo,
35671 c3_hi, c3_lo);
35672 }
35673};
35674
35675SHA512.prototype._update = function _update(msg, start) {
35676 this._prepareBlock(msg, start);
35677
35678 var W = this.W;
35679
35680 var ah = this.h[0];
35681 var al = this.h[1];
35682 var bh = this.h[2];
35683 var bl = this.h[3];
35684 var ch = this.h[4];
35685 var cl = this.h[5];
35686 var dh = this.h[6];
35687 var dl = this.h[7];
35688 var eh = this.h[8];
35689 var el = this.h[9];
35690 var fh = this.h[10];
35691 var fl = this.h[11];
35692 var gh = this.h[12];
35693 var gl = this.h[13];
35694 var hh = this.h[14];
35695 var hl = this.h[15];
35696
35697 assert(this.k.length === W.length);
35698 for (var i = 0; i < W.length; i += 2) {
35699 var c0_hi = hh;
35700 var c0_lo = hl;
35701 var c1_hi = s1_512_hi(eh, el);
35702 var c1_lo = s1_512_lo(eh, el);
35703 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
35704 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
35705 var c3_hi = this.k[i];
35706 var c3_lo = this.k[i + 1];
35707 var c4_hi = W[i];
35708 var c4_lo = W[i + 1];
35709
35710 var T1_hi = sum64_5_hi(
35711 c0_hi, c0_lo,
35712 c1_hi, c1_lo,
35713 c2_hi, c2_lo,
35714 c3_hi, c3_lo,
35715 c4_hi, c4_lo);
35716 var T1_lo = sum64_5_lo(
35717 c0_hi, c0_lo,
35718 c1_hi, c1_lo,
35719 c2_hi, c2_lo,
35720 c3_hi, c3_lo,
35721 c4_hi, c4_lo);
35722
35723 c0_hi = s0_512_hi(ah, al);
35724 c0_lo = s0_512_lo(ah, al);
35725 c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
35726 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
35727
35728 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
35729 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
35730
35731 hh = gh;
35732 hl = gl;
35733
35734 gh = fh;
35735 gl = fl;
35736
35737 fh = eh;
35738 fl = el;
35739
35740 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
35741 el = sum64_lo(dl, dl, T1_hi, T1_lo);
35742
35743 dh = ch;
35744 dl = cl;
35745
35746 ch = bh;
35747 cl = bl;
35748
35749 bh = ah;
35750 bl = al;
35751
35752 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
35753 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
35754 }
35755
35756 sum64(this.h, 0, ah, al);
35757 sum64(this.h, 2, bh, bl);
35758 sum64(this.h, 4, ch, cl);
35759 sum64(this.h, 6, dh, dl);
35760 sum64(this.h, 8, eh, el);
35761 sum64(this.h, 10, fh, fl);
35762 sum64(this.h, 12, gh, gl);
35763 sum64(this.h, 14, hh, hl);
35764};
35765
35766SHA512.prototype._digest = function digest(enc) {
35767 if (enc === 'hex')
35768 return utils.toHex32(this.h, 'big');
35769 else
35770 return utils.split32(this.h, 'big');
35771};
35772
35773function ch64_hi(xh, xl, yh, yl, zh) {
35774 var r = (xh & yh) ^ ((~xh) & zh);
35775 if (r < 0)
35776 r += 0x100000000;
35777 return r;
35778}
35779
35780function ch64_lo(xh, xl, yh, yl, zh, zl) {
35781 var r = (xl & yl) ^ ((~xl) & zl);
35782 if (r < 0)
35783 r += 0x100000000;
35784 return r;
35785}
35786
35787function maj64_hi(xh, xl, yh, yl, zh) {
35788 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
35789 if (r < 0)
35790 r += 0x100000000;
35791 return r;
35792}
35793
35794function maj64_lo(xh, xl, yh, yl, zh, zl) {
35795 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
35796 if (r < 0)
35797 r += 0x100000000;
35798 return r;
35799}
35800
35801function s0_512_hi(xh, xl) {
35802 var c0_hi = rotr64_hi(xh, xl, 28);
35803 var c1_hi = rotr64_hi(xl, xh, 2); // 34
35804 var c2_hi = rotr64_hi(xl, xh, 7); // 39
35805
35806 var r = c0_hi ^ c1_hi ^ c2_hi;
35807 if (r < 0)
35808 r += 0x100000000;
35809 return r;
35810}
35811
35812function s0_512_lo(xh, xl) {
35813 var c0_lo = rotr64_lo(xh, xl, 28);
35814 var c1_lo = rotr64_lo(xl, xh, 2); // 34
35815 var c2_lo = rotr64_lo(xl, xh, 7); // 39
35816
35817 var r = c0_lo ^ c1_lo ^ c2_lo;
35818 if (r < 0)
35819 r += 0x100000000;
35820 return r;
35821}
35822
35823function s1_512_hi(xh, xl) {
35824 var c0_hi = rotr64_hi(xh, xl, 14);
35825 var c1_hi = rotr64_hi(xh, xl, 18);
35826 var c2_hi = rotr64_hi(xl, xh, 9); // 41
35827
35828 var r = c0_hi ^ c1_hi ^ c2_hi;
35829 if (r < 0)
35830 r += 0x100000000;
35831 return r;
35832}
35833
35834function s1_512_lo(xh, xl) {
35835 var c0_lo = rotr64_lo(xh, xl, 14);
35836 var c1_lo = rotr64_lo(xh, xl, 18);
35837 var c2_lo = rotr64_lo(xl, xh, 9); // 41
35838
35839 var r = c0_lo ^ c1_lo ^ c2_lo;
35840 if (r < 0)
35841 r += 0x100000000;
35842 return r;
35843}
35844
35845function g0_512_hi(xh, xl) {
35846 var c0_hi = rotr64_hi(xh, xl, 1);
35847 var c1_hi = rotr64_hi(xh, xl, 8);
35848 var c2_hi = shr64_hi(xh, xl, 7);
35849
35850 var r = c0_hi ^ c1_hi ^ c2_hi;
35851 if (r < 0)
35852 r += 0x100000000;
35853 return r;
35854}
35855
35856function g0_512_lo(xh, xl) {
35857 var c0_lo = rotr64_lo(xh, xl, 1);
35858 var c1_lo = rotr64_lo(xh, xl, 8);
35859 var c2_lo = shr64_lo(xh, xl, 7);
35860
35861 var r = c0_lo ^ c1_lo ^ c2_lo;
35862 if (r < 0)
35863 r += 0x100000000;
35864 return r;
35865}
35866
35867function g1_512_hi(xh, xl) {
35868 var c0_hi = rotr64_hi(xh, xl, 19);
35869 var c1_hi = rotr64_hi(xl, xh, 29); // 61
35870 var c2_hi = shr64_hi(xh, xl, 6);
35871
35872 var r = c0_hi ^ c1_hi ^ c2_hi;
35873 if (r < 0)
35874 r += 0x100000000;
35875 return r;
35876}
35877
35878function g1_512_lo(xh, xl) {
35879 var c0_lo = rotr64_lo(xh, xl, 19);
35880 var c1_lo = rotr64_lo(xl, xh, 29); // 61
35881 var c2_lo = shr64_lo(xh, xl, 6);
35882
35883 var r = c0_lo ^ c1_lo ^ c2_lo;
35884 if (r < 0)
35885 r += 0x100000000;
35886 return r;
35887}
35888
35889},{"../common":191,"../utils":201,"minimalistic-assert":237}],200:[function(require,module,exports){
35890'use strict';
35891
35892var utils = require('../utils');
35893var rotr32 = utils.rotr32;
35894
35895function ft_1(s, x, y, z) {
35896 if (s === 0)
35897 return ch32(x, y, z);
35898 if (s === 1 || s === 3)
35899 return p32(x, y, z);
35900 if (s === 2)
35901 return maj32(x, y, z);
35902}
35903exports.ft_1 = ft_1;
35904
35905function ch32(x, y, z) {
35906 return (x & y) ^ ((~x) & z);
35907}
35908exports.ch32 = ch32;
35909
35910function maj32(x, y, z) {
35911 return (x & y) ^ (x & z) ^ (y & z);
35912}
35913exports.maj32 = maj32;
35914
35915function p32(x, y, z) {
35916 return x ^ y ^ z;
35917}
35918exports.p32 = p32;
35919
35920function s0_256(x) {
35921 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
35922}
35923exports.s0_256 = s0_256;
35924
35925function s1_256(x) {
35926 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
35927}
35928exports.s1_256 = s1_256;
35929
35930function g0_256(x) {
35931 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
35932}
35933exports.g0_256 = g0_256;
35934
35935function g1_256(x) {
35936 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
35937}
35938exports.g1_256 = g1_256;
35939
35940},{"../utils":201}],201:[function(require,module,exports){
35941'use strict';
35942
35943var assert = require('minimalistic-assert');
35944var inherits = require('inherits');
35945
35946exports.inherits = inherits;
35947
35948function isSurrogatePair(msg, i) {
35949 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
35950 return false;
35951 }
35952 if (i < 0 || i + 1 >= msg.length) {
35953 return false;
35954 }
35955 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
35956}
35957
35958function toArray(msg, enc) {
35959 if (Array.isArray(msg))
35960 return msg.slice();
35961 if (!msg)
35962 return [];
35963 var res = [];
35964 if (typeof msg === 'string') {
35965 if (!enc) {
35966 // Inspired by stringToUtf8ByteArray() in closure-library by Google
35967 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
35968 // Apache License 2.0
35969 // https://github.com/google/closure-library/blob/master/LICENSE
35970 var p = 0;
35971 for (var i = 0; i < msg.length; i++) {
35972 var c = msg.charCodeAt(i);
35973 if (c < 128) {
35974 res[p++] = c;
35975 } else if (c < 2048) {
35976 res[p++] = (c >> 6) | 192;
35977 res[p++] = (c & 63) | 128;
35978 } else if (isSurrogatePair(msg, i)) {
35979 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
35980 res[p++] = (c >> 18) | 240;
35981 res[p++] = ((c >> 12) & 63) | 128;
35982 res[p++] = ((c >> 6) & 63) | 128;
35983 res[p++] = (c & 63) | 128;
35984 } else {
35985 res[p++] = (c >> 12) | 224;
35986 res[p++] = ((c >> 6) & 63) | 128;
35987 res[p++] = (c & 63) | 128;
35988 }
35989 }
35990 } else if (enc === 'hex') {
35991 msg = msg.replace(/[^a-z0-9]+/ig, '');
35992 if (msg.length % 2 !== 0)
35993 msg = '0' + msg;
35994 for (i = 0; i < msg.length; i += 2)
35995 res.push(parseInt(msg[i] + msg[i + 1], 16));
35996 }
35997 } else {
35998 for (i = 0; i < msg.length; i++)
35999 res[i] = msg[i] | 0;
36000 }
36001 return res;
36002}
36003exports.toArray = toArray;
36004
36005function toHex(msg) {
36006 var res = '';
36007 for (var i = 0; i < msg.length; i++)
36008 res += zero2(msg[i].toString(16));
36009 return res;
36010}
36011exports.toHex = toHex;
36012
36013function htonl(w) {
36014 var res = (w >>> 24) |
36015 ((w >>> 8) & 0xff00) |
36016 ((w << 8) & 0xff0000) |
36017 ((w & 0xff) << 24);
36018 return res >>> 0;
36019}
36020exports.htonl = htonl;
36021
36022function toHex32(msg, endian) {
36023 var res = '';
36024 for (var i = 0; i < msg.length; i++) {
36025 var w = msg[i];
36026 if (endian === 'little')
36027 w = htonl(w);
36028 res += zero8(w.toString(16));
36029 }
36030 return res;
36031}
36032exports.toHex32 = toHex32;
36033
36034function zero2(word) {
36035 if (word.length === 1)
36036 return '0' + word;
36037 else
36038 return word;
36039}
36040exports.zero2 = zero2;
36041
36042function zero8(word) {
36043 if (word.length === 7)
36044 return '0' + word;
36045 else if (word.length === 6)
36046 return '00' + word;
36047 else if (word.length === 5)
36048 return '000' + word;
36049 else if (word.length === 4)
36050 return '0000' + word;
36051 else if (word.length === 3)
36052 return '00000' + word;
36053 else if (word.length === 2)
36054 return '000000' + word;
36055 else if (word.length === 1)
36056 return '0000000' + word;
36057 else
36058 return word;
36059}
36060exports.zero8 = zero8;
36061
36062function join32(msg, start, end, endian) {
36063 var len = end - start;
36064 assert(len % 4 === 0);
36065 var res = new Array(len / 4);
36066 for (var i = 0, k = start; i < res.length; i++, k += 4) {
36067 var w;
36068 if (endian === 'big')
36069 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
36070 else
36071 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
36072 res[i] = w >>> 0;
36073 }
36074 return res;
36075}
36076exports.join32 = join32;
36077
36078function split32(msg, endian) {
36079 var res = new Array(msg.length * 4);
36080 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
36081 var m = msg[i];
36082 if (endian === 'big') {
36083 res[k] = m >>> 24;
36084 res[k + 1] = (m >>> 16) & 0xff;
36085 res[k + 2] = (m >>> 8) & 0xff;
36086 res[k + 3] = m & 0xff;
36087 } else {
36088 res[k + 3] = m >>> 24;
36089 res[k + 2] = (m >>> 16) & 0xff;
36090 res[k + 1] = (m >>> 8) & 0xff;
36091 res[k] = m & 0xff;
36092 }
36093 }
36094 return res;
36095}
36096exports.split32 = split32;
36097
36098function rotr32(w, b) {
36099 return (w >>> b) | (w << (32 - b));
36100}
36101exports.rotr32 = rotr32;
36102
36103function rotl32(w, b) {
36104 return (w << b) | (w >>> (32 - b));
36105}
36106exports.rotl32 = rotl32;
36107
36108function sum32(a, b) {
36109 return (a + b) >>> 0;
36110}
36111exports.sum32 = sum32;
36112
36113function sum32_3(a, b, c) {
36114 return (a + b + c) >>> 0;
36115}
36116exports.sum32_3 = sum32_3;
36117
36118function sum32_4(a, b, c, d) {
36119 return (a + b + c + d) >>> 0;
36120}
36121exports.sum32_4 = sum32_4;
36122
36123function sum32_5(a, b, c, d, e) {
36124 return (a + b + c + d + e) >>> 0;
36125}
36126exports.sum32_5 = sum32_5;
36127
36128function sum64(buf, pos, ah, al) {
36129 var bh = buf[pos];
36130 var bl = buf[pos + 1];
36131
36132 var lo = (al + bl) >>> 0;
36133 var hi = (lo < al ? 1 : 0) + ah + bh;
36134 buf[pos] = hi >>> 0;
36135 buf[pos + 1] = lo;
36136}
36137exports.sum64 = sum64;
36138
36139function sum64_hi(ah, al, bh, bl) {
36140 var lo = (al + bl) >>> 0;
36141 var hi = (lo < al ? 1 : 0) + ah + bh;
36142 return hi >>> 0;
36143}
36144exports.sum64_hi = sum64_hi;
36145
36146function sum64_lo(ah, al, bh, bl) {
36147 var lo = al + bl;
36148 return lo >>> 0;
36149}
36150exports.sum64_lo = sum64_lo;
36151
36152function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
36153 var carry = 0;
36154 var lo = al;
36155 lo = (lo + bl) >>> 0;
36156 carry += lo < al ? 1 : 0;
36157 lo = (lo + cl) >>> 0;
36158 carry += lo < cl ? 1 : 0;
36159 lo = (lo + dl) >>> 0;
36160 carry += lo < dl ? 1 : 0;
36161
36162 var hi = ah + bh + ch + dh + carry;
36163 return hi >>> 0;
36164}
36165exports.sum64_4_hi = sum64_4_hi;
36166
36167function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
36168 var lo = al + bl + cl + dl;
36169 return lo >>> 0;
36170}
36171exports.sum64_4_lo = sum64_4_lo;
36172
36173function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
36174 var carry = 0;
36175 var lo = al;
36176 lo = (lo + bl) >>> 0;
36177 carry += lo < al ? 1 : 0;
36178 lo = (lo + cl) >>> 0;
36179 carry += lo < cl ? 1 : 0;
36180 lo = (lo + dl) >>> 0;
36181 carry += lo < dl ? 1 : 0;
36182 lo = (lo + el) >>> 0;
36183 carry += lo < el ? 1 : 0;
36184
36185 var hi = ah + bh + ch + dh + eh + carry;
36186 return hi >>> 0;
36187}
36188exports.sum64_5_hi = sum64_5_hi;
36189
36190function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
36191 var lo = al + bl + cl + dl + el;
36192
36193 return lo >>> 0;
36194}
36195exports.sum64_5_lo = sum64_5_lo;
36196
36197function rotr64_hi(ah, al, num) {
36198 var r = (al << (32 - num)) | (ah >>> num);
36199 return r >>> 0;
36200}
36201exports.rotr64_hi = rotr64_hi;
36202
36203function rotr64_lo(ah, al, num) {
36204 var r = (ah << (32 - num)) | (al >>> num);
36205 return r >>> 0;
36206}
36207exports.rotr64_lo = rotr64_lo;
36208
36209function shr64_hi(ah, al, num) {
36210 return ah >>> num;
36211}
36212exports.shr64_hi = shr64_hi;
36213
36214function shr64_lo(ah, al, num) {
36215 var r = (ah << (32 - num)) | (al >>> num);
36216 return r >>> 0;
36217}
36218exports.shr64_lo = shr64_lo;
36219
36220},{"inherits":210,"minimalistic-assert":237}],202:[function(require,module,exports){
36221'use strict';
36222
36223var hash = require('hash.js');
36224var utils = require('minimalistic-crypto-utils');
36225var assert = require('minimalistic-assert');
36226
36227function HmacDRBG(options) {
36228 if (!(this instanceof HmacDRBG))
36229 return new HmacDRBG(options);
36230 this.hash = options.hash;
36231 this.predResist = !!options.predResist;
36232
36233 this.outLen = this.hash.outSize;
36234 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
36235
36236 this._reseed = null;
36237 this.reseedInterval = null;
36238 this.K = null;
36239 this.V = null;
36240
36241 var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
36242 var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
36243 var pers = utils.toArray(options.pers, options.persEnc || 'hex');
36244 assert(entropy.length >= (this.minEntropy / 8),
36245 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
36246 this._init(entropy, nonce, pers);
36247}
36248module.exports = HmacDRBG;
36249
36250HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
36251 var seed = entropy.concat(nonce).concat(pers);
36252
36253 this.K = new Array(this.outLen / 8);
36254 this.V = new Array(this.outLen / 8);
36255 for (var i = 0; i < this.V.length; i++) {
36256 this.K[i] = 0x00;
36257 this.V[i] = 0x01;
36258 }
36259
36260 this._update(seed);
36261 this._reseed = 1;
36262 this.reseedInterval = 0x1000000000000; // 2^48
36263};
36264
36265HmacDRBG.prototype._hmac = function hmac() {
36266 return new hash.hmac(this.hash, this.K);
36267};
36268
36269HmacDRBG.prototype._update = function update(seed) {
36270 var kmac = this._hmac()
36271 .update(this.V)
36272 .update([ 0x00 ]);
36273 if (seed)
36274 kmac = kmac.update(seed);
36275 this.K = kmac.digest();
36276 this.V = this._hmac().update(this.V).digest();
36277 if (!seed)
36278 return;
36279
36280 this.K = this._hmac()
36281 .update(this.V)
36282 .update([ 0x01 ])
36283 .update(seed)
36284 .digest();
36285 this.V = this._hmac().update(this.V).digest();
36286};
36287
36288HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
36289 // Optional entropy enc
36290 if (typeof entropyEnc !== 'string') {
36291 addEnc = add;
36292 add = entropyEnc;
36293 entropyEnc = null;
36294 }
36295
36296 entropy = utils.toArray(entropy, entropyEnc);
36297 add = utils.toArray(add, addEnc);
36298
36299 assert(entropy.length >= (this.minEntropy / 8),
36300 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
36301
36302 this._update(entropy.concat(add || []));
36303 this._reseed = 1;
36304};
36305
36306HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
36307 if (this._reseed > this.reseedInterval)
36308 throw new Error('Reseed is required');
36309
36310 // Optional encoding
36311 if (typeof enc !== 'string') {
36312 addEnc = add;
36313 add = enc;
36314 enc = null;
36315 }
36316
36317 // Optional additional data
36318 if (add) {
36319 add = utils.toArray(add, addEnc || 'hex');
36320 this._update(add);
36321 }
36322
36323 var temp = [];
36324 while (temp.length < len) {
36325 this.V = this._hmac().update(this.V).digest();
36326 temp = temp.concat(this.V);
36327 }
36328
36329 var res = temp.slice(0, len);
36330 this._update(add);
36331 this._reseed++;
36332 return utils.encode(res, enc);
36333};
36334
36335},{"hash.js":190,"minimalistic-assert":237,"minimalistic-crypto-utils":238}],203:[function(require,module,exports){
36336// Copyright 2015 Joyent, Inc.
36337
36338var parser = require('./parser');
36339var signer = require('./signer');
36340var verify = require('./verify');
36341var utils = require('./utils');
36342
36343
36344
36345///--- API
36346
36347module.exports = {
36348
36349 parse: parser.parseRequest,
36350 parseRequest: parser.parseRequest,
36351
36352 sign: signer.signRequest,
36353 signRequest: signer.signRequest,
36354 createSigner: signer.createSigner,
36355 isSigner: signer.isSigner,
36356
36357 sshKeyToPEM: utils.sshKeyToPEM,
36358 sshKeyFingerprint: utils.fingerprint,
36359 pemToRsaSSHKey: utils.pemToRsaSSHKey,
36360
36361 verify: verify.verifySignature,
36362 verifySignature: verify.verifySignature,
36363 verifyHMAC: verify.verifyHMAC
36364};
36365
36366},{"./parser":204,"./signer":205,"./utils":206,"./verify":207}],204:[function(require,module,exports){
36367// Copyright 2012 Joyent, Inc. All rights reserved.
36368
36369var assert = require('assert-plus');
36370var util = require('util');
36371var utils = require('./utils');
36372
36373
36374
36375///--- Globals
36376
36377var HASH_ALGOS = utils.HASH_ALGOS;
36378var PK_ALGOS = utils.PK_ALGOS;
36379var HttpSignatureError = utils.HttpSignatureError;
36380var InvalidAlgorithmError = utils.InvalidAlgorithmError;
36381var validateAlgorithm = utils.validateAlgorithm;
36382
36383var State = {
36384 New: 0,
36385 Params: 1
36386};
36387
36388var ParamsState = {
36389 Name: 0,
36390 Quote: 1,
36391 Value: 2,
36392 Comma: 3
36393};
36394
36395
36396///--- Specific Errors
36397
36398
36399function ExpiredRequestError(message) {
36400 HttpSignatureError.call(this, message, ExpiredRequestError);
36401}
36402util.inherits(ExpiredRequestError, HttpSignatureError);
36403
36404
36405function InvalidHeaderError(message) {
36406 HttpSignatureError.call(this, message, InvalidHeaderError);
36407}
36408util.inherits(InvalidHeaderError, HttpSignatureError);
36409
36410
36411function InvalidParamsError(message) {
36412 HttpSignatureError.call(this, message, InvalidParamsError);
36413}
36414util.inherits(InvalidParamsError, HttpSignatureError);
36415
36416
36417function MissingHeaderError(message) {
36418 HttpSignatureError.call(this, message, MissingHeaderError);
36419}
36420util.inherits(MissingHeaderError, HttpSignatureError);
36421
36422function StrictParsingError(message) {
36423 HttpSignatureError.call(this, message, StrictParsingError);
36424}
36425util.inherits(StrictParsingError, HttpSignatureError);
36426
36427///--- Exported API
36428
36429module.exports = {
36430
36431 /**
36432 * Parses the 'Authorization' header out of an http.ServerRequest object.
36433 *
36434 * Note that this API will fully validate the Authorization header, and throw
36435 * on any error. It will not however check the signature, or the keyId format
36436 * as those are specific to your environment. You can use the options object
36437 * to pass in extra constraints.
36438 *
36439 * As a response object you can expect this:
36440 *
36441 * {
36442 * "scheme": "Signature",
36443 * "params": {
36444 * "keyId": "foo",
36445 * "algorithm": "rsa-sha256",
36446 * "headers": [
36447 * "date" or "x-date",
36448 * "digest"
36449 * ],
36450 * "signature": "base64"
36451 * },
36452 * "signingString": "ready to be passed to crypto.verify()"
36453 * }
36454 *
36455 * @param {Object} request an http.ServerRequest.
36456 * @param {Object} options an optional options object with:
36457 * - clockSkew: allowed clock skew in seconds (default 300).
36458 * - headers: required header names (def: date or x-date)
36459 * - algorithms: algorithms to support (default: all).
36460 * - strict: should enforce latest spec parsing
36461 * (default: false).
36462 * @return {Object} parsed out object (see above).
36463 * @throws {TypeError} on invalid input.
36464 * @throws {InvalidHeaderError} on an invalid Authorization header error.
36465 * @throws {InvalidParamsError} if the params in the scheme are invalid.
36466 * @throws {MissingHeaderError} if the params indicate a header not present,
36467 * either in the request headers from the params,
36468 * or not in the params from a required header
36469 * in options.
36470 * @throws {StrictParsingError} if old attributes are used in strict parsing
36471 * mode.
36472 * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew.
36473 */
36474 parseRequest: function parseRequest(request, options) {
36475 assert.object(request, 'request');
36476 assert.object(request.headers, 'request.headers');
36477 if (options === undefined) {
36478 options = {};
36479 }
36480 if (options.headers === undefined) {
36481 options.headers = [request.headers['x-date'] ? 'x-date' : 'date'];
36482 }
36483 assert.object(options, 'options');
36484 assert.arrayOfString(options.headers, 'options.headers');
36485 assert.optionalFinite(options.clockSkew, 'options.clockSkew');
36486
36487 var authzHeaderName = options.authorizationHeaderName || 'authorization';
36488
36489 if (!request.headers[authzHeaderName]) {
36490 throw new MissingHeaderError('no ' + authzHeaderName + ' header ' +
36491 'present in the request');
36492 }
36493
36494 options.clockSkew = options.clockSkew || 300;
36495
36496
36497 var i = 0;
36498 var state = State.New;
36499 var substate = ParamsState.Name;
36500 var tmpName = '';
36501 var tmpValue = '';
36502
36503 var parsed = {
36504 scheme: '',
36505 params: {},
36506 signingString: ''
36507 };
36508
36509 var authz = request.headers[authzHeaderName];
36510 for (i = 0; i < authz.length; i++) {
36511 var c = authz.charAt(i);
36512
36513 switch (Number(state)) {
36514
36515 case State.New:
36516 if (c !== ' ') parsed.scheme += c;
36517 else state = State.Params;
36518 break;
36519
36520 case State.Params:
36521 switch (Number(substate)) {
36522
36523 case ParamsState.Name:
36524 var code = c.charCodeAt(0);
36525 // restricted name of A-Z / a-z
36526 if ((code >= 0x41 && code <= 0x5a) || // A-Z
36527 (code >= 0x61 && code <= 0x7a)) { // a-z
36528 tmpName += c;
36529 } else if (c === '=') {
36530 if (tmpName.length === 0)
36531 throw new InvalidHeaderError('bad param format');
36532 substate = ParamsState.Quote;
36533 } else {
36534 throw new InvalidHeaderError('bad param format');
36535 }
36536 break;
36537
36538 case ParamsState.Quote:
36539 if (c === '"') {
36540 tmpValue = '';
36541 substate = ParamsState.Value;
36542 } else {
36543 throw new InvalidHeaderError('bad param format');
36544 }
36545 break;
36546
36547 case ParamsState.Value:
36548 if (c === '"') {
36549 parsed.params[tmpName] = tmpValue;
36550 substate = ParamsState.Comma;
36551 } else {
36552 tmpValue += c;
36553 }
36554 break;
36555
36556 case ParamsState.Comma:
36557 if (c === ',') {
36558 tmpName = '';
36559 substate = ParamsState.Name;
36560 } else {
36561 throw new InvalidHeaderError('bad param format');
36562 }
36563 break;
36564
36565 default:
36566 throw new Error('Invalid substate');
36567 }
36568 break;
36569
36570 default:
36571 throw new Error('Invalid substate');
36572 }
36573
36574 }
36575
36576 if (!parsed.params.headers || parsed.params.headers === '') {
36577 if (request.headers['x-date']) {
36578 parsed.params.headers = ['x-date'];
36579 } else {
36580 parsed.params.headers = ['date'];
36581 }
36582 } else {
36583 parsed.params.headers = parsed.params.headers.split(' ');
36584 }
36585
36586 // Minimally validate the parsed object
36587 if (!parsed.scheme || parsed.scheme !== 'Signature')
36588 throw new InvalidHeaderError('scheme was not "Signature"');
36589
36590 if (!parsed.params.keyId)
36591 throw new InvalidHeaderError('keyId was not specified');
36592
36593 if (!parsed.params.algorithm)
36594 throw new InvalidHeaderError('algorithm was not specified');
36595
36596 if (!parsed.params.signature)
36597 throw new InvalidHeaderError('signature was not specified');
36598
36599 // Check the algorithm against the official list
36600 parsed.params.algorithm = parsed.params.algorithm.toLowerCase();
36601 try {
36602 validateAlgorithm(parsed.params.algorithm);
36603 } catch (e) {
36604 if (e instanceof InvalidAlgorithmError)
36605 throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' +
36606 'supported'));
36607 else
36608 throw (e);
36609 }
36610
36611 // Build the signingString
36612 for (i = 0; i < parsed.params.headers.length; i++) {
36613 var h = parsed.params.headers[i].toLowerCase();
36614 parsed.params.headers[i] = h;
36615
36616 if (h === 'request-line') {
36617 if (!options.strict) {
36618 /*
36619 * We allow headers from the older spec drafts if strict parsing isn't
36620 * specified in options.
36621 */
36622 parsed.signingString +=
36623 request.method + ' ' + request.url + ' HTTP/' + request.httpVersion;
36624 } else {
36625 /* Strict parsing doesn't allow older draft headers. */
36626 throw (new StrictParsingError('request-line is not a valid header ' +
36627 'with strict parsing enabled.'));
36628 }
36629 } else if (h === '(request-target)') {
36630 parsed.signingString +=
36631 '(request-target): ' + request.method.toLowerCase() + ' ' +
36632 request.url;
36633 } else {
36634 var value = request.headers[h];
36635 if (value === undefined)
36636 throw new MissingHeaderError(h + ' was not in the request');
36637 parsed.signingString += h + ': ' + value;
36638 }
36639
36640 if ((i + 1) < parsed.params.headers.length)
36641 parsed.signingString += '\n';
36642 }
36643
36644 // Check against the constraints
36645 var date;
36646 if (request.headers.date || request.headers['x-date']) {
36647 if (request.headers['x-date']) {
36648 date = new Date(request.headers['x-date']);
36649 } else {
36650 date = new Date(request.headers.date);
36651 }
36652 var now = new Date();
36653 var skew = Math.abs(now.getTime() - date.getTime());
36654
36655 if (skew > options.clockSkew * 1000) {
36656 throw new ExpiredRequestError('clock skew of ' +
36657 (skew / 1000) +
36658 's was greater than ' +
36659 options.clockSkew + 's');
36660 }
36661 }
36662
36663 options.headers.forEach(function (hdr) {
36664 // Remember that we already checked any headers in the params
36665 // were in the request, so if this passes we're good.
36666 if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0)
36667 throw new MissingHeaderError(hdr + ' was not a signed header');
36668 });
36669
36670 if (options.algorithms) {
36671 if (options.algorithms.indexOf(parsed.params.algorithm) === -1)
36672 throw new InvalidParamsError(parsed.params.algorithm +
36673 ' is not a supported algorithm');
36674 }
36675
36676 parsed.algorithm = parsed.params.algorithm.toUpperCase();
36677 parsed.keyId = parsed.params.keyId;
36678 return parsed;
36679 }
36680
36681};
36682
36683},{"./utils":206,"assert-plus":67,"util":397}],205:[function(require,module,exports){
36684(function (Buffer){
36685// Copyright 2012 Joyent, Inc. All rights reserved.
36686
36687var assert = require('assert-plus');
36688var crypto = require('crypto');
36689var http = require('http');
36690var util = require('util');
36691var sshpk = require('sshpk');
36692var jsprim = require('jsprim');
36693var utils = require('./utils');
36694
36695var sprintf = require('util').format;
36696
36697var HASH_ALGOS = utils.HASH_ALGOS;
36698var PK_ALGOS = utils.PK_ALGOS;
36699var InvalidAlgorithmError = utils.InvalidAlgorithmError;
36700var HttpSignatureError = utils.HttpSignatureError;
36701var validateAlgorithm = utils.validateAlgorithm;
36702
36703///--- Globals
36704
36705var AUTHZ_FMT =
36706 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';
36707
36708///--- Specific Errors
36709
36710function MissingHeaderError(message) {
36711 HttpSignatureError.call(this, message, MissingHeaderError);
36712}
36713util.inherits(MissingHeaderError, HttpSignatureError);
36714
36715function StrictParsingError(message) {
36716 HttpSignatureError.call(this, message, StrictParsingError);
36717}
36718util.inherits(StrictParsingError, HttpSignatureError);
36719
36720/* See createSigner() */
36721function RequestSigner(options) {
36722 assert.object(options, 'options');
36723
36724 var alg = [];
36725 if (options.algorithm !== undefined) {
36726 assert.string(options.algorithm, 'options.algorithm');
36727 alg = validateAlgorithm(options.algorithm);
36728 }
36729 this.rs_alg = alg;
36730
36731 /*
36732 * RequestSigners come in two varieties: ones with an rs_signFunc, and ones
36733 * with an rs_signer.
36734 *
36735 * rs_signFunc-based RequestSigners have to build up their entire signing
36736 * string within the rs_lines array and give it to rs_signFunc as a single
36737 * concat'd blob. rs_signer-based RequestSigners can add a line at a time to
36738 * their signing state by using rs_signer.update(), thus only needing to
36739 * buffer the hash function state and one line at a time.
36740 */
36741 if (options.sign !== undefined) {
36742 assert.func(options.sign, 'options.sign');
36743 this.rs_signFunc = options.sign;
36744
36745 } else if (alg[0] === 'hmac' && options.key !== undefined) {
36746 assert.string(options.keyId, 'options.keyId');
36747 this.rs_keyId = options.keyId;
36748
36749 if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
36750 throw (new TypeError('options.key for HMAC must be a string or Buffer'));
36751
36752 /*
36753 * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their
36754 * data in chunks rather than requiring it all to be given in one go
36755 * at the end, so they are more similar to signers than signFuncs.
36756 */
36757 this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key);
36758 this.rs_signer.sign = function () {
36759 var digest = this.digest('base64');
36760 return ({
36761 hashAlgorithm: alg[1],
36762 toString: function () { return (digest); }
36763 });
36764 };
36765
36766 } else if (options.key !== undefined) {
36767 var key = options.key;
36768 if (typeof (key) === 'string' || Buffer.isBuffer(key))
36769 key = sshpk.parsePrivateKey(key);
36770
36771 assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
36772 'options.key must be a sshpk.PrivateKey');
36773 this.rs_key = key;
36774
36775 assert.string(options.keyId, 'options.keyId');
36776 this.rs_keyId = options.keyId;
36777
36778 if (!PK_ALGOS[key.type]) {
36779 throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
36780 'keys are not supported'));
36781 }
36782
36783 if (alg[0] !== undefined && key.type !== alg[0]) {
36784 throw (new InvalidAlgorithmError('options.key must be a ' +
36785 alg[0].toUpperCase() + ' key, was given a ' +
36786 key.type.toUpperCase() + ' key instead'));
36787 }
36788
36789 this.rs_signer = key.createSign(alg[1]);
36790
36791 } else {
36792 throw (new TypeError('options.sign (func) or options.key is required'));
36793 }
36794
36795 this.rs_headers = [];
36796 this.rs_lines = [];
36797}
36798
36799/**
36800 * Adds a header to be signed, with its value, into this signer.
36801 *
36802 * @param {String} header
36803 * @param {String} value
36804 * @return {String} value written
36805 */
36806RequestSigner.prototype.writeHeader = function (header, value) {
36807 assert.string(header, 'header');
36808 header = header.toLowerCase();
36809 assert.string(value, 'value');
36810
36811 this.rs_headers.push(header);
36812
36813 if (this.rs_signFunc) {
36814 this.rs_lines.push(header + ': ' + value);
36815
36816 } else {
36817 var line = header + ': ' + value;
36818 if (this.rs_headers.length > 0)
36819 line = '\n' + line;
36820 this.rs_signer.update(line);
36821 }
36822
36823 return (value);
36824};
36825
36826/**
36827 * Adds a default Date header, returning its value.
36828 *
36829 * @return {String}
36830 */
36831RequestSigner.prototype.writeDateHeader = function () {
36832 return (this.writeHeader('date', jsprim.rfc1123(new Date())));
36833};
36834
36835/**
36836 * Adds the request target line to be signed.
36837 *
36838 * @param {String} method, HTTP method (e.g. 'get', 'post', 'put')
36839 * @param {String} path
36840 */
36841RequestSigner.prototype.writeTarget = function (method, path) {
36842 assert.string(method, 'method');
36843 assert.string(path, 'path');
36844 method = method.toLowerCase();
36845 this.writeHeader('(request-target)', method + ' ' + path);
36846};
36847
36848/**
36849 * Calculate the value for the Authorization header on this request
36850 * asynchronously.
36851 *
36852 * @param {Func} callback (err, authz)
36853 */
36854RequestSigner.prototype.sign = function (cb) {
36855 assert.func(cb, 'callback');
36856
36857 if (this.rs_headers.length < 1)
36858 throw (new Error('At least one header must be signed'));
36859
36860 var alg, authz;
36861 if (this.rs_signFunc) {
36862 var data = this.rs_lines.join('\n');
36863 var self = this;
36864 this.rs_signFunc(data, function (err, sig) {
36865 if (err) {
36866 cb(err);
36867 return;
36868 }
36869 try {
36870 assert.object(sig, 'signature');
36871 assert.string(sig.keyId, 'signature.keyId');
36872 assert.string(sig.algorithm, 'signature.algorithm');
36873 assert.string(sig.signature, 'signature.signature');
36874 alg = validateAlgorithm(sig.algorithm);
36875
36876 authz = sprintf(AUTHZ_FMT,
36877 sig.keyId,
36878 sig.algorithm,
36879 self.rs_headers.join(' '),
36880 sig.signature);
36881 } catch (e) {
36882 cb(e);
36883 return;
36884 }
36885 cb(null, authz);
36886 });
36887
36888 } else {
36889 try {
36890 var sigObj = this.rs_signer.sign();
36891 } catch (e) {
36892 cb(e);
36893 return;
36894 }
36895 alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm;
36896 var signature = sigObj.toString();
36897 authz = sprintf(AUTHZ_FMT,
36898 this.rs_keyId,
36899 alg,
36900 this.rs_headers.join(' '),
36901 signature);
36902 cb(null, authz);
36903 }
36904};
36905
36906///--- Exported API
36907
36908module.exports = {
36909 /**
36910 * Identifies whether a given object is a request signer or not.
36911 *
36912 * @param {Object} object, the object to identify
36913 * @returns {Boolean}
36914 */
36915 isSigner: function (obj) {
36916 if (typeof (obj) === 'object' && obj instanceof RequestSigner)
36917 return (true);
36918 return (false);
36919 },
36920
36921 /**
36922 * Creates a request signer, used to asynchronously build a signature
36923 * for a request (does not have to be an http.ClientRequest).
36924 *
36925 * @param {Object} options, either:
36926 * - {String} keyId
36927 * - {String|Buffer} key
36928 * - {String} algorithm (optional, required for HMAC)
36929 * or:
36930 * - {Func} sign (data, cb)
36931 * @return {RequestSigner}
36932 */
36933 createSigner: function createSigner(options) {
36934 return (new RequestSigner(options));
36935 },
36936
36937 /**
36938 * Adds an 'Authorization' header to an http.ClientRequest object.
36939 *
36940 * Note that this API will add a Date header if it's not already set. Any
36941 * other headers in the options.headers array MUST be present, or this
36942 * will throw.
36943 *
36944 * You shouldn't need to check the return type; it's just there if you want
36945 * to be pedantic.
36946 *
36947 * The optional flag indicates whether parsing should use strict enforcement
36948 * of the version draft-cavage-http-signatures-04 of the spec or beyond.
36949 * The default is to be loose and support
36950 * older versions for compatibility.
36951 *
36952 * @param {Object} request an instance of http.ClientRequest.
36953 * @param {Object} options signing parameters object:
36954 * - {String} keyId required.
36955 * - {String} key required (either a PEM or HMAC key).
36956 * - {Array} headers optional; defaults to ['date'].
36957 * - {String} algorithm optional (unless key is HMAC);
36958 * default is the same as the sshpk default
36959 * signing algorithm for the type of key given
36960 * - {String} httpVersion optional; defaults to '1.1'.
36961 * - {Boolean} strict optional; defaults to 'false'.
36962 * @return {Boolean} true if Authorization (and optionally Date) were added.
36963 * @throws {TypeError} on bad parameter types (input).
36964 * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with
36965 * the given key.
36966 * @throws {sshpk.KeyParseError} if key was bad.
36967 * @throws {MissingHeaderError} if a header to be signed was specified but
36968 * was not present.
36969 */
36970 signRequest: function signRequest(request, options) {
36971 assert.object(request, 'request');
36972 assert.object(options, 'options');
36973 assert.optionalString(options.algorithm, 'options.algorithm');
36974 assert.string(options.keyId, 'options.keyId');
36975 assert.optionalArrayOfString(options.headers, 'options.headers');
36976 assert.optionalString(options.httpVersion, 'options.httpVersion');
36977
36978 if (!request.getHeader('Date'))
36979 request.setHeader('Date', jsprim.rfc1123(new Date()));
36980 if (!options.headers)
36981 options.headers = ['date'];
36982 if (!options.httpVersion)
36983 options.httpVersion = '1.1';
36984
36985 var alg = [];
36986 if (options.algorithm) {
36987 options.algorithm = options.algorithm.toLowerCase();
36988 alg = validateAlgorithm(options.algorithm);
36989 }
36990
36991 var i;
36992 var stringToSign = '';
36993 for (i = 0; i < options.headers.length; i++) {
36994 if (typeof (options.headers[i]) !== 'string')
36995 throw new TypeError('options.headers must be an array of Strings');
36996
36997 var h = options.headers[i].toLowerCase();
36998
36999 if (h === 'request-line') {
37000 if (!options.strict) {
37001 /**
37002 * We allow headers from the older spec drafts if strict parsing isn't
37003 * specified in options.
37004 */
37005 stringToSign +=
37006 request.method + ' ' + request.path + ' HTTP/' +
37007 options.httpVersion;
37008 } else {
37009 /* Strict parsing doesn't allow older draft headers. */
37010 throw (new StrictParsingError('request-line is not a valid header ' +
37011 'with strict parsing enabled.'));
37012 }
37013 } else if (h === '(request-target)') {
37014 stringToSign +=
37015 '(request-target): ' + request.method.toLowerCase() + ' ' +
37016 request.path;
37017 } else {
37018 var value = request.getHeader(h);
37019 if (value === undefined || value === '') {
37020 throw new MissingHeaderError(h + ' was not in the request');
37021 }
37022 stringToSign += h + ': ' + value;
37023 }
37024
37025 if ((i + 1) < options.headers.length)
37026 stringToSign += '\n';
37027 }
37028
37029 /* This is just for unit tests. */
37030 if (request.hasOwnProperty('_stringToSign')) {
37031 request._stringToSign = stringToSign;
37032 }
37033
37034 var signature;
37035 if (alg[0] === 'hmac') {
37036 if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
37037 throw (new TypeError('options.key must be a string or Buffer'));
37038
37039 var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key);
37040 hmac.update(stringToSign);
37041 signature = hmac.digest('base64');
37042
37043 } else {
37044 var key = options.key;
37045 if (typeof (key) === 'string' || Buffer.isBuffer(key))
37046 key = sshpk.parsePrivateKey(options.key);
37047
37048 assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
37049 'options.key must be a sshpk.PrivateKey');
37050
37051 if (!PK_ALGOS[key.type]) {
37052 throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
37053 'keys are not supported'));
37054 }
37055
37056 if (alg[0] !== undefined && key.type !== alg[0]) {
37057 throw (new InvalidAlgorithmError('options.key must be a ' +
37058 alg[0].toUpperCase() + ' key, was given a ' +
37059 key.type.toUpperCase() + ' key instead'));
37060 }
37061
37062 var signer = key.createSign(alg[1]);
37063 signer.update(stringToSign);
37064 var sigObj = signer.sign();
37065 if (!HASH_ALGOS[sigObj.hashAlgorithm]) {
37066 throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() +
37067 ' is not a supported hash algorithm'));
37068 }
37069 options.algorithm = key.type + '-' + sigObj.hashAlgorithm;
37070 signature = sigObj.toString();
37071 assert.notStrictEqual(signature, '', 'empty signature produced');
37072 }
37073
37074 var authzHeaderName = options.authorizationHeaderName || 'Authorization';
37075
37076 request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT,
37077 options.keyId,
37078 options.algorithm,
37079 options.headers.join(' '),
37080 signature));
37081
37082 return true;
37083 }
37084
37085};
37086
37087}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
37088},{"../../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){
37089// Copyright 2012 Joyent, Inc. All rights reserved.
37090
37091var assert = require('assert-plus');
37092var sshpk = require('sshpk');
37093var util = require('util');
37094
37095var HASH_ALGOS = {
37096 'sha1': true,
37097 'sha256': true,
37098 'sha512': true
37099};
37100
37101var PK_ALGOS = {
37102 'rsa': true,
37103 'dsa': true,
37104 'ecdsa': true
37105};
37106
37107function HttpSignatureError(message, caller) {
37108 if (Error.captureStackTrace)
37109 Error.captureStackTrace(this, caller || HttpSignatureError);
37110
37111 this.message = message;
37112 this.name = caller.name;
37113}
37114util.inherits(HttpSignatureError, Error);
37115
37116function InvalidAlgorithmError(message) {
37117 HttpSignatureError.call(this, message, InvalidAlgorithmError);
37118}
37119util.inherits(InvalidAlgorithmError, HttpSignatureError);
37120
37121function validateAlgorithm(algorithm) {
37122 var alg = algorithm.toLowerCase().split('-');
37123
37124 if (alg.length !== 2) {
37125 throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' +
37126 'valid algorithm'));
37127 }
37128
37129 if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) {
37130 throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' +
37131 'are not supported'));
37132 }
37133
37134 if (!HASH_ALGOS[alg[1]]) {
37135 throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' +
37136 'supported hash algorithm'));
37137 }
37138
37139 return (alg);
37140}
37141
37142///--- API
37143
37144module.exports = {
37145
37146 HASH_ALGOS: HASH_ALGOS,
37147 PK_ALGOS: PK_ALGOS,
37148
37149 HttpSignatureError: HttpSignatureError,
37150 InvalidAlgorithmError: InvalidAlgorithmError,
37151
37152 validateAlgorithm: validateAlgorithm,
37153
37154 /**
37155 * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file.
37156 *
37157 * The intent of this module is to interoperate with OpenSSL only,
37158 * specifically the node crypto module's `verify` method.
37159 *
37160 * @param {String} key an OpenSSH public key.
37161 * @return {String} PEM encoded form of the RSA public key.
37162 * @throws {TypeError} on bad input.
37163 * @throws {Error} on invalid ssh key formatted data.
37164 */
37165 sshKeyToPEM: function sshKeyToPEM(key) {
37166 assert.string(key, 'ssh_key');
37167
37168 var k = sshpk.parseKey(key, 'ssh');
37169 return (k.toString('pem'));
37170 },
37171
37172
37173 /**
37174 * Generates an OpenSSH fingerprint from an ssh public key.
37175 *
37176 * @param {String} key an OpenSSH public key.
37177 * @return {String} key fingerprint.
37178 * @throws {TypeError} on bad input.
37179 * @throws {Error} if what you passed doesn't look like an ssh public key.
37180 */
37181 fingerprint: function fingerprint(key) {
37182 assert.string(key, 'ssh_key');
37183
37184 var k = sshpk.parseKey(key, 'ssh');
37185 return (k.fingerprint('md5').toString('hex'));
37186 },
37187
37188 /**
37189 * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
37190 *
37191 * The reverse of the above function.
37192 */
37193 pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
37194 assert.equal('string', typeof (pem), 'typeof pem');
37195
37196 var k = sshpk.parseKey(pem, 'pem');
37197 k.comment = comment;
37198 return (k.toString('ssh'));
37199 }
37200};
37201
37202},{"assert-plus":67,"sshpk":354,"util":397}],207:[function(require,module,exports){
37203(function (Buffer){
37204// Copyright 2015 Joyent, Inc.
37205
37206var assert = require('assert-plus');
37207var crypto = require('crypto');
37208var sshpk = require('sshpk');
37209var utils = require('./utils');
37210
37211var HASH_ALGOS = utils.HASH_ALGOS;
37212var PK_ALGOS = utils.PK_ALGOS;
37213var InvalidAlgorithmError = utils.InvalidAlgorithmError;
37214var HttpSignatureError = utils.HttpSignatureError;
37215var validateAlgorithm = utils.validateAlgorithm;
37216
37217///--- Exported API
37218
37219module.exports = {
37220 /**
37221 * Verify RSA/DSA signature against public key. You are expected to pass in
37222 * an object that was returned from `parse()`.
37223 *
37224 * @param {Object} parsedSignature the object you got from `parse`.
37225 * @param {String} pubkey RSA/DSA private key PEM.
37226 * @return {Boolean} true if valid, false otherwise.
37227 * @throws {TypeError} if you pass in bad arguments.
37228 * @throws {InvalidAlgorithmError}
37229 */
37230 verifySignature: function verifySignature(parsedSignature, pubkey) {
37231 assert.object(parsedSignature, 'parsedSignature');
37232 if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey))
37233 pubkey = sshpk.parseKey(pubkey);
37234 assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key');
37235
37236 var alg = validateAlgorithm(parsedSignature.algorithm);
37237 if (alg[0] === 'hmac' || alg[0] !== pubkey.type)
37238 return (false);
37239
37240 var v = pubkey.createVerify(alg[1]);
37241 v.update(parsedSignature.signingString);
37242 return (v.verify(parsedSignature.params.signature, 'base64'));
37243 },
37244
37245 /**
37246 * Verify HMAC against shared secret. You are expected to pass in an object
37247 * that was returned from `parse()`.
37248 *
37249 * @param {Object} parsedSignature the object you got from `parse`.
37250 * @param {String} secret HMAC shared secret.
37251 * @return {Boolean} true if valid, false otherwise.
37252 * @throws {TypeError} if you pass in bad arguments.
37253 * @throws {InvalidAlgorithmError}
37254 */
37255 verifyHMAC: function verifyHMAC(parsedSignature, secret) {
37256 assert.object(parsedSignature, 'parsedHMAC');
37257 assert.string(secret, 'secret');
37258
37259 var alg = validateAlgorithm(parsedSignature.algorithm);
37260 if (alg[0] !== 'hmac')
37261 return (false);
37262
37263 var hashAlg = alg[1].toUpperCase();
37264
37265 var hmac = crypto.createHmac(hashAlg, secret);
37266 hmac.update(parsedSignature.signingString);
37267
37268 /*
37269 * Now double-hash to avoid leaking timing information - there's
37270 * no easy constant-time compare in JS, so we use this approach
37271 * instead. See for more info:
37272 * https://www.isecpartners.com/blog/2011/february/double-hmac-
37273 * verification.aspx
37274 */
37275 var h1 = crypto.createHmac(hashAlg, secret);
37276 h1.update(hmac.digest());
37277 h1 = h1.digest();
37278 var h2 = crypto.createHmac(hashAlg, secret);
37279 h2.update(new Buffer(parsedSignature.params.signature, 'base64'));
37280 h2 = h2.digest();
37281
37282 /* Node 0.8 returns strings from .digest(). */
37283 if (typeof (h1) === 'string')
37284 return (h1 === h2);
37285 /* And node 0.10 lacks the .equals() method on Buffers. */
37286 if (Buffer.isBuffer(h1) && !h1.equals)
37287 return (h1.toString('binary') === h2.toString('binary'));
37288
37289 return (h1.equals(h2));
37290 }
37291};
37292
37293}).call(this,require("buffer").Buffer)
37294},{"./utils":206,"assert-plus":67,"buffer":114,"crypto":126,"sshpk":354}],208:[function(require,module,exports){
37295var http = require('http')
37296var url = require('url')
37297
37298var https = module.exports
37299
37300for (var key in http) {
37301 if (http.hasOwnProperty(key)) https[key] = http[key]
37302}
37303
37304https.request = function (params, cb) {
37305 params = validateParams(params)
37306 return http.request.call(this, params, cb)
37307}
37308
37309https.get = function (params, cb) {
37310 params = validateParams(params)
37311 return http.get.call(this, params, cb)
37312}
37313
37314function validateParams (params) {
37315 if (typeof params === 'string') {
37316 params = url.parse(params)
37317 }
37318 if (!params.protocol) {
37319 params.protocol = 'https:'
37320 }
37321 if (params.protocol !== 'https:') {
37322 throw new Error('Protocol "' + params.protocol + '" not supported. Expected "https:"')
37323 }
37324 return params
37325}
37326
37327},{"http":362,"url":393}],209:[function(require,module,exports){
37328exports.read = function (buffer, offset, isLE, mLen, nBytes) {
37329 var e, m
37330 var eLen = (nBytes * 8) - mLen - 1
37331 var eMax = (1 << eLen) - 1
37332 var eBias = eMax >> 1
37333 var nBits = -7
37334 var i = isLE ? (nBytes - 1) : 0
37335 var d = isLE ? -1 : 1
37336 var s = buffer[offset + i]
37337
37338 i += d
37339
37340 e = s & ((1 << (-nBits)) - 1)
37341 s >>= (-nBits)
37342 nBits += eLen
37343 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
37344
37345 m = e & ((1 << (-nBits)) - 1)
37346 e >>= (-nBits)
37347 nBits += mLen
37348 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
37349
37350 if (e === 0) {
37351 e = 1 - eBias
37352 } else if (e === eMax) {
37353 return m ? NaN : ((s ? -1 : 1) * Infinity)
37354 } else {
37355 m = m + Math.pow(2, mLen)
37356 e = e - eBias
37357 }
37358 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
37359}
37360
37361exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
37362 var e, m, c
37363 var eLen = (nBytes * 8) - mLen - 1
37364 var eMax = (1 << eLen) - 1
37365 var eBias = eMax >> 1
37366 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
37367 var i = isLE ? 0 : (nBytes - 1)
37368 var d = isLE ? 1 : -1
37369 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
37370
37371 value = Math.abs(value)
37372
37373 if (isNaN(value) || value === Infinity) {
37374 m = isNaN(value) ? 1 : 0
37375 e = eMax
37376 } else {
37377 e = Math.floor(Math.log(value) / Math.LN2)
37378 if (value * (c = Math.pow(2, -e)) < 1) {
37379 e--
37380 c *= 2
37381 }
37382 if (e + eBias >= 1) {
37383 value += rt / c
37384 } else {
37385 value += rt * Math.pow(2, 1 - eBias)
37386 }
37387 if (value * c >= 2) {
37388 e++
37389 c /= 2
37390 }
37391
37392 if (e + eBias >= eMax) {
37393 m = 0
37394 e = eMax
37395 } else if (e + eBias >= 1) {
37396 m = ((value * c) - 1) * Math.pow(2, mLen)
37397 e = e + eBias
37398 } else {
37399 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
37400 e = 0
37401 }
37402 }
37403
37404 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
37405
37406 e = (e << mLen) | m
37407 eLen += mLen
37408 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
37409
37410 buffer[offset + i - d] |= s * 128
37411}
37412
37413},{}],210:[function(require,module,exports){
37414arguments[4][69][0].apply(exports,arguments)
37415},{"dup":69}],211:[function(require,module,exports){
37416/*!
37417 * Determine if an object is a Buffer
37418 *
37419 * @author Feross Aboukhadijeh <https://feross.org>
37420 * @license MIT
37421 */
37422
37423// The _isBuffer check is for Safari 5-7 support, because it's missing
37424// Object.prototype.constructor. Remove this eventually
37425module.exports = function (obj) {
37426 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
37427}
37428
37429function isBuffer (obj) {
37430 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
37431}
37432
37433// For Node v0.10 support. Remove this eventually.
37434function isSlowBuffer (obj) {
37435 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
37436}
37437
37438},{}],212:[function(require,module,exports){
37439module.exports = isTypedArray
37440isTypedArray.strict = isStrictTypedArray
37441isTypedArray.loose = isLooseTypedArray
37442
37443var toString = Object.prototype.toString
37444var names = {
37445 '[object Int8Array]': true
37446 , '[object Int16Array]': true
37447 , '[object Int32Array]': true
37448 , '[object Uint8Array]': true
37449 , '[object Uint8ClampedArray]': true
37450 , '[object Uint16Array]': true
37451 , '[object Uint32Array]': true
37452 , '[object Float32Array]': true
37453 , '[object Float64Array]': true
37454}
37455
37456function isTypedArray(arr) {
37457 return (
37458 isStrictTypedArray(arr)
37459 || isLooseTypedArray(arr)
37460 )
37461}
37462
37463function isStrictTypedArray(arr) {
37464 return (
37465 arr instanceof Int8Array
37466 || arr instanceof Int16Array
37467 || arr instanceof Int32Array
37468 || arr instanceof Uint8Array
37469 || arr instanceof Uint8ClampedArray
37470 || arr instanceof Uint16Array
37471 || arr instanceof Uint32Array
37472 || arr instanceof Float32Array
37473 || arr instanceof Float64Array
37474 )
37475}
37476
37477function isLooseTypedArray(arr) {
37478 return names[toString.call(arr)]
37479}
37480
37481},{}],213:[function(require,module,exports){
37482var toString = {}.toString;
37483
37484module.exports = Array.isArray || function (arr) {
37485 return toString.call(arr) == '[object Array]';
37486};
37487
37488},{}],214:[function(require,module,exports){
37489var stream = require('stream')
37490
37491
37492function isStream (obj) {
37493 return obj instanceof stream.Stream
37494}
37495
37496
37497function isReadable (obj) {
37498 return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object'
37499}
37500
37501
37502function isWritable (obj) {
37503 return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object'
37504}
37505
37506
37507function isDuplex (obj) {
37508 return isReadable(obj) && isWritable(obj)
37509}
37510
37511
37512module.exports = isStream
37513module.exports.isReadable = isReadable
37514module.exports.isWritable = isWritable
37515module.exports.isDuplex = isDuplex
37516
37517},{"stream":361}],215:[function(require,module,exports){
37518(function(){
37519
37520 // Copyright (c) 2005 Tom Wu
37521 // All Rights Reserved.
37522 // See "LICENSE" for details.
37523
37524 // Basic JavaScript BN library - subset useful for RSA encryption.
37525
37526 // Bits per digit
37527 var dbits;
37528
37529 // JavaScript engine analysis
37530 var canary = 0xdeadbeefcafe;
37531 var j_lm = ((canary&0xffffff)==0xefcafe);
37532
37533 // (public) Constructor
37534 function BigInteger(a,b,c) {
37535 if(a != null)
37536 if("number" == typeof a) this.fromNumber(a,b,c);
37537 else if(b == null && "string" != typeof a) this.fromString(a,256);
37538 else this.fromString(a,b);
37539 }
37540
37541 // return new, unset BigInteger
37542 function nbi() { return new BigInteger(null); }
37543
37544 // am: Compute w_j += (x*this_i), propagate carries,
37545 // c is initial carry, returns final carry.
37546 // c < 3*dvalue, x < 2*dvalue, this_i < dvalue
37547 // We need to select the fastest one that works in this environment.
37548
37549 // am1: use a single mult and divide to get the high bits,
37550 // max digit bits should be 26 because
37551 // max internal value = 2*dvalue^2-2*dvalue (< 2^53)
37552 function am1(i,x,w,j,c,n) {
37553 while(--n >= 0) {
37554 var v = x*this[i++]+w[j]+c;
37555 c = Math.floor(v/0x4000000);
37556 w[j++] = v&0x3ffffff;
37557 }
37558 return c;
37559 }
37560 // am2 avoids a big mult-and-extract completely.
37561 // Max digit bits should be <= 30 because we do bitwise ops
37562 // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
37563 function am2(i,x,w,j,c,n) {
37564 var xl = x&0x7fff, xh = x>>15;
37565 while(--n >= 0) {
37566 var l = this[i]&0x7fff;
37567 var h = this[i++]>>15;
37568 var m = xh*l+h*xl;
37569 l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff);
37570 c = (l>>>30)+(m>>>15)+xh*h+(c>>>30);
37571 w[j++] = l&0x3fffffff;
37572 }
37573 return c;
37574 }
37575 // Alternately, set max digit bits to 28 since some
37576 // browsers slow down when dealing with 32-bit numbers.
37577 function am3(i,x,w,j,c,n) {
37578 var xl = x&0x3fff, xh = x>>14;
37579 while(--n >= 0) {
37580 var l = this[i]&0x3fff;
37581 var h = this[i++]>>14;
37582 var m = xh*l+h*xl;
37583 l = xl*l+((m&0x3fff)<<14)+w[j]+c;
37584 c = (l>>28)+(m>>14)+xh*h;
37585 w[j++] = l&0xfffffff;
37586 }
37587 return c;
37588 }
37589 var inBrowser = typeof navigator !== "undefined";
37590 if(inBrowser && j_lm && (navigator.appName == "Microsoft Internet Explorer")) {
37591 BigInteger.prototype.am = am2;
37592 dbits = 30;
37593 }
37594 else if(inBrowser && j_lm && (navigator.appName != "Netscape")) {
37595 BigInteger.prototype.am = am1;
37596 dbits = 26;
37597 }
37598 else { // Mozilla/Netscape seems to prefer am3
37599 BigInteger.prototype.am = am3;
37600 dbits = 28;
37601 }
37602
37603 BigInteger.prototype.DB = dbits;
37604 BigInteger.prototype.DM = ((1<<dbits)-1);
37605 BigInteger.prototype.DV = (1<<dbits);
37606
37607 var BI_FP = 52;
37608 BigInteger.prototype.FV = Math.pow(2,BI_FP);
37609 BigInteger.prototype.F1 = BI_FP-dbits;
37610 BigInteger.prototype.F2 = 2*dbits-BI_FP;
37611
37612 // Digit conversions
37613 var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz";
37614 var BI_RC = new Array();
37615 var rr,vv;
37616 rr = "0".charCodeAt(0);
37617 for(vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv;
37618 rr = "a".charCodeAt(0);
37619 for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
37620 rr = "A".charCodeAt(0);
37621 for(vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv;
37622
37623 function int2char(n) { return BI_RM.charAt(n); }
37624 function intAt(s,i) {
37625 var c = BI_RC[s.charCodeAt(i)];
37626 return (c==null)?-1:c;
37627 }
37628
37629 // (protected) copy this to r
37630 function bnpCopyTo(r) {
37631 for(var i = this.t-1; i >= 0; --i) r[i] = this[i];
37632 r.t = this.t;
37633 r.s = this.s;
37634 }
37635
37636 // (protected) set from integer value x, -DV <= x < DV
37637 function bnpFromInt(x) {
37638 this.t = 1;
37639 this.s = (x<0)?-1:0;
37640 if(x > 0) this[0] = x;
37641 else if(x < -1) this[0] = x+this.DV;
37642 else this.t = 0;
37643 }
37644
37645 // return bigint initialized to value
37646 function nbv(i) { var r = nbi(); r.fromInt(i); return r; }
37647
37648 // (protected) set from string and radix
37649 function bnpFromString(s,b) {
37650 var k;
37651 if(b == 16) k = 4;
37652 else if(b == 8) k = 3;
37653 else if(b == 256) k = 8; // byte array
37654 else if(b == 2) k = 1;
37655 else if(b == 32) k = 5;
37656 else if(b == 4) k = 2;
37657 else { this.fromRadix(s,b); return; }
37658 this.t = 0;
37659 this.s = 0;
37660 var i = s.length, mi = false, sh = 0;
37661 while(--i >= 0) {
37662 var x = (k==8)?s[i]&0xff:intAt(s,i);
37663 if(x < 0) {
37664 if(s.charAt(i) == "-") mi = true;
37665 continue;
37666 }
37667 mi = false;
37668 if(sh == 0)
37669 this[this.t++] = x;
37670 else if(sh+k > this.DB) {
37671 this[this.t-1] |= (x&((1<<(this.DB-sh))-1))<<sh;
37672 this[this.t++] = (x>>(this.DB-sh));
37673 }
37674 else
37675 this[this.t-1] |= x<<sh;
37676 sh += k;
37677 if(sh >= this.DB) sh -= this.DB;
37678 }
37679 if(k == 8 && (s[0]&0x80) != 0) {
37680 this.s = -1;
37681 if(sh > 0) this[this.t-1] |= ((1<<(this.DB-sh))-1)<<sh;
37682 }
37683 this.clamp();
37684 if(mi) BigInteger.ZERO.subTo(this,this);
37685 }
37686
37687 // (protected) clamp off excess high words
37688 function bnpClamp() {
37689 var c = this.s&this.DM;
37690 while(this.t > 0 && this[this.t-1] == c) --this.t;
37691 }
37692
37693 // (public) return string representation in given radix
37694 function bnToString(b) {
37695 if(this.s < 0) return "-"+this.negate().toString(b);
37696 var k;
37697 if(b == 16) k = 4;
37698 else if(b == 8) k = 3;
37699 else if(b == 2) k = 1;
37700 else if(b == 32) k = 5;
37701 else if(b == 4) k = 2;
37702 else return this.toRadix(b);
37703 var km = (1<<k)-1, d, m = false, r = "", i = this.t;
37704 var p = this.DB-(i*this.DB)%k;
37705 if(i-- > 0) {
37706 if(p < this.DB && (d = this[i]>>p) > 0) { m = true; r = int2char(d); }
37707 while(i >= 0) {
37708 if(p < k) {
37709 d = (this[i]&((1<<p)-1))<<(k-p);
37710 d |= this[--i]>>(p+=this.DB-k);
37711 }
37712 else {
37713 d = (this[i]>>(p-=k))&km;
37714 if(p <= 0) { p += this.DB; --i; }
37715 }
37716 if(d > 0) m = true;
37717 if(m) r += int2char(d);
37718 }
37719 }
37720 return m?r:"0";
37721 }
37722
37723 // (public) -this
37724 function bnNegate() { var r = nbi(); BigInteger.ZERO.subTo(this,r); return r; }
37725
37726 // (public) |this|
37727 function bnAbs() { return (this.s<0)?this.negate():this; }
37728
37729 // (public) return + if this > a, - if this < a, 0 if equal
37730 function bnCompareTo(a) {
37731 var r = this.s-a.s;
37732 if(r != 0) return r;
37733 var i = this.t;
37734 r = i-a.t;
37735 if(r != 0) return (this.s<0)?-r:r;
37736 while(--i >= 0) if((r=this[i]-a[i]) != 0) return r;
37737 return 0;
37738 }
37739
37740 // returns bit length of the integer x
37741 function nbits(x) {
37742 var r = 1, t;
37743 if((t=x>>>16) != 0) { x = t; r += 16; }
37744 if((t=x>>8) != 0) { x = t; r += 8; }
37745 if((t=x>>4) != 0) { x = t; r += 4; }
37746 if((t=x>>2) != 0) { x = t; r += 2; }
37747 if((t=x>>1) != 0) { x = t; r += 1; }
37748 return r;
37749 }
37750
37751 // (public) return the number of bits in "this"
37752 function bnBitLength() {
37753 if(this.t <= 0) return 0;
37754 return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM));
37755 }
37756
37757 // (protected) r = this << n*DB
37758 function bnpDLShiftTo(n,r) {
37759 var i;
37760 for(i = this.t-1; i >= 0; --i) r[i+n] = this[i];
37761 for(i = n-1; i >= 0; --i) r[i] = 0;
37762 r.t = this.t+n;
37763 r.s = this.s;
37764 }
37765
37766 // (protected) r = this >> n*DB
37767 function bnpDRShiftTo(n,r) {
37768 for(var i = n; i < this.t; ++i) r[i-n] = this[i];
37769 r.t = Math.max(this.t-n,0);
37770 r.s = this.s;
37771 }
37772
37773 // (protected) r = this << n
37774 function bnpLShiftTo(n,r) {
37775 var bs = n%this.DB;
37776 var cbs = this.DB-bs;
37777 var bm = (1<<cbs)-1;
37778 var ds = Math.floor(n/this.DB), c = (this.s<<bs)&this.DM, i;
37779 for(i = this.t-1; i >= 0; --i) {
37780 r[i+ds+1] = (this[i]>>cbs)|c;
37781 c = (this[i]&bm)<<bs;
37782 }
37783 for(i = ds-1; i >= 0; --i) r[i] = 0;
37784 r[ds] = c;
37785 r.t = this.t+ds+1;
37786 r.s = this.s;
37787 r.clamp();
37788 }
37789
37790 // (protected) r = this >> n
37791 function bnpRShiftTo(n,r) {
37792 r.s = this.s;
37793 var ds = Math.floor(n/this.DB);
37794 if(ds >= this.t) { r.t = 0; return; }
37795 var bs = n%this.DB;
37796 var cbs = this.DB-bs;
37797 var bm = (1<<bs)-1;
37798 r[0] = this[ds]>>bs;
37799 for(var i = ds+1; i < this.t; ++i) {
37800 r[i-ds-1] |= (this[i]&bm)<<cbs;
37801 r[i-ds] = this[i]>>bs;
37802 }
37803 if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs;
37804 r.t = this.t-ds;
37805 r.clamp();
37806 }
37807
37808 // (protected) r = this - a
37809 function bnpSubTo(a,r) {
37810 var i = 0, c = 0, m = Math.min(a.t,this.t);
37811 while(i < m) {
37812 c += this[i]-a[i];
37813 r[i++] = c&this.DM;
37814 c >>= this.DB;
37815 }
37816 if(a.t < this.t) {
37817 c -= a.s;
37818 while(i < this.t) {
37819 c += this[i];
37820 r[i++] = c&this.DM;
37821 c >>= this.DB;
37822 }
37823 c += this.s;
37824 }
37825 else {
37826 c += this.s;
37827 while(i < a.t) {
37828 c -= a[i];
37829 r[i++] = c&this.DM;
37830 c >>= this.DB;
37831 }
37832 c -= a.s;
37833 }
37834 r.s = (c<0)?-1:0;
37835 if(c < -1) r[i++] = this.DV+c;
37836 else if(c > 0) r[i++] = c;
37837 r.t = i;
37838 r.clamp();
37839 }
37840
37841 // (protected) r = this * a, r != this,a (HAC 14.12)
37842 // "this" should be the larger one if appropriate.
37843 function bnpMultiplyTo(a,r) {
37844 var x = this.abs(), y = a.abs();
37845 var i = x.t;
37846 r.t = i+y.t;
37847 while(--i >= 0) r[i] = 0;
37848 for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t);
37849 r.s = 0;
37850 r.clamp();
37851 if(this.s != a.s) BigInteger.ZERO.subTo(r,r);
37852 }
37853
37854 // (protected) r = this^2, r != this (HAC 14.16)
37855 function bnpSquareTo(r) {
37856 var x = this.abs();
37857 var i = r.t = 2*x.t;
37858 while(--i >= 0) r[i] = 0;
37859 for(i = 0; i < x.t-1; ++i) {
37860 var c = x.am(i,x[i],r,2*i,0,1);
37861 if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.DV) {
37862 r[i+x.t] -= x.DV;
37863 r[i+x.t+1] = 1;
37864 }
37865 }
37866 if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1);
37867 r.s = 0;
37868 r.clamp();
37869 }
37870
37871 // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
37872 // r != q, this != m. q or r may be null.
37873 function bnpDivRemTo(m,q,r) {
37874 var pm = m.abs();
37875 if(pm.t <= 0) return;
37876 var pt = this.abs();
37877 if(pt.t < pm.t) {
37878 if(q != null) q.fromInt(0);
37879 if(r != null) this.copyTo(r);
37880 return;
37881 }
37882 if(r == null) r = nbi();
37883 var y = nbi(), ts = this.s, ms = m.s;
37884 var nsh = this.DB-nbits(pm[pm.t-1]); // normalize modulus
37885 if(nsh > 0) { pm.lShiftTo(nsh,y); pt.lShiftTo(nsh,r); }
37886 else { pm.copyTo(y); pt.copyTo(r); }
37887 var ys = y.t;
37888 var y0 = y[ys-1];
37889 if(y0 == 0) return;
37890 var yt = y0*(1<<this.F1)+((ys>1)?y[ys-2]>>this.F2:0);
37891 var d1 = this.FV/yt, d2 = (1<<this.F1)/yt, e = 1<<this.F2;
37892 var i = r.t, j = i-ys, t = (q==null)?nbi():q;
37893 y.dlShiftTo(j,t);
37894 if(r.compareTo(t) >= 0) {
37895 r[r.t++] = 1;
37896 r.subTo(t,r);
37897 }
37898 BigInteger.ONE.dlShiftTo(ys,t);
37899 t.subTo(y,y); // "negative" y so we can replace sub with am later
37900 while(y.t < ys) y[y.t++] = 0;
37901 while(--j >= 0) {
37902 // Estimate quotient digit
37903 var qd = (r[--i]==y0)?this.DM:Math.floor(r[i]*d1+(r[i-1]+e)*d2);
37904 if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out
37905 y.dlShiftTo(j,t);
37906 r.subTo(t,r);
37907 while(r[i] < --qd) r.subTo(t,r);
37908 }
37909 }
37910 if(q != null) {
37911 r.drShiftTo(ys,q);
37912 if(ts != ms) BigInteger.ZERO.subTo(q,q);
37913 }
37914 r.t = ys;
37915 r.clamp();
37916 if(nsh > 0) r.rShiftTo(nsh,r); // Denormalize remainder
37917 if(ts < 0) BigInteger.ZERO.subTo(r,r);
37918 }
37919
37920 // (public) this mod a
37921 function bnMod(a) {
37922 var r = nbi();
37923 this.abs().divRemTo(a,null,r);
37924 if(this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r,r);
37925 return r;
37926 }
37927
37928 // Modular reduction using "classic" algorithm
37929 function Classic(m) { this.m = m; }
37930 function cConvert(x) {
37931 if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m);
37932 else return x;
37933 }
37934 function cRevert(x) { return x; }
37935 function cReduce(x) { x.divRemTo(this.m,null,x); }
37936 function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
37937 function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
37938
37939 Classic.prototype.convert = cConvert;
37940 Classic.prototype.revert = cRevert;
37941 Classic.prototype.reduce = cReduce;
37942 Classic.prototype.mulTo = cMulTo;
37943 Classic.prototype.sqrTo = cSqrTo;
37944
37945 // (protected) return "-1/this % 2^DB"; useful for Mont. reduction
37946 // justification:
37947 // xy == 1 (mod m)
37948 // xy = 1+km
37949 // xy(2-xy) = (1+km)(1-km)
37950 // x[y(2-xy)] = 1-k^2m^2
37951 // x[y(2-xy)] == 1 (mod m^2)
37952 // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
37953 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
37954 // JS multiply "overflows" differently from C/C++, so care is needed here.
37955 function bnpInvDigit() {
37956 if(this.t < 1) return 0;
37957 var x = this[0];
37958 if((x&1) == 0) return 0;
37959 var y = x&3; // y == 1/x mod 2^2
37960 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4
37961 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8
37962 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16
37963 // last step - calculate inverse mod DV directly;
37964 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
37965 y = (y*(2-x*y%this.DV))%this.DV; // y == 1/x mod 2^dbits
37966 // we really want the negative inverse, and -DV < y < DV
37967 return (y>0)?this.DV-y:-y;
37968 }
37969
37970 // Montgomery reduction
37971 function Montgomery(m) {
37972 this.m = m;
37973 this.mp = m.invDigit();
37974 this.mpl = this.mp&0x7fff;
37975 this.mph = this.mp>>15;
37976 this.um = (1<<(m.DB-15))-1;
37977 this.mt2 = 2*m.t;
37978 }
37979
37980 // xR mod m
37981 function montConvert(x) {
37982 var r = nbi();
37983 x.abs().dlShiftTo(this.m.t,r);
37984 r.divRemTo(this.m,null,r);
37985 if(x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r,r);
37986 return r;
37987 }
37988
37989 // x/R mod m
37990 function montRevert(x) {
37991 var r = nbi();
37992 x.copyTo(r);
37993 this.reduce(r);
37994 return r;
37995 }
37996
37997 // x = x/R mod m (HAC 14.32)
37998 function montReduce(x) {
37999 while(x.t <= this.mt2) // pad x so am has enough room later
38000 x[x.t++] = 0;
38001 for(var i = 0; i < this.m.t; ++i) {
38002 // faster way of calculating u0 = x[i]*mp mod DV
38003 var j = x[i]&0x7fff;
38004 var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.DM;
38005 // use am to combine the multiply-shift-add into one call
38006 j = i+this.m.t;
38007 x[j] += this.m.am(0,u0,x,i,0,this.m.t);
38008 // propagate carry
38009 while(x[j] >= x.DV) { x[j] -= x.DV; x[++j]++; }
38010 }
38011 x.clamp();
38012 x.drShiftTo(this.m.t,x);
38013 if(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
38014 }
38015
38016 // r = "x^2/R mod m"; x != r
38017 function montSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
38018
38019 // r = "xy/R mod m"; x,y != r
38020 function montMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
38021
38022 Montgomery.prototype.convert = montConvert;
38023 Montgomery.prototype.revert = montRevert;
38024 Montgomery.prototype.reduce = montReduce;
38025 Montgomery.prototype.mulTo = montMulTo;
38026 Montgomery.prototype.sqrTo = montSqrTo;
38027
38028 // (protected) true iff this is even
38029 function bnpIsEven() { return ((this.t>0)?(this[0]&1):this.s) == 0; }
38030
38031 // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
38032 function bnpExp(e,z) {
38033 if(e > 0xffffffff || e < 1) return BigInteger.ONE;
38034 var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1;
38035 g.copyTo(r);
38036 while(--i >= 0) {
38037 z.sqrTo(r,r2);
38038 if((e&(1<<i)) > 0) z.mulTo(r2,g,r);
38039 else { var t = r; r = r2; r2 = t; }
38040 }
38041 return z.revert(r);
38042 }
38043
38044 // (public) this^e % m, 0 <= e < 2^32
38045 function bnModPowInt(e,m) {
38046 var z;
38047 if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m);
38048 return this.exp(e,z);
38049 }
38050
38051 // protected
38052 BigInteger.prototype.copyTo = bnpCopyTo;
38053 BigInteger.prototype.fromInt = bnpFromInt;
38054 BigInteger.prototype.fromString = bnpFromString;
38055 BigInteger.prototype.clamp = bnpClamp;
38056 BigInteger.prototype.dlShiftTo = bnpDLShiftTo;
38057 BigInteger.prototype.drShiftTo = bnpDRShiftTo;
38058 BigInteger.prototype.lShiftTo = bnpLShiftTo;
38059 BigInteger.prototype.rShiftTo = bnpRShiftTo;
38060 BigInteger.prototype.subTo = bnpSubTo;
38061 BigInteger.prototype.multiplyTo = bnpMultiplyTo;
38062 BigInteger.prototype.squareTo = bnpSquareTo;
38063 BigInteger.prototype.divRemTo = bnpDivRemTo;
38064 BigInteger.prototype.invDigit = bnpInvDigit;
38065 BigInteger.prototype.isEven = bnpIsEven;
38066 BigInteger.prototype.exp = bnpExp;
38067
38068 // public
38069 BigInteger.prototype.toString = bnToString;
38070 BigInteger.prototype.negate = bnNegate;
38071 BigInteger.prototype.abs = bnAbs;
38072 BigInteger.prototype.compareTo = bnCompareTo;
38073 BigInteger.prototype.bitLength = bnBitLength;
38074 BigInteger.prototype.mod = bnMod;
38075 BigInteger.prototype.modPowInt = bnModPowInt;
38076
38077 // "constants"
38078 BigInteger.ZERO = nbv(0);
38079 BigInteger.ONE = nbv(1);
38080
38081 // Copyright (c) 2005-2009 Tom Wu
38082 // All Rights Reserved.
38083 // See "LICENSE" for details.
38084
38085 // Extended JavaScript BN functions, required for RSA private ops.
38086
38087 // Version 1.1: new BigInteger("0", 10) returns "proper" zero
38088 // Version 1.2: square() API, isProbablePrime fix
38089
38090 // (public)
38091 function bnClone() { var r = nbi(); this.copyTo(r); return r; }
38092
38093 // (public) return value as integer
38094 function bnIntValue() {
38095 if(this.s < 0) {
38096 if(this.t == 1) return this[0]-this.DV;
38097 else if(this.t == 0) return -1;
38098 }
38099 else if(this.t == 1) return this[0];
38100 else if(this.t == 0) return 0;
38101 // assumes 16 < DB < 32
38102 return ((this[1]&((1<<(32-this.DB))-1))<<this.DB)|this[0];
38103 }
38104
38105 // (public) return value as byte
38106 function bnByteValue() { return (this.t==0)?this.s:(this[0]<<24)>>24; }
38107
38108 // (public) return value as short (assumes DB>=16)
38109 function bnShortValue() { return (this.t==0)?this.s:(this[0]<<16)>>16; }
38110
38111 // (protected) return x s.t. r^x < DV
38112 function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); }
38113
38114 // (public) 0 if this == 0, 1 if this > 0
38115 function bnSigNum() {
38116 if(this.s < 0) return -1;
38117 else if(this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0;
38118 else return 1;
38119 }
38120
38121 // (protected) convert to radix string
38122 function bnpToRadix(b) {
38123 if(b == null) b = 10;
38124 if(this.signum() == 0 || b < 2 || b > 36) return "0";
38125 var cs = this.chunkSize(b);
38126 var a = Math.pow(b,cs);
38127 var d = nbv(a), y = nbi(), z = nbi(), r = "";
38128 this.divRemTo(d,y,z);
38129 while(y.signum() > 0) {
38130 r = (a+z.intValue()).toString(b).substr(1) + r;
38131 y.divRemTo(d,y,z);
38132 }
38133 return z.intValue().toString(b) + r;
38134 }
38135
38136 // (protected) convert from radix string
38137 function bnpFromRadix(s,b) {
38138 this.fromInt(0);
38139 if(b == null) b = 10;
38140 var cs = this.chunkSize(b);
38141 var d = Math.pow(b,cs), mi = false, j = 0, w = 0;
38142 for(var i = 0; i < s.length; ++i) {
38143 var x = intAt(s,i);
38144 if(x < 0) {
38145 if(s.charAt(i) == "-" && this.signum() == 0) mi = true;
38146 continue;
38147 }
38148 w = b*w+x;
38149 if(++j >= cs) {
38150 this.dMultiply(d);
38151 this.dAddOffset(w,0);
38152 j = 0;
38153 w = 0;
38154 }
38155 }
38156 if(j > 0) {
38157 this.dMultiply(Math.pow(b,j));
38158 this.dAddOffset(w,0);
38159 }
38160 if(mi) BigInteger.ZERO.subTo(this,this);
38161 }
38162
38163 // (protected) alternate constructor
38164 function bnpFromNumber(a,b,c) {
38165 if("number" == typeof b) {
38166 // new BigInteger(int,int,RNG)
38167 if(a < 2) this.fromInt(1);
38168 else {
38169 this.fromNumber(a,c);
38170 if(!this.testBit(a-1)) // force MSB set
38171 this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this);
38172 if(this.isEven()) this.dAddOffset(1,0); // force odd
38173 while(!this.isProbablePrime(b)) {
38174 this.dAddOffset(2,0);
38175 if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this);
38176 }
38177 }
38178 }
38179 else {
38180 // new BigInteger(int,RNG)
38181 var x = new Array(), t = a&7;
38182 x.length = (a>>3)+1;
38183 b.nextBytes(x);
38184 if(t > 0) x[0] &= ((1<<t)-1); else x[0] = 0;
38185 this.fromString(x,256);
38186 }
38187 }
38188
38189 // (public) convert to bigendian byte array
38190 function bnToByteArray() {
38191 var i = this.t, r = new Array();
38192 r[0] = this.s;
38193 var p = this.DB-(i*this.DB)%8, d, k = 0;
38194 if(i-- > 0) {
38195 if(p < this.DB && (d = this[i]>>p) != (this.s&this.DM)>>p)
38196 r[k++] = d|(this.s<<(this.DB-p));
38197 while(i >= 0) {
38198 if(p < 8) {
38199 d = (this[i]&((1<<p)-1))<<(8-p);
38200 d |= this[--i]>>(p+=this.DB-8);
38201 }
38202 else {
38203 d = (this[i]>>(p-=8))&0xff;
38204 if(p <= 0) { p += this.DB; --i; }
38205 }
38206 if((d&0x80) != 0) d |= -256;
38207 if(k == 0 && (this.s&0x80) != (d&0x80)) ++k;
38208 if(k > 0 || d != this.s) r[k++] = d;
38209 }
38210 }
38211 return r;
38212 }
38213
38214 function bnEquals(a) { return(this.compareTo(a)==0); }
38215 function bnMin(a) { return(this.compareTo(a)<0)?this:a; }
38216 function bnMax(a) { return(this.compareTo(a)>0)?this:a; }
38217
38218 // (protected) r = this op a (bitwise)
38219 function bnpBitwiseTo(a,op,r) {
38220 var i, f, m = Math.min(a.t,this.t);
38221 for(i = 0; i < m; ++i) r[i] = op(this[i],a[i]);
38222 if(a.t < this.t) {
38223 f = a.s&this.DM;
38224 for(i = m; i < this.t; ++i) r[i] = op(this[i],f);
38225 r.t = this.t;
38226 }
38227 else {
38228 f = this.s&this.DM;
38229 for(i = m; i < a.t; ++i) r[i] = op(f,a[i]);
38230 r.t = a.t;
38231 }
38232 r.s = op(this.s,a.s);
38233 r.clamp();
38234 }
38235
38236 // (public) this & a
38237 function op_and(x,y) { return x&y; }
38238 function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; }
38239
38240 // (public) this | a
38241 function op_or(x,y) { return x|y; }
38242 function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; }
38243
38244 // (public) this ^ a
38245 function op_xor(x,y) { return x^y; }
38246 function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; }
38247
38248 // (public) this & ~a
38249 function op_andnot(x,y) { return x&~y; }
38250 function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; }
38251
38252 // (public) ~this
38253 function bnNot() {
38254 var r = nbi();
38255 for(var i = 0; i < this.t; ++i) r[i] = this.DM&~this[i];
38256 r.t = this.t;
38257 r.s = ~this.s;
38258 return r;
38259 }
38260
38261 // (public) this << n
38262 function bnShiftLeft(n) {
38263 var r = nbi();
38264 if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r);
38265 return r;
38266 }
38267
38268 // (public) this >> n
38269 function bnShiftRight(n) {
38270 var r = nbi();
38271 if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r);
38272 return r;
38273 }
38274
38275 // return index of lowest 1-bit in x, x < 2^31
38276 function lbit(x) {
38277 if(x == 0) return -1;
38278 var r = 0;
38279 if((x&0xffff) == 0) { x >>= 16; r += 16; }
38280 if((x&0xff) == 0) { x >>= 8; r += 8; }
38281 if((x&0xf) == 0) { x >>= 4; r += 4; }
38282 if((x&3) == 0) { x >>= 2; r += 2; }
38283 if((x&1) == 0) ++r;
38284 return r;
38285 }
38286
38287 // (public) returns index of lowest 1-bit (or -1 if none)
38288 function bnGetLowestSetBit() {
38289 for(var i = 0; i < this.t; ++i)
38290 if(this[i] != 0) return i*this.DB+lbit(this[i]);
38291 if(this.s < 0) return this.t*this.DB;
38292 return -1;
38293 }
38294
38295 // return number of 1 bits in x
38296 function cbit(x) {
38297 var r = 0;
38298 while(x != 0) { x &= x-1; ++r; }
38299 return r;
38300 }
38301
38302 // (public) return number of set bits
38303 function bnBitCount() {
38304 var r = 0, x = this.s&this.DM;
38305 for(var i = 0; i < this.t; ++i) r += cbit(this[i]^x);
38306 return r;
38307 }
38308
38309 // (public) true iff nth bit is set
38310 function bnTestBit(n) {
38311 var j = Math.floor(n/this.DB);
38312 if(j >= this.t) return(this.s!=0);
38313 return((this[j]&(1<<(n%this.DB)))!=0);
38314 }
38315
38316 // (protected) this op (1<<n)
38317 function bnpChangeBit(n,op) {
38318 var r = BigInteger.ONE.shiftLeft(n);
38319 this.bitwiseTo(r,op,r);
38320 return r;
38321 }
38322
38323 // (public) this | (1<<n)
38324 function bnSetBit(n) { return this.changeBit(n,op_or); }
38325
38326 // (public) this & ~(1<<n)
38327 function bnClearBit(n) { return this.changeBit(n,op_andnot); }
38328
38329 // (public) this ^ (1<<n)
38330 function bnFlipBit(n) { return this.changeBit(n,op_xor); }
38331
38332 // (protected) r = this + a
38333 function bnpAddTo(a,r) {
38334 var i = 0, c = 0, m = Math.min(a.t,this.t);
38335 while(i < m) {
38336 c += this[i]+a[i];
38337 r[i++] = c&this.DM;
38338 c >>= this.DB;
38339 }
38340 if(a.t < this.t) {
38341 c += a.s;
38342 while(i < this.t) {
38343 c += this[i];
38344 r[i++] = c&this.DM;
38345 c >>= this.DB;
38346 }
38347 c += this.s;
38348 }
38349 else {
38350 c += this.s;
38351 while(i < a.t) {
38352 c += a[i];
38353 r[i++] = c&this.DM;
38354 c >>= this.DB;
38355 }
38356 c += a.s;
38357 }
38358 r.s = (c<0)?-1:0;
38359 if(c > 0) r[i++] = c;
38360 else if(c < -1) r[i++] = this.DV+c;
38361 r.t = i;
38362 r.clamp();
38363 }
38364
38365 // (public) this + a
38366 function bnAdd(a) { var r = nbi(); this.addTo(a,r); return r; }
38367
38368 // (public) this - a
38369 function bnSubtract(a) { var r = nbi(); this.subTo(a,r); return r; }
38370
38371 // (public) this * a
38372 function bnMultiply(a) { var r = nbi(); this.multiplyTo(a,r); return r; }
38373
38374 // (public) this^2
38375 function bnSquare() { var r = nbi(); this.squareTo(r); return r; }
38376
38377 // (public) this / a
38378 function bnDivide(a) { var r = nbi(); this.divRemTo(a,r,null); return r; }
38379
38380 // (public) this % a
38381 function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; }
38382
38383 // (public) [this/a,this%a]
38384 function bnDivideAndRemainder(a) {
38385 var q = nbi(), r = nbi();
38386 this.divRemTo(a,q,r);
38387 return new Array(q,r);
38388 }
38389
38390 // (protected) this *= n, this >= 0, 1 < n < DV
38391 function bnpDMultiply(n) {
38392 this[this.t] = this.am(0,n-1,this,0,0,this.t);
38393 ++this.t;
38394 this.clamp();
38395 }
38396
38397 // (protected) this += n << w words, this >= 0
38398 function bnpDAddOffset(n,w) {
38399 if(n == 0) return;
38400 while(this.t <= w) this[this.t++] = 0;
38401 this[w] += n;
38402 while(this[w] >= this.DV) {
38403 this[w] -= this.DV;
38404 if(++w >= this.t) this[this.t++] = 0;
38405 ++this[w];
38406 }
38407 }
38408
38409 // A "null" reducer
38410 function NullExp() {}
38411 function nNop(x) { return x; }
38412 function nMulTo(x,y,r) { x.multiplyTo(y,r); }
38413 function nSqrTo(x,r) { x.squareTo(r); }
38414
38415 NullExp.prototype.convert = nNop;
38416 NullExp.prototype.revert = nNop;
38417 NullExp.prototype.mulTo = nMulTo;
38418 NullExp.prototype.sqrTo = nSqrTo;
38419
38420 // (public) this^e
38421 function bnPow(e) { return this.exp(e,new NullExp()); }
38422
38423 // (protected) r = lower n words of "this * a", a.t <= n
38424 // "this" should be the larger one if appropriate.
38425 function bnpMultiplyLowerTo(a,n,r) {
38426 var i = Math.min(this.t+a.t,n);
38427 r.s = 0; // assumes a,this >= 0
38428 r.t = i;
38429 while(i > 0) r[--i] = 0;
38430 var j;
38431 for(j = r.t-this.t; i < j; ++i) r[i+this.t] = this.am(0,a[i],r,i,0,this.t);
38432 for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a[i],r,i,0,n-i);
38433 r.clamp();
38434 }
38435
38436 // (protected) r = "this * a" without lower n words, n > 0
38437 // "this" should be the larger one if appropriate.
38438 function bnpMultiplyUpperTo(a,n,r) {
38439 --n;
38440 var i = r.t = this.t+a.t-n;
38441 r.s = 0; // assumes a,this >= 0
38442 while(--i >= 0) r[i] = 0;
38443 for(i = Math.max(n-this.t,0); i < a.t; ++i)
38444 r[this.t+i-n] = this.am(n-i,a[i],r,0,0,this.t+i-n);
38445 r.clamp();
38446 r.drShiftTo(1,r);
38447 }
38448
38449 // Barrett modular reduction
38450 function Barrett(m) {
38451 // setup Barrett
38452 this.r2 = nbi();
38453 this.q3 = nbi();
38454 BigInteger.ONE.dlShiftTo(2*m.t,this.r2);
38455 this.mu = this.r2.divide(m);
38456 this.m = m;
38457 }
38458
38459 function barrettConvert(x) {
38460 if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m);
38461 else if(x.compareTo(this.m) < 0) return x;
38462 else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; }
38463 }
38464
38465 function barrettRevert(x) { return x; }
38466
38467 // x = x mod m (HAC 14.42)
38468 function barrettReduce(x) {
38469 x.drShiftTo(this.m.t-1,this.r2);
38470 if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); }
38471 this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);
38472 this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);
38473 while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1);
38474 x.subTo(this.r2,x);
38475 while(x.compareTo(this.m) >= 0) x.subTo(this.m,x);
38476 }
38477
38478 // r = x^2 mod m; x != r
38479 function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); }
38480
38481 // r = x*y mod m; x,y != r
38482 function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); }
38483
38484 Barrett.prototype.convert = barrettConvert;
38485 Barrett.prototype.revert = barrettRevert;
38486 Barrett.prototype.reduce = barrettReduce;
38487 Barrett.prototype.mulTo = barrettMulTo;
38488 Barrett.prototype.sqrTo = barrettSqrTo;
38489
38490 // (public) this^e % m (HAC 14.85)
38491 function bnModPow(e,m) {
38492 var i = e.bitLength(), k, r = nbv(1), z;
38493 if(i <= 0) return r;
38494 else if(i < 18) k = 1;
38495 else if(i < 48) k = 3;
38496 else if(i < 144) k = 4;
38497 else if(i < 768) k = 5;
38498 else k = 6;
38499 if(i < 8)
38500 z = new Classic(m);
38501 else if(m.isEven())
38502 z = new Barrett(m);
38503 else
38504 z = new Montgomery(m);
38505
38506 // precomputation
38507 var g = new Array(), n = 3, k1 = k-1, km = (1<<k)-1;
38508 g[1] = z.convert(this);
38509 if(k > 1) {
38510 var g2 = nbi();
38511 z.sqrTo(g[1],g2);
38512 while(n <= km) {
38513 g[n] = nbi();
38514 z.mulTo(g2,g[n-2],g[n]);
38515 n += 2;
38516 }
38517 }
38518
38519 var j = e.t-1, w, is1 = true, r2 = nbi(), t;
38520 i = nbits(e[j])-1;
38521 while(j >= 0) {
38522 if(i >= k1) w = (e[j]>>(i-k1))&km;
38523 else {
38524 w = (e[j]&((1<<(i+1))-1))<<(k1-i);
38525 if(j > 0) w |= e[j-1]>>(this.DB+i-k1);
38526 }
38527
38528 n = k;
38529 while((w&1) == 0) { w >>= 1; --n; }
38530 if((i -= n) < 0) { i += this.DB; --j; }
38531 if(is1) { // ret == 1, don't bother squaring or multiplying it
38532 g[w].copyTo(r);
38533 is1 = false;
38534 }
38535 else {
38536 while(n > 1) { z.sqrTo(r,r2); z.sqrTo(r2,r); n -= 2; }
38537 if(n > 0) z.sqrTo(r,r2); else { t = r; r = r2; r2 = t; }
38538 z.mulTo(r2,g[w],r);
38539 }
38540
38541 while(j >= 0 && (e[j]&(1<<i)) == 0) {
38542 z.sqrTo(r,r2); t = r; r = r2; r2 = t;
38543 if(--i < 0) { i = this.DB-1; --j; }
38544 }
38545 }
38546 return z.revert(r);
38547 }
38548
38549 // (public) gcd(this,a) (HAC 14.54)
38550 function bnGCD(a) {
38551 var x = (this.s<0)?this.negate():this.clone();
38552 var y = (a.s<0)?a.negate():a.clone();
38553 if(x.compareTo(y) < 0) { var t = x; x = y; y = t; }
38554 var i = x.getLowestSetBit(), g = y.getLowestSetBit();
38555 if(g < 0) return x;
38556 if(i < g) g = i;
38557 if(g > 0) {
38558 x.rShiftTo(g,x);
38559 y.rShiftTo(g,y);
38560 }
38561 while(x.signum() > 0) {
38562 if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x);
38563 if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y);
38564 if(x.compareTo(y) >= 0) {
38565 x.subTo(y,x);
38566 x.rShiftTo(1,x);
38567 }
38568 else {
38569 y.subTo(x,y);
38570 y.rShiftTo(1,y);
38571 }
38572 }
38573 if(g > 0) y.lShiftTo(g,y);
38574 return y;
38575 }
38576
38577 // (protected) this % n, n < 2^26
38578 function bnpModInt(n) {
38579 if(n <= 0) return 0;
38580 var d = this.DV%n, r = (this.s<0)?n-1:0;
38581 if(this.t > 0)
38582 if(d == 0) r = this[0]%n;
38583 else for(var i = this.t-1; i >= 0; --i) r = (d*r+this[i])%n;
38584 return r;
38585 }
38586
38587 // (public) 1/this % m (HAC 14.61)
38588 function bnModInverse(m) {
38589 var ac = m.isEven();
38590 if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO;
38591 var u = m.clone(), v = this.clone();
38592 var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1);
38593 while(u.signum() != 0) {
38594 while(u.isEven()) {
38595 u.rShiftTo(1,u);
38596 if(ac) {
38597 if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); }
38598 a.rShiftTo(1,a);
38599 }
38600 else if(!b.isEven()) b.subTo(m,b);
38601 b.rShiftTo(1,b);
38602 }
38603 while(v.isEven()) {
38604 v.rShiftTo(1,v);
38605 if(ac) {
38606 if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); }
38607 c.rShiftTo(1,c);
38608 }
38609 else if(!d.isEven()) d.subTo(m,d);
38610 d.rShiftTo(1,d);
38611 }
38612 if(u.compareTo(v) >= 0) {
38613 u.subTo(v,u);
38614 if(ac) a.subTo(c,a);
38615 b.subTo(d,b);
38616 }
38617 else {
38618 v.subTo(u,v);
38619 if(ac) c.subTo(a,c);
38620 d.subTo(b,d);
38621 }
38622 }
38623 if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO;
38624 if(d.compareTo(m) >= 0) return d.subtract(m);
38625 if(d.signum() < 0) d.addTo(m,d); else return d;
38626 if(d.signum() < 0) return d.add(m); else return d;
38627 }
38628
38629 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];
38630 var lplim = (1<<26)/lowprimes[lowprimes.length-1];
38631
38632 // (public) test primality with certainty >= 1-.5^t
38633 function bnIsProbablePrime(t) {
38634 var i, x = this.abs();
38635 if(x.t == 1 && x[0] <= lowprimes[lowprimes.length-1]) {
38636 for(i = 0; i < lowprimes.length; ++i)
38637 if(x[0] == lowprimes[i]) return true;
38638 return false;
38639 }
38640 if(x.isEven()) return false;
38641 i = 1;
38642 while(i < lowprimes.length) {
38643 var m = lowprimes[i], j = i+1;
38644 while(j < lowprimes.length && m < lplim) m *= lowprimes[j++];
38645 m = x.modInt(m);
38646 while(i < j) if(m%lowprimes[i++] == 0) return false;
38647 }
38648 return x.millerRabin(t);
38649 }
38650
38651 // (protected) true if probably prime (HAC 4.24, Miller-Rabin)
38652 function bnpMillerRabin(t) {
38653 var n1 = this.subtract(BigInteger.ONE);
38654 var k = n1.getLowestSetBit();
38655 if(k <= 0) return false;
38656 var r = n1.shiftRight(k);
38657 t = (t+1)>>1;
38658 if(t > lowprimes.length) t = lowprimes.length;
38659 var a = nbi();
38660 for(var i = 0; i < t; ++i) {
38661 //Pick bases at random, instead of starting at 2
38662 a.fromInt(lowprimes[Math.floor(Math.random()*lowprimes.length)]);
38663 var y = a.modPow(r,this);
38664 if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
38665 var j = 1;
38666 while(j++ < k && y.compareTo(n1) != 0) {
38667 y = y.modPowInt(2,this);
38668 if(y.compareTo(BigInteger.ONE) == 0) return false;
38669 }
38670 if(y.compareTo(n1) != 0) return false;
38671 }
38672 }
38673 return true;
38674 }
38675
38676 // protected
38677 BigInteger.prototype.chunkSize = bnpChunkSize;
38678 BigInteger.prototype.toRadix = bnpToRadix;
38679 BigInteger.prototype.fromRadix = bnpFromRadix;
38680 BigInteger.prototype.fromNumber = bnpFromNumber;
38681 BigInteger.prototype.bitwiseTo = bnpBitwiseTo;
38682 BigInteger.prototype.changeBit = bnpChangeBit;
38683 BigInteger.prototype.addTo = bnpAddTo;
38684 BigInteger.prototype.dMultiply = bnpDMultiply;
38685 BigInteger.prototype.dAddOffset = bnpDAddOffset;
38686 BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo;
38687 BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo;
38688 BigInteger.prototype.modInt = bnpModInt;
38689 BigInteger.prototype.millerRabin = bnpMillerRabin;
38690
38691 // public
38692 BigInteger.prototype.clone = bnClone;
38693 BigInteger.prototype.intValue = bnIntValue;
38694 BigInteger.prototype.byteValue = bnByteValue;
38695 BigInteger.prototype.shortValue = bnShortValue;
38696 BigInteger.prototype.signum = bnSigNum;
38697 BigInteger.prototype.toByteArray = bnToByteArray;
38698 BigInteger.prototype.equals = bnEquals;
38699 BigInteger.prototype.min = bnMin;
38700 BigInteger.prototype.max = bnMax;
38701 BigInteger.prototype.and = bnAnd;
38702 BigInteger.prototype.or = bnOr;
38703 BigInteger.prototype.xor = bnXor;
38704 BigInteger.prototype.andNot = bnAndNot;
38705 BigInteger.prototype.not = bnNot;
38706 BigInteger.prototype.shiftLeft = bnShiftLeft;
38707 BigInteger.prototype.shiftRight = bnShiftRight;
38708 BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit;
38709 BigInteger.prototype.bitCount = bnBitCount;
38710 BigInteger.prototype.testBit = bnTestBit;
38711 BigInteger.prototype.setBit = bnSetBit;
38712 BigInteger.prototype.clearBit = bnClearBit;
38713 BigInteger.prototype.flipBit = bnFlipBit;
38714 BigInteger.prototype.add = bnAdd;
38715 BigInteger.prototype.subtract = bnSubtract;
38716 BigInteger.prototype.multiply = bnMultiply;
38717 BigInteger.prototype.divide = bnDivide;
38718 BigInteger.prototype.remainder = bnRemainder;
38719 BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder;
38720 BigInteger.prototype.modPow = bnModPow;
38721 BigInteger.prototype.modInverse = bnModInverse;
38722 BigInteger.prototype.pow = bnPow;
38723 BigInteger.prototype.gcd = bnGCD;
38724 BigInteger.prototype.isProbablePrime = bnIsProbablePrime;
38725
38726 // JSBN-specific extension
38727 BigInteger.prototype.square = bnSquare;
38728
38729 // Expose the Barrett function
38730 BigInteger.prototype.Barrett = Barrett
38731
38732 // BigInteger interfaces not implemented in jsbn:
38733
38734 // BigInteger(int signum, byte[] magnitude)
38735 // double doubleValue()
38736 // float floatValue()
38737 // int hashCode()
38738 // long longValue()
38739 // static BigInteger valueOf(long val)
38740
38741 // Random number generator - requires a PRNG backend, e.g. prng4.js
38742
38743 // For best results, put code like
38744 // <body onClick='rng_seed_time();' onKeyPress='rng_seed_time();'>
38745 // in your main HTML document.
38746
38747 var rng_state;
38748 var rng_pool;
38749 var rng_pptr;
38750
38751 // Mix in a 32-bit integer into the pool
38752 function rng_seed_int(x) {
38753 rng_pool[rng_pptr++] ^= x & 255;
38754 rng_pool[rng_pptr++] ^= (x >> 8) & 255;
38755 rng_pool[rng_pptr++] ^= (x >> 16) & 255;
38756 rng_pool[rng_pptr++] ^= (x >> 24) & 255;
38757 if(rng_pptr >= rng_psize) rng_pptr -= rng_psize;
38758 }
38759
38760 // Mix in the current time (w/milliseconds) into the pool
38761 function rng_seed_time() {
38762 rng_seed_int(new Date().getTime());
38763 }
38764
38765 // Initialize the pool with junk if needed.
38766 if(rng_pool == null) {
38767 rng_pool = new Array();
38768 rng_pptr = 0;
38769 var t;
38770 if(typeof window !== "undefined" && window.crypto) {
38771 if (window.crypto.getRandomValues) {
38772 // Use webcrypto if available
38773 var ua = new Uint8Array(32);
38774 window.crypto.getRandomValues(ua);
38775 for(t = 0; t < 32; ++t)
38776 rng_pool[rng_pptr++] = ua[t];
38777 }
38778 else if(navigator.appName == "Netscape" && navigator.appVersion < "5") {
38779 // Extract entropy (256 bits) from NS4 RNG if available
38780 var z = window.crypto.random(32);
38781 for(t = 0; t < z.length; ++t)
38782 rng_pool[rng_pptr++] = z.charCodeAt(t) & 255;
38783 }
38784 }
38785 while(rng_pptr < rng_psize) { // extract some randomness from Math.random()
38786 t = Math.floor(65536 * Math.random());
38787 rng_pool[rng_pptr++] = t >>> 8;
38788 rng_pool[rng_pptr++] = t & 255;
38789 }
38790 rng_pptr = 0;
38791 rng_seed_time();
38792 //rng_seed_int(window.screenX);
38793 //rng_seed_int(window.screenY);
38794 }
38795
38796 function rng_get_byte() {
38797 if(rng_state == null) {
38798 rng_seed_time();
38799 rng_state = prng_newstate();
38800 rng_state.init(rng_pool);
38801 for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr)
38802 rng_pool[rng_pptr] = 0;
38803 rng_pptr = 0;
38804 //rng_pool = null;
38805 }
38806 // TODO: allow reseeding after first request
38807 return rng_state.next();
38808 }
38809
38810 function rng_get_bytes(ba) {
38811 var i;
38812 for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte();
38813 }
38814
38815 function SecureRandom() {}
38816
38817 SecureRandom.prototype.nextBytes = rng_get_bytes;
38818
38819 // prng4.js - uses Arcfour as a PRNG
38820
38821 function Arcfour() {
38822 this.i = 0;
38823 this.j = 0;
38824 this.S = new Array();
38825 }
38826
38827 // Initialize arcfour context from key, an array of ints, each from [0..255]
38828 function ARC4init(key) {
38829 var i, j, t;
38830 for(i = 0; i < 256; ++i)
38831 this.S[i] = i;
38832 j = 0;
38833 for(i = 0; i < 256; ++i) {
38834 j = (j + this.S[i] + key[i % key.length]) & 255;
38835 t = this.S[i];
38836 this.S[i] = this.S[j];
38837 this.S[j] = t;
38838 }
38839 this.i = 0;
38840 this.j = 0;
38841 }
38842
38843 function ARC4next() {
38844 var t;
38845 this.i = (this.i + 1) & 255;
38846 this.j = (this.j + this.S[this.i]) & 255;
38847 t = this.S[this.i];
38848 this.S[this.i] = this.S[this.j];
38849 this.S[this.j] = t;
38850 return this.S[(t + this.S[this.i]) & 255];
38851 }
38852
38853 Arcfour.prototype.init = ARC4init;
38854 Arcfour.prototype.next = ARC4next;
38855
38856 // Plug in your RNG constructor here
38857 function prng_newstate() {
38858 return new Arcfour();
38859 }
38860
38861 // Pool size must be a multiple of 4 and greater than 32.
38862 // An array of bytes the size of the pool will be passed to init()
38863 var rng_psize = 256;
38864
38865 BigInteger.SecureRandom = SecureRandom;
38866 BigInteger.BigInteger = BigInteger;
38867 if (typeof exports !== 'undefined') {
38868 exports = module.exports = BigInteger;
38869 } else {
38870 this.BigInteger = BigInteger;
38871 this.SecureRandom = SecureRandom;
38872 }
38873
38874}).call(this);
38875
38876},{}],216:[function(require,module,exports){
38877'use strict';
38878
38879var traverse = module.exports = function (schema, opts, cb) {
38880 // Legacy support for v0.3.1 and earlier.
38881 if (typeof opts == 'function') {
38882 cb = opts;
38883 opts = {};
38884 }
38885
38886 cb = opts.cb || cb;
38887 var pre = (typeof cb == 'function') ? cb : cb.pre || function() {};
38888 var post = cb.post || function() {};
38889
38890 _traverse(opts, pre, post, schema, '', schema);
38891};
38892
38893
38894traverse.keywords = {
38895 additionalItems: true,
38896 items: true,
38897 contains: true,
38898 additionalProperties: true,
38899 propertyNames: true,
38900 not: true
38901};
38902
38903traverse.arrayKeywords = {
38904 items: true,
38905 allOf: true,
38906 anyOf: true,
38907 oneOf: true
38908};
38909
38910traverse.propsKeywords = {
38911 definitions: true,
38912 properties: true,
38913 patternProperties: true,
38914 dependencies: true
38915};
38916
38917traverse.skipKeywords = {
38918 default: true,
38919 enum: true,
38920 const: true,
38921 required: true,
38922 maximum: true,
38923 minimum: true,
38924 exclusiveMaximum: true,
38925 exclusiveMinimum: true,
38926 multipleOf: true,
38927 maxLength: true,
38928 minLength: true,
38929 pattern: true,
38930 format: true,
38931 maxItems: true,
38932 minItems: true,
38933 uniqueItems: true,
38934 maxProperties: true,
38935 minProperties: true
38936};
38937
38938
38939function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
38940 if (schema && typeof schema == 'object' && !Array.isArray(schema)) {
38941 pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
38942 for (var key in schema) {
38943 var sch = schema[key];
38944 if (Array.isArray(sch)) {
38945 if (key in traverse.arrayKeywords) {
38946 for (var i=0; i<sch.length; i++)
38947 _traverse(opts, pre, post, sch[i], jsonPtr + '/' + key + '/' + i, rootSchema, jsonPtr, key, schema, i);
38948 }
38949 } else if (key in traverse.propsKeywords) {
38950 if (sch && typeof sch == 'object') {
38951 for (var prop in sch)
38952 _traverse(opts, pre, post, sch[prop], jsonPtr + '/' + key + '/' + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
38953 }
38954 } else if (key in traverse.keywords || (opts.allKeys && !(key in traverse.skipKeywords))) {
38955 _traverse(opts, pre, post, sch, jsonPtr + '/' + key, rootSchema, jsonPtr, key, schema);
38956 }
38957 }
38958 post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
38959 }
38960}
38961
38962
38963function escapeJsonPtr(str) {
38964 return str.replace(/~/g, '~0').replace(/\//g, '~1');
38965}
38966
38967},{}],217:[function(require,module,exports){
38968/**
38969 * JSONSchema Validator - Validates JavaScript objects using JSON Schemas
38970 * (http://www.json.com/json-schema-proposal/)
38971 *
38972 * Copyright (c) 2007 Kris Zyp SitePen (www.sitepen.com)
38973 * Licensed under the MIT (MIT-LICENSE.txt) license.
38974To use the validator call the validate function with an instance object and an optional schema object.
38975If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
38976that schema will be used to validate and the schema parameter is not necessary (if both exist,
38977both validations will occur).
38978The validate method will return an array of validation errors. If there are no errors, then an
38979empty list will be returned. A validation error will have two properties:
38980"property" which indicates which property had the error
38981"message" which indicates what the error was
38982 */
38983(function (root, factory) {
38984 if (typeof define === 'function' && define.amd) {
38985 // AMD. Register as an anonymous module.
38986 define([], function () {
38987 return factory();
38988 });
38989 } else if (typeof module === 'object' && module.exports) {
38990 // Node. Does not work with strict CommonJS, but
38991 // only CommonJS-like environments that support module.exports,
38992 // like Node.
38993 module.exports = factory();
38994 } else {
38995 // Browser globals
38996 root.jsonSchema = factory();
38997 }
38998}(this, function () {// setup primitive classes to be JSON Schema types
38999var exports = validate
39000exports.Integer = {type:"integer"};
39001var primitiveConstructors = {
39002 String: String,
39003 Boolean: Boolean,
39004 Number: Number,
39005 Object: Object,
39006 Array: Array,
39007 Date: Date
39008}
39009exports.validate = validate;
39010function validate(/*Any*/instance,/*Object*/schema) {
39011 // Summary:
39012 // To use the validator call JSONSchema.validate with an instance object and an optional schema object.
39013 // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating),
39014 // that schema will be used to validate and the schema parameter is not necessary (if both exist,
39015 // both validations will occur).
39016 // The validate method will return an object with two properties:
39017 // valid: A boolean indicating if the instance is valid by the schema
39018 // errors: An array of validation errors. If there are no errors, then an
39019 // empty list will be returned. A validation error will have two properties:
39020 // property: which indicates which property had the error
39021 // message: which indicates what the error was
39022 //
39023 return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false});
39024 };
39025exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) {
39026 // Summary:
39027 // The checkPropertyChange method will check to see if an value can legally be in property with the given schema
39028 // This is slightly different than the validate method in that it will fail if the schema is readonly and it will
39029 // not check for self-validation, it is assumed that the passed in value is already internally valid.
39030 // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for
39031 // information.
39032 //
39033 return validate(value, schema, {changing: property || "property"});
39034 };
39035var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) {
39036
39037 if (!options) options = {};
39038 var _changing = options.changing;
39039
39040 function getType(schema){
39041 return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase());
39042 }
39043 var errors = [];
39044 // validate a value against a property definition
39045 function checkProp(value, schema, path,i){
39046
39047 var l;
39048 path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i;
39049 function addError(message){
39050 errors.push({property:path,message:message});
39051 }
39052
39053 if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){
39054 if(typeof schema == 'function'){
39055 if(!(value instanceof schema)){
39056 addError("is not an instance of the class/constructor " + schema.name);
39057 }
39058 }else if(schema){
39059 addError("Invalid schema/property definition " + schema);
39060 }
39061 return null;
39062 }
39063 if(_changing && schema.readonly){
39064 addError("is a readonly field, it can not be changed");
39065 }
39066 if(schema['extends']){ // if it extends another schema, it must pass that schema as well
39067 checkProp(value,schema['extends'],path,i);
39068 }
39069 // validate a value against a type definition
39070 function checkType(type,value){
39071 if(type){
39072 if(typeof type == 'string' && type != 'any' &&
39073 (type == 'null' ? value !== null : typeof value != type) &&
39074 !(value instanceof Array && type == 'array') &&
39075 !(value instanceof Date && type == 'date') &&
39076 !(type == 'integer' && value%1===0)){
39077 return [{property:path,message:(typeof value) + " value found, but a " + type + " is required"}];
39078 }
39079 if(type instanceof Array){
39080 var unionErrors=[];
39081 for(var j = 0; j < type.length; j++){ // a union type
39082 if(!(unionErrors=checkType(type[j],value)).length){
39083 break;
39084 }
39085 }
39086 if(unionErrors.length){
39087 return unionErrors;
39088 }
39089 }else if(typeof type == 'object'){
39090 var priorErrors = errors;
39091 errors = [];
39092 checkProp(value,type,path);
39093 var theseErrors = errors;
39094 errors = priorErrors;
39095 return theseErrors;
39096 }
39097 }
39098 return [];
39099 }
39100 if(value === undefined){
39101 if(schema.required){
39102 addError("is missing and it is required");
39103 }
39104 }else{
39105 errors = errors.concat(checkType(getType(schema),value));
39106 if(schema.disallow && !checkType(schema.disallow,value).length){
39107 addError(" disallowed value was matched");
39108 }
39109 if(value !== null){
39110 if(value instanceof Array){
39111 if(schema.items){
39112 var itemsIsArray = schema.items instanceof Array;
39113 var propDef = schema.items;
39114 for (i = 0, l = value.length; i < l; i += 1) {
39115 if (itemsIsArray)
39116 propDef = schema.items[i];
39117 if (options.coerce)
39118 value[i] = options.coerce(value[i], propDef);
39119 errors.concat(checkProp(value[i],propDef,path,i));
39120 }
39121 }
39122 if(schema.minItems && value.length < schema.minItems){
39123 addError("There must be a minimum of " + schema.minItems + " in the array");
39124 }
39125 if(schema.maxItems && value.length > schema.maxItems){
39126 addError("There must be a maximum of " + schema.maxItems + " in the array");
39127 }
39128 }else if(schema.properties || schema.additionalProperties){
39129 errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties));
39130 }
39131 if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){
39132 addError("does not match the regex pattern " + schema.pattern);
39133 }
39134 if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){
39135 addError("may only be " + schema.maxLength + " characters long");
39136 }
39137 if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){
39138 addError("must be at least " + schema.minLength + " characters long");
39139 }
39140 if(typeof schema.minimum !== undefined && typeof value == typeof schema.minimum &&
39141 schema.minimum > value){
39142 addError("must have a minimum value of " + schema.minimum);
39143 }
39144 if(typeof schema.maximum !== undefined && typeof value == typeof schema.maximum &&
39145 schema.maximum < value){
39146 addError("must have a maximum value of " + schema.maximum);
39147 }
39148 if(schema['enum']){
39149 var enumer = schema['enum'];
39150 l = enumer.length;
39151 var found;
39152 for(var j = 0; j < l; j++){
39153 if(enumer[j]===value){
39154 found=1;
39155 break;
39156 }
39157 }
39158 if(!found){
39159 addError("does not have a value in the enumeration " + enumer.join(", "));
39160 }
39161 }
39162 if(typeof schema.maxDecimal == 'number' &&
39163 (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){
39164 addError("may only have " + schema.maxDecimal + " digits of decimal places");
39165 }
39166 }
39167 }
39168 return null;
39169 }
39170 // validate an object against a schema
39171 function checkObj(instance,objTypeDef,path,additionalProp){
39172
39173 if(typeof objTypeDef =='object'){
39174 if(typeof instance != 'object' || instance instanceof Array){
39175 errors.push({property:path,message:"an object is required"});
39176 }
39177
39178 for(var i in objTypeDef){
39179 if(objTypeDef.hasOwnProperty(i)){
39180 var value = instance[i];
39181 // skip _not_ specified properties
39182 if (value === undefined && options.existingOnly) continue;
39183 var propDef = objTypeDef[i];
39184 // set default
39185 if(value === undefined && propDef["default"]){
39186 value = instance[i] = propDef["default"];
39187 }
39188 if(options.coerce && i in instance){
39189 value = instance[i] = options.coerce(value, propDef);
39190 }
39191 checkProp(value,propDef,path,i);
39192 }
39193 }
39194 }
39195 for(i in instance){
39196 if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){
39197 if (options.filter) {
39198 delete instance[i];
39199 continue;
39200 } else {
39201 errors.push({property:path,message:(typeof value) + "The property " + i +
39202 " is not defined in the schema and the schema does not allow additional properties"});
39203 }
39204 }
39205 var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires;
39206 if(requires && !(requires in instance)){
39207 errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"});
39208 }
39209 value = instance[i];
39210 if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){
39211 if(options.coerce){
39212 value = instance[i] = options.coerce(value, additionalProp);
39213 }
39214 checkProp(value,additionalProp,path,i);
39215 }
39216 if(!_changing && value && value.$schema){
39217 errors = errors.concat(checkProp(value,value.$schema,path,i));
39218 }
39219 }
39220 return errors;
39221 }
39222 if(schema){
39223 checkProp(instance,schema,'',_changing || '');
39224 }
39225 if(!_changing && instance && instance.$schema){
39226 checkProp(instance,instance.$schema,'','');
39227 }
39228 return {valid:!errors.length,errors:errors};
39229};
39230exports.mustBeValid = function(result){
39231 // summary:
39232 // This checks to ensure that the result is valid and will throw an appropriate error message if it is not
39233 // result: the result returned from checkPropertyChange or validate
39234 if(!result.valid){
39235 throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n"));
39236 }
39237}
39238
39239return exports;
39240}));
39241
39242},{}],218:[function(require,module,exports){
39243exports = module.exports = stringify
39244exports.getSerialize = serializer
39245
39246function stringify(obj, replacer, spaces, cycleReplacer) {
39247 return JSON.stringify(obj, serializer(replacer, cycleReplacer), spaces)
39248}
39249
39250function serializer(replacer, cycleReplacer) {
39251 var stack = [], keys = []
39252
39253 if (cycleReplacer == null) cycleReplacer = function(key, value) {
39254 if (stack[0] === value) return "[Circular ~]"
39255 return "[Circular ~." + keys.slice(0, stack.indexOf(value)).join(".") + "]"
39256 }
39257
39258 return function(key, value) {
39259 if (stack.length > 0) {
39260 var thisPos = stack.indexOf(this)
39261 ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)
39262 ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)
39263 if (~stack.indexOf(value)) value = cycleReplacer.call(this, key, value)
39264 }
39265 else stack.push(value)
39266
39267 return replacer == null ? value : replacer.call(this, key, value)
39268 }
39269}
39270
39271},{}],219:[function(require,module,exports){
39272/*
39273 * lib/jsprim.js: utilities for primitive JavaScript types
39274 */
39275
39276var mod_assert = require('assert-plus');
39277var mod_util = require('util');
39278
39279var mod_extsprintf = require('extsprintf');
39280var mod_verror = require('verror');
39281var mod_jsonschema = require('json-schema');
39282
39283/*
39284 * Public interface
39285 */
39286exports.deepCopy = deepCopy;
39287exports.deepEqual = deepEqual;
39288exports.isEmpty = isEmpty;
39289exports.hasKey = hasKey;
39290exports.forEachKey = forEachKey;
39291exports.pluck = pluck;
39292exports.flattenObject = flattenObject;
39293exports.flattenIter = flattenIter;
39294exports.validateJsonObject = validateJsonObjectJS;
39295exports.validateJsonObjectJS = validateJsonObjectJS;
39296exports.randElt = randElt;
39297exports.extraProperties = extraProperties;
39298exports.mergeObjects = mergeObjects;
39299
39300exports.startsWith = startsWith;
39301exports.endsWith = endsWith;
39302
39303exports.parseInteger = parseInteger;
39304
39305exports.iso8601 = iso8601;
39306exports.rfc1123 = rfc1123;
39307exports.parseDateTime = parseDateTime;
39308
39309exports.hrtimediff = hrtimeDiff;
39310exports.hrtimeDiff = hrtimeDiff;
39311exports.hrtimeAccum = hrtimeAccum;
39312exports.hrtimeAdd = hrtimeAdd;
39313exports.hrtimeNanosec = hrtimeNanosec;
39314exports.hrtimeMicrosec = hrtimeMicrosec;
39315exports.hrtimeMillisec = hrtimeMillisec;
39316
39317
39318/*
39319 * Deep copy an acyclic *basic* Javascript object. This only handles basic
39320 * scalars (strings, numbers, booleans) and arbitrarily deep arrays and objects
39321 * containing these. This does *not* handle instances of other classes.
39322 */
39323function deepCopy(obj)
39324{
39325 var ret, key;
39326 var marker = '__deepCopy';
39327
39328 if (obj && obj[marker])
39329 throw (new Error('attempted deep copy of cyclic object'));
39330
39331 if (obj && obj.constructor == Object) {
39332 ret = {};
39333 obj[marker] = true;
39334
39335 for (key in obj) {
39336 if (key == marker)
39337 continue;
39338
39339 ret[key] = deepCopy(obj[key]);
39340 }
39341
39342 delete (obj[marker]);
39343 return (ret);
39344 }
39345
39346 if (obj && obj.constructor == Array) {
39347 ret = [];
39348 obj[marker] = true;
39349
39350 for (key = 0; key < obj.length; key++)
39351 ret.push(deepCopy(obj[key]));
39352
39353 delete (obj[marker]);
39354 return (ret);
39355 }
39356
39357 /*
39358 * It must be a primitive type -- just return it.
39359 */
39360 return (obj);
39361}
39362
39363function deepEqual(obj1, obj2)
39364{
39365 if (typeof (obj1) != typeof (obj2))
39366 return (false);
39367
39368 if (obj1 === null || obj2 === null || typeof (obj1) != 'object')
39369 return (obj1 === obj2);
39370
39371 if (obj1.constructor != obj2.constructor)
39372 return (false);
39373
39374 var k;
39375 for (k in obj1) {
39376 if (!obj2.hasOwnProperty(k))
39377 return (false);
39378
39379 if (!deepEqual(obj1[k], obj2[k]))
39380 return (false);
39381 }
39382
39383 for (k in obj2) {
39384 if (!obj1.hasOwnProperty(k))
39385 return (false);
39386 }
39387
39388 return (true);
39389}
39390
39391function isEmpty(obj)
39392{
39393 var key;
39394 for (key in obj)
39395 return (false);
39396 return (true);
39397}
39398
39399function hasKey(obj, key)
39400{
39401 mod_assert.equal(typeof (key), 'string');
39402 return (Object.prototype.hasOwnProperty.call(obj, key));
39403}
39404
39405function forEachKey(obj, callback)
39406{
39407 for (var key in obj) {
39408 if (hasKey(obj, key)) {
39409 callback(key, obj[key]);
39410 }
39411 }
39412}
39413
39414function pluck(obj, key)
39415{
39416 mod_assert.equal(typeof (key), 'string');
39417 return (pluckv(obj, key));
39418}
39419
39420function pluckv(obj, key)
39421{
39422 if (obj === null || typeof (obj) !== 'object')
39423 return (undefined);
39424
39425 if (obj.hasOwnProperty(key))
39426 return (obj[key]);
39427
39428 var i = key.indexOf('.');
39429 if (i == -1)
39430 return (undefined);
39431
39432 var key1 = key.substr(0, i);
39433 if (!obj.hasOwnProperty(key1))
39434 return (undefined);
39435
39436 return (pluckv(obj[key1], key.substr(i + 1)));
39437}
39438
39439/*
39440 * Invoke callback(row) for each entry in the array that would be returned by
39441 * flattenObject(data, depth). This is just like flattenObject(data,
39442 * depth).forEach(callback), except that the intermediate array is never
39443 * created.
39444 */
39445function flattenIter(data, depth, callback)
39446{
39447 doFlattenIter(data, depth, [], callback);
39448}
39449
39450function doFlattenIter(data, depth, accum, callback)
39451{
39452 var each;
39453 var key;
39454
39455 if (depth === 0) {
39456 each = accum.slice(0);
39457 each.push(data);
39458 callback(each);
39459 return;
39460 }
39461
39462 mod_assert.ok(data !== null);
39463 mod_assert.equal(typeof (data), 'object');
39464 mod_assert.equal(typeof (depth), 'number');
39465 mod_assert.ok(depth >= 0);
39466
39467 for (key in data) {
39468 each = accum.slice(0);
39469 each.push(key);
39470 doFlattenIter(data[key], depth - 1, each, callback);
39471 }
39472}
39473
39474function flattenObject(data, depth)
39475{
39476 if (depth === 0)
39477 return ([ data ]);
39478
39479 mod_assert.ok(data !== null);
39480 mod_assert.equal(typeof (data), 'object');
39481 mod_assert.equal(typeof (depth), 'number');
39482 mod_assert.ok(depth >= 0);
39483
39484 var rv = [];
39485 var key;
39486
39487 for (key in data) {
39488 flattenObject(data[key], depth - 1).forEach(function (p) {
39489 rv.push([ key ].concat(p));
39490 });
39491 }
39492
39493 return (rv);
39494}
39495
39496function startsWith(str, prefix)
39497{
39498 return (str.substr(0, prefix.length) == prefix);
39499}
39500
39501function endsWith(str, suffix)
39502{
39503 return (str.substr(
39504 str.length - suffix.length, suffix.length) == suffix);
39505}
39506
39507function iso8601(d)
39508{
39509 if (typeof (d) == 'number')
39510 d = new Date(d);
39511 mod_assert.ok(d.constructor === Date);
39512 return (mod_extsprintf.sprintf('%4d-%02d-%02dT%02d:%02d:%02d.%03dZ',
39513 d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(),
39514 d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(),
39515 d.getUTCMilliseconds()));
39516}
39517
39518var RFC1123_MONTHS = [
39519 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
39520 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
39521var RFC1123_DAYS = [
39522 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
39523
39524function rfc1123(date) {
39525 return (mod_extsprintf.sprintf('%s, %02d %s %04d %02d:%02d:%02d GMT',
39526 RFC1123_DAYS[date.getUTCDay()], date.getUTCDate(),
39527 RFC1123_MONTHS[date.getUTCMonth()], date.getUTCFullYear(),
39528 date.getUTCHours(), date.getUTCMinutes(),
39529 date.getUTCSeconds()));
39530}
39531
39532/*
39533 * Parses a date expressed as a string, as either a number of milliseconds since
39534 * the epoch or any string format that Date accepts, giving preference to the
39535 * former where these two sets overlap (e.g., small numbers).
39536 */
39537function parseDateTime(str)
39538{
39539 /*
39540 * This is irritatingly implicit, but significantly more concise than
39541 * alternatives. The "+str" will convert a string containing only a
39542 * number directly to a Number, or NaN for other strings. Thus, if the
39543 * conversion succeeds, we use it (this is the milliseconds-since-epoch
39544 * case). Otherwise, we pass the string directly to the Date
39545 * constructor to parse.
39546 */
39547 var numeric = +str;
39548 if (!isNaN(numeric)) {
39549 return (new Date(numeric));
39550 } else {
39551 return (new Date(str));
39552 }
39553}
39554
39555
39556/*
39557 * Number.*_SAFE_INTEGER isn't present before node v0.12, so we hardcode
39558 * the ES6 definitions here, while allowing for them to someday be higher.
39559 */
39560var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;
39561var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER || -9007199254740991;
39562
39563
39564/*
39565 * Default options for parseInteger().
39566 */
39567var PI_DEFAULTS = {
39568 base: 10,
39569 allowSign: true,
39570 allowPrefix: false,
39571 allowTrailing: false,
39572 allowImprecise: false,
39573 trimWhitespace: false,
39574 leadingZeroIsOctal: false
39575};
39576
39577var CP_0 = 0x30;
39578var CP_9 = 0x39;
39579
39580var CP_A = 0x41;
39581var CP_B = 0x42;
39582var CP_O = 0x4f;
39583var CP_T = 0x54;
39584var CP_X = 0x58;
39585var CP_Z = 0x5a;
39586
39587var CP_a = 0x61;
39588var CP_b = 0x62;
39589var CP_o = 0x6f;
39590var CP_t = 0x74;
39591var CP_x = 0x78;
39592var CP_z = 0x7a;
39593
39594var PI_CONV_DEC = 0x30;
39595var PI_CONV_UC = 0x37;
39596var PI_CONV_LC = 0x57;
39597
39598
39599/*
39600 * A stricter version of parseInt() that provides options for changing what
39601 * is an acceptable string (for example, disallowing trailing characters).
39602 */
39603function parseInteger(str, uopts)
39604{
39605 mod_assert.string(str, 'str');
39606 mod_assert.optionalObject(uopts, 'options');
39607
39608 var baseOverride = false;
39609 var options = PI_DEFAULTS;
39610
39611 if (uopts) {
39612 baseOverride = hasKey(uopts, 'base');
39613 options = mergeObjects(options, uopts);
39614 mod_assert.number(options.base, 'options.base');
39615 mod_assert.ok(options.base >= 2, 'options.base >= 2');
39616 mod_assert.ok(options.base <= 36, 'options.base <= 36');
39617 mod_assert.bool(options.allowSign, 'options.allowSign');
39618 mod_assert.bool(options.allowPrefix, 'options.allowPrefix');
39619 mod_assert.bool(options.allowTrailing,
39620 'options.allowTrailing');
39621 mod_assert.bool(options.allowImprecise,
39622 'options.allowImprecise');
39623 mod_assert.bool(options.trimWhitespace,
39624 'options.trimWhitespace');
39625 mod_assert.bool(options.leadingZeroIsOctal,
39626 'options.leadingZeroIsOctal');
39627
39628 if (options.leadingZeroIsOctal) {
39629 mod_assert.ok(!baseOverride,
39630 '"base" and "leadingZeroIsOctal" are ' +
39631 'mutually exclusive');
39632 }
39633 }
39634
39635 var c;
39636 var pbase = -1;
39637 var base = options.base;
39638 var start;
39639 var mult = 1;
39640 var value = 0;
39641 var idx = 0;
39642 var len = str.length;
39643
39644 /* Trim any whitespace on the left side. */
39645 if (options.trimWhitespace) {
39646 while (idx < len && isSpace(str.charCodeAt(idx))) {
39647 ++idx;
39648 }
39649 }
39650
39651 /* Check the number for a leading sign. */
39652 if (options.allowSign) {
39653 if (str[idx] === '-') {
39654 idx += 1;
39655 mult = -1;
39656 } else if (str[idx] === '+') {
39657 idx += 1;
39658 }
39659 }
39660
39661 /* Parse the base-indicating prefix if there is one. */
39662 if (str[idx] === '0') {
39663 if (options.allowPrefix) {
39664 pbase = prefixToBase(str.charCodeAt(idx + 1));
39665 if (pbase !== -1 && (!baseOverride || pbase === base)) {
39666 base = pbase;
39667 idx += 2;
39668 }
39669 }
39670
39671 if (pbase === -1 && options.leadingZeroIsOctal) {
39672 base = 8;
39673 }
39674 }
39675
39676 /* Parse the actual digits. */
39677 for (start = idx; idx < len; ++idx) {
39678 c = translateDigit(str.charCodeAt(idx));
39679 if (c !== -1 && c < base) {
39680 value *= base;
39681 value += c;
39682 } else {
39683 break;
39684 }
39685 }
39686
39687 /* If we didn't parse any digits, we have an invalid number. */
39688 if (start === idx) {
39689 return (new Error('invalid number: ' + JSON.stringify(str)));
39690 }
39691
39692 /* Trim any whitespace on the right side. */
39693 if (options.trimWhitespace) {
39694 while (idx < len && isSpace(str.charCodeAt(idx))) {
39695 ++idx;
39696 }
39697 }
39698
39699 /* Check for trailing characters. */
39700 if (idx < len && !options.allowTrailing) {
39701 return (new Error('trailing characters after number: ' +
39702 JSON.stringify(str.slice(idx))));
39703 }
39704
39705 /* If our value is 0, we return now, to avoid returning -0. */
39706 if (value === 0) {
39707 return (0);
39708 }
39709
39710 /* Calculate our final value. */
39711 var result = value * mult;
39712
39713 /*
39714 * If the string represents a value that cannot be precisely represented
39715 * by JavaScript, then we want to check that:
39716 *
39717 * - We never increased the value past MAX_SAFE_INTEGER
39718 * - We don't make the result negative and below MIN_SAFE_INTEGER
39719 *
39720 * Because we only ever increment the value during parsing, there's no
39721 * chance of moving past MAX_SAFE_INTEGER and then dropping below it
39722 * again, losing precision in the process. This means that we only need
39723 * to do our checks here, at the end.
39724 */
39725 if (!options.allowImprecise &&
39726 (value > MAX_SAFE_INTEGER || result < MIN_SAFE_INTEGER)) {
39727 return (new Error('number is outside of the supported range: ' +
39728 JSON.stringify(str.slice(start, idx))));
39729 }
39730
39731 return (result);
39732}
39733
39734
39735/*
39736 * Interpret a character code as a base-36 digit.
39737 */
39738function translateDigit(d)
39739{
39740 if (d >= CP_0 && d <= CP_9) {
39741 /* '0' to '9' -> 0 to 9 */
39742 return (d - PI_CONV_DEC);
39743 } else if (d >= CP_A && d <= CP_Z) {
39744 /* 'A' - 'Z' -> 10 to 35 */
39745 return (d - PI_CONV_UC);
39746 } else if (d >= CP_a && d <= CP_z) {
39747 /* 'a' - 'z' -> 10 to 35 */
39748 return (d - PI_CONV_LC);
39749 } else {
39750 /* Invalid character code */
39751 return (-1);
39752 }
39753}
39754
39755
39756/*
39757 * Test if a value matches the ECMAScript definition of trimmable whitespace.
39758 */
39759function isSpace(c)
39760{
39761 return (c === 0x20) ||
39762 (c >= 0x0009 && c <= 0x000d) ||
39763 (c === 0x00a0) ||
39764 (c === 0x1680) ||
39765 (c === 0x180e) ||
39766 (c >= 0x2000 && c <= 0x200a) ||
39767 (c === 0x2028) ||
39768 (c === 0x2029) ||
39769 (c === 0x202f) ||
39770 (c === 0x205f) ||
39771 (c === 0x3000) ||
39772 (c === 0xfeff);
39773}
39774
39775
39776/*
39777 * Determine which base a character indicates (e.g., 'x' indicates hex).
39778 */
39779function prefixToBase(c)
39780{
39781 if (c === CP_b || c === CP_B) {
39782 /* 0b/0B (binary) */
39783 return (2);
39784 } else if (c === CP_o || c === CP_O) {
39785 /* 0o/0O (octal) */
39786 return (8);
39787 } else if (c === CP_t || c === CP_T) {
39788 /* 0t/0T (decimal) */
39789 return (10);
39790 } else if (c === CP_x || c === CP_X) {
39791 /* 0x/0X (hexadecimal) */
39792 return (16);
39793 } else {
39794 /* Not a meaningful character */
39795 return (-1);
39796 }
39797}
39798
39799
39800function validateJsonObjectJS(schema, input)
39801{
39802 var report = mod_jsonschema.validate(input, schema);
39803
39804 if (report.errors.length === 0)
39805 return (null);
39806
39807 /* Currently, we only do anything useful with the first error. */
39808 var error = report.errors[0];
39809
39810 /* The failed property is given by a URI with an irrelevant prefix. */
39811 var propname = error['property'];
39812 var reason = error['message'].toLowerCase();
39813 var i, j;
39814
39815 /*
39816 * There's at least one case where the property error message is
39817 * confusing at best. We work around this here.
39818 */
39819 if ((i = reason.indexOf('the property ')) != -1 &&
39820 (j = reason.indexOf(' is not defined in the schema and the ' +
39821 'schema does not allow additional properties')) != -1) {
39822 i += 'the property '.length;
39823 if (propname === '')
39824 propname = reason.substr(i, j - i);
39825 else
39826 propname = propname + '.' + reason.substr(i, j - i);
39827
39828 reason = 'unsupported property';
39829 }
39830
39831 var rv = new mod_verror.VError('property "%s": %s', propname, reason);
39832 rv.jsv_details = error;
39833 return (rv);
39834}
39835
39836function randElt(arr)
39837{
39838 mod_assert.ok(Array.isArray(arr) && arr.length > 0,
39839 'randElt argument must be a non-empty array');
39840
39841 return (arr[Math.floor(Math.random() * arr.length)]);
39842}
39843
39844function assertHrtime(a)
39845{
39846 mod_assert.ok(a[0] >= 0 && a[1] >= 0,
39847 'negative numbers not allowed in hrtimes');
39848 mod_assert.ok(a[1] < 1e9, 'nanoseconds column overflow');
39849}
39850
39851/*
39852 * Compute the time elapsed between hrtime readings A and B, where A is later
39853 * than B. hrtime readings come from Node's process.hrtime(). There is no
39854 * defined way to represent negative deltas, so it's illegal to diff B from A
39855 * where the time denoted by B is later than the time denoted by A. If this
39856 * becomes valuable, we can define a representation and extend the
39857 * implementation to support it.
39858 */
39859function hrtimeDiff(a, b)
39860{
39861 assertHrtime(a);
39862 assertHrtime(b);
39863 mod_assert.ok(a[0] > b[0] || (a[0] == b[0] && a[1] >= b[1]),
39864 'negative differences not allowed');
39865
39866 var rv = [ a[0] - b[0], 0 ];
39867
39868 if (a[1] >= b[1]) {
39869 rv[1] = a[1] - b[1];
39870 } else {
39871 rv[0]--;
39872 rv[1] = 1e9 - (b[1] - a[1]);
39873 }
39874
39875 return (rv);
39876}
39877
39878/*
39879 * Convert a hrtime reading from the array format returned by Node's
39880 * process.hrtime() into a scalar number of nanoseconds.
39881 */
39882function hrtimeNanosec(a)
39883{
39884 assertHrtime(a);
39885
39886 return (Math.floor(a[0] * 1e9 + a[1]));
39887}
39888
39889/*
39890 * Convert a hrtime reading from the array format returned by Node's
39891 * process.hrtime() into a scalar number of microseconds.
39892 */
39893function hrtimeMicrosec(a)
39894{
39895 assertHrtime(a);
39896
39897 return (Math.floor(a[0] * 1e6 + a[1] / 1e3));
39898}
39899
39900/*
39901 * Convert a hrtime reading from the array format returned by Node's
39902 * process.hrtime() into a scalar number of milliseconds.
39903 */
39904function hrtimeMillisec(a)
39905{
39906 assertHrtime(a);
39907
39908 return (Math.floor(a[0] * 1e3 + a[1] / 1e6));
39909}
39910
39911/*
39912 * Add two hrtime readings A and B, overwriting A with the result of the
39913 * addition. This function is useful for accumulating several hrtime intervals
39914 * into a counter. Returns A.
39915 */
39916function hrtimeAccum(a, b)
39917{
39918 assertHrtime(a);
39919 assertHrtime(b);
39920
39921 /*
39922 * Accumulate the nanosecond component.
39923 */
39924 a[1] += b[1];
39925 if (a[1] >= 1e9) {
39926 /*
39927 * The nanosecond component overflowed, so carry to the seconds
39928 * field.
39929 */
39930 a[0]++;
39931 a[1] -= 1e9;
39932 }
39933
39934 /*
39935 * Accumulate the seconds component.
39936 */
39937 a[0] += b[0];
39938
39939 return (a);
39940}
39941
39942/*
39943 * Add two hrtime readings A and B, returning the result as a new hrtime array.
39944 * Does not modify either input argument.
39945 */
39946function hrtimeAdd(a, b)
39947{
39948 assertHrtime(a);
39949
39950 var rv = [ a[0], a[1] ];
39951
39952 return (hrtimeAccum(rv, b));
39953}
39954
39955
39956/*
39957 * Check an object for unexpected properties. Accepts the object to check, and
39958 * an array of allowed property names (strings). Returns an array of key names
39959 * that were found on the object, but did not appear in the list of allowed
39960 * properties. If no properties were found, the returned array will be of
39961 * zero length.
39962 */
39963function extraProperties(obj, allowed)
39964{
39965 mod_assert.ok(typeof (obj) === 'object' && obj !== null,
39966 'obj argument must be a non-null object');
39967 mod_assert.ok(Array.isArray(allowed),
39968 'allowed argument must be an array of strings');
39969 for (var i = 0; i < allowed.length; i++) {
39970 mod_assert.ok(typeof (allowed[i]) === 'string',
39971 'allowed argument must be an array of strings');
39972 }
39973
39974 return (Object.keys(obj).filter(function (key) {
39975 return (allowed.indexOf(key) === -1);
39976 }));
39977}
39978
39979/*
39980 * Given three sets of properties "provided" (may be undefined), "overrides"
39981 * (required), and "defaults" (may be undefined), construct an object containing
39982 * the union of these sets with "overrides" overriding "provided", and
39983 * "provided" overriding "defaults". None of the input objects are modified.
39984 */
39985function mergeObjects(provided, overrides, defaults)
39986{
39987 var rv, k;
39988
39989 rv = {};
39990 if (defaults) {
39991 for (k in defaults)
39992 rv[k] = defaults[k];
39993 }
39994
39995 if (provided) {
39996 for (k in provided)
39997 rv[k] = provided[k];
39998 }
39999
40000 if (overrides) {
40001 for (k in overrides)
40002 rv[k] = overrides[k];
40003 }
40004
40005 return (rv);
40006}
40007
40008},{"assert-plus":67,"extsprintf":162,"json-schema":217,"util":397,"verror":401}],220:[function(require,module,exports){
40009var root = require('./_root');
40010
40011/** Built-in value references. */
40012var Symbol = root.Symbol;
40013
40014module.exports = Symbol;
40015
40016},{"./_root":225}],221:[function(require,module,exports){
40017var Symbol = require('./_Symbol'),
40018 getRawTag = require('./_getRawTag'),
40019 objectToString = require('./_objectToString');
40020
40021/** `Object#toString` result references. */
40022var nullTag = '[object Null]',
40023 undefinedTag = '[object Undefined]';
40024
40025/** Built-in value references. */
40026var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
40027
40028/**
40029 * The base implementation of `getTag` without fallbacks for buggy environments.
40030 *
40031 * @private
40032 * @param {*} value The value to query.
40033 * @returns {string} Returns the `toStringTag`.
40034 */
40035function baseGetTag(value) {
40036 if (value == null) {
40037 return value === undefined ? undefinedTag : nullTag;
40038 }
40039 return (symToStringTag && symToStringTag in Object(value))
40040 ? getRawTag(value)
40041 : objectToString(value);
40042}
40043
40044module.exports = baseGetTag;
40045
40046},{"./_Symbol":220,"./_getRawTag":223,"./_objectToString":224}],222:[function(require,module,exports){
40047(function (global){
40048/** Detect free variable `global` from Node.js. */
40049var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
40050
40051module.exports = freeGlobal;
40052
40053}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
40054},{}],223:[function(require,module,exports){
40055var Symbol = require('./_Symbol');
40056
40057/** Used for built-in method references. */
40058var objectProto = Object.prototype;
40059
40060/** Used to check objects for own properties. */
40061var hasOwnProperty = objectProto.hasOwnProperty;
40062
40063/**
40064 * Used to resolve the
40065 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
40066 * of values.
40067 */
40068var nativeObjectToString = objectProto.toString;
40069
40070/** Built-in value references. */
40071var symToStringTag = Symbol ? Symbol.toStringTag : undefined;
40072
40073/**
40074 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
40075 *
40076 * @private
40077 * @param {*} value The value to query.
40078 * @returns {string} Returns the raw `toStringTag`.
40079 */
40080function getRawTag(value) {
40081 var isOwn = hasOwnProperty.call(value, symToStringTag),
40082 tag = value[symToStringTag];
40083
40084 try {
40085 value[symToStringTag] = undefined;
40086 var unmasked = true;
40087 } catch (e) {}
40088
40089 var result = nativeObjectToString.call(value);
40090 if (unmasked) {
40091 if (isOwn) {
40092 value[symToStringTag] = tag;
40093 } else {
40094 delete value[symToStringTag];
40095 }
40096 }
40097 return result;
40098}
40099
40100module.exports = getRawTag;
40101
40102},{"./_Symbol":220}],224:[function(require,module,exports){
40103/** Used for built-in method references. */
40104var objectProto = Object.prototype;
40105
40106/**
40107 * Used to resolve the
40108 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
40109 * of values.
40110 */
40111var nativeObjectToString = objectProto.toString;
40112
40113/**
40114 * Converts `value` to a string using `Object.prototype.toString`.
40115 *
40116 * @private
40117 * @param {*} value The value to convert.
40118 * @returns {string} Returns the converted string.
40119 */
40120function objectToString(value) {
40121 return nativeObjectToString.call(value);
40122}
40123
40124module.exports = objectToString;
40125
40126},{}],225:[function(require,module,exports){
40127var freeGlobal = require('./_freeGlobal');
40128
40129/** Detect free variable `self`. */
40130var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
40131
40132/** Used as a reference to the global object. */
40133var root = freeGlobal || freeSelf || Function('return this')();
40134
40135module.exports = root;
40136
40137},{"./_freeGlobal":222}],226:[function(require,module,exports){
40138/**
40139 * Checks if `value` is classified as an `Array` object.
40140 *
40141 * @static
40142 * @memberOf _
40143 * @since 0.1.0
40144 * @category Lang
40145 * @param {*} value The value to check.
40146 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
40147 * @example
40148 *
40149 * _.isArray([1, 2, 3]);
40150 * // => true
40151 *
40152 * _.isArray(document.body.children);
40153 * // => false
40154 *
40155 * _.isArray('abc');
40156 * // => false
40157 *
40158 * _.isArray(_.noop);
40159 * // => false
40160 */
40161var isArray = Array.isArray;
40162
40163module.exports = isArray;
40164
40165},{}],227:[function(require,module,exports){
40166var baseGetTag = require('./_baseGetTag'),
40167 isObject = require('./isObject');
40168
40169/** `Object#toString` result references. */
40170var asyncTag = '[object AsyncFunction]',
40171 funcTag = '[object Function]',
40172 genTag = '[object GeneratorFunction]',
40173 proxyTag = '[object Proxy]';
40174
40175/**
40176 * Checks if `value` is classified as a `Function` object.
40177 *
40178 * @static
40179 * @memberOf _
40180 * @since 0.1.0
40181 * @category Lang
40182 * @param {*} value The value to check.
40183 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
40184 * @example
40185 *
40186 * _.isFunction(_);
40187 * // => true
40188 *
40189 * _.isFunction(/abc/);
40190 * // => false
40191 */
40192function isFunction(value) {
40193 if (!isObject(value)) {
40194 return false;
40195 }
40196 // The use of `Object#toString` avoids issues with the `typeof` operator
40197 // in Safari 9 which returns 'object' for typed arrays and other constructors.
40198 var tag = baseGetTag(value);
40199 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
40200}
40201
40202module.exports = isFunction;
40203
40204},{"./_baseGetTag":221,"./isObject":228}],228:[function(require,module,exports){
40205/**
40206 * Checks if `value` is the
40207 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
40208 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
40209 *
40210 * @static
40211 * @memberOf _
40212 * @since 0.1.0
40213 * @category Lang
40214 * @param {*} value The value to check.
40215 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
40216 * @example
40217 *
40218 * _.isObject({});
40219 * // => true
40220 *
40221 * _.isObject([1, 2, 3]);
40222 * // => true
40223 *
40224 * _.isObject(_.noop);
40225 * // => true
40226 *
40227 * _.isObject(null);
40228 * // => false
40229 */
40230function isObject(value) {
40231 var type = typeof value;
40232 return value != null && (type == 'object' || type == 'function');
40233}
40234
40235module.exports = isObject;
40236
40237},{}],229:[function(require,module,exports){
40238/**
40239 * Checks if `value` is object-like. A value is object-like if it's not `null`
40240 * and has a `typeof` result of "object".
40241 *
40242 * @static
40243 * @memberOf _
40244 * @since 4.0.0
40245 * @category Lang
40246 * @param {*} value The value to check.
40247 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
40248 * @example
40249 *
40250 * _.isObjectLike({});
40251 * // => true
40252 *
40253 * _.isObjectLike([1, 2, 3]);
40254 * // => true
40255 *
40256 * _.isObjectLike(_.noop);
40257 * // => false
40258 *
40259 * _.isObjectLike(null);
40260 * // => false
40261 */
40262function isObjectLike(value) {
40263 return value != null && typeof value == 'object';
40264}
40265
40266module.exports = isObjectLike;
40267
40268},{}],230:[function(require,module,exports){
40269var baseGetTag = require('./_baseGetTag'),
40270 isArray = require('./isArray'),
40271 isObjectLike = require('./isObjectLike');
40272
40273/** `Object#toString` result references. */
40274var stringTag = '[object String]';
40275
40276/**
40277 * Checks if `value` is classified as a `String` primitive or object.
40278 *
40279 * @static
40280 * @since 0.1.0
40281 * @memberOf _
40282 * @category Lang
40283 * @param {*} value The value to check.
40284 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
40285 * @example
40286 *
40287 * _.isString('abc');
40288 * // => true
40289 *
40290 * _.isString(1);
40291 * // => false
40292 */
40293function isString(value) {
40294 return typeof value == 'string' ||
40295 (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
40296}
40297
40298module.exports = isString;
40299
40300},{"./_baseGetTag":221,"./isArray":226,"./isObjectLike":229}],231:[function(require,module,exports){
40301/**
40302 * Checks if `value` is `undefined`.
40303 *
40304 * @static
40305 * @since 0.1.0
40306 * @memberOf _
40307 * @category Lang
40308 * @param {*} value The value to check.
40309 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
40310 * @example
40311 *
40312 * _.isUndefined(void 0);
40313 * // => true
40314 *
40315 * _.isUndefined(null);
40316 * // => false
40317 */
40318function isUndefined(value) {
40319 return value === undefined;
40320}
40321
40322module.exports = isUndefined;
40323
40324},{}],232:[function(require,module,exports){
40325'use strict'
40326var inherits = require('inherits')
40327var HashBase = require('hash-base')
40328var Buffer = require('safe-buffer').Buffer
40329
40330var ARRAY16 = new Array(16)
40331
40332function MD5 () {
40333 HashBase.call(this, 64)
40334
40335 // state
40336 this._a = 0x67452301
40337 this._b = 0xefcdab89
40338 this._c = 0x98badcfe
40339 this._d = 0x10325476
40340}
40341
40342inherits(MD5, HashBase)
40343
40344MD5.prototype._update = function () {
40345 var M = ARRAY16
40346 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
40347
40348 var a = this._a
40349 var b = this._b
40350 var c = this._c
40351 var d = this._d
40352
40353 a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
40354 d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
40355 c = fnF(c, d, a, b, M[2], 0x242070db, 17)
40356 b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
40357 a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
40358 d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
40359 c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
40360 b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
40361 a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
40362 d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
40363 c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
40364 b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
40365 a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
40366 d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
40367 c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
40368 b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
40369
40370 a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
40371 d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
40372 c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
40373 b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
40374 a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
40375 d = fnG(d, a, b, c, M[10], 0x02441453, 9)
40376 c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
40377 b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
40378 a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
40379 d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
40380 c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
40381 b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
40382 a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
40383 d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
40384 c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
40385 b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
40386
40387 a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
40388 d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
40389 c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
40390 b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
40391 a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
40392 d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
40393 c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
40394 b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
40395 a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
40396 d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
40397 c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
40398 b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
40399 a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
40400 d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
40401 c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
40402 b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
40403
40404 a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
40405 d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
40406 c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
40407 b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
40408 a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
40409 d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
40410 c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
40411 b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
40412 a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
40413 d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
40414 c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
40415 b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
40416 a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
40417 d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
40418 c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
40419 b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
40420
40421 this._a = (this._a + a) | 0
40422 this._b = (this._b + b) | 0
40423 this._c = (this._c + c) | 0
40424 this._d = (this._d + d) | 0
40425}
40426
40427MD5.prototype._digest = function () {
40428 // create padding and handle blocks
40429 this._block[this._blockOffset++] = 0x80
40430 if (this._blockOffset > 56) {
40431 this._block.fill(0, this._blockOffset, 64)
40432 this._update()
40433 this._blockOffset = 0
40434 }
40435
40436 this._block.fill(0, this._blockOffset, 56)
40437 this._block.writeUInt32LE(this._length[0], 56)
40438 this._block.writeUInt32LE(this._length[1], 60)
40439 this._update()
40440
40441 // produce result
40442 var buffer = Buffer.allocUnsafe(16)
40443 buffer.writeInt32LE(this._a, 0)
40444 buffer.writeInt32LE(this._b, 4)
40445 buffer.writeInt32LE(this._c, 8)
40446 buffer.writeInt32LE(this._d, 12)
40447 return buffer
40448}
40449
40450function rotl (x, n) {
40451 return (x << n) | (x >>> (32 - n))
40452}
40453
40454function fnF (a, b, c, d, m, k, s) {
40455 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
40456}
40457
40458function fnG (a, b, c, d, m, k, s) {
40459 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
40460}
40461
40462function fnH (a, b, c, d, m, k, s) {
40463 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
40464}
40465
40466function fnI (a, b, c, d, m, k, s) {
40467 return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
40468}
40469
40470module.exports = MD5
40471
40472},{"hash-base":189,"inherits":210,"safe-buffer":325}],233:[function(require,module,exports){
40473var bn = require('bn.js');
40474var brorand = require('brorand');
40475
40476function MillerRabin(rand) {
40477 this.rand = rand || new brorand.Rand();
40478}
40479module.exports = MillerRabin;
40480
40481MillerRabin.create = function create(rand) {
40482 return new MillerRabin(rand);
40483};
40484
40485MillerRabin.prototype._randbelow = function _randbelow(n) {
40486 var len = n.bitLength();
40487 var min_bytes = Math.ceil(len / 8);
40488
40489 // Generage random bytes until a number less than n is found.
40490 // This ensures that 0..n-1 have an equal probability of being selected.
40491 do
40492 var a = new bn(this.rand.generate(min_bytes));
40493 while (a.cmp(n) >= 0);
40494
40495 return a;
40496};
40497
40498MillerRabin.prototype._randrange = function _randrange(start, stop) {
40499 // Generate a random number greater than or equal to start and less than stop.
40500 var size = stop.sub(start);
40501 return start.add(this._randbelow(size));
40502};
40503
40504MillerRabin.prototype.test = function test(n, k, cb) {
40505 var len = n.bitLength();
40506 var red = bn.mont(n);
40507 var rone = new bn(1).toRed(red);
40508
40509 if (!k)
40510 k = Math.max(1, (len / 48) | 0);
40511
40512 // Find d and s, (n - 1) = (2 ^ s) * d;
40513 var n1 = n.subn(1);
40514 for (var s = 0; !n1.testn(s); s++) {}
40515 var d = n.shrn(s);
40516
40517 var rn1 = n1.toRed(red);
40518
40519 var prime = true;
40520 for (; k > 0; k--) {
40521 var a = this._randrange(new bn(2), n1);
40522 if (cb)
40523 cb(a);
40524
40525 var x = a.toRed(red).redPow(d);
40526 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
40527 continue;
40528
40529 for (var i = 1; i < s; i++) {
40530 x = x.redSqr();
40531
40532 if (x.cmp(rone) === 0)
40533 return false;
40534 if (x.cmp(rn1) === 0)
40535 break;
40536 }
40537
40538 if (i === s)
40539 return false;
40540 }
40541
40542 return prime;
40543};
40544
40545MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
40546 var len = n.bitLength();
40547 var red = bn.mont(n);
40548 var rone = new bn(1).toRed(red);
40549
40550 if (!k)
40551 k = Math.max(1, (len / 48) | 0);
40552
40553 // Find d and s, (n - 1) = (2 ^ s) * d;
40554 var n1 = n.subn(1);
40555 for (var s = 0; !n1.testn(s); s++) {}
40556 var d = n.shrn(s);
40557
40558 var rn1 = n1.toRed(red);
40559
40560 for (; k > 0; k--) {
40561 var a = this._randrange(new bn(2), n1);
40562
40563 var g = n.gcd(a);
40564 if (g.cmpn(1) !== 0)
40565 return g;
40566
40567 var x = a.toRed(red).redPow(d);
40568 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
40569 continue;
40570
40571 for (var i = 1; i < s; i++) {
40572 x = x.redSqr();
40573
40574 if (x.cmp(rone) === 0)
40575 return x.fromRed().subn(1).gcd(n);
40576 if (x.cmp(rn1) === 0)
40577 break;
40578 }
40579
40580 if (i === s) {
40581 x = x.redSqr();
40582 return x.fromRed().subn(1).gcd(n);
40583 }
40584 }
40585
40586 return false;
40587};
40588
40589},{"bn.js":80,"brorand":81}],234:[function(require,module,exports){
40590module.exports={
40591 "application/1d-interleaved-parityfec": {
40592 "source": "iana"
40593 },
40594 "application/3gpdash-qoe-report+xml": {
40595 "source": "iana",
40596 "compressible": true
40597 },
40598 "application/3gpp-ims+xml": {
40599 "source": "iana",
40600 "compressible": true
40601 },
40602 "application/a2l": {
40603 "source": "iana"
40604 },
40605 "application/activemessage": {
40606 "source": "iana"
40607 },
40608 "application/activity+json": {
40609 "source": "iana",
40610 "compressible": true
40611 },
40612 "application/alto-costmap+json": {
40613 "source": "iana",
40614 "compressible": true
40615 },
40616 "application/alto-costmapfilter+json": {
40617 "source": "iana",
40618 "compressible": true
40619 },
40620 "application/alto-directory+json": {
40621 "source": "iana",
40622 "compressible": true
40623 },
40624 "application/alto-endpointcost+json": {
40625 "source": "iana",
40626 "compressible": true
40627 },
40628 "application/alto-endpointcostparams+json": {
40629 "source": "iana",
40630 "compressible": true
40631 },
40632 "application/alto-endpointprop+json": {
40633 "source": "iana",
40634 "compressible": true
40635 },
40636 "application/alto-endpointpropparams+json": {
40637 "source": "iana",
40638 "compressible": true
40639 },
40640 "application/alto-error+json": {
40641 "source": "iana",
40642 "compressible": true
40643 },
40644 "application/alto-networkmap+json": {
40645 "source": "iana",
40646 "compressible": true
40647 },
40648 "application/alto-networkmapfilter+json": {
40649 "source": "iana",
40650 "compressible": true
40651 },
40652 "application/aml": {
40653 "source": "iana"
40654 },
40655 "application/andrew-inset": {
40656 "source": "iana",
40657 "extensions": ["ez"]
40658 },
40659 "application/applefile": {
40660 "source": "iana"
40661 },
40662 "application/applixware": {
40663 "source": "apache",
40664 "extensions": ["aw"]
40665 },
40666 "application/atf": {
40667 "source": "iana"
40668 },
40669 "application/atfx": {
40670 "source": "iana"
40671 },
40672 "application/atom+xml": {
40673 "source": "iana",
40674 "compressible": true,
40675 "extensions": ["atom"]
40676 },
40677 "application/atomcat+xml": {
40678 "source": "iana",
40679 "compressible": true,
40680 "extensions": ["atomcat"]
40681 },
40682 "application/atomdeleted+xml": {
40683 "source": "iana",
40684 "compressible": true
40685 },
40686 "application/atomicmail": {
40687 "source": "iana"
40688 },
40689 "application/atomsvc+xml": {
40690 "source": "iana",
40691 "compressible": true,
40692 "extensions": ["atomsvc"]
40693 },
40694 "application/atsc-dwd+xml": {
40695 "source": "iana",
40696 "compressible": true
40697 },
40698 "application/atsc-held+xml": {
40699 "source": "iana",
40700 "compressible": true
40701 },
40702 "application/atsc-rsat+xml": {
40703 "source": "iana",
40704 "compressible": true
40705 },
40706 "application/atxml": {
40707 "source": "iana"
40708 },
40709 "application/auth-policy+xml": {
40710 "source": "iana",
40711 "compressible": true
40712 },
40713 "application/bacnet-xdd+zip": {
40714 "source": "iana",
40715 "compressible": false
40716 },
40717 "application/batch-smtp": {
40718 "source": "iana"
40719 },
40720 "application/bdoc": {
40721 "compressible": false,
40722 "extensions": ["bdoc"]
40723 },
40724 "application/beep+xml": {
40725 "source": "iana",
40726 "compressible": true
40727 },
40728 "application/calendar+json": {
40729 "source": "iana",
40730 "compressible": true
40731 },
40732 "application/calendar+xml": {
40733 "source": "iana",
40734 "compressible": true
40735 },
40736 "application/call-completion": {
40737 "source": "iana"
40738 },
40739 "application/cals-1840": {
40740 "source": "iana"
40741 },
40742 "application/cbor": {
40743 "source": "iana"
40744 },
40745 "application/cccex": {
40746 "source": "iana"
40747 },
40748 "application/ccmp+xml": {
40749 "source": "iana",
40750 "compressible": true
40751 },
40752 "application/ccxml+xml": {
40753 "source": "iana",
40754 "compressible": true,
40755 "extensions": ["ccxml"]
40756 },
40757 "application/cdfx+xml": {
40758 "source": "iana",
40759 "compressible": true
40760 },
40761 "application/cdmi-capability": {
40762 "source": "iana",
40763 "extensions": ["cdmia"]
40764 },
40765 "application/cdmi-container": {
40766 "source": "iana",
40767 "extensions": ["cdmic"]
40768 },
40769 "application/cdmi-domain": {
40770 "source": "iana",
40771 "extensions": ["cdmid"]
40772 },
40773 "application/cdmi-object": {
40774 "source": "iana",
40775 "extensions": ["cdmio"]
40776 },
40777 "application/cdmi-queue": {
40778 "source": "iana",
40779 "extensions": ["cdmiq"]
40780 },
40781 "application/cdni": {
40782 "source": "iana"
40783 },
40784 "application/cea": {
40785 "source": "iana"
40786 },
40787 "application/cea-2018+xml": {
40788 "source": "iana",
40789 "compressible": true
40790 },
40791 "application/cellml+xml": {
40792 "source": "iana",
40793 "compressible": true
40794 },
40795 "application/cfw": {
40796 "source": "iana"
40797 },
40798 "application/clue_info+xml": {
40799 "source": "iana",
40800 "compressible": true
40801 },
40802 "application/cms": {
40803 "source": "iana"
40804 },
40805 "application/cnrp+xml": {
40806 "source": "iana",
40807 "compressible": true
40808 },
40809 "application/coap-group+json": {
40810 "source": "iana",
40811 "compressible": true
40812 },
40813 "application/coap-payload": {
40814 "source": "iana"
40815 },
40816 "application/commonground": {
40817 "source": "iana"
40818 },
40819 "application/conference-info+xml": {
40820 "source": "iana",
40821 "compressible": true
40822 },
40823 "application/cose": {
40824 "source": "iana"
40825 },
40826 "application/cose-key": {
40827 "source": "iana"
40828 },
40829 "application/cose-key-set": {
40830 "source": "iana"
40831 },
40832 "application/cpl+xml": {
40833 "source": "iana",
40834 "compressible": true
40835 },
40836 "application/csrattrs": {
40837 "source": "iana"
40838 },
40839 "application/csta+xml": {
40840 "source": "iana",
40841 "compressible": true
40842 },
40843 "application/cstadata+xml": {
40844 "source": "iana",
40845 "compressible": true
40846 },
40847 "application/csvm+json": {
40848 "source": "iana",
40849 "compressible": true
40850 },
40851 "application/cu-seeme": {
40852 "source": "apache",
40853 "extensions": ["cu"]
40854 },
40855 "application/cwt": {
40856 "source": "iana"
40857 },
40858 "application/cybercash": {
40859 "source": "iana"
40860 },
40861 "application/dart": {
40862 "compressible": true
40863 },
40864 "application/dash+xml": {
40865 "source": "iana",
40866 "compressible": true,
40867 "extensions": ["mpd"]
40868 },
40869 "application/dashdelta": {
40870 "source": "iana"
40871 },
40872 "application/davmount+xml": {
40873 "source": "iana",
40874 "compressible": true,
40875 "extensions": ["davmount"]
40876 },
40877 "application/dca-rft": {
40878 "source": "iana"
40879 },
40880 "application/dcd": {
40881 "source": "iana"
40882 },
40883 "application/dec-dx": {
40884 "source": "iana"
40885 },
40886 "application/dialog-info+xml": {
40887 "source": "iana",
40888 "compressible": true
40889 },
40890 "application/dicom": {
40891 "source": "iana"
40892 },
40893 "application/dicom+json": {
40894 "source": "iana",
40895 "compressible": true
40896 },
40897 "application/dicom+xml": {
40898 "source": "iana",
40899 "compressible": true
40900 },
40901 "application/dii": {
40902 "source": "iana"
40903 },
40904 "application/dit": {
40905 "source": "iana"
40906 },
40907 "application/dns": {
40908 "source": "iana"
40909 },
40910 "application/dns+json": {
40911 "source": "iana",
40912 "compressible": true
40913 },
40914 "application/dns-message": {
40915 "source": "iana"
40916 },
40917 "application/docbook+xml": {
40918 "source": "apache",
40919 "compressible": true,
40920 "extensions": ["dbk"]
40921 },
40922 "application/dskpp+xml": {
40923 "source": "iana",
40924 "compressible": true
40925 },
40926 "application/dssc+der": {
40927 "source": "iana",
40928 "extensions": ["dssc"]
40929 },
40930 "application/dssc+xml": {
40931 "source": "iana",
40932 "compressible": true,
40933 "extensions": ["xdssc"]
40934 },
40935 "application/dvcs": {
40936 "source": "iana"
40937 },
40938 "application/ecmascript": {
40939 "source": "iana",
40940 "compressible": true,
40941 "extensions": ["ecma","es"]
40942 },
40943 "application/edi-consent": {
40944 "source": "iana"
40945 },
40946 "application/edi-x12": {
40947 "source": "iana",
40948 "compressible": false
40949 },
40950 "application/edifact": {
40951 "source": "iana",
40952 "compressible": false
40953 },
40954 "application/efi": {
40955 "source": "iana"
40956 },
40957 "application/emergencycalldata.comment+xml": {
40958 "source": "iana",
40959 "compressible": true
40960 },
40961 "application/emergencycalldata.control+xml": {
40962 "source": "iana",
40963 "compressible": true
40964 },
40965 "application/emergencycalldata.deviceinfo+xml": {
40966 "source": "iana",
40967 "compressible": true
40968 },
40969 "application/emergencycalldata.ecall.msd": {
40970 "source": "iana"
40971 },
40972 "application/emergencycalldata.providerinfo+xml": {
40973 "source": "iana",
40974 "compressible": true
40975 },
40976 "application/emergencycalldata.serviceinfo+xml": {
40977 "source": "iana",
40978 "compressible": true
40979 },
40980 "application/emergencycalldata.subscriberinfo+xml": {
40981 "source": "iana",
40982 "compressible": true
40983 },
40984 "application/emergencycalldata.veds+xml": {
40985 "source": "iana",
40986 "compressible": true
40987 },
40988 "application/emma+xml": {
40989 "source": "iana",
40990 "compressible": true,
40991 "extensions": ["emma"]
40992 },
40993 "application/emotionml+xml": {
40994 "source": "iana",
40995 "compressible": true
40996 },
40997 "application/encaprtp": {
40998 "source": "iana"
40999 },
41000 "application/epp+xml": {
41001 "source": "iana",
41002 "compressible": true
41003 },
41004 "application/epub+zip": {
41005 "source": "iana",
41006 "compressible": false,
41007 "extensions": ["epub"]
41008 },
41009 "application/eshop": {
41010 "source": "iana"
41011 },
41012 "application/exi": {
41013 "source": "iana",
41014 "extensions": ["exi"]
41015 },
41016 "application/expect-ct-report+json": {
41017 "source": "iana",
41018 "compressible": true
41019 },
41020 "application/fastinfoset": {
41021 "source": "iana"
41022 },
41023 "application/fastsoap": {
41024 "source": "iana"
41025 },
41026 "application/fdt+xml": {
41027 "source": "iana",
41028 "compressible": true
41029 },
41030 "application/fhir+json": {
41031 "source": "iana",
41032 "compressible": true
41033 },
41034 "application/fhir+xml": {
41035 "source": "iana",
41036 "compressible": true
41037 },
41038 "application/fido.trusted-apps+json": {
41039 "compressible": true
41040 },
41041 "application/fits": {
41042 "source": "iana"
41043 },
41044 "application/font-sfnt": {
41045 "source": "iana"
41046 },
41047 "application/font-tdpfr": {
41048 "source": "iana",
41049 "extensions": ["pfr"]
41050 },
41051 "application/font-woff": {
41052 "source": "iana",
41053 "compressible": false
41054 },
41055 "application/framework-attributes+xml": {
41056 "source": "iana",
41057 "compressible": true
41058 },
41059 "application/geo+json": {
41060 "source": "iana",
41061 "compressible": true,
41062 "extensions": ["geojson"]
41063 },
41064 "application/geo+json-seq": {
41065 "source": "iana"
41066 },
41067 "application/geopackage+sqlite3": {
41068 "source": "iana"
41069 },
41070 "application/geoxacml+xml": {
41071 "source": "iana",
41072 "compressible": true
41073 },
41074 "application/gltf-buffer": {
41075 "source": "iana"
41076 },
41077 "application/gml+xml": {
41078 "source": "iana",
41079 "compressible": true,
41080 "extensions": ["gml"]
41081 },
41082 "application/gpx+xml": {
41083 "source": "apache",
41084 "compressible": true,
41085 "extensions": ["gpx"]
41086 },
41087 "application/gxf": {
41088 "source": "apache",
41089 "extensions": ["gxf"]
41090 },
41091 "application/gzip": {
41092 "source": "iana",
41093 "compressible": false,
41094 "extensions": ["gz"]
41095 },
41096 "application/h224": {
41097 "source": "iana"
41098 },
41099 "application/held+xml": {
41100 "source": "iana",
41101 "compressible": true
41102 },
41103 "application/hjson": {
41104 "extensions": ["hjson"]
41105 },
41106 "application/http": {
41107 "source": "iana"
41108 },
41109 "application/hyperstudio": {
41110 "source": "iana",
41111 "extensions": ["stk"]
41112 },
41113 "application/ibe-key-request+xml": {
41114 "source": "iana",
41115 "compressible": true
41116 },
41117 "application/ibe-pkg-reply+xml": {
41118 "source": "iana",
41119 "compressible": true
41120 },
41121 "application/ibe-pp-data": {
41122 "source": "iana"
41123 },
41124 "application/iges": {
41125 "source": "iana"
41126 },
41127 "application/im-iscomposing+xml": {
41128 "source": "iana",
41129 "compressible": true
41130 },
41131 "application/index": {
41132 "source": "iana"
41133 },
41134 "application/index.cmd": {
41135 "source": "iana"
41136 },
41137 "application/index.obj": {
41138 "source": "iana"
41139 },
41140 "application/index.response": {
41141 "source": "iana"
41142 },
41143 "application/index.vnd": {
41144 "source": "iana"
41145 },
41146 "application/inkml+xml": {
41147 "source": "iana",
41148 "compressible": true,
41149 "extensions": ["ink","inkml"]
41150 },
41151 "application/iotp": {
41152 "source": "iana"
41153 },
41154 "application/ipfix": {
41155 "source": "iana",
41156 "extensions": ["ipfix"]
41157 },
41158 "application/ipp": {
41159 "source": "iana"
41160 },
41161 "application/isup": {
41162 "source": "iana"
41163 },
41164 "application/its+xml": {
41165 "source": "iana",
41166 "compressible": true
41167 },
41168 "application/java-archive": {
41169 "source": "apache",
41170 "compressible": false,
41171 "extensions": ["jar","war","ear"]
41172 },
41173 "application/java-serialized-object": {
41174 "source": "apache",
41175 "compressible": false,
41176 "extensions": ["ser"]
41177 },
41178 "application/java-vm": {
41179 "source": "apache",
41180 "compressible": false,
41181 "extensions": ["class"]
41182 },
41183 "application/javascript": {
41184 "source": "iana",
41185 "charset": "UTF-8",
41186 "compressible": true,
41187 "extensions": ["js","mjs"]
41188 },
41189 "application/jf2feed+json": {
41190 "source": "iana",
41191 "compressible": true
41192 },
41193 "application/jose": {
41194 "source": "iana"
41195 },
41196 "application/jose+json": {
41197 "source": "iana",
41198 "compressible": true
41199 },
41200 "application/jrd+json": {
41201 "source": "iana",
41202 "compressible": true
41203 },
41204 "application/json": {
41205 "source": "iana",
41206 "charset": "UTF-8",
41207 "compressible": true,
41208 "extensions": ["json","map"]
41209 },
41210 "application/json-patch+json": {
41211 "source": "iana",
41212 "compressible": true
41213 },
41214 "application/json-seq": {
41215 "source": "iana"
41216 },
41217 "application/json5": {
41218 "extensions": ["json5"]
41219 },
41220 "application/jsonml+json": {
41221 "source": "apache",
41222 "compressible": true,
41223 "extensions": ["jsonml"]
41224 },
41225 "application/jwk+json": {
41226 "source": "iana",
41227 "compressible": true
41228 },
41229 "application/jwk-set+json": {
41230 "source": "iana",
41231 "compressible": true
41232 },
41233 "application/jwt": {
41234 "source": "iana"
41235 },
41236 "application/kpml-request+xml": {
41237 "source": "iana",
41238 "compressible": true
41239 },
41240 "application/kpml-response+xml": {
41241 "source": "iana",
41242 "compressible": true
41243 },
41244 "application/ld+json": {
41245 "source": "iana",
41246 "compressible": true,
41247 "extensions": ["jsonld"]
41248 },
41249 "application/lgr+xml": {
41250 "source": "iana",
41251 "compressible": true
41252 },
41253 "application/link-format": {
41254 "source": "iana"
41255 },
41256 "application/load-control+xml": {
41257 "source": "iana",
41258 "compressible": true
41259 },
41260 "application/lost+xml": {
41261 "source": "iana",
41262 "compressible": true,
41263 "extensions": ["lostxml"]
41264 },
41265 "application/lostsync+xml": {
41266 "source": "iana",
41267 "compressible": true
41268 },
41269 "application/lxf": {
41270 "source": "iana"
41271 },
41272 "application/mac-binhex40": {
41273 "source": "iana",
41274 "extensions": ["hqx"]
41275 },
41276 "application/mac-compactpro": {
41277 "source": "apache",
41278 "extensions": ["cpt"]
41279 },
41280 "application/macwriteii": {
41281 "source": "iana"
41282 },
41283 "application/mads+xml": {
41284 "source": "iana",
41285 "compressible": true,
41286 "extensions": ["mads"]
41287 },
41288 "application/manifest+json": {
41289 "charset": "UTF-8",
41290 "compressible": true,
41291 "extensions": ["webmanifest"]
41292 },
41293 "application/marc": {
41294 "source": "iana",
41295 "extensions": ["mrc"]
41296 },
41297 "application/marcxml+xml": {
41298 "source": "iana",
41299 "compressible": true,
41300 "extensions": ["mrcx"]
41301 },
41302 "application/mathematica": {
41303 "source": "iana",
41304 "extensions": ["ma","nb","mb"]
41305 },
41306 "application/mathml+xml": {
41307 "source": "iana",
41308 "compressible": true,
41309 "extensions": ["mathml"]
41310 },
41311 "application/mathml-content+xml": {
41312 "source": "iana",
41313 "compressible": true
41314 },
41315 "application/mathml-presentation+xml": {
41316 "source": "iana",
41317 "compressible": true
41318 },
41319 "application/mbms-associated-procedure-description+xml": {
41320 "source": "iana",
41321 "compressible": true
41322 },
41323 "application/mbms-deregister+xml": {
41324 "source": "iana",
41325 "compressible": true
41326 },
41327 "application/mbms-envelope+xml": {
41328 "source": "iana",
41329 "compressible": true
41330 },
41331 "application/mbms-msk+xml": {
41332 "source": "iana",
41333 "compressible": true
41334 },
41335 "application/mbms-msk-response+xml": {
41336 "source": "iana",
41337 "compressible": true
41338 },
41339 "application/mbms-protection-description+xml": {
41340 "source": "iana",
41341 "compressible": true
41342 },
41343 "application/mbms-reception-report+xml": {
41344 "source": "iana",
41345 "compressible": true
41346 },
41347 "application/mbms-register+xml": {
41348 "source": "iana",
41349 "compressible": true
41350 },
41351 "application/mbms-register-response+xml": {
41352 "source": "iana",
41353 "compressible": true
41354 },
41355 "application/mbms-schedule+xml": {
41356 "source": "iana",
41357 "compressible": true
41358 },
41359 "application/mbms-user-service-description+xml": {
41360 "source": "iana",
41361 "compressible": true
41362 },
41363 "application/mbox": {
41364 "source": "iana",
41365 "extensions": ["mbox"]
41366 },
41367 "application/media-policy-dataset+xml": {
41368 "source": "iana",
41369 "compressible": true
41370 },
41371 "application/media_control+xml": {
41372 "source": "iana",
41373 "compressible": true
41374 },
41375 "application/mediaservercontrol+xml": {
41376 "source": "iana",
41377 "compressible": true,
41378 "extensions": ["mscml"]
41379 },
41380 "application/merge-patch+json": {
41381 "source": "iana",
41382 "compressible": true
41383 },
41384 "application/metalink+xml": {
41385 "source": "apache",
41386 "compressible": true,
41387 "extensions": ["metalink"]
41388 },
41389 "application/metalink4+xml": {
41390 "source": "iana",
41391 "compressible": true,
41392 "extensions": ["meta4"]
41393 },
41394 "application/mets+xml": {
41395 "source": "iana",
41396 "compressible": true,
41397 "extensions": ["mets"]
41398 },
41399 "application/mf4": {
41400 "source": "iana"
41401 },
41402 "application/mikey": {
41403 "source": "iana"
41404 },
41405 "application/mmt-aei+xml": {
41406 "source": "iana",
41407 "compressible": true
41408 },
41409 "application/mmt-usd+xml": {
41410 "source": "iana",
41411 "compressible": true
41412 },
41413 "application/mods+xml": {
41414 "source": "iana",
41415 "compressible": true,
41416 "extensions": ["mods"]
41417 },
41418 "application/moss-keys": {
41419 "source": "iana"
41420 },
41421 "application/moss-signature": {
41422 "source": "iana"
41423 },
41424 "application/mosskey-data": {
41425 "source": "iana"
41426 },
41427 "application/mosskey-request": {
41428 "source": "iana"
41429 },
41430 "application/mp21": {
41431 "source": "iana",
41432 "extensions": ["m21","mp21"]
41433 },
41434 "application/mp4": {
41435 "source": "iana",
41436 "extensions": ["mp4s","m4p"]
41437 },
41438 "application/mpeg4-generic": {
41439 "source": "iana"
41440 },
41441 "application/mpeg4-iod": {
41442 "source": "iana"
41443 },
41444 "application/mpeg4-iod-xmt": {
41445 "source": "iana"
41446 },
41447 "application/mrb-consumer+xml": {
41448 "source": "iana",
41449 "compressible": true
41450 },
41451 "application/mrb-publish+xml": {
41452 "source": "iana",
41453 "compressible": true
41454 },
41455 "application/msc-ivr+xml": {
41456 "source": "iana",
41457 "compressible": true
41458 },
41459 "application/msc-mixer+xml": {
41460 "source": "iana",
41461 "compressible": true
41462 },
41463 "application/msword": {
41464 "source": "iana",
41465 "compressible": false,
41466 "extensions": ["doc","dot"]
41467 },
41468 "application/mud+json": {
41469 "source": "iana",
41470 "compressible": true
41471 },
41472 "application/mxf": {
41473 "source": "iana",
41474 "extensions": ["mxf"]
41475 },
41476 "application/n-quads": {
41477 "source": "iana",
41478 "extensions": ["nq"]
41479 },
41480 "application/n-triples": {
41481 "source": "iana",
41482 "extensions": ["nt"]
41483 },
41484 "application/nasdata": {
41485 "source": "iana"
41486 },
41487 "application/news-checkgroups": {
41488 "source": "iana"
41489 },
41490 "application/news-groupinfo": {
41491 "source": "iana"
41492 },
41493 "application/news-transmission": {
41494 "source": "iana"
41495 },
41496 "application/nlsml+xml": {
41497 "source": "iana",
41498 "compressible": true
41499 },
41500 "application/node": {
41501 "source": "iana"
41502 },
41503 "application/nss": {
41504 "source": "iana"
41505 },
41506 "application/ocsp-request": {
41507 "source": "iana"
41508 },
41509 "application/ocsp-response": {
41510 "source": "iana"
41511 },
41512 "application/octet-stream": {
41513 "source": "iana",
41514 "compressible": false,
41515 "extensions": ["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"]
41516 },
41517 "application/oda": {
41518 "source": "iana",
41519 "extensions": ["oda"]
41520 },
41521 "application/odm+xml": {
41522 "source": "iana",
41523 "compressible": true
41524 },
41525 "application/odx": {
41526 "source": "iana"
41527 },
41528 "application/oebps-package+xml": {
41529 "source": "iana",
41530 "compressible": true,
41531 "extensions": ["opf"]
41532 },
41533 "application/ogg": {
41534 "source": "iana",
41535 "compressible": false,
41536 "extensions": ["ogx"]
41537 },
41538 "application/omdoc+xml": {
41539 "source": "apache",
41540 "compressible": true,
41541 "extensions": ["omdoc"]
41542 },
41543 "application/onenote": {
41544 "source": "apache",
41545 "extensions": ["onetoc","onetoc2","onetmp","onepkg"]
41546 },
41547 "application/oscore": {
41548 "source": "iana"
41549 },
41550 "application/oxps": {
41551 "source": "iana",
41552 "extensions": ["oxps"]
41553 },
41554 "application/p2p-overlay+xml": {
41555 "source": "iana",
41556 "compressible": true
41557 },
41558 "application/parityfec": {
41559 "source": "iana"
41560 },
41561 "application/passport": {
41562 "source": "iana"
41563 },
41564 "application/patch-ops-error+xml": {
41565 "source": "iana",
41566 "compressible": true,
41567 "extensions": ["xer"]
41568 },
41569 "application/pdf": {
41570 "source": "iana",
41571 "compressible": false,
41572 "extensions": ["pdf"]
41573 },
41574 "application/pdx": {
41575 "source": "iana"
41576 },
41577 "application/pem-certificate-chain": {
41578 "source": "iana"
41579 },
41580 "application/pgp-encrypted": {
41581 "source": "iana",
41582 "compressible": false,
41583 "extensions": ["pgp"]
41584 },
41585 "application/pgp-keys": {
41586 "source": "iana"
41587 },
41588 "application/pgp-signature": {
41589 "source": "iana",
41590 "extensions": ["asc","sig"]
41591 },
41592 "application/pics-rules": {
41593 "source": "apache",
41594 "extensions": ["prf"]
41595 },
41596 "application/pidf+xml": {
41597 "source": "iana",
41598 "compressible": true
41599 },
41600 "application/pidf-diff+xml": {
41601 "source": "iana",
41602 "compressible": true
41603 },
41604 "application/pkcs10": {
41605 "source": "iana",
41606 "extensions": ["p10"]
41607 },
41608 "application/pkcs12": {
41609 "source": "iana"
41610 },
41611 "application/pkcs7-mime": {
41612 "source": "iana",
41613 "extensions": ["p7m","p7c"]
41614 },
41615 "application/pkcs7-signature": {
41616 "source": "iana",
41617 "extensions": ["p7s"]
41618 },
41619 "application/pkcs8": {
41620 "source": "iana",
41621 "extensions": ["p8"]
41622 },
41623 "application/pkcs8-encrypted": {
41624 "source": "iana"
41625 },
41626 "application/pkix-attr-cert": {
41627 "source": "iana",
41628 "extensions": ["ac"]
41629 },
41630 "application/pkix-cert": {
41631 "source": "iana",
41632 "extensions": ["cer"]
41633 },
41634 "application/pkix-crl": {
41635 "source": "iana",
41636 "extensions": ["crl"]
41637 },
41638 "application/pkix-pkipath": {
41639 "source": "iana",
41640 "extensions": ["pkipath"]
41641 },
41642 "application/pkixcmp": {
41643 "source": "iana",
41644 "extensions": ["pki"]
41645 },
41646 "application/pls+xml": {
41647 "source": "iana",
41648 "compressible": true,
41649 "extensions": ["pls"]
41650 },
41651 "application/poc-settings+xml": {
41652 "source": "iana",
41653 "compressible": true
41654 },
41655 "application/postscript": {
41656 "source": "iana",
41657 "compressible": true,
41658 "extensions": ["ai","eps","ps"]
41659 },
41660 "application/ppsp-tracker+json": {
41661 "source": "iana",
41662 "compressible": true
41663 },
41664 "application/problem+json": {
41665 "source": "iana",
41666 "compressible": true
41667 },
41668 "application/problem+xml": {
41669 "source": "iana",
41670 "compressible": true
41671 },
41672 "application/provenance+xml": {
41673 "source": "iana",
41674 "compressible": true
41675 },
41676 "application/prs.alvestrand.titrax-sheet": {
41677 "source": "iana"
41678 },
41679 "application/prs.cww": {
41680 "source": "iana",
41681 "extensions": ["cww"]
41682 },
41683 "application/prs.hpub+zip": {
41684 "source": "iana",
41685 "compressible": false
41686 },
41687 "application/prs.nprend": {
41688 "source": "iana"
41689 },
41690 "application/prs.plucker": {
41691 "source": "iana"
41692 },
41693 "application/prs.rdf-xml-crypt": {
41694 "source": "iana"
41695 },
41696 "application/prs.xsf+xml": {
41697 "source": "iana",
41698 "compressible": true
41699 },
41700 "application/pskc+xml": {
41701 "source": "iana",
41702 "compressible": true,
41703 "extensions": ["pskcxml"]
41704 },
41705 "application/qsig": {
41706 "source": "iana"
41707 },
41708 "application/raml+yaml": {
41709 "compressible": true,
41710 "extensions": ["raml"]
41711 },
41712 "application/raptorfec": {
41713 "source": "iana"
41714 },
41715 "application/rdap+json": {
41716 "source": "iana",
41717 "compressible": true
41718 },
41719 "application/rdf+xml": {
41720 "source": "iana",
41721 "compressible": true,
41722 "extensions": ["rdf","owl"]
41723 },
41724 "application/reginfo+xml": {
41725 "source": "iana",
41726 "compressible": true,
41727 "extensions": ["rif"]
41728 },
41729 "application/relax-ng-compact-syntax": {
41730 "source": "iana",
41731 "extensions": ["rnc"]
41732 },
41733 "application/remote-printing": {
41734 "source": "iana"
41735 },
41736 "application/reputon+json": {
41737 "source": "iana",
41738 "compressible": true
41739 },
41740 "application/resource-lists+xml": {
41741 "source": "iana",
41742 "compressible": true,
41743 "extensions": ["rl"]
41744 },
41745 "application/resource-lists-diff+xml": {
41746 "source": "iana",
41747 "compressible": true,
41748 "extensions": ["rld"]
41749 },
41750 "application/rfc+xml": {
41751 "source": "iana",
41752 "compressible": true
41753 },
41754 "application/riscos": {
41755 "source": "iana"
41756 },
41757 "application/rlmi+xml": {
41758 "source": "iana",
41759 "compressible": true
41760 },
41761 "application/rls-services+xml": {
41762 "source": "iana",
41763 "compressible": true,
41764 "extensions": ["rs"]
41765 },
41766 "application/route-apd+xml": {
41767 "source": "iana",
41768 "compressible": true
41769 },
41770 "application/route-s-tsid+xml": {
41771 "source": "iana",
41772 "compressible": true
41773 },
41774 "application/route-usd+xml": {
41775 "source": "iana",
41776 "compressible": true
41777 },
41778 "application/rpki-ghostbusters": {
41779 "source": "iana",
41780 "extensions": ["gbr"]
41781 },
41782 "application/rpki-manifest": {
41783 "source": "iana",
41784 "extensions": ["mft"]
41785 },
41786 "application/rpki-publication": {
41787 "source": "iana"
41788 },
41789 "application/rpki-roa": {
41790 "source": "iana",
41791 "extensions": ["roa"]
41792 },
41793 "application/rpki-updown": {
41794 "source": "iana"
41795 },
41796 "application/rsd+xml": {
41797 "source": "apache",
41798 "compressible": true,
41799 "extensions": ["rsd"]
41800 },
41801 "application/rss+xml": {
41802 "source": "apache",
41803 "compressible": true,
41804 "extensions": ["rss"]
41805 },
41806 "application/rtf": {
41807 "source": "iana",
41808 "compressible": true,
41809 "extensions": ["rtf"]
41810 },
41811 "application/rtploopback": {
41812 "source": "iana"
41813 },
41814 "application/rtx": {
41815 "source": "iana"
41816 },
41817 "application/samlassertion+xml": {
41818 "source": "iana",
41819 "compressible": true
41820 },
41821 "application/samlmetadata+xml": {
41822 "source": "iana",
41823 "compressible": true
41824 },
41825 "application/sbml+xml": {
41826 "source": "iana",
41827 "compressible": true,
41828 "extensions": ["sbml"]
41829 },
41830 "application/scaip+xml": {
41831 "source": "iana",
41832 "compressible": true
41833 },
41834 "application/scim+json": {
41835 "source": "iana",
41836 "compressible": true
41837 },
41838 "application/scvp-cv-request": {
41839 "source": "iana",
41840 "extensions": ["scq"]
41841 },
41842 "application/scvp-cv-response": {
41843 "source": "iana",
41844 "extensions": ["scs"]
41845 },
41846 "application/scvp-vp-request": {
41847 "source": "iana",
41848 "extensions": ["spq"]
41849 },
41850 "application/scvp-vp-response": {
41851 "source": "iana",
41852 "extensions": ["spp"]
41853 },
41854 "application/sdp": {
41855 "source": "iana",
41856 "extensions": ["sdp"]
41857 },
41858 "application/secevent+jwt": {
41859 "source": "iana"
41860 },
41861 "application/senml+cbor": {
41862 "source": "iana"
41863 },
41864 "application/senml+json": {
41865 "source": "iana",
41866 "compressible": true
41867 },
41868 "application/senml+xml": {
41869 "source": "iana",
41870 "compressible": true
41871 },
41872 "application/senml-exi": {
41873 "source": "iana"
41874 },
41875 "application/sensml+cbor": {
41876 "source": "iana"
41877 },
41878 "application/sensml+json": {
41879 "source": "iana",
41880 "compressible": true
41881 },
41882 "application/sensml+xml": {
41883 "source": "iana",
41884 "compressible": true
41885 },
41886 "application/sensml-exi": {
41887 "source": "iana"
41888 },
41889 "application/sep+xml": {
41890 "source": "iana",
41891 "compressible": true
41892 },
41893 "application/sep-exi": {
41894 "source": "iana"
41895 },
41896 "application/session-info": {
41897 "source": "iana"
41898 },
41899 "application/set-payment": {
41900 "source": "iana"
41901 },
41902 "application/set-payment-initiation": {
41903 "source": "iana",
41904 "extensions": ["setpay"]
41905 },
41906 "application/set-registration": {
41907 "source": "iana"
41908 },
41909 "application/set-registration-initiation": {
41910 "source": "iana",
41911 "extensions": ["setreg"]
41912 },
41913 "application/sgml": {
41914 "source": "iana"
41915 },
41916 "application/sgml-open-catalog": {
41917 "source": "iana"
41918 },
41919 "application/shf+xml": {
41920 "source": "iana",
41921 "compressible": true,
41922 "extensions": ["shf"]
41923 },
41924 "application/sieve": {
41925 "source": "iana",
41926 "extensions": ["siv","sieve"]
41927 },
41928 "application/simple-filter+xml": {
41929 "source": "iana",
41930 "compressible": true
41931 },
41932 "application/simple-message-summary": {
41933 "source": "iana"
41934 },
41935 "application/simplesymbolcontainer": {
41936 "source": "iana"
41937 },
41938 "application/slate": {
41939 "source": "iana"
41940 },
41941 "application/smil": {
41942 "source": "iana"
41943 },
41944 "application/smil+xml": {
41945 "source": "iana",
41946 "compressible": true,
41947 "extensions": ["smi","smil"]
41948 },
41949 "application/smpte336m": {
41950 "source": "iana"
41951 },
41952 "application/soap+fastinfoset": {
41953 "source": "iana"
41954 },
41955 "application/soap+xml": {
41956 "source": "iana",
41957 "compressible": true
41958 },
41959 "application/sparql-query": {
41960 "source": "iana",
41961 "extensions": ["rq"]
41962 },
41963 "application/sparql-results+xml": {
41964 "source": "iana",
41965 "compressible": true,
41966 "extensions": ["srx"]
41967 },
41968 "application/spirits-event+xml": {
41969 "source": "iana",
41970 "compressible": true
41971 },
41972 "application/sql": {
41973 "source": "iana"
41974 },
41975 "application/srgs": {
41976 "source": "iana",
41977 "extensions": ["gram"]
41978 },
41979 "application/srgs+xml": {
41980 "source": "iana",
41981 "compressible": true,
41982 "extensions": ["grxml"]
41983 },
41984 "application/sru+xml": {
41985 "source": "iana",
41986 "compressible": true,
41987 "extensions": ["sru"]
41988 },
41989 "application/ssdl+xml": {
41990 "source": "apache",
41991 "compressible": true,
41992 "extensions": ["ssdl"]
41993 },
41994 "application/ssml+xml": {
41995 "source": "iana",
41996 "compressible": true,
41997 "extensions": ["ssml"]
41998 },
41999 "application/stix+json": {
42000 "source": "iana",
42001 "compressible": true
42002 },
42003 "application/tamp-apex-update": {
42004 "source": "iana"
42005 },
42006 "application/tamp-apex-update-confirm": {
42007 "source": "iana"
42008 },
42009 "application/tamp-community-update": {
42010 "source": "iana"
42011 },
42012 "application/tamp-community-update-confirm": {
42013 "source": "iana"
42014 },
42015 "application/tamp-error": {
42016 "source": "iana"
42017 },
42018 "application/tamp-sequence-adjust": {
42019 "source": "iana"
42020 },
42021 "application/tamp-sequence-adjust-confirm": {
42022 "source": "iana"
42023 },
42024 "application/tamp-status-query": {
42025 "source": "iana"
42026 },
42027 "application/tamp-status-response": {
42028 "source": "iana"
42029 },
42030 "application/tamp-update": {
42031 "source": "iana"
42032 },
42033 "application/tamp-update-confirm": {
42034 "source": "iana"
42035 },
42036 "application/tar": {
42037 "compressible": true
42038 },
42039 "application/taxii+json": {
42040 "source": "iana",
42041 "compressible": true
42042 },
42043 "application/tei+xml": {
42044 "source": "iana",
42045 "compressible": true,
42046 "extensions": ["tei","teicorpus"]
42047 },
42048 "application/tetra_isi": {
42049 "source": "iana"
42050 },
42051 "application/thraud+xml": {
42052 "source": "iana",
42053 "compressible": true,
42054 "extensions": ["tfi"]
42055 },
42056 "application/timestamp-query": {
42057 "source": "iana"
42058 },
42059 "application/timestamp-reply": {
42060 "source": "iana"
42061 },
42062 "application/timestamped-data": {
42063 "source": "iana",
42064 "extensions": ["tsd"]
42065 },
42066 "application/tlsrpt+gzip": {
42067 "source": "iana"
42068 },
42069 "application/tlsrpt+json": {
42070 "source": "iana",
42071 "compressible": true
42072 },
42073 "application/tnauthlist": {
42074 "source": "iana"
42075 },
42076 "application/trickle-ice-sdpfrag": {
42077 "source": "iana"
42078 },
42079 "application/trig": {
42080 "source": "iana"
42081 },
42082 "application/ttml+xml": {
42083 "source": "iana",
42084 "compressible": true
42085 },
42086 "application/tve-trigger": {
42087 "source": "iana"
42088 },
42089 "application/tzif": {
42090 "source": "iana"
42091 },
42092 "application/tzif-leap": {
42093 "source": "iana"
42094 },
42095 "application/ulpfec": {
42096 "source": "iana"
42097 },
42098 "application/urc-grpsheet+xml": {
42099 "source": "iana",
42100 "compressible": true
42101 },
42102 "application/urc-ressheet+xml": {
42103 "source": "iana",
42104 "compressible": true
42105 },
42106 "application/urc-targetdesc+xml": {
42107 "source": "iana",
42108 "compressible": true
42109 },
42110 "application/urc-uisocketdesc+xml": {
42111 "source": "iana",
42112 "compressible": true
42113 },
42114 "application/vcard+json": {
42115 "source": "iana",
42116 "compressible": true
42117 },
42118 "application/vcard+xml": {
42119 "source": "iana",
42120 "compressible": true
42121 },
42122 "application/vemmi": {
42123 "source": "iana"
42124 },
42125 "application/vividence.scriptfile": {
42126 "source": "apache"
42127 },
42128 "application/vnd.1000minds.decision-model+xml": {
42129 "source": "iana",
42130 "compressible": true
42131 },
42132 "application/vnd.3gpp-prose+xml": {
42133 "source": "iana",
42134 "compressible": true
42135 },
42136 "application/vnd.3gpp-prose-pc3ch+xml": {
42137 "source": "iana",
42138 "compressible": true
42139 },
42140 "application/vnd.3gpp-v2x-local-service-information": {
42141 "source": "iana"
42142 },
42143 "application/vnd.3gpp.access-transfer-events+xml": {
42144 "source": "iana",
42145 "compressible": true
42146 },
42147 "application/vnd.3gpp.bsf+xml": {
42148 "source": "iana",
42149 "compressible": true
42150 },
42151 "application/vnd.3gpp.gmop+xml": {
42152 "source": "iana",
42153 "compressible": true
42154 },
42155 "application/vnd.3gpp.mc-signalling-ear": {
42156 "source": "iana"
42157 },
42158 "application/vnd.3gpp.mcdata-affiliation-command+xml": {
42159 "source": "iana",
42160 "compressible": true
42161 },
42162 "application/vnd.3gpp.mcdata-info+xml": {
42163 "source": "iana",
42164 "compressible": true
42165 },
42166 "application/vnd.3gpp.mcdata-payload": {
42167 "source": "iana"
42168 },
42169 "application/vnd.3gpp.mcdata-service-config+xml": {
42170 "source": "iana",
42171 "compressible": true
42172 },
42173 "application/vnd.3gpp.mcdata-signalling": {
42174 "source": "iana"
42175 },
42176 "application/vnd.3gpp.mcdata-ue-config+xml": {
42177 "source": "iana",
42178 "compressible": true
42179 },
42180 "application/vnd.3gpp.mcdata-user-profile+xml": {
42181 "source": "iana",
42182 "compressible": true
42183 },
42184 "application/vnd.3gpp.mcptt-affiliation-command+xml": {
42185 "source": "iana",
42186 "compressible": true
42187 },
42188 "application/vnd.3gpp.mcptt-floor-request+xml": {
42189 "source": "iana",
42190 "compressible": true
42191 },
42192 "application/vnd.3gpp.mcptt-info+xml": {
42193 "source": "iana",
42194 "compressible": true
42195 },
42196 "application/vnd.3gpp.mcptt-location-info+xml": {
42197 "source": "iana",
42198 "compressible": true
42199 },
42200 "application/vnd.3gpp.mcptt-mbms-usage-info+xml": {
42201 "source": "iana",
42202 "compressible": true
42203 },
42204 "application/vnd.3gpp.mcptt-service-config+xml": {
42205 "source": "iana",
42206 "compressible": true
42207 },
42208 "application/vnd.3gpp.mcptt-signed+xml": {
42209 "source": "iana",
42210 "compressible": true
42211 },
42212 "application/vnd.3gpp.mcptt-ue-config+xml": {
42213 "source": "iana",
42214 "compressible": true
42215 },
42216 "application/vnd.3gpp.mcptt-ue-init-config+xml": {
42217 "source": "iana",
42218 "compressible": true
42219 },
42220 "application/vnd.3gpp.mcptt-user-profile+xml": {
42221 "source": "iana",
42222 "compressible": true
42223 },
42224 "application/vnd.3gpp.mcvideo-affiliation-command+xml": {
42225 "source": "iana",
42226 "compressible": true
42227 },
42228 "application/vnd.3gpp.mcvideo-affiliation-info+xml": {
42229 "source": "iana",
42230 "compressible": true
42231 },
42232 "application/vnd.3gpp.mcvideo-location-info+xml": {
42233 "source": "iana",
42234 "compressible": true
42235 },
42236 "application/vnd.3gpp.mcvideo-mbms-usage-info+xml": {
42237 "source": "iana",
42238 "compressible": true
42239 },
42240 "application/vnd.3gpp.mcvideo-service-config+xml": {
42241 "source": "iana",
42242 "compressible": true
42243 },
42244 "application/vnd.3gpp.mcvideo-transmission-request+xml": {
42245 "source": "iana",
42246 "compressible": true
42247 },
42248 "application/vnd.3gpp.mcvideo-ue-config+xml": {
42249 "source": "iana",
42250 "compressible": true
42251 },
42252 "application/vnd.3gpp.mcvideo-user-profile+xml": {
42253 "source": "iana",
42254 "compressible": true
42255 },
42256 "application/vnd.3gpp.mid-call+xml": {
42257 "source": "iana",
42258 "compressible": true
42259 },
42260 "application/vnd.3gpp.pic-bw-large": {
42261 "source": "iana",
42262 "extensions": ["plb"]
42263 },
42264 "application/vnd.3gpp.pic-bw-small": {
42265 "source": "iana",
42266 "extensions": ["psb"]
42267 },
42268 "application/vnd.3gpp.pic-bw-var": {
42269 "source": "iana",
42270 "extensions": ["pvb"]
42271 },
42272 "application/vnd.3gpp.sms": {
42273 "source": "iana"
42274 },
42275 "application/vnd.3gpp.sms+xml": {
42276 "source": "iana",
42277 "compressible": true
42278 },
42279 "application/vnd.3gpp.srvcc-ext+xml": {
42280 "source": "iana",
42281 "compressible": true
42282 },
42283 "application/vnd.3gpp.srvcc-info+xml": {
42284 "source": "iana",
42285 "compressible": true
42286 },
42287 "application/vnd.3gpp.state-and-event-info+xml": {
42288 "source": "iana",
42289 "compressible": true
42290 },
42291 "application/vnd.3gpp.ussd+xml": {
42292 "source": "iana",
42293 "compressible": true
42294 },
42295 "application/vnd.3gpp2.bcmcsinfo+xml": {
42296 "source": "iana",
42297 "compressible": true
42298 },
42299 "application/vnd.3gpp2.sms": {
42300 "source": "iana"
42301 },
42302 "application/vnd.3gpp2.tcap": {
42303 "source": "iana",
42304 "extensions": ["tcap"]
42305 },
42306 "application/vnd.3lightssoftware.imagescal": {
42307 "source": "iana"
42308 },
42309 "application/vnd.3m.post-it-notes": {
42310 "source": "iana",
42311 "extensions": ["pwn"]
42312 },
42313 "application/vnd.accpac.simply.aso": {
42314 "source": "iana",
42315 "extensions": ["aso"]
42316 },
42317 "application/vnd.accpac.simply.imp": {
42318 "source": "iana",
42319 "extensions": ["imp"]
42320 },
42321 "application/vnd.acucobol": {
42322 "source": "iana",
42323 "extensions": ["acu"]
42324 },
42325 "application/vnd.acucorp": {
42326 "source": "iana",
42327 "extensions": ["atc","acutc"]
42328 },
42329 "application/vnd.adobe.air-application-installer-package+zip": {
42330 "source": "apache",
42331 "compressible": false,
42332 "extensions": ["air"]
42333 },
42334 "application/vnd.adobe.flash.movie": {
42335 "source": "iana"
42336 },
42337 "application/vnd.adobe.formscentral.fcdt": {
42338 "source": "iana",
42339 "extensions": ["fcdt"]
42340 },
42341 "application/vnd.adobe.fxp": {
42342 "source": "iana",
42343 "extensions": ["fxp","fxpl"]
42344 },
42345 "application/vnd.adobe.partial-upload": {
42346 "source": "iana"
42347 },
42348 "application/vnd.adobe.xdp+xml": {
42349 "source": "iana",
42350 "compressible": true,
42351 "extensions": ["xdp"]
42352 },
42353 "application/vnd.adobe.xfdf": {
42354 "source": "iana",
42355 "extensions": ["xfdf"]
42356 },
42357 "application/vnd.aether.imp": {
42358 "source": "iana"
42359 },
42360 "application/vnd.afpc.afplinedata": {
42361 "source": "iana"
42362 },
42363 "application/vnd.afpc.modca": {
42364 "source": "iana"
42365 },
42366 "application/vnd.ah-barcode": {
42367 "source": "iana"
42368 },
42369 "application/vnd.ahead.space": {
42370 "source": "iana",
42371 "extensions": ["ahead"]
42372 },
42373 "application/vnd.airzip.filesecure.azf": {
42374 "source": "iana",
42375 "extensions": ["azf"]
42376 },
42377 "application/vnd.airzip.filesecure.azs": {
42378 "source": "iana",
42379 "extensions": ["azs"]
42380 },
42381 "application/vnd.amadeus+json": {
42382 "source": "iana",
42383 "compressible": true
42384 },
42385 "application/vnd.amazon.ebook": {
42386 "source": "apache",
42387 "extensions": ["azw"]
42388 },
42389 "application/vnd.amazon.mobi8-ebook": {
42390 "source": "iana"
42391 },
42392 "application/vnd.americandynamics.acc": {
42393 "source": "iana",
42394 "extensions": ["acc"]
42395 },
42396 "application/vnd.amiga.ami": {
42397 "source": "iana",
42398 "extensions": ["ami"]
42399 },
42400 "application/vnd.amundsen.maze+xml": {
42401 "source": "iana",
42402 "compressible": true
42403 },
42404 "application/vnd.android.package-archive": {
42405 "source": "apache",
42406 "compressible": false,
42407 "extensions": ["apk"]
42408 },
42409 "application/vnd.anki": {
42410 "source": "iana"
42411 },
42412 "application/vnd.anser-web-certificate-issue-initiation": {
42413 "source": "iana",
42414 "extensions": ["cii"]
42415 },
42416 "application/vnd.anser-web-funds-transfer-initiation": {
42417 "source": "apache",
42418 "extensions": ["fti"]
42419 },
42420 "application/vnd.antix.game-component": {
42421 "source": "iana",
42422 "extensions": ["atx"]
42423 },
42424 "application/vnd.apache.thrift.binary": {
42425 "source": "iana"
42426 },
42427 "application/vnd.apache.thrift.compact": {
42428 "source": "iana"
42429 },
42430 "application/vnd.apache.thrift.json": {
42431 "source": "iana"
42432 },
42433 "application/vnd.api+json": {
42434 "source": "iana",
42435 "compressible": true
42436 },
42437 "application/vnd.apothekende.reservation+json": {
42438 "source": "iana",
42439 "compressible": true
42440 },
42441 "application/vnd.apple.installer+xml": {
42442 "source": "iana",
42443 "compressible": true,
42444 "extensions": ["mpkg"]
42445 },
42446 "application/vnd.apple.keynote": {
42447 "source": "iana",
42448 "extensions": ["keynote"]
42449 },
42450 "application/vnd.apple.mpegurl": {
42451 "source": "iana",
42452 "extensions": ["m3u8"]
42453 },
42454 "application/vnd.apple.numbers": {
42455 "source": "iana",
42456 "extensions": ["numbers"]
42457 },
42458 "application/vnd.apple.pages": {
42459 "source": "iana",
42460 "extensions": ["pages"]
42461 },
42462 "application/vnd.apple.pkpass": {
42463 "compressible": false,
42464 "extensions": ["pkpass"]
42465 },
42466 "application/vnd.arastra.swi": {
42467 "source": "iana"
42468 },
42469 "application/vnd.aristanetworks.swi": {
42470 "source": "iana",
42471 "extensions": ["swi"]
42472 },
42473 "application/vnd.artisan+json": {
42474 "source": "iana",
42475 "compressible": true
42476 },
42477 "application/vnd.artsquare": {
42478 "source": "iana"
42479 },
42480 "application/vnd.astraea-software.iota": {
42481 "source": "iana",
42482 "extensions": ["iota"]
42483 },
42484 "application/vnd.audiograph": {
42485 "source": "iana",
42486 "extensions": ["aep"]
42487 },
42488 "application/vnd.autopackage": {
42489 "source": "iana"
42490 },
42491 "application/vnd.avalon+json": {
42492 "source": "iana",
42493 "compressible": true
42494 },
42495 "application/vnd.avistar+xml": {
42496 "source": "iana",
42497 "compressible": true
42498 },
42499 "application/vnd.balsamiq.bmml+xml": {
42500 "source": "iana",
42501 "compressible": true
42502 },
42503 "application/vnd.balsamiq.bmpr": {
42504 "source": "iana"
42505 },
42506 "application/vnd.banana-accounting": {
42507 "source": "iana"
42508 },
42509 "application/vnd.bbf.usp.msg": {
42510 "source": "iana"
42511 },
42512 "application/vnd.bbf.usp.msg+json": {
42513 "source": "iana",
42514 "compressible": true
42515 },
42516 "application/vnd.bekitzur-stech+json": {
42517 "source": "iana",
42518 "compressible": true
42519 },
42520 "application/vnd.bint.med-content": {
42521 "source": "iana"
42522 },
42523 "application/vnd.biopax.rdf+xml": {
42524 "source": "iana",
42525 "compressible": true
42526 },
42527 "application/vnd.blink-idb-value-wrapper": {
42528 "source": "iana"
42529 },
42530 "application/vnd.blueice.multipass": {
42531 "source": "iana",
42532 "extensions": ["mpm"]
42533 },
42534 "application/vnd.bluetooth.ep.oob": {
42535 "source": "iana"
42536 },
42537 "application/vnd.bluetooth.le.oob": {
42538 "source": "iana"
42539 },
42540 "application/vnd.bmi": {
42541 "source": "iana",
42542 "extensions": ["bmi"]
42543 },
42544 "application/vnd.businessobjects": {
42545 "source": "iana",
42546 "extensions": ["rep"]
42547 },
42548 "application/vnd.byu.uapi+json": {
42549 "source": "iana",
42550 "compressible": true
42551 },
42552 "application/vnd.cab-jscript": {
42553 "source": "iana"
42554 },
42555 "application/vnd.canon-cpdl": {
42556 "source": "iana"
42557 },
42558 "application/vnd.canon-lips": {
42559 "source": "iana"
42560 },
42561 "application/vnd.capasystems-pg+json": {
42562 "source": "iana",
42563 "compressible": true
42564 },
42565 "application/vnd.cendio.thinlinc.clientconf": {
42566 "source": "iana"
42567 },
42568 "application/vnd.century-systems.tcp_stream": {
42569 "source": "iana"
42570 },
42571 "application/vnd.chemdraw+xml": {
42572 "source": "iana",
42573 "compressible": true,
42574 "extensions": ["cdxml"]
42575 },
42576 "application/vnd.chess-pgn": {
42577 "source": "iana"
42578 },
42579 "application/vnd.chipnuts.karaoke-mmd": {
42580 "source": "iana",
42581 "extensions": ["mmd"]
42582 },
42583 "application/vnd.cinderella": {
42584 "source": "iana",
42585 "extensions": ["cdy"]
42586 },
42587 "application/vnd.cirpack.isdn-ext": {
42588 "source": "iana"
42589 },
42590 "application/vnd.citationstyles.style+xml": {
42591 "source": "iana",
42592 "compressible": true,
42593 "extensions": ["csl"]
42594 },
42595 "application/vnd.claymore": {
42596 "source": "iana",
42597 "extensions": ["cla"]
42598 },
42599 "application/vnd.cloanto.rp9": {
42600 "source": "iana",
42601 "extensions": ["rp9"]
42602 },
42603 "application/vnd.clonk.c4group": {
42604 "source": "iana",
42605 "extensions": ["c4g","c4d","c4f","c4p","c4u"]
42606 },
42607 "application/vnd.cluetrust.cartomobile-config": {
42608 "source": "iana",
42609 "extensions": ["c11amc"]
42610 },
42611 "application/vnd.cluetrust.cartomobile-config-pkg": {
42612 "source": "iana",
42613 "extensions": ["c11amz"]
42614 },
42615 "application/vnd.coffeescript": {
42616 "source": "iana"
42617 },
42618 "application/vnd.collabio.xodocuments.document": {
42619 "source": "iana"
42620 },
42621 "application/vnd.collabio.xodocuments.document-template": {
42622 "source": "iana"
42623 },
42624 "application/vnd.collabio.xodocuments.presentation": {
42625 "source": "iana"
42626 },
42627 "application/vnd.collabio.xodocuments.presentation-template": {
42628 "source": "iana"
42629 },
42630 "application/vnd.collabio.xodocuments.spreadsheet": {
42631 "source": "iana"
42632 },
42633 "application/vnd.collabio.xodocuments.spreadsheet-template": {
42634 "source": "iana"
42635 },
42636 "application/vnd.collection+json": {
42637 "source": "iana",
42638 "compressible": true
42639 },
42640 "application/vnd.collection.doc+json": {
42641 "source": "iana",
42642 "compressible": true
42643 },
42644 "application/vnd.collection.next+json": {
42645 "source": "iana",
42646 "compressible": true
42647 },
42648 "application/vnd.comicbook+zip": {
42649 "source": "iana",
42650 "compressible": false
42651 },
42652 "application/vnd.comicbook-rar": {
42653 "source": "iana"
42654 },
42655 "application/vnd.commerce-battelle": {
42656 "source": "iana"
42657 },
42658 "application/vnd.commonspace": {
42659 "source": "iana",
42660 "extensions": ["csp"]
42661 },
42662 "application/vnd.contact.cmsg": {
42663 "source": "iana",
42664 "extensions": ["cdbcmsg"]
42665 },
42666 "application/vnd.coreos.ignition+json": {
42667 "source": "iana",
42668 "compressible": true
42669 },
42670 "application/vnd.cosmocaller": {
42671 "source": "iana",
42672 "extensions": ["cmc"]
42673 },
42674 "application/vnd.crick.clicker": {
42675 "source": "iana",
42676 "extensions": ["clkx"]
42677 },
42678 "application/vnd.crick.clicker.keyboard": {
42679 "source": "iana",
42680 "extensions": ["clkk"]
42681 },
42682 "application/vnd.crick.clicker.palette": {
42683 "source": "iana",
42684 "extensions": ["clkp"]
42685 },
42686 "application/vnd.crick.clicker.template": {
42687 "source": "iana",
42688 "extensions": ["clkt"]
42689 },
42690 "application/vnd.crick.clicker.wordbank": {
42691 "source": "iana",
42692 "extensions": ["clkw"]
42693 },
42694 "application/vnd.criticaltools.wbs+xml": {
42695 "source": "iana",
42696 "compressible": true,
42697 "extensions": ["wbs"]
42698 },
42699 "application/vnd.ctc-posml": {
42700 "source": "iana",
42701 "extensions": ["pml"]
42702 },
42703 "application/vnd.ctct.ws+xml": {
42704 "source": "iana",
42705 "compressible": true
42706 },
42707 "application/vnd.cups-pdf": {
42708 "source": "iana"
42709 },
42710 "application/vnd.cups-postscript": {
42711 "source": "iana"
42712 },
42713 "application/vnd.cups-ppd": {
42714 "source": "iana",
42715 "extensions": ["ppd"]
42716 },
42717 "application/vnd.cups-raster": {
42718 "source": "iana"
42719 },
42720 "application/vnd.cups-raw": {
42721 "source": "iana"
42722 },
42723 "application/vnd.curl": {
42724 "source": "iana"
42725 },
42726 "application/vnd.curl.car": {
42727 "source": "apache",
42728 "extensions": ["car"]
42729 },
42730 "application/vnd.curl.pcurl": {
42731 "source": "apache",
42732 "extensions": ["pcurl"]
42733 },
42734 "application/vnd.cyan.dean.root+xml": {
42735 "source": "iana",
42736 "compressible": true
42737 },
42738 "application/vnd.cybank": {
42739 "source": "iana"
42740 },
42741 "application/vnd.d2l.coursepackage1p0+zip": {
42742 "source": "iana",
42743 "compressible": false
42744 },
42745 "application/vnd.dart": {
42746 "source": "iana",
42747 "compressible": true,
42748 "extensions": ["dart"]
42749 },
42750 "application/vnd.data-vision.rdz": {
42751 "source": "iana",
42752 "extensions": ["rdz"]
42753 },
42754 "application/vnd.datapackage+json": {
42755 "source": "iana",
42756 "compressible": true
42757 },
42758 "application/vnd.dataresource+json": {
42759 "source": "iana",
42760 "compressible": true
42761 },
42762 "application/vnd.debian.binary-package": {
42763 "source": "iana"
42764 },
42765 "application/vnd.dece.data": {
42766 "source": "iana",
42767 "extensions": ["uvf","uvvf","uvd","uvvd"]
42768 },
42769 "application/vnd.dece.ttml+xml": {
42770 "source": "iana",
42771 "compressible": true,
42772 "extensions": ["uvt","uvvt"]
42773 },
42774 "application/vnd.dece.unspecified": {
42775 "source": "iana",
42776 "extensions": ["uvx","uvvx"]
42777 },
42778 "application/vnd.dece.zip": {
42779 "source": "iana",
42780 "extensions": ["uvz","uvvz"]
42781 },
42782 "application/vnd.denovo.fcselayout-link": {
42783 "source": "iana",
42784 "extensions": ["fe_launch"]
42785 },
42786 "application/vnd.desmume.movie": {
42787 "source": "iana"
42788 },
42789 "application/vnd.dir-bi.plate-dl-nosuffix": {
42790 "source": "iana"
42791 },
42792 "application/vnd.dm.delegation+xml": {
42793 "source": "iana",
42794 "compressible": true
42795 },
42796 "application/vnd.dna": {
42797 "source": "iana",
42798 "extensions": ["dna"]
42799 },
42800 "application/vnd.document+json": {
42801 "source": "iana",
42802 "compressible": true
42803 },
42804 "application/vnd.dolby.mlp": {
42805 "source": "apache",
42806 "extensions": ["mlp"]
42807 },
42808 "application/vnd.dolby.mobile.1": {
42809 "source": "iana"
42810 },
42811 "application/vnd.dolby.mobile.2": {
42812 "source": "iana"
42813 },
42814 "application/vnd.doremir.scorecloud-binary-document": {
42815 "source": "iana"
42816 },
42817 "application/vnd.dpgraph": {
42818 "source": "iana",
42819 "extensions": ["dpg"]
42820 },
42821 "application/vnd.dreamfactory": {
42822 "source": "iana",
42823 "extensions": ["dfac"]
42824 },
42825 "application/vnd.drive+json": {
42826 "source": "iana",
42827 "compressible": true
42828 },
42829 "application/vnd.ds-keypoint": {
42830 "source": "apache",
42831 "extensions": ["kpxx"]
42832 },
42833 "application/vnd.dtg.local": {
42834 "source": "iana"
42835 },
42836 "application/vnd.dtg.local.flash": {
42837 "source": "iana"
42838 },
42839 "application/vnd.dtg.local.html": {
42840 "source": "iana"
42841 },
42842 "application/vnd.dvb.ait": {
42843 "source": "iana",
42844 "extensions": ["ait"]
42845 },
42846 "application/vnd.dvb.dvbj": {
42847 "source": "iana"
42848 },
42849 "application/vnd.dvb.esgcontainer": {
42850 "source": "iana"
42851 },
42852 "application/vnd.dvb.ipdcdftnotifaccess": {
42853 "source": "iana"
42854 },
42855 "application/vnd.dvb.ipdcesgaccess": {
42856 "source": "iana"
42857 },
42858 "application/vnd.dvb.ipdcesgaccess2": {
42859 "source": "iana"
42860 },
42861 "application/vnd.dvb.ipdcesgpdd": {
42862 "source": "iana"
42863 },
42864 "application/vnd.dvb.ipdcroaming": {
42865 "source": "iana"
42866 },
42867 "application/vnd.dvb.iptv.alfec-base": {
42868 "source": "iana"
42869 },
42870 "application/vnd.dvb.iptv.alfec-enhancement": {
42871 "source": "iana"
42872 },
42873 "application/vnd.dvb.notif-aggregate-root+xml": {
42874 "source": "iana",
42875 "compressible": true
42876 },
42877 "application/vnd.dvb.notif-container+xml": {
42878 "source": "iana",
42879 "compressible": true
42880 },
42881 "application/vnd.dvb.notif-generic+xml": {
42882 "source": "iana",
42883 "compressible": true
42884 },
42885 "application/vnd.dvb.notif-ia-msglist+xml": {
42886 "source": "iana",
42887 "compressible": true
42888 },
42889 "application/vnd.dvb.notif-ia-registration-request+xml": {
42890 "source": "iana",
42891 "compressible": true
42892 },
42893 "application/vnd.dvb.notif-ia-registration-response+xml": {
42894 "source": "iana",
42895 "compressible": true
42896 },
42897 "application/vnd.dvb.notif-init+xml": {
42898 "source": "iana",
42899 "compressible": true
42900 },
42901 "application/vnd.dvb.pfr": {
42902 "source": "iana"
42903 },
42904 "application/vnd.dvb.service": {
42905 "source": "iana",
42906 "extensions": ["svc"]
42907 },
42908 "application/vnd.dxr": {
42909 "source": "iana"
42910 },
42911 "application/vnd.dynageo": {
42912 "source": "iana",
42913 "extensions": ["geo"]
42914 },
42915 "application/vnd.dzr": {
42916 "source": "iana"
42917 },
42918 "application/vnd.easykaraoke.cdgdownload": {
42919 "source": "iana"
42920 },
42921 "application/vnd.ecdis-update": {
42922 "source": "iana"
42923 },
42924 "application/vnd.ecip.rlp": {
42925 "source": "iana"
42926 },
42927 "application/vnd.ecowin.chart": {
42928 "source": "iana",
42929 "extensions": ["mag"]
42930 },
42931 "application/vnd.ecowin.filerequest": {
42932 "source": "iana"
42933 },
42934 "application/vnd.ecowin.fileupdate": {
42935 "source": "iana"
42936 },
42937 "application/vnd.ecowin.series": {
42938 "source": "iana"
42939 },
42940 "application/vnd.ecowin.seriesrequest": {
42941 "source": "iana"
42942 },
42943 "application/vnd.ecowin.seriesupdate": {
42944 "source": "iana"
42945 },
42946 "application/vnd.efi.img": {
42947 "source": "iana"
42948 },
42949 "application/vnd.efi.iso": {
42950 "source": "iana"
42951 },
42952 "application/vnd.emclient.accessrequest+xml": {
42953 "source": "iana",
42954 "compressible": true
42955 },
42956 "application/vnd.enliven": {
42957 "source": "iana",
42958 "extensions": ["nml"]
42959 },
42960 "application/vnd.enphase.envoy": {
42961 "source": "iana"
42962 },
42963 "application/vnd.eprints.data+xml": {
42964 "source": "iana",
42965 "compressible": true
42966 },
42967 "application/vnd.epson.esf": {
42968 "source": "iana",
42969 "extensions": ["esf"]
42970 },
42971 "application/vnd.epson.msf": {
42972 "source": "iana",
42973 "extensions": ["msf"]
42974 },
42975 "application/vnd.epson.quickanime": {
42976 "source": "iana",
42977 "extensions": ["qam"]
42978 },
42979 "application/vnd.epson.salt": {
42980 "source": "iana",
42981 "extensions": ["slt"]
42982 },
42983 "application/vnd.epson.ssf": {
42984 "source": "iana",
42985 "extensions": ["ssf"]
42986 },
42987 "application/vnd.ericsson.quickcall": {
42988 "source": "iana"
42989 },
42990 "application/vnd.espass-espass+zip": {
42991 "source": "iana",
42992 "compressible": false
42993 },
42994 "application/vnd.eszigno3+xml": {
42995 "source": "iana",
42996 "compressible": true,
42997 "extensions": ["es3","et3"]
42998 },
42999 "application/vnd.etsi.aoc+xml": {
43000 "source": "iana",
43001 "compressible": true
43002 },
43003 "application/vnd.etsi.asic-e+zip": {
43004 "source": "iana",
43005 "compressible": false
43006 },
43007 "application/vnd.etsi.asic-s+zip": {
43008 "source": "iana",
43009 "compressible": false
43010 },
43011 "application/vnd.etsi.cug+xml": {
43012 "source": "iana",
43013 "compressible": true
43014 },
43015 "application/vnd.etsi.iptvcommand+xml": {
43016 "source": "iana",
43017 "compressible": true
43018 },
43019 "application/vnd.etsi.iptvdiscovery+xml": {
43020 "source": "iana",
43021 "compressible": true
43022 },
43023 "application/vnd.etsi.iptvprofile+xml": {
43024 "source": "iana",
43025 "compressible": true
43026 },
43027 "application/vnd.etsi.iptvsad-bc+xml": {
43028 "source": "iana",
43029 "compressible": true
43030 },
43031 "application/vnd.etsi.iptvsad-cod+xml": {
43032 "source": "iana",
43033 "compressible": true
43034 },
43035 "application/vnd.etsi.iptvsad-npvr+xml": {
43036 "source": "iana",
43037 "compressible": true
43038 },
43039 "application/vnd.etsi.iptvservice+xml": {
43040 "source": "iana",
43041 "compressible": true
43042 },
43043 "application/vnd.etsi.iptvsync+xml": {
43044 "source": "iana",
43045 "compressible": true
43046 },
43047 "application/vnd.etsi.iptvueprofile+xml": {
43048 "source": "iana",
43049 "compressible": true
43050 },
43051 "application/vnd.etsi.mcid+xml": {
43052 "source": "iana",
43053 "compressible": true
43054 },
43055 "application/vnd.etsi.mheg5": {
43056 "source": "iana"
43057 },
43058 "application/vnd.etsi.overload-control-policy-dataset+xml": {
43059 "source": "iana",
43060 "compressible": true
43061 },
43062 "application/vnd.etsi.pstn+xml": {
43063 "source": "iana",
43064 "compressible": true
43065 },
43066 "application/vnd.etsi.sci+xml": {
43067 "source": "iana",
43068 "compressible": true
43069 },
43070 "application/vnd.etsi.simservs+xml": {
43071 "source": "iana",
43072 "compressible": true
43073 },
43074 "application/vnd.etsi.timestamp-token": {
43075 "source": "iana"
43076 },
43077 "application/vnd.etsi.tsl+xml": {
43078 "source": "iana",
43079 "compressible": true
43080 },
43081 "application/vnd.etsi.tsl.der": {
43082 "source": "iana"
43083 },
43084 "application/vnd.eudora.data": {
43085 "source": "iana"
43086 },
43087 "application/vnd.evolv.ecig.profile": {
43088 "source": "iana"
43089 },
43090 "application/vnd.evolv.ecig.settings": {
43091 "source": "iana"
43092 },
43093 "application/vnd.evolv.ecig.theme": {
43094 "source": "iana"
43095 },
43096 "application/vnd.exstream-empower+zip": {
43097 "source": "iana",
43098 "compressible": false
43099 },
43100 "application/vnd.exstream-package": {
43101 "source": "iana"
43102 },
43103 "application/vnd.ezpix-album": {
43104 "source": "iana",
43105 "extensions": ["ez2"]
43106 },
43107 "application/vnd.ezpix-package": {
43108 "source": "iana",
43109 "extensions": ["ez3"]
43110 },
43111 "application/vnd.f-secure.mobile": {
43112 "source": "iana"
43113 },
43114 "application/vnd.fastcopy-disk-image": {
43115 "source": "iana"
43116 },
43117 "application/vnd.fdf": {
43118 "source": "iana",
43119 "extensions": ["fdf"]
43120 },
43121 "application/vnd.fdsn.mseed": {
43122 "source": "iana",
43123 "extensions": ["mseed"]
43124 },
43125 "application/vnd.fdsn.seed": {
43126 "source": "iana",
43127 "extensions": ["seed","dataless"]
43128 },
43129 "application/vnd.ffsns": {
43130 "source": "iana"
43131 },
43132 "application/vnd.filmit.zfc": {
43133 "source": "iana"
43134 },
43135 "application/vnd.fints": {
43136 "source": "iana"
43137 },
43138 "application/vnd.firemonkeys.cloudcell": {
43139 "source": "iana"
43140 },
43141 "application/vnd.flographit": {
43142 "source": "iana",
43143 "extensions": ["gph"]
43144 },
43145 "application/vnd.fluxtime.clip": {
43146 "source": "iana",
43147 "extensions": ["ftc"]
43148 },
43149 "application/vnd.font-fontforge-sfd": {
43150 "source": "iana"
43151 },
43152 "application/vnd.framemaker": {
43153 "source": "iana",
43154 "extensions": ["fm","frame","maker","book"]
43155 },
43156 "application/vnd.frogans.fnc": {
43157 "source": "iana",
43158 "extensions": ["fnc"]
43159 },
43160 "application/vnd.frogans.ltf": {
43161 "source": "iana",
43162 "extensions": ["ltf"]
43163 },
43164 "application/vnd.fsc.weblaunch": {
43165 "source": "iana",
43166 "extensions": ["fsc"]
43167 },
43168 "application/vnd.fujitsu.oasys": {
43169 "source": "iana",
43170 "extensions": ["oas"]
43171 },
43172 "application/vnd.fujitsu.oasys2": {
43173 "source": "iana",
43174 "extensions": ["oa2"]
43175 },
43176 "application/vnd.fujitsu.oasys3": {
43177 "source": "iana",
43178 "extensions": ["oa3"]
43179 },
43180 "application/vnd.fujitsu.oasysgp": {
43181 "source": "iana",
43182 "extensions": ["fg5"]
43183 },
43184 "application/vnd.fujitsu.oasysprs": {
43185 "source": "iana",
43186 "extensions": ["bh2"]
43187 },
43188 "application/vnd.fujixerox.art-ex": {
43189 "source": "iana"
43190 },
43191 "application/vnd.fujixerox.art4": {
43192 "source": "iana"
43193 },
43194 "application/vnd.fujixerox.ddd": {
43195 "source": "iana",
43196 "extensions": ["ddd"]
43197 },
43198 "application/vnd.fujixerox.docuworks": {
43199 "source": "iana",
43200 "extensions": ["xdw"]
43201 },
43202 "application/vnd.fujixerox.docuworks.binder": {
43203 "source": "iana",
43204 "extensions": ["xbd"]
43205 },
43206 "application/vnd.fujixerox.docuworks.container": {
43207 "source": "iana"
43208 },
43209 "application/vnd.fujixerox.hbpl": {
43210 "source": "iana"
43211 },
43212 "application/vnd.fut-misnet": {
43213 "source": "iana"
43214 },
43215 "application/vnd.futoin+cbor": {
43216 "source": "iana"
43217 },
43218 "application/vnd.futoin+json": {
43219 "source": "iana",
43220 "compressible": true
43221 },
43222 "application/vnd.fuzzysheet": {
43223 "source": "iana",
43224 "extensions": ["fzs"]
43225 },
43226 "application/vnd.genomatix.tuxedo": {
43227 "source": "iana",
43228 "extensions": ["txd"]
43229 },
43230 "application/vnd.geo+json": {
43231 "source": "iana",
43232 "compressible": true
43233 },
43234 "application/vnd.geocube+xml": {
43235 "source": "iana",
43236 "compressible": true
43237 },
43238 "application/vnd.geogebra.file": {
43239 "source": "iana",
43240 "extensions": ["ggb"]
43241 },
43242 "application/vnd.geogebra.tool": {
43243 "source": "iana",
43244 "extensions": ["ggt"]
43245 },
43246 "application/vnd.geometry-explorer": {
43247 "source": "iana",
43248 "extensions": ["gex","gre"]
43249 },
43250 "application/vnd.geonext": {
43251 "source": "iana",
43252 "extensions": ["gxt"]
43253 },
43254 "application/vnd.geoplan": {
43255 "source": "iana",
43256 "extensions": ["g2w"]
43257 },
43258 "application/vnd.geospace": {
43259 "source": "iana",
43260 "extensions": ["g3w"]
43261 },
43262 "application/vnd.gerber": {
43263 "source": "iana"
43264 },
43265 "application/vnd.globalplatform.card-content-mgt": {
43266 "source": "iana"
43267 },
43268 "application/vnd.globalplatform.card-content-mgt-response": {
43269 "source": "iana"
43270 },
43271 "application/vnd.gmx": {
43272 "source": "iana",
43273 "extensions": ["gmx"]
43274 },
43275 "application/vnd.google-apps.document": {
43276 "compressible": false,
43277 "extensions": ["gdoc"]
43278 },
43279 "application/vnd.google-apps.presentation": {
43280 "compressible": false,
43281 "extensions": ["gslides"]
43282 },
43283 "application/vnd.google-apps.spreadsheet": {
43284 "compressible": false,
43285 "extensions": ["gsheet"]
43286 },
43287 "application/vnd.google-earth.kml+xml": {
43288 "source": "iana",
43289 "compressible": true,
43290 "extensions": ["kml"]
43291 },
43292 "application/vnd.google-earth.kmz": {
43293 "source": "iana",
43294 "compressible": false,
43295 "extensions": ["kmz"]
43296 },
43297 "application/vnd.gov.sk.e-form+xml": {
43298 "source": "iana",
43299 "compressible": true
43300 },
43301 "application/vnd.gov.sk.e-form+zip": {
43302 "source": "iana",
43303 "compressible": false
43304 },
43305 "application/vnd.gov.sk.xmldatacontainer+xml": {
43306 "source": "iana",
43307 "compressible": true
43308 },
43309 "application/vnd.grafeq": {
43310 "source": "iana",
43311 "extensions": ["gqf","gqs"]
43312 },
43313 "application/vnd.gridmp": {
43314 "source": "iana"
43315 },
43316 "application/vnd.groove-account": {
43317 "source": "iana",
43318 "extensions": ["gac"]
43319 },
43320 "application/vnd.groove-help": {
43321 "source": "iana",
43322 "extensions": ["ghf"]
43323 },
43324 "application/vnd.groove-identity-message": {
43325 "source": "iana",
43326 "extensions": ["gim"]
43327 },
43328 "application/vnd.groove-injector": {
43329 "source": "iana",
43330 "extensions": ["grv"]
43331 },
43332 "application/vnd.groove-tool-message": {
43333 "source": "iana",
43334 "extensions": ["gtm"]
43335 },
43336 "application/vnd.groove-tool-template": {
43337 "source": "iana",
43338 "extensions": ["tpl"]
43339 },
43340 "application/vnd.groove-vcard": {
43341 "source": "iana",
43342 "extensions": ["vcg"]
43343 },
43344 "application/vnd.hal+json": {
43345 "source": "iana",
43346 "compressible": true
43347 },
43348 "application/vnd.hal+xml": {
43349 "source": "iana",
43350 "compressible": true,
43351 "extensions": ["hal"]
43352 },
43353 "application/vnd.handheld-entertainment+xml": {
43354 "source": "iana",
43355 "compressible": true,
43356 "extensions": ["zmm"]
43357 },
43358 "application/vnd.hbci": {
43359 "source": "iana",
43360 "extensions": ["hbci"]
43361 },
43362 "application/vnd.hc+json": {
43363 "source": "iana",
43364 "compressible": true
43365 },
43366 "application/vnd.hcl-bireports": {
43367 "source": "iana"
43368 },
43369 "application/vnd.hdt": {
43370 "source": "iana"
43371 },
43372 "application/vnd.heroku+json": {
43373 "source": "iana",
43374 "compressible": true
43375 },
43376 "application/vnd.hhe.lesson-player": {
43377 "source": "iana",
43378 "extensions": ["les"]
43379 },
43380 "application/vnd.hp-hpgl": {
43381 "source": "iana",
43382 "extensions": ["hpgl"]
43383 },
43384 "application/vnd.hp-hpid": {
43385 "source": "iana",
43386 "extensions": ["hpid"]
43387 },
43388 "application/vnd.hp-hps": {
43389 "source": "iana",
43390 "extensions": ["hps"]
43391 },
43392 "application/vnd.hp-jlyt": {
43393 "source": "iana",
43394 "extensions": ["jlt"]
43395 },
43396 "application/vnd.hp-pcl": {
43397 "source": "iana",
43398 "extensions": ["pcl"]
43399 },
43400 "application/vnd.hp-pclxl": {
43401 "source": "iana",
43402 "extensions": ["pclxl"]
43403 },
43404 "application/vnd.httphone": {
43405 "source": "iana"
43406 },
43407 "application/vnd.hydrostatix.sof-data": {
43408 "source": "iana",
43409 "extensions": ["sfd-hdstx"]
43410 },
43411 "application/vnd.hyper+json": {
43412 "source": "iana",
43413 "compressible": true
43414 },
43415 "application/vnd.hyper-item+json": {
43416 "source": "iana",
43417 "compressible": true
43418 },
43419 "application/vnd.hyperdrive+json": {
43420 "source": "iana",
43421 "compressible": true
43422 },
43423 "application/vnd.hzn-3d-crossword": {
43424 "source": "iana"
43425 },
43426 "application/vnd.ibm.afplinedata": {
43427 "source": "iana"
43428 },
43429 "application/vnd.ibm.electronic-media": {
43430 "source": "iana"
43431 },
43432 "application/vnd.ibm.minipay": {
43433 "source": "iana",
43434 "extensions": ["mpy"]
43435 },
43436 "application/vnd.ibm.modcap": {
43437 "source": "iana",
43438 "extensions": ["afp","listafp","list3820"]
43439 },
43440 "application/vnd.ibm.rights-management": {
43441 "source": "iana",
43442 "extensions": ["irm"]
43443 },
43444 "application/vnd.ibm.secure-container": {
43445 "source": "iana",
43446 "extensions": ["sc"]
43447 },
43448 "application/vnd.iccprofile": {
43449 "source": "iana",
43450 "extensions": ["icc","icm"]
43451 },
43452 "application/vnd.ieee.1905": {
43453 "source": "iana"
43454 },
43455 "application/vnd.igloader": {
43456 "source": "iana",
43457 "extensions": ["igl"]
43458 },
43459 "application/vnd.imagemeter.folder+zip": {
43460 "source": "iana",
43461 "compressible": false
43462 },
43463 "application/vnd.imagemeter.image+zip": {
43464 "source": "iana",
43465 "compressible": false
43466 },
43467 "application/vnd.immervision-ivp": {
43468 "source": "iana",
43469 "extensions": ["ivp"]
43470 },
43471 "application/vnd.immervision-ivu": {
43472 "source": "iana",
43473 "extensions": ["ivu"]
43474 },
43475 "application/vnd.ims.imsccv1p1": {
43476 "source": "iana"
43477 },
43478 "application/vnd.ims.imsccv1p2": {
43479 "source": "iana"
43480 },
43481 "application/vnd.ims.imsccv1p3": {
43482 "source": "iana"
43483 },
43484 "application/vnd.ims.lis.v2.result+json": {
43485 "source": "iana",
43486 "compressible": true
43487 },
43488 "application/vnd.ims.lti.v2.toolconsumerprofile+json": {
43489 "source": "iana",
43490 "compressible": true
43491 },
43492 "application/vnd.ims.lti.v2.toolproxy+json": {
43493 "source": "iana",
43494 "compressible": true
43495 },
43496 "application/vnd.ims.lti.v2.toolproxy.id+json": {
43497 "source": "iana",
43498 "compressible": true
43499 },
43500 "application/vnd.ims.lti.v2.toolsettings+json": {
43501 "source": "iana",
43502 "compressible": true
43503 },
43504 "application/vnd.ims.lti.v2.toolsettings.simple+json": {
43505 "source": "iana",
43506 "compressible": true
43507 },
43508 "application/vnd.informedcontrol.rms+xml": {
43509 "source": "iana",
43510 "compressible": true
43511 },
43512 "application/vnd.informix-visionary": {
43513 "source": "iana"
43514 },
43515 "application/vnd.infotech.project": {
43516 "source": "iana"
43517 },
43518 "application/vnd.infotech.project+xml": {
43519 "source": "iana",
43520 "compressible": true
43521 },
43522 "application/vnd.innopath.wamp.notification": {
43523 "source": "iana"
43524 },
43525 "application/vnd.insors.igm": {
43526 "source": "iana",
43527 "extensions": ["igm"]
43528 },
43529 "application/vnd.intercon.formnet": {
43530 "source": "iana",
43531 "extensions": ["xpw","xpx"]
43532 },
43533 "application/vnd.intergeo": {
43534 "source": "iana",
43535 "extensions": ["i2g"]
43536 },
43537 "application/vnd.intertrust.digibox": {
43538 "source": "iana"
43539 },
43540 "application/vnd.intertrust.nncp": {
43541 "source": "iana"
43542 },
43543 "application/vnd.intu.qbo": {
43544 "source": "iana",
43545 "extensions": ["qbo"]
43546 },
43547 "application/vnd.intu.qfx": {
43548 "source": "iana",
43549 "extensions": ["qfx"]
43550 },
43551 "application/vnd.iptc.g2.catalogitem+xml": {
43552 "source": "iana",
43553 "compressible": true
43554 },
43555 "application/vnd.iptc.g2.conceptitem+xml": {
43556 "source": "iana",
43557 "compressible": true
43558 },
43559 "application/vnd.iptc.g2.knowledgeitem+xml": {
43560 "source": "iana",
43561 "compressible": true
43562 },
43563 "application/vnd.iptc.g2.newsitem+xml": {
43564 "source": "iana",
43565 "compressible": true
43566 },
43567 "application/vnd.iptc.g2.newsmessage+xml": {
43568 "source": "iana",
43569 "compressible": true
43570 },
43571 "application/vnd.iptc.g2.packageitem+xml": {
43572 "source": "iana",
43573 "compressible": true
43574 },
43575 "application/vnd.iptc.g2.planningitem+xml": {
43576 "source": "iana",
43577 "compressible": true
43578 },
43579 "application/vnd.ipunplugged.rcprofile": {
43580 "source": "iana",
43581 "extensions": ["rcprofile"]
43582 },
43583 "application/vnd.irepository.package+xml": {
43584 "source": "iana",
43585 "compressible": true,
43586 "extensions": ["irp"]
43587 },
43588 "application/vnd.is-xpr": {
43589 "source": "iana",
43590 "extensions": ["xpr"]
43591 },
43592 "application/vnd.isac.fcs": {
43593 "source": "iana",
43594 "extensions": ["fcs"]
43595 },
43596 "application/vnd.jam": {
43597 "source": "iana",
43598 "extensions": ["jam"]
43599 },
43600 "application/vnd.japannet-directory-service": {
43601 "source": "iana"
43602 },
43603 "application/vnd.japannet-jpnstore-wakeup": {
43604 "source": "iana"
43605 },
43606 "application/vnd.japannet-payment-wakeup": {
43607 "source": "iana"
43608 },
43609 "application/vnd.japannet-registration": {
43610 "source": "iana"
43611 },
43612 "application/vnd.japannet-registration-wakeup": {
43613 "source": "iana"
43614 },
43615 "application/vnd.japannet-setstore-wakeup": {
43616 "source": "iana"
43617 },
43618 "application/vnd.japannet-verification": {
43619 "source": "iana"
43620 },
43621 "application/vnd.japannet-verification-wakeup": {
43622 "source": "iana"
43623 },
43624 "application/vnd.jcp.javame.midlet-rms": {
43625 "source": "iana",
43626 "extensions": ["rms"]
43627 },
43628 "application/vnd.jisp": {
43629 "source": "iana",
43630 "extensions": ["jisp"]
43631 },
43632 "application/vnd.joost.joda-archive": {
43633 "source": "iana",
43634 "extensions": ["joda"]
43635 },
43636 "application/vnd.jsk.isdn-ngn": {
43637 "source": "iana"
43638 },
43639 "application/vnd.kahootz": {
43640 "source": "iana",
43641 "extensions": ["ktz","ktr"]
43642 },
43643 "application/vnd.kde.karbon": {
43644 "source": "iana",
43645 "extensions": ["karbon"]
43646 },
43647 "application/vnd.kde.kchart": {
43648 "source": "iana",
43649 "extensions": ["chrt"]
43650 },
43651 "application/vnd.kde.kformula": {
43652 "source": "iana",
43653 "extensions": ["kfo"]
43654 },
43655 "application/vnd.kde.kivio": {
43656 "source": "iana",
43657 "extensions": ["flw"]
43658 },
43659 "application/vnd.kde.kontour": {
43660 "source": "iana",
43661 "extensions": ["kon"]
43662 },
43663 "application/vnd.kde.kpresenter": {
43664 "source": "iana",
43665 "extensions": ["kpr","kpt"]
43666 },
43667 "application/vnd.kde.kspread": {
43668 "source": "iana",
43669 "extensions": ["ksp"]
43670 },
43671 "application/vnd.kde.kword": {
43672 "source": "iana",
43673 "extensions": ["kwd","kwt"]
43674 },
43675 "application/vnd.kenameaapp": {
43676 "source": "iana",
43677 "extensions": ["htke"]
43678 },
43679 "application/vnd.kidspiration": {
43680 "source": "iana",
43681 "extensions": ["kia"]
43682 },
43683 "application/vnd.kinar": {
43684 "source": "iana",
43685 "extensions": ["kne","knp"]
43686 },
43687 "application/vnd.koan": {
43688 "source": "iana",
43689 "extensions": ["skp","skd","skt","skm"]
43690 },
43691 "application/vnd.kodak-descriptor": {
43692 "source": "iana",
43693 "extensions": ["sse"]
43694 },
43695 "application/vnd.las.las+json": {
43696 "source": "iana",
43697 "compressible": true
43698 },
43699 "application/vnd.las.las+xml": {
43700 "source": "iana",
43701 "compressible": true,
43702 "extensions": ["lasxml"]
43703 },
43704 "application/vnd.leap+json": {
43705 "source": "iana",
43706 "compressible": true
43707 },
43708 "application/vnd.liberty-request+xml": {
43709 "source": "iana",
43710 "compressible": true
43711 },
43712 "application/vnd.llamagraphics.life-balance.desktop": {
43713 "source": "iana",
43714 "extensions": ["lbd"]
43715 },
43716 "application/vnd.llamagraphics.life-balance.exchange+xml": {
43717 "source": "iana",
43718 "compressible": true,
43719 "extensions": ["lbe"]
43720 },
43721 "application/vnd.lotus-1-2-3": {
43722 "source": "iana",
43723 "extensions": ["123"]
43724 },
43725 "application/vnd.lotus-approach": {
43726 "source": "iana",
43727 "extensions": ["apr"]
43728 },
43729 "application/vnd.lotus-freelance": {
43730 "source": "iana",
43731 "extensions": ["pre"]
43732 },
43733 "application/vnd.lotus-notes": {
43734 "source": "iana",
43735 "extensions": ["nsf"]
43736 },
43737 "application/vnd.lotus-organizer": {
43738 "source": "iana",
43739 "extensions": ["org"]
43740 },
43741 "application/vnd.lotus-screencam": {
43742 "source": "iana",
43743 "extensions": ["scm"]
43744 },
43745 "application/vnd.lotus-wordpro": {
43746 "source": "iana",
43747 "extensions": ["lwp"]
43748 },
43749 "application/vnd.macports.portpkg": {
43750 "source": "iana",
43751 "extensions": ["portpkg"]
43752 },
43753 "application/vnd.mapbox-vector-tile": {
43754 "source": "iana"
43755 },
43756 "application/vnd.marlin.drm.actiontoken+xml": {
43757 "source": "iana",
43758 "compressible": true
43759 },
43760 "application/vnd.marlin.drm.conftoken+xml": {
43761 "source": "iana",
43762 "compressible": true
43763 },
43764 "application/vnd.marlin.drm.license+xml": {
43765 "source": "iana",
43766 "compressible": true
43767 },
43768 "application/vnd.marlin.drm.mdcf": {
43769 "source": "iana"
43770 },
43771 "application/vnd.mason+json": {
43772 "source": "iana",
43773 "compressible": true
43774 },
43775 "application/vnd.maxmind.maxmind-db": {
43776 "source": "iana"
43777 },
43778 "application/vnd.mcd": {
43779 "source": "iana",
43780 "extensions": ["mcd"]
43781 },
43782 "application/vnd.medcalcdata": {
43783 "source": "iana",
43784 "extensions": ["mc1"]
43785 },
43786 "application/vnd.mediastation.cdkey": {
43787 "source": "iana",
43788 "extensions": ["cdkey"]
43789 },
43790 "application/vnd.meridian-slingshot": {
43791 "source": "iana"
43792 },
43793 "application/vnd.mfer": {
43794 "source": "iana",
43795 "extensions": ["mwf"]
43796 },
43797 "application/vnd.mfmp": {
43798 "source": "iana",
43799 "extensions": ["mfm"]
43800 },
43801 "application/vnd.micro+json": {
43802 "source": "iana",
43803 "compressible": true
43804 },
43805 "application/vnd.micrografx.flo": {
43806 "source": "iana",
43807 "extensions": ["flo"]
43808 },
43809 "application/vnd.micrografx.igx": {
43810 "source": "iana",
43811 "extensions": ["igx"]
43812 },
43813 "application/vnd.microsoft.portable-executable": {
43814 "source": "iana"
43815 },
43816 "application/vnd.microsoft.windows.thumbnail-cache": {
43817 "source": "iana"
43818 },
43819 "application/vnd.miele+json": {
43820 "source": "iana",
43821 "compressible": true
43822 },
43823 "application/vnd.mif": {
43824 "source": "iana",
43825 "extensions": ["mif"]
43826 },
43827 "application/vnd.minisoft-hp3000-save": {
43828 "source": "iana"
43829 },
43830 "application/vnd.mitsubishi.misty-guard.trustweb": {
43831 "source": "iana"
43832 },
43833 "application/vnd.mobius.daf": {
43834 "source": "iana",
43835 "extensions": ["daf"]
43836 },
43837 "application/vnd.mobius.dis": {
43838 "source": "iana",
43839 "extensions": ["dis"]
43840 },
43841 "application/vnd.mobius.mbk": {
43842 "source": "iana",
43843 "extensions": ["mbk"]
43844 },
43845 "application/vnd.mobius.mqy": {
43846 "source": "iana",
43847 "extensions": ["mqy"]
43848 },
43849 "application/vnd.mobius.msl": {
43850 "source": "iana",
43851 "extensions": ["msl"]
43852 },
43853 "application/vnd.mobius.plc": {
43854 "source": "iana",
43855 "extensions": ["plc"]
43856 },
43857 "application/vnd.mobius.txf": {
43858 "source": "iana",
43859 "extensions": ["txf"]
43860 },
43861 "application/vnd.mophun.application": {
43862 "source": "iana",
43863 "extensions": ["mpn"]
43864 },
43865 "application/vnd.mophun.certificate": {
43866 "source": "iana",
43867 "extensions": ["mpc"]
43868 },
43869 "application/vnd.motorola.flexsuite": {
43870 "source": "iana"
43871 },
43872 "application/vnd.motorola.flexsuite.adsi": {
43873 "source": "iana"
43874 },
43875 "application/vnd.motorola.flexsuite.fis": {
43876 "source": "iana"
43877 },
43878 "application/vnd.motorola.flexsuite.gotap": {
43879 "source": "iana"
43880 },
43881 "application/vnd.motorola.flexsuite.kmr": {
43882 "source": "iana"
43883 },
43884 "application/vnd.motorola.flexsuite.ttc": {
43885 "source": "iana"
43886 },
43887 "application/vnd.motorola.flexsuite.wem": {
43888 "source": "iana"
43889 },
43890 "application/vnd.motorola.iprm": {
43891 "source": "iana"
43892 },
43893 "application/vnd.mozilla.xul+xml": {
43894 "source": "iana",
43895 "compressible": true,
43896 "extensions": ["xul"]
43897 },
43898 "application/vnd.ms-3mfdocument": {
43899 "source": "iana"
43900 },
43901 "application/vnd.ms-artgalry": {
43902 "source": "iana",
43903 "extensions": ["cil"]
43904 },
43905 "application/vnd.ms-asf": {
43906 "source": "iana"
43907 },
43908 "application/vnd.ms-cab-compressed": {
43909 "source": "iana",
43910 "extensions": ["cab"]
43911 },
43912 "application/vnd.ms-color.iccprofile": {
43913 "source": "apache"
43914 },
43915 "application/vnd.ms-excel": {
43916 "source": "iana",
43917 "compressible": false,
43918 "extensions": ["xls","xlm","xla","xlc","xlt","xlw"]
43919 },
43920 "application/vnd.ms-excel.addin.macroenabled.12": {
43921 "source": "iana",
43922 "extensions": ["xlam"]
43923 },
43924 "application/vnd.ms-excel.sheet.binary.macroenabled.12": {
43925 "source": "iana",
43926 "extensions": ["xlsb"]
43927 },
43928 "application/vnd.ms-excel.sheet.macroenabled.12": {
43929 "source": "iana",
43930 "extensions": ["xlsm"]
43931 },
43932 "application/vnd.ms-excel.template.macroenabled.12": {
43933 "source": "iana",
43934 "extensions": ["xltm"]
43935 },
43936 "application/vnd.ms-fontobject": {
43937 "source": "iana",
43938 "compressible": true,
43939 "extensions": ["eot"]
43940 },
43941 "application/vnd.ms-htmlhelp": {
43942 "source": "iana",
43943 "extensions": ["chm"]
43944 },
43945 "application/vnd.ms-ims": {
43946 "source": "iana",
43947 "extensions": ["ims"]
43948 },
43949 "application/vnd.ms-lrm": {
43950 "source": "iana",
43951 "extensions": ["lrm"]
43952 },
43953 "application/vnd.ms-office.activex+xml": {
43954 "source": "iana",
43955 "compressible": true
43956 },
43957 "application/vnd.ms-officetheme": {
43958 "source": "iana",
43959 "extensions": ["thmx"]
43960 },
43961 "application/vnd.ms-opentype": {
43962 "source": "apache",
43963 "compressible": true
43964 },
43965 "application/vnd.ms-outlook": {
43966 "compressible": false,
43967 "extensions": ["msg"]
43968 },
43969 "application/vnd.ms-package.obfuscated-opentype": {
43970 "source": "apache"
43971 },
43972 "application/vnd.ms-pki.seccat": {
43973 "source": "apache",
43974 "extensions": ["cat"]
43975 },
43976 "application/vnd.ms-pki.stl": {
43977 "source": "apache",
43978 "extensions": ["stl"]
43979 },
43980 "application/vnd.ms-playready.initiator+xml": {
43981 "source": "iana",
43982 "compressible": true
43983 },
43984 "application/vnd.ms-powerpoint": {
43985 "source": "iana",
43986 "compressible": false,
43987 "extensions": ["ppt","pps","pot"]
43988 },
43989 "application/vnd.ms-powerpoint.addin.macroenabled.12": {
43990 "source": "iana",
43991 "extensions": ["ppam"]
43992 },
43993 "application/vnd.ms-powerpoint.presentation.macroenabled.12": {
43994 "source": "iana",
43995 "extensions": ["pptm"]
43996 },
43997 "application/vnd.ms-powerpoint.slide.macroenabled.12": {
43998 "source": "iana",
43999 "extensions": ["sldm"]
44000 },
44001 "application/vnd.ms-powerpoint.slideshow.macroenabled.12": {
44002 "source": "iana",
44003 "extensions": ["ppsm"]
44004 },
44005 "application/vnd.ms-powerpoint.template.macroenabled.12": {
44006 "source": "iana",
44007 "extensions": ["potm"]
44008 },
44009 "application/vnd.ms-printdevicecapabilities+xml": {
44010 "source": "iana",
44011 "compressible": true
44012 },
44013 "application/vnd.ms-printing.printticket+xml": {
44014 "source": "apache",
44015 "compressible": true
44016 },
44017 "application/vnd.ms-printschematicket+xml": {
44018 "source": "iana",
44019 "compressible": true
44020 },
44021 "application/vnd.ms-project": {
44022 "source": "iana",
44023 "extensions": ["mpp","mpt"]
44024 },
44025 "application/vnd.ms-tnef": {
44026 "source": "iana"
44027 },
44028 "application/vnd.ms-windows.devicepairing": {
44029 "source": "iana"
44030 },
44031 "application/vnd.ms-windows.nwprinting.oob": {
44032 "source": "iana"
44033 },
44034 "application/vnd.ms-windows.printerpairing": {
44035 "source": "iana"
44036 },
44037 "application/vnd.ms-windows.wsd.oob": {
44038 "source": "iana"
44039 },
44040 "application/vnd.ms-wmdrm.lic-chlg-req": {
44041 "source": "iana"
44042 },
44043 "application/vnd.ms-wmdrm.lic-resp": {
44044 "source": "iana"
44045 },
44046 "application/vnd.ms-wmdrm.meter-chlg-req": {
44047 "source": "iana"
44048 },
44049 "application/vnd.ms-wmdrm.meter-resp": {
44050 "source": "iana"
44051 },
44052 "application/vnd.ms-word.document.macroenabled.12": {
44053 "source": "iana",
44054 "extensions": ["docm"]
44055 },
44056 "application/vnd.ms-word.template.macroenabled.12": {
44057 "source": "iana",
44058 "extensions": ["dotm"]
44059 },
44060 "application/vnd.ms-works": {
44061 "source": "iana",
44062 "extensions": ["wps","wks","wcm","wdb"]
44063 },
44064 "application/vnd.ms-wpl": {
44065 "source": "iana",
44066 "extensions": ["wpl"]
44067 },
44068 "application/vnd.ms-xpsdocument": {
44069 "source": "iana",
44070 "compressible": false,
44071 "extensions": ["xps"]
44072 },
44073 "application/vnd.msa-disk-image": {
44074 "source": "iana"
44075 },
44076 "application/vnd.mseq": {
44077 "source": "iana",
44078 "extensions": ["mseq"]
44079 },
44080 "application/vnd.msign": {
44081 "source": "iana"
44082 },
44083 "application/vnd.multiad.creator": {
44084 "source": "iana"
44085 },
44086 "application/vnd.multiad.creator.cif": {
44087 "source": "iana"
44088 },
44089 "application/vnd.music-niff": {
44090 "source": "iana"
44091 },
44092 "application/vnd.musician": {
44093 "source": "iana",
44094 "extensions": ["mus"]
44095 },
44096 "application/vnd.muvee.style": {
44097 "source": "iana",
44098 "extensions": ["msty"]
44099 },
44100 "application/vnd.mynfc": {
44101 "source": "iana",
44102 "extensions": ["taglet"]
44103 },
44104 "application/vnd.ncd.control": {
44105 "source": "iana"
44106 },
44107 "application/vnd.ncd.reference": {
44108 "source": "iana"
44109 },
44110 "application/vnd.nearst.inv+json": {
44111 "source": "iana",
44112 "compressible": true
44113 },
44114 "application/vnd.nervana": {
44115 "source": "iana"
44116 },
44117 "application/vnd.netfpx": {
44118 "source": "iana"
44119 },
44120 "application/vnd.neurolanguage.nlu": {
44121 "source": "iana",
44122 "extensions": ["nlu"]
44123 },
44124 "application/vnd.nimn": {
44125 "source": "iana"
44126 },
44127 "application/vnd.nintendo.nitro.rom": {
44128 "source": "iana"
44129 },
44130 "application/vnd.nintendo.snes.rom": {
44131 "source": "iana"
44132 },
44133 "application/vnd.nitf": {
44134 "source": "iana",
44135 "extensions": ["ntf","nitf"]
44136 },
44137 "application/vnd.noblenet-directory": {
44138 "source": "iana",
44139 "extensions": ["nnd"]
44140 },
44141 "application/vnd.noblenet-sealer": {
44142 "source": "iana",
44143 "extensions": ["nns"]
44144 },
44145 "application/vnd.noblenet-web": {
44146 "source": "iana",
44147 "extensions": ["nnw"]
44148 },
44149 "application/vnd.nokia.catalogs": {
44150 "source": "iana"
44151 },
44152 "application/vnd.nokia.conml+wbxml": {
44153 "source": "iana"
44154 },
44155 "application/vnd.nokia.conml+xml": {
44156 "source": "iana",
44157 "compressible": true
44158 },
44159 "application/vnd.nokia.iptv.config+xml": {
44160 "source": "iana",
44161 "compressible": true
44162 },
44163 "application/vnd.nokia.isds-radio-presets": {
44164 "source": "iana"
44165 },
44166 "application/vnd.nokia.landmark+wbxml": {
44167 "source": "iana"
44168 },
44169 "application/vnd.nokia.landmark+xml": {
44170 "source": "iana",
44171 "compressible": true
44172 },
44173 "application/vnd.nokia.landmarkcollection+xml": {
44174 "source": "iana",
44175 "compressible": true
44176 },
44177 "application/vnd.nokia.n-gage.ac+xml": {
44178 "source": "iana",
44179 "compressible": true
44180 },
44181 "application/vnd.nokia.n-gage.data": {
44182 "source": "iana",
44183 "extensions": ["ngdat"]
44184 },
44185 "application/vnd.nokia.n-gage.symbian.install": {
44186 "source": "iana",
44187 "extensions": ["n-gage"]
44188 },
44189 "application/vnd.nokia.ncd": {
44190 "source": "iana"
44191 },
44192 "application/vnd.nokia.pcd+wbxml": {
44193 "source": "iana"
44194 },
44195 "application/vnd.nokia.pcd+xml": {
44196 "source": "iana",
44197 "compressible": true
44198 },
44199 "application/vnd.nokia.radio-preset": {
44200 "source": "iana",
44201 "extensions": ["rpst"]
44202 },
44203 "application/vnd.nokia.radio-presets": {
44204 "source": "iana",
44205 "extensions": ["rpss"]
44206 },
44207 "application/vnd.novadigm.edm": {
44208 "source": "iana",
44209 "extensions": ["edm"]
44210 },
44211 "application/vnd.novadigm.edx": {
44212 "source": "iana",
44213 "extensions": ["edx"]
44214 },
44215 "application/vnd.novadigm.ext": {
44216 "source": "iana",
44217 "extensions": ["ext"]
44218 },
44219 "application/vnd.ntt-local.content-share": {
44220 "source": "iana"
44221 },
44222 "application/vnd.ntt-local.file-transfer": {
44223 "source": "iana"
44224 },
44225 "application/vnd.ntt-local.ogw_remote-access": {
44226 "source": "iana"
44227 },
44228 "application/vnd.ntt-local.sip-ta_remote": {
44229 "source": "iana"
44230 },
44231 "application/vnd.ntt-local.sip-ta_tcp_stream": {
44232 "source": "iana"
44233 },
44234 "application/vnd.oasis.opendocument.chart": {
44235 "source": "iana",
44236 "extensions": ["odc"]
44237 },
44238 "application/vnd.oasis.opendocument.chart-template": {
44239 "source": "iana",
44240 "extensions": ["otc"]
44241 },
44242 "application/vnd.oasis.opendocument.database": {
44243 "source": "iana",
44244 "extensions": ["odb"]
44245 },
44246 "application/vnd.oasis.opendocument.formula": {
44247 "source": "iana",
44248 "extensions": ["odf"]
44249 },
44250 "application/vnd.oasis.opendocument.formula-template": {
44251 "source": "iana",
44252 "extensions": ["odft"]
44253 },
44254 "application/vnd.oasis.opendocument.graphics": {
44255 "source": "iana",
44256 "compressible": false,
44257 "extensions": ["odg"]
44258 },
44259 "application/vnd.oasis.opendocument.graphics-template": {
44260 "source": "iana",
44261 "extensions": ["otg"]
44262 },
44263 "application/vnd.oasis.opendocument.image": {
44264 "source": "iana",
44265 "extensions": ["odi"]
44266 },
44267 "application/vnd.oasis.opendocument.image-template": {
44268 "source": "iana",
44269 "extensions": ["oti"]
44270 },
44271 "application/vnd.oasis.opendocument.presentation": {
44272 "source": "iana",
44273 "compressible": false,
44274 "extensions": ["odp"]
44275 },
44276 "application/vnd.oasis.opendocument.presentation-template": {
44277 "source": "iana",
44278 "extensions": ["otp"]
44279 },
44280 "application/vnd.oasis.opendocument.spreadsheet": {
44281 "source": "iana",
44282 "compressible": false,
44283 "extensions": ["ods"]
44284 },
44285 "application/vnd.oasis.opendocument.spreadsheet-template": {
44286 "source": "iana",
44287 "extensions": ["ots"]
44288 },
44289 "application/vnd.oasis.opendocument.text": {
44290 "source": "iana",
44291 "compressible": false,
44292 "extensions": ["odt"]
44293 },
44294 "application/vnd.oasis.opendocument.text-master": {
44295 "source": "iana",
44296 "extensions": ["odm"]
44297 },
44298 "application/vnd.oasis.opendocument.text-template": {
44299 "source": "iana",
44300 "extensions": ["ott"]
44301 },
44302 "application/vnd.oasis.opendocument.text-web": {
44303 "source": "iana",
44304 "extensions": ["oth"]
44305 },
44306 "application/vnd.obn": {
44307 "source": "iana"
44308 },
44309 "application/vnd.ocf+cbor": {
44310 "source": "iana"
44311 },
44312 "application/vnd.oftn.l10n+json": {
44313 "source": "iana",
44314 "compressible": true
44315 },
44316 "application/vnd.oipf.contentaccessdownload+xml": {
44317 "source": "iana",
44318 "compressible": true
44319 },
44320 "application/vnd.oipf.contentaccessstreaming+xml": {
44321 "source": "iana",
44322 "compressible": true
44323 },
44324 "application/vnd.oipf.cspg-hexbinary": {
44325 "source": "iana"
44326 },
44327 "application/vnd.oipf.dae.svg+xml": {
44328 "source": "iana",
44329 "compressible": true
44330 },
44331 "application/vnd.oipf.dae.xhtml+xml": {
44332 "source": "iana",
44333 "compressible": true
44334 },
44335 "application/vnd.oipf.mippvcontrolmessage+xml": {
44336 "source": "iana",
44337 "compressible": true
44338 },
44339 "application/vnd.oipf.pae.gem": {
44340 "source": "iana"
44341 },
44342 "application/vnd.oipf.spdiscovery+xml": {
44343 "source": "iana",
44344 "compressible": true
44345 },
44346 "application/vnd.oipf.spdlist+xml": {
44347 "source": "iana",
44348 "compressible": true
44349 },
44350 "application/vnd.oipf.ueprofile+xml": {
44351 "source": "iana",
44352 "compressible": true
44353 },
44354 "application/vnd.oipf.userprofile+xml": {
44355 "source": "iana",
44356 "compressible": true
44357 },
44358 "application/vnd.olpc-sugar": {
44359 "source": "iana",
44360 "extensions": ["xo"]
44361 },
44362 "application/vnd.oma-scws-config": {
44363 "source": "iana"
44364 },
44365 "application/vnd.oma-scws-http-request": {
44366 "source": "iana"
44367 },
44368 "application/vnd.oma-scws-http-response": {
44369 "source": "iana"
44370 },
44371 "application/vnd.oma.bcast.associated-procedure-parameter+xml": {
44372 "source": "iana",
44373 "compressible": true
44374 },
44375 "application/vnd.oma.bcast.drm-trigger+xml": {
44376 "source": "iana",
44377 "compressible": true
44378 },
44379 "application/vnd.oma.bcast.imd+xml": {
44380 "source": "iana",
44381 "compressible": true
44382 },
44383 "application/vnd.oma.bcast.ltkm": {
44384 "source": "iana"
44385 },
44386 "application/vnd.oma.bcast.notification+xml": {
44387 "source": "iana",
44388 "compressible": true
44389 },
44390 "application/vnd.oma.bcast.provisioningtrigger": {
44391 "source": "iana"
44392 },
44393 "application/vnd.oma.bcast.sgboot": {
44394 "source": "iana"
44395 },
44396 "application/vnd.oma.bcast.sgdd+xml": {
44397 "source": "iana",
44398 "compressible": true
44399 },
44400 "application/vnd.oma.bcast.sgdu": {
44401 "source": "iana"
44402 },
44403 "application/vnd.oma.bcast.simple-symbol-container": {
44404 "source": "iana"
44405 },
44406 "application/vnd.oma.bcast.smartcard-trigger+xml": {
44407 "source": "iana",
44408 "compressible": true
44409 },
44410 "application/vnd.oma.bcast.sprov+xml": {
44411 "source": "iana",
44412 "compressible": true
44413 },
44414 "application/vnd.oma.bcast.stkm": {
44415 "source": "iana"
44416 },
44417 "application/vnd.oma.cab-address-book+xml": {
44418 "source": "iana",
44419 "compressible": true
44420 },
44421 "application/vnd.oma.cab-feature-handler+xml": {
44422 "source": "iana",
44423 "compressible": true
44424 },
44425 "application/vnd.oma.cab-pcc+xml": {
44426 "source": "iana",
44427 "compressible": true
44428 },
44429 "application/vnd.oma.cab-subs-invite+xml": {
44430 "source": "iana",
44431 "compressible": true
44432 },
44433 "application/vnd.oma.cab-user-prefs+xml": {
44434 "source": "iana",
44435 "compressible": true
44436 },
44437 "application/vnd.oma.dcd": {
44438 "source": "iana"
44439 },
44440 "application/vnd.oma.dcdc": {
44441 "source": "iana"
44442 },
44443 "application/vnd.oma.dd2+xml": {
44444 "source": "iana",
44445 "compressible": true,
44446 "extensions": ["dd2"]
44447 },
44448 "application/vnd.oma.drm.risd+xml": {
44449 "source": "iana",
44450 "compressible": true
44451 },
44452 "application/vnd.oma.group-usage-list+xml": {
44453 "source": "iana",
44454 "compressible": true
44455 },
44456 "application/vnd.oma.lwm2m+json": {
44457 "source": "iana",
44458 "compressible": true
44459 },
44460 "application/vnd.oma.lwm2m+tlv": {
44461 "source": "iana"
44462 },
44463 "application/vnd.oma.pal+xml": {
44464 "source": "iana",
44465 "compressible": true
44466 },
44467 "application/vnd.oma.poc.detailed-progress-report+xml": {
44468 "source": "iana",
44469 "compressible": true
44470 },
44471 "application/vnd.oma.poc.final-report+xml": {
44472 "source": "iana",
44473 "compressible": true
44474 },
44475 "application/vnd.oma.poc.groups+xml": {
44476 "source": "iana",
44477 "compressible": true
44478 },
44479 "application/vnd.oma.poc.invocation-descriptor+xml": {
44480 "source": "iana",
44481 "compressible": true
44482 },
44483 "application/vnd.oma.poc.optimized-progress-report+xml": {
44484 "source": "iana",
44485 "compressible": true
44486 },
44487 "application/vnd.oma.push": {
44488 "source": "iana"
44489 },
44490 "application/vnd.oma.scidm.messages+xml": {
44491 "source": "iana",
44492 "compressible": true
44493 },
44494 "application/vnd.oma.xcap-directory+xml": {
44495 "source": "iana",
44496 "compressible": true
44497 },
44498 "application/vnd.omads-email+xml": {
44499 "source": "iana",
44500 "compressible": true
44501 },
44502 "application/vnd.omads-file+xml": {
44503 "source": "iana",
44504 "compressible": true
44505 },
44506 "application/vnd.omads-folder+xml": {
44507 "source": "iana",
44508 "compressible": true
44509 },
44510 "application/vnd.omaloc-supl-init": {
44511 "source": "iana"
44512 },
44513 "application/vnd.onepager": {
44514 "source": "iana"
44515 },
44516 "application/vnd.onepagertamp": {
44517 "source": "iana"
44518 },
44519 "application/vnd.onepagertamx": {
44520 "source": "iana"
44521 },
44522 "application/vnd.onepagertat": {
44523 "source": "iana"
44524 },
44525 "application/vnd.onepagertatp": {
44526 "source": "iana"
44527 },
44528 "application/vnd.onepagertatx": {
44529 "source": "iana"
44530 },
44531 "application/vnd.openblox.game+xml": {
44532 "source": "iana",
44533 "compressible": true
44534 },
44535 "application/vnd.openblox.game-binary": {
44536 "source": "iana"
44537 },
44538 "application/vnd.openeye.oeb": {
44539 "source": "iana"
44540 },
44541 "application/vnd.openofficeorg.extension": {
44542 "source": "apache",
44543 "extensions": ["oxt"]
44544 },
44545 "application/vnd.openstreetmap.data+xml": {
44546 "source": "iana",
44547 "compressible": true
44548 },
44549 "application/vnd.openxmlformats-officedocument.custom-properties+xml": {
44550 "source": "iana",
44551 "compressible": true
44552 },
44553 "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": {
44554 "source": "iana",
44555 "compressible": true
44556 },
44557 "application/vnd.openxmlformats-officedocument.drawing+xml": {
44558 "source": "iana",
44559 "compressible": true
44560 },
44561 "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": {
44562 "source": "iana",
44563 "compressible": true
44564 },
44565 "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": {
44566 "source": "iana",
44567 "compressible": true
44568 },
44569 "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": {
44570 "source": "iana",
44571 "compressible": true
44572 },
44573 "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": {
44574 "source": "iana",
44575 "compressible": true
44576 },
44577 "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": {
44578 "source": "iana",
44579 "compressible": true
44580 },
44581 "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": {
44582 "source": "iana",
44583 "compressible": true
44584 },
44585 "application/vnd.openxmlformats-officedocument.extended-properties+xml": {
44586 "source": "iana",
44587 "compressible": true
44588 },
44589 "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": {
44590 "source": "iana",
44591 "compressible": true
44592 },
44593 "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": {
44594 "source": "iana",
44595 "compressible": true
44596 },
44597 "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": {
44598 "source": "iana",
44599 "compressible": true
44600 },
44601 "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": {
44602 "source": "iana",
44603 "compressible": true
44604 },
44605 "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": {
44606 "source": "iana",
44607 "compressible": true
44608 },
44609 "application/vnd.openxmlformats-officedocument.presentationml.presentation": {
44610 "source": "iana",
44611 "compressible": false,
44612 "extensions": ["pptx"]
44613 },
44614 "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": {
44615 "source": "iana",
44616 "compressible": true
44617 },
44618 "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": {
44619 "source": "iana",
44620 "compressible": true
44621 },
44622 "application/vnd.openxmlformats-officedocument.presentationml.slide": {
44623 "source": "iana",
44624 "extensions": ["sldx"]
44625 },
44626 "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": {
44627 "source": "iana",
44628 "compressible": true
44629 },
44630 "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": {
44631 "source": "iana",
44632 "compressible": true
44633 },
44634 "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": {
44635 "source": "iana",
44636 "compressible": true
44637 },
44638 "application/vnd.openxmlformats-officedocument.presentationml.slideshow": {
44639 "source": "iana",
44640 "extensions": ["ppsx"]
44641 },
44642 "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": {
44643 "source": "iana",
44644 "compressible": true
44645 },
44646 "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": {
44647 "source": "iana",
44648 "compressible": true
44649 },
44650 "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": {
44651 "source": "iana",
44652 "compressible": true
44653 },
44654 "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": {
44655 "source": "iana",
44656 "compressible": true
44657 },
44658 "application/vnd.openxmlformats-officedocument.presentationml.template": {
44659 "source": "iana",
44660 "extensions": ["potx"]
44661 },
44662 "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": {
44663 "source": "iana",
44664 "compressible": true
44665 },
44666 "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": {
44667 "source": "iana",
44668 "compressible": true
44669 },
44670 "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": {
44671 "source": "iana",
44672 "compressible": true
44673 },
44674 "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": {
44675 "source": "iana",
44676 "compressible": true
44677 },
44678 "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": {
44679 "source": "iana",
44680 "compressible": true
44681 },
44682 "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": {
44683 "source": "iana",
44684 "compressible": true
44685 },
44686 "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": {
44687 "source": "iana",
44688 "compressible": true
44689 },
44690 "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": {
44691 "source": "iana",
44692 "compressible": true
44693 },
44694 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": {
44695 "source": "iana",
44696 "compressible": true
44697 },
44698 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": {
44699 "source": "iana",
44700 "compressible": true
44701 },
44702 "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": {
44703 "source": "iana",
44704 "compressible": true
44705 },
44706 "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": {
44707 "source": "iana",
44708 "compressible": true
44709 },
44710 "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": {
44711 "source": "iana",
44712 "compressible": true
44713 },
44714 "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": {
44715 "source": "iana",
44716 "compressible": true
44717 },
44718 "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": {
44719 "source": "iana",
44720 "compressible": true
44721 },
44722 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {
44723 "source": "iana",
44724 "compressible": false,
44725 "extensions": ["xlsx"]
44726 },
44727 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": {
44728 "source": "iana",
44729 "compressible": true
44730 },
44731 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": {
44732 "source": "iana",
44733 "compressible": true
44734 },
44735 "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": {
44736 "source": "iana",
44737 "compressible": true
44738 },
44739 "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": {
44740 "source": "iana",
44741 "compressible": true
44742 },
44743 "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": {
44744 "source": "iana",
44745 "compressible": true
44746 },
44747 "application/vnd.openxmlformats-officedocument.spreadsheetml.template": {
44748 "source": "iana",
44749 "extensions": ["xltx"]
44750 },
44751 "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": {
44752 "source": "iana",
44753 "compressible": true
44754 },
44755 "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": {
44756 "source": "iana",
44757 "compressible": true
44758 },
44759 "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": {
44760 "source": "iana",
44761 "compressible": true
44762 },
44763 "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": {
44764 "source": "iana",
44765 "compressible": true
44766 },
44767 "application/vnd.openxmlformats-officedocument.theme+xml": {
44768 "source": "iana",
44769 "compressible": true
44770 },
44771 "application/vnd.openxmlformats-officedocument.themeoverride+xml": {
44772 "source": "iana",
44773 "compressible": true
44774 },
44775 "application/vnd.openxmlformats-officedocument.vmldrawing": {
44776 "source": "iana"
44777 },
44778 "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": {
44779 "source": "iana",
44780 "compressible": true
44781 },
44782 "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {
44783 "source": "iana",
44784 "compressible": false,
44785 "extensions": ["docx"]
44786 },
44787 "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": {
44788 "source": "iana",
44789 "compressible": true
44790 },
44791 "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": {
44792 "source": "iana",
44793 "compressible": true
44794 },
44795 "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": {
44796 "source": "iana",
44797 "compressible": true
44798 },
44799 "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": {
44800 "source": "iana",
44801 "compressible": true
44802 },
44803 "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": {
44804 "source": "iana",
44805 "compressible": true
44806 },
44807 "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": {
44808 "source": "iana",
44809 "compressible": true
44810 },
44811 "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": {
44812 "source": "iana",
44813 "compressible": true
44814 },
44815 "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": {
44816 "source": "iana",
44817 "compressible": true
44818 },
44819 "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": {
44820 "source": "iana",
44821 "compressible": true
44822 },
44823 "application/vnd.openxmlformats-officedocument.wordprocessingml.template": {
44824 "source": "iana",
44825 "extensions": ["dotx"]
44826 },
44827 "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": {
44828 "source": "iana",
44829 "compressible": true
44830 },
44831 "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": {
44832 "source": "iana",
44833 "compressible": true
44834 },
44835 "application/vnd.openxmlformats-package.core-properties+xml": {
44836 "source": "iana",
44837 "compressible": true
44838 },
44839 "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": {
44840 "source": "iana",
44841 "compressible": true
44842 },
44843 "application/vnd.openxmlformats-package.relationships+xml": {
44844 "source": "iana",
44845 "compressible": true
44846 },
44847 "application/vnd.oracle.resource+json": {
44848 "source": "iana",
44849 "compressible": true
44850 },
44851 "application/vnd.orange.indata": {
44852 "source": "iana"
44853 },
44854 "application/vnd.osa.netdeploy": {
44855 "source": "iana"
44856 },
44857 "application/vnd.osgeo.mapguide.package": {
44858 "source": "iana",
44859 "extensions": ["mgp"]
44860 },
44861 "application/vnd.osgi.bundle": {
44862 "source": "iana"
44863 },
44864 "application/vnd.osgi.dp": {
44865 "source": "iana",
44866 "extensions": ["dp"]
44867 },
44868 "application/vnd.osgi.subsystem": {
44869 "source": "iana",
44870 "extensions": ["esa"]
44871 },
44872 "application/vnd.otps.ct-kip+xml": {
44873 "source": "iana",
44874 "compressible": true
44875 },
44876 "application/vnd.oxli.countgraph": {
44877 "source": "iana"
44878 },
44879 "application/vnd.pagerduty+json": {
44880 "source": "iana",
44881 "compressible": true
44882 },
44883 "application/vnd.palm": {
44884 "source": "iana",
44885 "extensions": ["pdb","pqa","oprc"]
44886 },
44887 "application/vnd.panoply": {
44888 "source": "iana"
44889 },
44890 "application/vnd.paos.xml": {
44891 "source": "iana"
44892 },
44893 "application/vnd.patentdive": {
44894 "source": "iana"
44895 },
44896 "application/vnd.patientecommsdoc": {
44897 "source": "iana"
44898 },
44899 "application/vnd.pawaafile": {
44900 "source": "iana",
44901 "extensions": ["paw"]
44902 },
44903 "application/vnd.pcos": {
44904 "source": "iana"
44905 },
44906 "application/vnd.pg.format": {
44907 "source": "iana",
44908 "extensions": ["str"]
44909 },
44910 "application/vnd.pg.osasli": {
44911 "source": "iana",
44912 "extensions": ["ei6"]
44913 },
44914 "application/vnd.piaccess.application-licence": {
44915 "source": "iana"
44916 },
44917 "application/vnd.picsel": {
44918 "source": "iana",
44919 "extensions": ["efif"]
44920 },
44921 "application/vnd.pmi.widget": {
44922 "source": "iana",
44923 "extensions": ["wg"]
44924 },
44925 "application/vnd.poc.group-advertisement+xml": {
44926 "source": "iana",
44927 "compressible": true
44928 },
44929 "application/vnd.pocketlearn": {
44930 "source": "iana",
44931 "extensions": ["plf"]
44932 },
44933 "application/vnd.powerbuilder6": {
44934 "source": "iana",
44935 "extensions": ["pbd"]
44936 },
44937 "application/vnd.powerbuilder6-s": {
44938 "source": "iana"
44939 },
44940 "application/vnd.powerbuilder7": {
44941 "source": "iana"
44942 },
44943 "application/vnd.powerbuilder7-s": {
44944 "source": "iana"
44945 },
44946 "application/vnd.powerbuilder75": {
44947 "source": "iana"
44948 },
44949 "application/vnd.powerbuilder75-s": {
44950 "source": "iana"
44951 },
44952 "application/vnd.preminet": {
44953 "source": "iana"
44954 },
44955 "application/vnd.previewsystems.box": {
44956 "source": "iana",
44957 "extensions": ["box"]
44958 },
44959 "application/vnd.proteus.magazine": {
44960 "source": "iana",
44961 "extensions": ["mgz"]
44962 },
44963 "application/vnd.psfs": {
44964 "source": "iana"
44965 },
44966 "application/vnd.publishare-delta-tree": {
44967 "source": "iana",
44968 "extensions": ["qps"]
44969 },
44970 "application/vnd.pvi.ptid1": {
44971 "source": "iana",
44972 "extensions": ["ptid"]
44973 },
44974 "application/vnd.pwg-multiplexed": {
44975 "source": "iana"
44976 },
44977 "application/vnd.pwg-xhtml-print+xml": {
44978 "source": "iana",
44979 "compressible": true
44980 },
44981 "application/vnd.qualcomm.brew-app-res": {
44982 "source": "iana"
44983 },
44984 "application/vnd.quarantainenet": {
44985 "source": "iana"
44986 },
44987 "application/vnd.quark.quarkxpress": {
44988 "source": "iana",
44989 "extensions": ["qxd","qxt","qwd","qwt","qxl","qxb"]
44990 },
44991 "application/vnd.quobject-quoxdocument": {
44992 "source": "iana"
44993 },
44994 "application/vnd.radisys.moml+xml": {
44995 "source": "iana",
44996 "compressible": true
44997 },
44998 "application/vnd.radisys.msml+xml": {
44999 "source": "iana",
45000 "compressible": true
45001 },
45002 "application/vnd.radisys.msml-audit+xml": {
45003 "source": "iana",
45004 "compressible": true
45005 },
45006 "application/vnd.radisys.msml-audit-conf+xml": {
45007 "source": "iana",
45008 "compressible": true
45009 },
45010 "application/vnd.radisys.msml-audit-conn+xml": {
45011 "source": "iana",
45012 "compressible": true
45013 },
45014 "application/vnd.radisys.msml-audit-dialog+xml": {
45015 "source": "iana",
45016 "compressible": true
45017 },
45018 "application/vnd.radisys.msml-audit-stream+xml": {
45019 "source": "iana",
45020 "compressible": true
45021 },
45022 "application/vnd.radisys.msml-conf+xml": {
45023 "source": "iana",
45024 "compressible": true
45025 },
45026 "application/vnd.radisys.msml-dialog+xml": {
45027 "source": "iana",
45028 "compressible": true
45029 },
45030 "application/vnd.radisys.msml-dialog-base+xml": {
45031 "source": "iana",
45032 "compressible": true
45033 },
45034 "application/vnd.radisys.msml-dialog-fax-detect+xml": {
45035 "source": "iana",
45036 "compressible": true
45037 },
45038 "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": {
45039 "source": "iana",
45040 "compressible": true
45041 },
45042 "application/vnd.radisys.msml-dialog-group+xml": {
45043 "source": "iana",
45044 "compressible": true
45045 },
45046 "application/vnd.radisys.msml-dialog-speech+xml": {
45047 "source": "iana",
45048 "compressible": true
45049 },
45050 "application/vnd.radisys.msml-dialog-transform+xml": {
45051 "source": "iana",
45052 "compressible": true
45053 },
45054 "application/vnd.rainstor.data": {
45055 "source": "iana"
45056 },
45057 "application/vnd.rapid": {
45058 "source": "iana"
45059 },
45060 "application/vnd.rar": {
45061 "source": "iana"
45062 },
45063 "application/vnd.realvnc.bed": {
45064 "source": "iana",
45065 "extensions": ["bed"]
45066 },
45067 "application/vnd.recordare.musicxml": {
45068 "source": "iana",
45069 "extensions": ["mxl"]
45070 },
45071 "application/vnd.recordare.musicxml+xml": {
45072 "source": "iana",
45073 "compressible": true,
45074 "extensions": ["musicxml"]
45075 },
45076 "application/vnd.renlearn.rlprint": {
45077 "source": "iana"
45078 },
45079 "application/vnd.restful+json": {
45080 "source": "iana",
45081 "compressible": true
45082 },
45083 "application/vnd.rig.cryptonote": {
45084 "source": "iana",
45085 "extensions": ["cryptonote"]
45086 },
45087 "application/vnd.rim.cod": {
45088 "source": "apache",
45089 "extensions": ["cod"]
45090 },
45091 "application/vnd.rn-realmedia": {
45092 "source": "apache",
45093 "extensions": ["rm"]
45094 },
45095 "application/vnd.rn-realmedia-vbr": {
45096 "source": "apache",
45097 "extensions": ["rmvb"]
45098 },
45099 "application/vnd.route66.link66+xml": {
45100 "source": "iana",
45101 "compressible": true,
45102 "extensions": ["link66"]
45103 },
45104 "application/vnd.rs-274x": {
45105 "source": "iana"
45106 },
45107 "application/vnd.ruckus.download": {
45108 "source": "iana"
45109 },
45110 "application/vnd.s3sms": {
45111 "source": "iana"
45112 },
45113 "application/vnd.sailingtracker.track": {
45114 "source": "iana",
45115 "extensions": ["st"]
45116 },
45117 "application/vnd.sbm.cid": {
45118 "source": "iana"
45119 },
45120 "application/vnd.sbm.mid2": {
45121 "source": "iana"
45122 },
45123 "application/vnd.scribus": {
45124 "source": "iana"
45125 },
45126 "application/vnd.sealed.3df": {
45127 "source": "iana"
45128 },
45129 "application/vnd.sealed.csf": {
45130 "source": "iana"
45131 },
45132 "application/vnd.sealed.doc": {
45133 "source": "iana"
45134 },
45135 "application/vnd.sealed.eml": {
45136 "source": "iana"
45137 },
45138 "application/vnd.sealed.mht": {
45139 "source": "iana"
45140 },
45141 "application/vnd.sealed.net": {
45142 "source": "iana"
45143 },
45144 "application/vnd.sealed.ppt": {
45145 "source": "iana"
45146 },
45147 "application/vnd.sealed.tiff": {
45148 "source": "iana"
45149 },
45150 "application/vnd.sealed.xls": {
45151 "source": "iana"
45152 },
45153 "application/vnd.sealedmedia.softseal.html": {
45154 "source": "iana"
45155 },
45156 "application/vnd.sealedmedia.softseal.pdf": {
45157 "source": "iana"
45158 },
45159 "application/vnd.seemail": {
45160 "source": "iana",
45161 "extensions": ["see"]
45162 },
45163 "application/vnd.sema": {
45164 "source": "iana",
45165 "extensions": ["sema"]
45166 },
45167 "application/vnd.semd": {
45168 "source": "iana",
45169 "extensions": ["semd"]
45170 },
45171 "application/vnd.semf": {
45172 "source": "iana",
45173 "extensions": ["semf"]
45174 },
45175 "application/vnd.shana.informed.formdata": {
45176 "source": "iana",
45177 "extensions": ["ifm"]
45178 },
45179 "application/vnd.shana.informed.formtemplate": {
45180 "source": "iana",
45181 "extensions": ["itp"]
45182 },
45183 "application/vnd.shana.informed.interchange": {
45184 "source": "iana",
45185 "extensions": ["iif"]
45186 },
45187 "application/vnd.shana.informed.package": {
45188 "source": "iana",
45189 "extensions": ["ipk"]
45190 },
45191 "application/vnd.shootproof+json": {
45192 "source": "iana",
45193 "compressible": true
45194 },
45195 "application/vnd.sigrok.session": {
45196 "source": "iana"
45197 },
45198 "application/vnd.simtech-mindmapper": {
45199 "source": "iana",
45200 "extensions": ["twd","twds"]
45201 },
45202 "application/vnd.siren+json": {
45203 "source": "iana",
45204 "compressible": true
45205 },
45206 "application/vnd.smaf": {
45207 "source": "iana",
45208 "extensions": ["mmf"]
45209 },
45210 "application/vnd.smart.notebook": {
45211 "source": "iana"
45212 },
45213 "application/vnd.smart.teacher": {
45214 "source": "iana",
45215 "extensions": ["teacher"]
45216 },
45217 "application/vnd.software602.filler.form+xml": {
45218 "source": "iana",
45219 "compressible": true
45220 },
45221 "application/vnd.software602.filler.form-xml-zip": {
45222 "source": "iana"
45223 },
45224 "application/vnd.solent.sdkm+xml": {
45225 "source": "iana",
45226 "compressible": true,
45227 "extensions": ["sdkm","sdkd"]
45228 },
45229 "application/vnd.spotfire.dxp": {
45230 "source": "iana",
45231 "extensions": ["dxp"]
45232 },
45233 "application/vnd.spotfire.sfs": {
45234 "source": "iana",
45235 "extensions": ["sfs"]
45236 },
45237 "application/vnd.sqlite3": {
45238 "source": "iana"
45239 },
45240 "application/vnd.sss-cod": {
45241 "source": "iana"
45242 },
45243 "application/vnd.sss-dtf": {
45244 "source": "iana"
45245 },
45246 "application/vnd.sss-ntf": {
45247 "source": "iana"
45248 },
45249 "application/vnd.stardivision.calc": {
45250 "source": "apache",
45251 "extensions": ["sdc"]
45252 },
45253 "application/vnd.stardivision.draw": {
45254 "source": "apache",
45255 "extensions": ["sda"]
45256 },
45257 "application/vnd.stardivision.impress": {
45258 "source": "apache",
45259 "extensions": ["sdd"]
45260 },
45261 "application/vnd.stardivision.math": {
45262 "source": "apache",
45263 "extensions": ["smf"]
45264 },
45265 "application/vnd.stardivision.writer": {
45266 "source": "apache",
45267 "extensions": ["sdw","vor"]
45268 },
45269 "application/vnd.stardivision.writer-global": {
45270 "source": "apache",
45271 "extensions": ["sgl"]
45272 },
45273 "application/vnd.stepmania.package": {
45274 "source": "iana",
45275 "extensions": ["smzip"]
45276 },
45277 "application/vnd.stepmania.stepchart": {
45278 "source": "iana",
45279 "extensions": ["sm"]
45280 },
45281 "application/vnd.street-stream": {
45282 "source": "iana"
45283 },
45284 "application/vnd.sun.wadl+xml": {
45285 "source": "iana",
45286 "compressible": true,
45287 "extensions": ["wadl"]
45288 },
45289 "application/vnd.sun.xml.calc": {
45290 "source": "apache",
45291 "extensions": ["sxc"]
45292 },
45293 "application/vnd.sun.xml.calc.template": {
45294 "source": "apache",
45295 "extensions": ["stc"]
45296 },
45297 "application/vnd.sun.xml.draw": {
45298 "source": "apache",
45299 "extensions": ["sxd"]
45300 },
45301 "application/vnd.sun.xml.draw.template": {
45302 "source": "apache",
45303 "extensions": ["std"]
45304 },
45305 "application/vnd.sun.xml.impress": {
45306 "source": "apache",
45307 "extensions": ["sxi"]
45308 },
45309 "application/vnd.sun.xml.impress.template": {
45310 "source": "apache",
45311 "extensions": ["sti"]
45312 },
45313 "application/vnd.sun.xml.math": {
45314 "source": "apache",
45315 "extensions": ["sxm"]
45316 },
45317 "application/vnd.sun.xml.writer": {
45318 "source": "apache",
45319 "extensions": ["sxw"]
45320 },
45321 "application/vnd.sun.xml.writer.global": {
45322 "source": "apache",
45323 "extensions": ["sxg"]
45324 },
45325 "application/vnd.sun.xml.writer.template": {
45326 "source": "apache",
45327 "extensions": ["stw"]
45328 },
45329 "application/vnd.sus-calendar": {
45330 "source": "iana",
45331 "extensions": ["sus","susp"]
45332 },
45333 "application/vnd.svd": {
45334 "source": "iana",
45335 "extensions": ["svd"]
45336 },
45337 "application/vnd.swiftview-ics": {
45338 "source": "iana"
45339 },
45340 "application/vnd.symbian.install": {
45341 "source": "apache",
45342 "extensions": ["sis","sisx"]
45343 },
45344 "application/vnd.syncml+xml": {
45345 "source": "iana",
45346 "compressible": true,
45347 "extensions": ["xsm"]
45348 },
45349 "application/vnd.syncml.dm+wbxml": {
45350 "source": "iana",
45351 "extensions": ["bdm"]
45352 },
45353 "application/vnd.syncml.dm+xml": {
45354 "source": "iana",
45355 "compressible": true,
45356 "extensions": ["xdm"]
45357 },
45358 "application/vnd.syncml.dm.notification": {
45359 "source": "iana"
45360 },
45361 "application/vnd.syncml.dmddf+wbxml": {
45362 "source": "iana"
45363 },
45364 "application/vnd.syncml.dmddf+xml": {
45365 "source": "iana",
45366 "compressible": true
45367 },
45368 "application/vnd.syncml.dmtnds+wbxml": {
45369 "source": "iana"
45370 },
45371 "application/vnd.syncml.dmtnds+xml": {
45372 "source": "iana",
45373 "compressible": true
45374 },
45375 "application/vnd.syncml.ds.notification": {
45376 "source": "iana"
45377 },
45378 "application/vnd.tableschema+json": {
45379 "source": "iana",
45380 "compressible": true
45381 },
45382 "application/vnd.tao.intent-module-archive": {
45383 "source": "iana",
45384 "extensions": ["tao"]
45385 },
45386 "application/vnd.tcpdump.pcap": {
45387 "source": "iana",
45388 "extensions": ["pcap","cap","dmp"]
45389 },
45390 "application/vnd.think-cell.ppttc+json": {
45391 "source": "iana",
45392 "compressible": true
45393 },
45394 "application/vnd.tmd.mediaflex.api+xml": {
45395 "source": "iana",
45396 "compressible": true
45397 },
45398 "application/vnd.tml": {
45399 "source": "iana"
45400 },
45401 "application/vnd.tmobile-livetv": {
45402 "source": "iana",
45403 "extensions": ["tmo"]
45404 },
45405 "application/vnd.tri.onesource": {
45406 "source": "iana"
45407 },
45408 "application/vnd.trid.tpt": {
45409 "source": "iana",
45410 "extensions": ["tpt"]
45411 },
45412 "application/vnd.triscape.mxs": {
45413 "source": "iana",
45414 "extensions": ["mxs"]
45415 },
45416 "application/vnd.trueapp": {
45417 "source": "iana",
45418 "extensions": ["tra"]
45419 },
45420 "application/vnd.truedoc": {
45421 "source": "iana"
45422 },
45423 "application/vnd.ubisoft.webplayer": {
45424 "source": "iana"
45425 },
45426 "application/vnd.ufdl": {
45427 "source": "iana",
45428 "extensions": ["ufd","ufdl"]
45429 },
45430 "application/vnd.uiq.theme": {
45431 "source": "iana",
45432 "extensions": ["utz"]
45433 },
45434 "application/vnd.umajin": {
45435 "source": "iana",
45436 "extensions": ["umj"]
45437 },
45438 "application/vnd.unity": {
45439 "source": "iana",
45440 "extensions": ["unityweb"]
45441 },
45442 "application/vnd.uoml+xml": {
45443 "source": "iana",
45444 "compressible": true,
45445 "extensions": ["uoml"]
45446 },
45447 "application/vnd.uplanet.alert": {
45448 "source": "iana"
45449 },
45450 "application/vnd.uplanet.alert-wbxml": {
45451 "source": "iana"
45452 },
45453 "application/vnd.uplanet.bearer-choice": {
45454 "source": "iana"
45455 },
45456 "application/vnd.uplanet.bearer-choice-wbxml": {
45457 "source": "iana"
45458 },
45459 "application/vnd.uplanet.cacheop": {
45460 "source": "iana"
45461 },
45462 "application/vnd.uplanet.cacheop-wbxml": {
45463 "source": "iana"
45464 },
45465 "application/vnd.uplanet.channel": {
45466 "source": "iana"
45467 },
45468 "application/vnd.uplanet.channel-wbxml": {
45469 "source": "iana"
45470 },
45471 "application/vnd.uplanet.list": {
45472 "source": "iana"
45473 },
45474 "application/vnd.uplanet.list-wbxml": {
45475 "source": "iana"
45476 },
45477 "application/vnd.uplanet.listcmd": {
45478 "source": "iana"
45479 },
45480 "application/vnd.uplanet.listcmd-wbxml": {
45481 "source": "iana"
45482 },
45483 "application/vnd.uplanet.signal": {
45484 "source": "iana"
45485 },
45486 "application/vnd.uri-map": {
45487 "source": "iana"
45488 },
45489 "application/vnd.valve.source.material": {
45490 "source": "iana"
45491 },
45492 "application/vnd.vcx": {
45493 "source": "iana",
45494 "extensions": ["vcx"]
45495 },
45496 "application/vnd.vd-study": {
45497 "source": "iana"
45498 },
45499 "application/vnd.vectorworks": {
45500 "source": "iana"
45501 },
45502 "application/vnd.vel+json": {
45503 "source": "iana",
45504 "compressible": true
45505 },
45506 "application/vnd.verimatrix.vcas": {
45507 "source": "iana"
45508 },
45509 "application/vnd.veryant.thin": {
45510 "source": "iana"
45511 },
45512 "application/vnd.vidsoft.vidconference": {
45513 "source": "iana"
45514 },
45515 "application/vnd.visio": {
45516 "source": "iana",
45517 "extensions": ["vsd","vst","vss","vsw"]
45518 },
45519 "application/vnd.visionary": {
45520 "source": "iana",
45521 "extensions": ["vis"]
45522 },
45523 "application/vnd.vividence.scriptfile": {
45524 "source": "iana"
45525 },
45526 "application/vnd.vsf": {
45527 "source": "iana",
45528 "extensions": ["vsf"]
45529 },
45530 "application/vnd.wap.sic": {
45531 "source": "iana"
45532 },
45533 "application/vnd.wap.slc": {
45534 "source": "iana"
45535 },
45536 "application/vnd.wap.wbxml": {
45537 "source": "iana",
45538 "extensions": ["wbxml"]
45539 },
45540 "application/vnd.wap.wmlc": {
45541 "source": "iana",
45542 "extensions": ["wmlc"]
45543 },
45544 "application/vnd.wap.wmlscriptc": {
45545 "source": "iana",
45546 "extensions": ["wmlsc"]
45547 },
45548 "application/vnd.webturbo": {
45549 "source": "iana",
45550 "extensions": ["wtb"]
45551 },
45552 "application/vnd.wfa.p2p": {
45553 "source": "iana"
45554 },
45555 "application/vnd.wfa.wsc": {
45556 "source": "iana"
45557 },
45558 "application/vnd.windows.devicepairing": {
45559 "source": "iana"
45560 },
45561 "application/vnd.wmc": {
45562 "source": "iana"
45563 },
45564 "application/vnd.wmf.bootstrap": {
45565 "source": "iana"
45566 },
45567 "application/vnd.wolfram.mathematica": {
45568 "source": "iana"
45569 },
45570 "application/vnd.wolfram.mathematica.package": {
45571 "source": "iana"
45572 },
45573 "application/vnd.wolfram.player": {
45574 "source": "iana",
45575 "extensions": ["nbp"]
45576 },
45577 "application/vnd.wordperfect": {
45578 "source": "iana",
45579 "extensions": ["wpd"]
45580 },
45581 "application/vnd.wqd": {
45582 "source": "iana",
45583 "extensions": ["wqd"]
45584 },
45585 "application/vnd.wrq-hp3000-labelled": {
45586 "source": "iana"
45587 },
45588 "application/vnd.wt.stf": {
45589 "source": "iana",
45590 "extensions": ["stf"]
45591 },
45592 "application/vnd.wv.csp+wbxml": {
45593 "source": "iana"
45594 },
45595 "application/vnd.wv.csp+xml": {
45596 "source": "iana",
45597 "compressible": true
45598 },
45599 "application/vnd.wv.ssp+xml": {
45600 "source": "iana",
45601 "compressible": true
45602 },
45603 "application/vnd.xacml+json": {
45604 "source": "iana",
45605 "compressible": true
45606 },
45607 "application/vnd.xara": {
45608 "source": "iana",
45609 "extensions": ["xar"]
45610 },
45611 "application/vnd.xfdl": {
45612 "source": "iana",
45613 "extensions": ["xfdl"]
45614 },
45615 "application/vnd.xfdl.webform": {
45616 "source": "iana"
45617 },
45618 "application/vnd.xmi+xml": {
45619 "source": "iana",
45620 "compressible": true
45621 },
45622 "application/vnd.xmpie.cpkg": {
45623 "source": "iana"
45624 },
45625 "application/vnd.xmpie.dpkg": {
45626 "source": "iana"
45627 },
45628 "application/vnd.xmpie.plan": {
45629 "source": "iana"
45630 },
45631 "application/vnd.xmpie.ppkg": {
45632 "source": "iana"
45633 },
45634 "application/vnd.xmpie.xlim": {
45635 "source": "iana"
45636 },
45637 "application/vnd.yamaha.hv-dic": {
45638 "source": "iana",
45639 "extensions": ["hvd"]
45640 },
45641 "application/vnd.yamaha.hv-script": {
45642 "source": "iana",
45643 "extensions": ["hvs"]
45644 },
45645 "application/vnd.yamaha.hv-voice": {
45646 "source": "iana",
45647 "extensions": ["hvp"]
45648 },
45649 "application/vnd.yamaha.openscoreformat": {
45650 "source": "iana",
45651 "extensions": ["osf"]
45652 },
45653 "application/vnd.yamaha.openscoreformat.osfpvg+xml": {
45654 "source": "iana",
45655 "compressible": true,
45656 "extensions": ["osfpvg"]
45657 },
45658 "application/vnd.yamaha.remote-setup": {
45659 "source": "iana"
45660 },
45661 "application/vnd.yamaha.smaf-audio": {
45662 "source": "iana",
45663 "extensions": ["saf"]
45664 },
45665 "application/vnd.yamaha.smaf-phrase": {
45666 "source": "iana",
45667 "extensions": ["spf"]
45668 },
45669 "application/vnd.yamaha.through-ngn": {
45670 "source": "iana"
45671 },
45672 "application/vnd.yamaha.tunnel-udpencap": {
45673 "source": "iana"
45674 },
45675 "application/vnd.yaoweme": {
45676 "source": "iana"
45677 },
45678 "application/vnd.yellowriver-custom-menu": {
45679 "source": "iana",
45680 "extensions": ["cmp"]
45681 },
45682 "application/vnd.youtube.yt": {
45683 "source": "iana"
45684 },
45685 "application/vnd.zul": {
45686 "source": "iana",
45687 "extensions": ["zir","zirz"]
45688 },
45689 "application/vnd.zzazz.deck+xml": {
45690 "source": "iana",
45691 "compressible": true,
45692 "extensions": ["zaz"]
45693 },
45694 "application/voicexml+xml": {
45695 "source": "iana",
45696 "compressible": true,
45697 "extensions": ["vxml"]
45698 },
45699 "application/voucher-cms+json": {
45700 "source": "iana",
45701 "compressible": true
45702 },
45703 "application/vq-rtcpxr": {
45704 "source": "iana"
45705 },
45706 "application/wasm": {
45707 "compressible": true,
45708 "extensions": ["wasm"]
45709 },
45710 "application/watcherinfo+xml": {
45711 "source": "iana",
45712 "compressible": true
45713 },
45714 "application/webpush-options+json": {
45715 "source": "iana",
45716 "compressible": true
45717 },
45718 "application/whoispp-query": {
45719 "source": "iana"
45720 },
45721 "application/whoispp-response": {
45722 "source": "iana"
45723 },
45724 "application/widget": {
45725 "source": "iana",
45726 "extensions": ["wgt"]
45727 },
45728 "application/winhlp": {
45729 "source": "apache",
45730 "extensions": ["hlp"]
45731 },
45732 "application/wita": {
45733 "source": "iana"
45734 },
45735 "application/wordperfect5.1": {
45736 "source": "iana"
45737 },
45738 "application/wsdl+xml": {
45739 "source": "iana",
45740 "compressible": true,
45741 "extensions": ["wsdl"]
45742 },
45743 "application/wspolicy+xml": {
45744 "source": "iana",
45745 "compressible": true,
45746 "extensions": ["wspolicy"]
45747 },
45748 "application/x-7z-compressed": {
45749 "source": "apache",
45750 "compressible": false,
45751 "extensions": ["7z"]
45752 },
45753 "application/x-abiword": {
45754 "source": "apache",
45755 "extensions": ["abw"]
45756 },
45757 "application/x-ace-compressed": {
45758 "source": "apache",
45759 "extensions": ["ace"]
45760 },
45761 "application/x-amf": {
45762 "source": "apache"
45763 },
45764 "application/x-apple-diskimage": {
45765 "source": "apache",
45766 "extensions": ["dmg"]
45767 },
45768 "application/x-arj": {
45769 "compressible": false,
45770 "extensions": ["arj"]
45771 },
45772 "application/x-authorware-bin": {
45773 "source": "apache",
45774 "extensions": ["aab","x32","u32","vox"]
45775 },
45776 "application/x-authorware-map": {
45777 "source": "apache",
45778 "extensions": ["aam"]
45779 },
45780 "application/x-authorware-seg": {
45781 "source": "apache",
45782 "extensions": ["aas"]
45783 },
45784 "application/x-bcpio": {
45785 "source": "apache",
45786 "extensions": ["bcpio"]
45787 },
45788 "application/x-bdoc": {
45789 "compressible": false,
45790 "extensions": ["bdoc"]
45791 },
45792 "application/x-bittorrent": {
45793 "source": "apache",
45794 "extensions": ["torrent"]
45795 },
45796 "application/x-blorb": {
45797 "source": "apache",
45798 "extensions": ["blb","blorb"]
45799 },
45800 "application/x-bzip": {
45801 "source": "apache",
45802 "compressible": false,
45803 "extensions": ["bz"]
45804 },
45805 "application/x-bzip2": {
45806 "source": "apache",
45807 "compressible": false,
45808 "extensions": ["bz2","boz"]
45809 },
45810 "application/x-cbr": {
45811 "source": "apache",
45812 "extensions": ["cbr","cba","cbt","cbz","cb7"]
45813 },
45814 "application/x-cdlink": {
45815 "source": "apache",
45816 "extensions": ["vcd"]
45817 },
45818 "application/x-cfs-compressed": {
45819 "source": "apache",
45820 "extensions": ["cfs"]
45821 },
45822 "application/x-chat": {
45823 "source": "apache",
45824 "extensions": ["chat"]
45825 },
45826 "application/x-chess-pgn": {
45827 "source": "apache",
45828 "extensions": ["pgn"]
45829 },
45830 "application/x-chrome-extension": {
45831 "extensions": ["crx"]
45832 },
45833 "application/x-cocoa": {
45834 "source": "nginx",
45835 "extensions": ["cco"]
45836 },
45837 "application/x-compress": {
45838 "source": "apache"
45839 },
45840 "application/x-conference": {
45841 "source": "apache",
45842 "extensions": ["nsc"]
45843 },
45844 "application/x-cpio": {
45845 "source": "apache",
45846 "extensions": ["cpio"]
45847 },
45848 "application/x-csh": {
45849 "source": "apache",
45850 "extensions": ["csh"]
45851 },
45852 "application/x-deb": {
45853 "compressible": false
45854 },
45855 "application/x-debian-package": {
45856 "source": "apache",
45857 "extensions": ["deb","udeb"]
45858 },
45859 "application/x-dgc-compressed": {
45860 "source": "apache",
45861 "extensions": ["dgc"]
45862 },
45863 "application/x-director": {
45864 "source": "apache",
45865 "extensions": ["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"]
45866 },
45867 "application/x-doom": {
45868 "source": "apache",
45869 "extensions": ["wad"]
45870 },
45871 "application/x-dtbncx+xml": {
45872 "source": "apache",
45873 "compressible": true,
45874 "extensions": ["ncx"]
45875 },
45876 "application/x-dtbook+xml": {
45877 "source": "apache",
45878 "compressible": true,
45879 "extensions": ["dtb"]
45880 },
45881 "application/x-dtbresource+xml": {
45882 "source": "apache",
45883 "compressible": true,
45884 "extensions": ["res"]
45885 },
45886 "application/x-dvi": {
45887 "source": "apache",
45888 "compressible": false,
45889 "extensions": ["dvi"]
45890 },
45891 "application/x-envoy": {
45892 "source": "apache",
45893 "extensions": ["evy"]
45894 },
45895 "application/x-eva": {
45896 "source": "apache",
45897 "extensions": ["eva"]
45898 },
45899 "application/x-font-bdf": {
45900 "source": "apache",
45901 "extensions": ["bdf"]
45902 },
45903 "application/x-font-dos": {
45904 "source": "apache"
45905 },
45906 "application/x-font-framemaker": {
45907 "source": "apache"
45908 },
45909 "application/x-font-ghostscript": {
45910 "source": "apache",
45911 "extensions": ["gsf"]
45912 },
45913 "application/x-font-libgrx": {
45914 "source": "apache"
45915 },
45916 "application/x-font-linux-psf": {
45917 "source": "apache",
45918 "extensions": ["psf"]
45919 },
45920 "application/x-font-pcf": {
45921 "source": "apache",
45922 "extensions": ["pcf"]
45923 },
45924 "application/x-font-snf": {
45925 "source": "apache",
45926 "extensions": ["snf"]
45927 },
45928 "application/x-font-speedo": {
45929 "source": "apache"
45930 },
45931 "application/x-font-sunos-news": {
45932 "source": "apache"
45933 },
45934 "application/x-font-type1": {
45935 "source": "apache",
45936 "extensions": ["pfa","pfb","pfm","afm"]
45937 },
45938 "application/x-font-vfont": {
45939 "source": "apache"
45940 },
45941 "application/x-freearc": {
45942 "source": "apache",
45943 "extensions": ["arc"]
45944 },
45945 "application/x-futuresplash": {
45946 "source": "apache",
45947 "extensions": ["spl"]
45948 },
45949 "application/x-gca-compressed": {
45950 "source": "apache",
45951 "extensions": ["gca"]
45952 },
45953 "application/x-glulx": {
45954 "source": "apache",
45955 "extensions": ["ulx"]
45956 },
45957 "application/x-gnumeric": {
45958 "source": "apache",
45959 "extensions": ["gnumeric"]
45960 },
45961 "application/x-gramps-xml": {
45962 "source": "apache",
45963 "extensions": ["gramps"]
45964 },
45965 "application/x-gtar": {
45966 "source": "apache",
45967 "extensions": ["gtar"]
45968 },
45969 "application/x-gzip": {
45970 "source": "apache"
45971 },
45972 "application/x-hdf": {
45973 "source": "apache",
45974 "extensions": ["hdf"]
45975 },
45976 "application/x-httpd-php": {
45977 "compressible": true,
45978 "extensions": ["php"]
45979 },
45980 "application/x-install-instructions": {
45981 "source": "apache",
45982 "extensions": ["install"]
45983 },
45984 "application/x-iso9660-image": {
45985 "source": "apache",
45986 "extensions": ["iso"]
45987 },
45988 "application/x-java-archive-diff": {
45989 "source": "nginx",
45990 "extensions": ["jardiff"]
45991 },
45992 "application/x-java-jnlp-file": {
45993 "source": "apache",
45994 "compressible": false,
45995 "extensions": ["jnlp"]
45996 },
45997 "application/x-javascript": {
45998 "compressible": true
45999 },
46000 "application/x-latex": {
46001 "source": "apache",
46002 "compressible": false,
46003 "extensions": ["latex"]
46004 },
46005 "application/x-lua-bytecode": {
46006 "extensions": ["luac"]
46007 },
46008 "application/x-lzh-compressed": {
46009 "source": "apache",
46010 "extensions": ["lzh","lha"]
46011 },
46012 "application/x-makeself": {
46013 "source": "nginx",
46014 "extensions": ["run"]
46015 },
46016 "application/x-mie": {
46017 "source": "apache",
46018 "extensions": ["mie"]
46019 },
46020 "application/x-mobipocket-ebook": {
46021 "source": "apache",
46022 "extensions": ["prc","mobi"]
46023 },
46024 "application/x-mpegurl": {
46025 "compressible": false
46026 },
46027 "application/x-ms-application": {
46028 "source": "apache",
46029 "extensions": ["application"]
46030 },
46031 "application/x-ms-shortcut": {
46032 "source": "apache",
46033 "extensions": ["lnk"]
46034 },
46035 "application/x-ms-wmd": {
46036 "source": "apache",
46037 "extensions": ["wmd"]
46038 },
46039 "application/x-ms-wmz": {
46040 "source": "apache",
46041 "extensions": ["wmz"]
46042 },
46043 "application/x-ms-xbap": {
46044 "source": "apache",
46045 "extensions": ["xbap"]
46046 },
46047 "application/x-msaccess": {
46048 "source": "apache",
46049 "extensions": ["mdb"]
46050 },
46051 "application/x-msbinder": {
46052 "source": "apache",
46053 "extensions": ["obd"]
46054 },
46055 "application/x-mscardfile": {
46056 "source": "apache",
46057 "extensions": ["crd"]
46058 },
46059 "application/x-msclip": {
46060 "source": "apache",
46061 "extensions": ["clp"]
46062 },
46063 "application/x-msdos-program": {
46064 "extensions": ["exe"]
46065 },
46066 "application/x-msdownload": {
46067 "source": "apache",
46068 "extensions": ["exe","dll","com","bat","msi"]
46069 },
46070 "application/x-msmediaview": {
46071 "source": "apache",
46072 "extensions": ["mvb","m13","m14"]
46073 },
46074 "application/x-msmetafile": {
46075 "source": "apache",
46076 "extensions": ["wmf","wmz","emf","emz"]
46077 },
46078 "application/x-msmoney": {
46079 "source": "apache",
46080 "extensions": ["mny"]
46081 },
46082 "application/x-mspublisher": {
46083 "source": "apache",
46084 "extensions": ["pub"]
46085 },
46086 "application/x-msschedule": {
46087 "source": "apache",
46088 "extensions": ["scd"]
46089 },
46090 "application/x-msterminal": {
46091 "source": "apache",
46092 "extensions": ["trm"]
46093 },
46094 "application/x-mswrite": {
46095 "source": "apache",
46096 "extensions": ["wri"]
46097 },
46098 "application/x-netcdf": {
46099 "source": "apache",
46100 "extensions": ["nc","cdf"]
46101 },
46102 "application/x-ns-proxy-autoconfig": {
46103 "compressible": true,
46104 "extensions": ["pac"]
46105 },
46106 "application/x-nzb": {
46107 "source": "apache",
46108 "extensions": ["nzb"]
46109 },
46110 "application/x-perl": {
46111 "source": "nginx",
46112 "extensions": ["pl","pm"]
46113 },
46114 "application/x-pilot": {
46115 "source": "nginx",
46116 "extensions": ["prc","pdb"]
46117 },
46118 "application/x-pkcs12": {
46119 "source": "apache",
46120 "compressible": false,
46121 "extensions": ["p12","pfx"]
46122 },
46123 "application/x-pkcs7-certificates": {
46124 "source": "apache",
46125 "extensions": ["p7b","spc"]
46126 },
46127 "application/x-pkcs7-certreqresp": {
46128 "source": "apache",
46129 "extensions": ["p7r"]
46130 },
46131 "application/x-rar-compressed": {
46132 "source": "apache",
46133 "compressible": false,
46134 "extensions": ["rar"]
46135 },
46136 "application/x-redhat-package-manager": {
46137 "source": "nginx",
46138 "extensions": ["rpm"]
46139 },
46140 "application/x-research-info-systems": {
46141 "source": "apache",
46142 "extensions": ["ris"]
46143 },
46144 "application/x-sea": {
46145 "source": "nginx",
46146 "extensions": ["sea"]
46147 },
46148 "application/x-sh": {
46149 "source": "apache",
46150 "compressible": true,
46151 "extensions": ["sh"]
46152 },
46153 "application/x-shar": {
46154 "source": "apache",
46155 "extensions": ["shar"]
46156 },
46157 "application/x-shockwave-flash": {
46158 "source": "apache",
46159 "compressible": false,
46160 "extensions": ["swf"]
46161 },
46162 "application/x-silverlight-app": {
46163 "source": "apache",
46164 "extensions": ["xap"]
46165 },
46166 "application/x-sql": {
46167 "source": "apache",
46168 "extensions": ["sql"]
46169 },
46170 "application/x-stuffit": {
46171 "source": "apache",
46172 "compressible": false,
46173 "extensions": ["sit"]
46174 },
46175 "application/x-stuffitx": {
46176 "source": "apache",
46177 "extensions": ["sitx"]
46178 },
46179 "application/x-subrip": {
46180 "source": "apache",
46181 "extensions": ["srt"]
46182 },
46183 "application/x-sv4cpio": {
46184 "source": "apache",
46185 "extensions": ["sv4cpio"]
46186 },
46187 "application/x-sv4crc": {
46188 "source": "apache",
46189 "extensions": ["sv4crc"]
46190 },
46191 "application/x-t3vm-image": {
46192 "source": "apache",
46193 "extensions": ["t3"]
46194 },
46195 "application/x-tads": {
46196 "source": "apache",
46197 "extensions": ["gam"]
46198 },
46199 "application/x-tar": {
46200 "source": "apache",
46201 "compressible": true,
46202 "extensions": ["tar"]
46203 },
46204 "application/x-tcl": {
46205 "source": "apache",
46206 "extensions": ["tcl","tk"]
46207 },
46208 "application/x-tex": {
46209 "source": "apache",
46210 "extensions": ["tex"]
46211 },
46212 "application/x-tex-tfm": {
46213 "source": "apache",
46214 "extensions": ["tfm"]
46215 },
46216 "application/x-texinfo": {
46217 "source": "apache",
46218 "extensions": ["texinfo","texi"]
46219 },
46220 "application/x-tgif": {
46221 "source": "apache",
46222 "extensions": ["obj"]
46223 },
46224 "application/x-ustar": {
46225 "source": "apache",
46226 "extensions": ["ustar"]
46227 },
46228 "application/x-virtualbox-hdd": {
46229 "compressible": true,
46230 "extensions": ["hdd"]
46231 },
46232 "application/x-virtualbox-ova": {
46233 "compressible": true,
46234 "extensions": ["ova"]
46235 },
46236 "application/x-virtualbox-ovf": {
46237 "compressible": true,
46238 "extensions": ["ovf"]
46239 },
46240 "application/x-virtualbox-vbox": {
46241 "compressible": true,
46242 "extensions": ["vbox"]
46243 },
46244 "application/x-virtualbox-vbox-extpack": {
46245 "compressible": false,
46246 "extensions": ["vbox-extpack"]
46247 },
46248 "application/x-virtualbox-vdi": {
46249 "compressible": true,
46250 "extensions": ["vdi"]
46251 },
46252 "application/x-virtualbox-vhd": {
46253 "compressible": true,
46254 "extensions": ["vhd"]
46255 },
46256 "application/x-virtualbox-vmdk": {
46257 "compressible": true,
46258 "extensions": ["vmdk"]
46259 },
46260 "application/x-wais-source": {
46261 "source": "apache",
46262 "extensions": ["src"]
46263 },
46264 "application/x-web-app-manifest+json": {
46265 "compressible": true,
46266 "extensions": ["webapp"]
46267 },
46268 "application/x-www-form-urlencoded": {
46269 "source": "iana",
46270 "compressible": true
46271 },
46272 "application/x-x509-ca-cert": {
46273 "source": "apache",
46274 "extensions": ["der","crt","pem"]
46275 },
46276 "application/x-xfig": {
46277 "source": "apache",
46278 "extensions": ["fig"]
46279 },
46280 "application/x-xliff+xml": {
46281 "source": "apache",
46282 "compressible": true,
46283 "extensions": ["xlf"]
46284 },
46285 "application/x-xpinstall": {
46286 "source": "apache",
46287 "compressible": false,
46288 "extensions": ["xpi"]
46289 },
46290 "application/x-xz": {
46291 "source": "apache",
46292 "extensions": ["xz"]
46293 },
46294 "application/x-zmachine": {
46295 "source": "apache",
46296 "extensions": ["z1","z2","z3","z4","z5","z6","z7","z8"]
46297 },
46298 "application/x400-bp": {
46299 "source": "iana"
46300 },
46301 "application/xacml+xml": {
46302 "source": "iana",
46303 "compressible": true
46304 },
46305 "application/xaml+xml": {
46306 "source": "apache",
46307 "compressible": true,
46308 "extensions": ["xaml"]
46309 },
46310 "application/xcap-att+xml": {
46311 "source": "iana",
46312 "compressible": true
46313 },
46314 "application/xcap-caps+xml": {
46315 "source": "iana",
46316 "compressible": true
46317 },
46318 "application/xcap-diff+xml": {
46319 "source": "iana",
46320 "compressible": true,
46321 "extensions": ["xdf"]
46322 },
46323 "application/xcap-el+xml": {
46324 "source": "iana",
46325 "compressible": true
46326 },
46327 "application/xcap-error+xml": {
46328 "source": "iana",
46329 "compressible": true
46330 },
46331 "application/xcap-ns+xml": {
46332 "source": "iana",
46333 "compressible": true
46334 },
46335 "application/xcon-conference-info+xml": {
46336 "source": "iana",
46337 "compressible": true
46338 },
46339 "application/xcon-conference-info-diff+xml": {
46340 "source": "iana",
46341 "compressible": true
46342 },
46343 "application/xenc+xml": {
46344 "source": "iana",
46345 "compressible": true,
46346 "extensions": ["xenc"]
46347 },
46348 "application/xhtml+xml": {
46349 "source": "iana",
46350 "compressible": true,
46351 "extensions": ["xhtml","xht"]
46352 },
46353 "application/xhtml-voice+xml": {
46354 "source": "apache",
46355 "compressible": true
46356 },
46357 "application/xliff+xml": {
46358 "source": "iana",
46359 "compressible": true
46360 },
46361 "application/xml": {
46362 "source": "iana",
46363 "compressible": true,
46364 "extensions": ["xml","xsl","xsd","rng"]
46365 },
46366 "application/xml-dtd": {
46367 "source": "iana",
46368 "compressible": true,
46369 "extensions": ["dtd"]
46370 },
46371 "application/xml-external-parsed-entity": {
46372 "source": "iana"
46373 },
46374 "application/xml-patch+xml": {
46375 "source": "iana",
46376 "compressible": true
46377 },
46378 "application/xmpp+xml": {
46379 "source": "iana",
46380 "compressible": true
46381 },
46382 "application/xop+xml": {
46383 "source": "iana",
46384 "compressible": true,
46385 "extensions": ["xop"]
46386 },
46387 "application/xproc+xml": {
46388 "source": "apache",
46389 "compressible": true,
46390 "extensions": ["xpl"]
46391 },
46392 "application/xslt+xml": {
46393 "source": "iana",
46394 "compressible": true,
46395 "extensions": ["xslt"]
46396 },
46397 "application/xspf+xml": {
46398 "source": "apache",
46399 "compressible": true,
46400 "extensions": ["xspf"]
46401 },
46402 "application/xv+xml": {
46403 "source": "iana",
46404 "compressible": true,
46405 "extensions": ["mxml","xhvml","xvml","xvm"]
46406 },
46407 "application/yang": {
46408 "source": "iana",
46409 "extensions": ["yang"]
46410 },
46411 "application/yang-data+json": {
46412 "source": "iana",
46413 "compressible": true
46414 },
46415 "application/yang-data+xml": {
46416 "source": "iana",
46417 "compressible": true
46418 },
46419 "application/yang-patch+json": {
46420 "source": "iana",
46421 "compressible": true
46422 },
46423 "application/yang-patch+xml": {
46424 "source": "iana",
46425 "compressible": true
46426 },
46427 "application/yin+xml": {
46428 "source": "iana",
46429 "compressible": true,
46430 "extensions": ["yin"]
46431 },
46432 "application/zip": {
46433 "source": "iana",
46434 "compressible": false,
46435 "extensions": ["zip"]
46436 },
46437 "application/zlib": {
46438 "source": "iana"
46439 },
46440 "application/zstd": {
46441 "source": "iana"
46442 },
46443 "audio/1d-interleaved-parityfec": {
46444 "source": "iana"
46445 },
46446 "audio/32kadpcm": {
46447 "source": "iana"
46448 },
46449 "audio/3gpp": {
46450 "source": "iana",
46451 "compressible": false,
46452 "extensions": ["3gpp"]
46453 },
46454 "audio/3gpp2": {
46455 "source": "iana"
46456 },
46457 "audio/aac": {
46458 "source": "iana"
46459 },
46460 "audio/ac3": {
46461 "source": "iana"
46462 },
46463 "audio/adpcm": {
46464 "source": "apache",
46465 "extensions": ["adp"]
46466 },
46467 "audio/amr": {
46468 "source": "iana"
46469 },
46470 "audio/amr-wb": {
46471 "source": "iana"
46472 },
46473 "audio/amr-wb+": {
46474 "source": "iana"
46475 },
46476 "audio/aptx": {
46477 "source": "iana"
46478 },
46479 "audio/asc": {
46480 "source": "iana"
46481 },
46482 "audio/atrac-advanced-lossless": {
46483 "source": "iana"
46484 },
46485 "audio/atrac-x": {
46486 "source": "iana"
46487 },
46488 "audio/atrac3": {
46489 "source": "iana"
46490 },
46491 "audio/basic": {
46492 "source": "iana",
46493 "compressible": false,
46494 "extensions": ["au","snd"]
46495 },
46496 "audio/bv16": {
46497 "source": "iana"
46498 },
46499 "audio/bv32": {
46500 "source": "iana"
46501 },
46502 "audio/clearmode": {
46503 "source": "iana"
46504 },
46505 "audio/cn": {
46506 "source": "iana"
46507 },
46508 "audio/dat12": {
46509 "source": "iana"
46510 },
46511 "audio/dls": {
46512 "source": "iana"
46513 },
46514 "audio/dsr-es201108": {
46515 "source": "iana"
46516 },
46517 "audio/dsr-es202050": {
46518 "source": "iana"
46519 },
46520 "audio/dsr-es202211": {
46521 "source": "iana"
46522 },
46523 "audio/dsr-es202212": {
46524 "source": "iana"
46525 },
46526 "audio/dv": {
46527 "source": "iana"
46528 },
46529 "audio/dvi4": {
46530 "source": "iana"
46531 },
46532 "audio/eac3": {
46533 "source": "iana"
46534 },
46535 "audio/encaprtp": {
46536 "source": "iana"
46537 },
46538 "audio/evrc": {
46539 "source": "iana"
46540 },
46541 "audio/evrc-qcp": {
46542 "source": "iana"
46543 },
46544 "audio/evrc0": {
46545 "source": "iana"
46546 },
46547 "audio/evrc1": {
46548 "source": "iana"
46549 },
46550 "audio/evrcb": {
46551 "source": "iana"
46552 },
46553 "audio/evrcb0": {
46554 "source": "iana"
46555 },
46556 "audio/evrcb1": {
46557 "source": "iana"
46558 },
46559 "audio/evrcnw": {
46560 "source": "iana"
46561 },
46562 "audio/evrcnw0": {
46563 "source": "iana"
46564 },
46565 "audio/evrcnw1": {
46566 "source": "iana"
46567 },
46568 "audio/evrcwb": {
46569 "source": "iana"
46570 },
46571 "audio/evrcwb0": {
46572 "source": "iana"
46573 },
46574 "audio/evrcwb1": {
46575 "source": "iana"
46576 },
46577 "audio/evs": {
46578 "source": "iana"
46579 },
46580 "audio/fwdred": {
46581 "source": "iana"
46582 },
46583 "audio/g711-0": {
46584 "source": "iana"
46585 },
46586 "audio/g719": {
46587 "source": "iana"
46588 },
46589 "audio/g722": {
46590 "source": "iana"
46591 },
46592 "audio/g7221": {
46593 "source": "iana"
46594 },
46595 "audio/g723": {
46596 "source": "iana"
46597 },
46598 "audio/g726-16": {
46599 "source": "iana"
46600 },
46601 "audio/g726-24": {
46602 "source": "iana"
46603 },
46604 "audio/g726-32": {
46605 "source": "iana"
46606 },
46607 "audio/g726-40": {
46608 "source": "iana"
46609 },
46610 "audio/g728": {
46611 "source": "iana"
46612 },
46613 "audio/g729": {
46614 "source": "iana"
46615 },
46616 "audio/g7291": {
46617 "source": "iana"
46618 },
46619 "audio/g729d": {
46620 "source": "iana"
46621 },
46622 "audio/g729e": {
46623 "source": "iana"
46624 },
46625 "audio/gsm": {
46626 "source": "iana"
46627 },
46628 "audio/gsm-efr": {
46629 "source": "iana"
46630 },
46631 "audio/gsm-hr-08": {
46632 "source": "iana"
46633 },
46634 "audio/ilbc": {
46635 "source": "iana"
46636 },
46637 "audio/ip-mr_v2.5": {
46638 "source": "iana"
46639 },
46640 "audio/isac": {
46641 "source": "apache"
46642 },
46643 "audio/l16": {
46644 "source": "iana"
46645 },
46646 "audio/l20": {
46647 "source": "iana"
46648 },
46649 "audio/l24": {
46650 "source": "iana",
46651 "compressible": false
46652 },
46653 "audio/l8": {
46654 "source": "iana"
46655 },
46656 "audio/lpc": {
46657 "source": "iana"
46658 },
46659 "audio/melp": {
46660 "source": "iana"
46661 },
46662 "audio/melp1200": {
46663 "source": "iana"
46664 },
46665 "audio/melp2400": {
46666 "source": "iana"
46667 },
46668 "audio/melp600": {
46669 "source": "iana"
46670 },
46671 "audio/midi": {
46672 "source": "apache",
46673 "extensions": ["mid","midi","kar","rmi"]
46674 },
46675 "audio/mobile-xmf": {
46676 "source": "iana"
46677 },
46678 "audio/mp3": {
46679 "compressible": false,
46680 "extensions": ["mp3"]
46681 },
46682 "audio/mp4": {
46683 "source": "iana",
46684 "compressible": false,
46685 "extensions": ["m4a","mp4a"]
46686 },
46687 "audio/mp4a-latm": {
46688 "source": "iana"
46689 },
46690 "audio/mpa": {
46691 "source": "iana"
46692 },
46693 "audio/mpa-robust": {
46694 "source": "iana"
46695 },
46696 "audio/mpeg": {
46697 "source": "iana",
46698 "compressible": false,
46699 "extensions": ["mpga","mp2","mp2a","mp3","m2a","m3a"]
46700 },
46701 "audio/mpeg4-generic": {
46702 "source": "iana"
46703 },
46704 "audio/musepack": {
46705 "source": "apache"
46706 },
46707 "audio/ogg": {
46708 "source": "iana",
46709 "compressible": false,
46710 "extensions": ["oga","ogg","spx"]
46711 },
46712 "audio/opus": {
46713 "source": "iana"
46714 },
46715 "audio/parityfec": {
46716 "source": "iana"
46717 },
46718 "audio/pcma": {
46719 "source": "iana"
46720 },
46721 "audio/pcma-wb": {
46722 "source": "iana"
46723 },
46724 "audio/pcmu": {
46725 "source": "iana"
46726 },
46727 "audio/pcmu-wb": {
46728 "source": "iana"
46729 },
46730 "audio/prs.sid": {
46731 "source": "iana"
46732 },
46733 "audio/qcelp": {
46734 "source": "iana"
46735 },
46736 "audio/raptorfec": {
46737 "source": "iana"
46738 },
46739 "audio/red": {
46740 "source": "iana"
46741 },
46742 "audio/rtp-enc-aescm128": {
46743 "source": "iana"
46744 },
46745 "audio/rtp-midi": {
46746 "source": "iana"
46747 },
46748 "audio/rtploopback": {
46749 "source": "iana"
46750 },
46751 "audio/rtx": {
46752 "source": "iana"
46753 },
46754 "audio/s3m": {
46755 "source": "apache",
46756 "extensions": ["s3m"]
46757 },
46758 "audio/silk": {
46759 "source": "apache",
46760 "extensions": ["sil"]
46761 },
46762 "audio/smv": {
46763 "source": "iana"
46764 },
46765 "audio/smv-qcp": {
46766 "source": "iana"
46767 },
46768 "audio/smv0": {
46769 "source": "iana"
46770 },
46771 "audio/sp-midi": {
46772 "source": "iana"
46773 },
46774 "audio/speex": {
46775 "source": "iana"
46776 },
46777 "audio/t140c": {
46778 "source": "iana"
46779 },
46780 "audio/t38": {
46781 "source": "iana"
46782 },
46783 "audio/telephone-event": {
46784 "source": "iana"
46785 },
46786 "audio/tetra_acelp": {
46787 "source": "iana"
46788 },
46789 "audio/tone": {
46790 "source": "iana"
46791 },
46792 "audio/uemclip": {
46793 "source": "iana"
46794 },
46795 "audio/ulpfec": {
46796 "source": "iana"
46797 },
46798 "audio/usac": {
46799 "source": "iana"
46800 },
46801 "audio/vdvi": {
46802 "source": "iana"
46803 },
46804 "audio/vmr-wb": {
46805 "source": "iana"
46806 },
46807 "audio/vnd.3gpp.iufp": {
46808 "source": "iana"
46809 },
46810 "audio/vnd.4sb": {
46811 "source": "iana"
46812 },
46813 "audio/vnd.audiokoz": {
46814 "source": "iana"
46815 },
46816 "audio/vnd.celp": {
46817 "source": "iana"
46818 },
46819 "audio/vnd.cisco.nse": {
46820 "source": "iana"
46821 },
46822 "audio/vnd.cmles.radio-events": {
46823 "source": "iana"
46824 },
46825 "audio/vnd.cns.anp1": {
46826 "source": "iana"
46827 },
46828 "audio/vnd.cns.inf1": {
46829 "source": "iana"
46830 },
46831 "audio/vnd.dece.audio": {
46832 "source": "iana",
46833 "extensions": ["uva","uvva"]
46834 },
46835 "audio/vnd.digital-winds": {
46836 "source": "iana",
46837 "extensions": ["eol"]
46838 },
46839 "audio/vnd.dlna.adts": {
46840 "source": "iana"
46841 },
46842 "audio/vnd.dolby.heaac.1": {
46843 "source": "iana"
46844 },
46845 "audio/vnd.dolby.heaac.2": {
46846 "source": "iana"
46847 },
46848 "audio/vnd.dolby.mlp": {
46849 "source": "iana"
46850 },
46851 "audio/vnd.dolby.mps": {
46852 "source": "iana"
46853 },
46854 "audio/vnd.dolby.pl2": {
46855 "source": "iana"
46856 },
46857 "audio/vnd.dolby.pl2x": {
46858 "source": "iana"
46859 },
46860 "audio/vnd.dolby.pl2z": {
46861 "source": "iana"
46862 },
46863 "audio/vnd.dolby.pulse.1": {
46864 "source": "iana"
46865 },
46866 "audio/vnd.dra": {
46867 "source": "iana",
46868 "extensions": ["dra"]
46869 },
46870 "audio/vnd.dts": {
46871 "source": "iana",
46872 "extensions": ["dts"]
46873 },
46874 "audio/vnd.dts.hd": {
46875 "source": "iana",
46876 "extensions": ["dtshd"]
46877 },
46878 "audio/vnd.dts.uhd": {
46879 "source": "iana"
46880 },
46881 "audio/vnd.dvb.file": {
46882 "source": "iana"
46883 },
46884 "audio/vnd.everad.plj": {
46885 "source": "iana"
46886 },
46887 "audio/vnd.hns.audio": {
46888 "source": "iana"
46889 },
46890 "audio/vnd.lucent.voice": {
46891 "source": "iana",
46892 "extensions": ["lvp"]
46893 },
46894 "audio/vnd.ms-playready.media.pya": {
46895 "source": "iana",
46896 "extensions": ["pya"]
46897 },
46898 "audio/vnd.nokia.mobile-xmf": {
46899 "source": "iana"
46900 },
46901 "audio/vnd.nortel.vbk": {
46902 "source": "iana"
46903 },
46904 "audio/vnd.nuera.ecelp4800": {
46905 "source": "iana",
46906 "extensions": ["ecelp4800"]
46907 },
46908 "audio/vnd.nuera.ecelp7470": {
46909 "source": "iana",
46910 "extensions": ["ecelp7470"]
46911 },
46912 "audio/vnd.nuera.ecelp9600": {
46913 "source": "iana",
46914 "extensions": ["ecelp9600"]
46915 },
46916 "audio/vnd.octel.sbc": {
46917 "source": "iana"
46918 },
46919 "audio/vnd.presonus.multitrack": {
46920 "source": "iana"
46921 },
46922 "audio/vnd.qcelp": {
46923 "source": "iana"
46924 },
46925 "audio/vnd.rhetorex.32kadpcm": {
46926 "source": "iana"
46927 },
46928 "audio/vnd.rip": {
46929 "source": "iana",
46930 "extensions": ["rip"]
46931 },
46932 "audio/vnd.rn-realaudio": {
46933 "compressible": false
46934 },
46935 "audio/vnd.sealedmedia.softseal.mpeg": {
46936 "source": "iana"
46937 },
46938 "audio/vnd.vmx.cvsd": {
46939 "source": "iana"
46940 },
46941 "audio/vnd.wave": {
46942 "compressible": false
46943 },
46944 "audio/vorbis": {
46945 "source": "iana",
46946 "compressible": false
46947 },
46948 "audio/vorbis-config": {
46949 "source": "iana"
46950 },
46951 "audio/wav": {
46952 "compressible": false,
46953 "extensions": ["wav"]
46954 },
46955 "audio/wave": {
46956 "compressible": false,
46957 "extensions": ["wav"]
46958 },
46959 "audio/webm": {
46960 "source": "apache",
46961 "compressible": false,
46962 "extensions": ["weba"]
46963 },
46964 "audio/x-aac": {
46965 "source": "apache",
46966 "compressible": false,
46967 "extensions": ["aac"]
46968 },
46969 "audio/x-aiff": {
46970 "source": "apache",
46971 "extensions": ["aif","aiff","aifc"]
46972 },
46973 "audio/x-caf": {
46974 "source": "apache",
46975 "compressible": false,
46976 "extensions": ["caf"]
46977 },
46978 "audio/x-flac": {
46979 "source": "apache",
46980 "extensions": ["flac"]
46981 },
46982 "audio/x-m4a": {
46983 "source": "nginx",
46984 "extensions": ["m4a"]
46985 },
46986 "audio/x-matroska": {
46987 "source": "apache",
46988 "extensions": ["mka"]
46989 },
46990 "audio/x-mpegurl": {
46991 "source": "apache",
46992 "extensions": ["m3u"]
46993 },
46994 "audio/x-ms-wax": {
46995 "source": "apache",
46996 "extensions": ["wax"]
46997 },
46998 "audio/x-ms-wma": {
46999 "source": "apache",
47000 "extensions": ["wma"]
47001 },
47002 "audio/x-pn-realaudio": {
47003 "source": "apache",
47004 "extensions": ["ram","ra"]
47005 },
47006 "audio/x-pn-realaudio-plugin": {
47007 "source": "apache",
47008 "extensions": ["rmp"]
47009 },
47010 "audio/x-realaudio": {
47011 "source": "nginx",
47012 "extensions": ["ra"]
47013 },
47014 "audio/x-tta": {
47015 "source": "apache"
47016 },
47017 "audio/x-wav": {
47018 "source": "apache",
47019 "extensions": ["wav"]
47020 },
47021 "audio/xm": {
47022 "source": "apache",
47023 "extensions": ["xm"]
47024 },
47025 "chemical/x-cdx": {
47026 "source": "apache",
47027 "extensions": ["cdx"]
47028 },
47029 "chemical/x-cif": {
47030 "source": "apache",
47031 "extensions": ["cif"]
47032 },
47033 "chemical/x-cmdf": {
47034 "source": "apache",
47035 "extensions": ["cmdf"]
47036 },
47037 "chemical/x-cml": {
47038 "source": "apache",
47039 "extensions": ["cml"]
47040 },
47041 "chemical/x-csml": {
47042 "source": "apache",
47043 "extensions": ["csml"]
47044 },
47045 "chemical/x-pdb": {
47046 "source": "apache"
47047 },
47048 "chemical/x-xyz": {
47049 "source": "apache",
47050 "extensions": ["xyz"]
47051 },
47052 "font/collection": {
47053 "source": "iana",
47054 "extensions": ["ttc"]
47055 },
47056 "font/otf": {
47057 "source": "iana",
47058 "compressible": true,
47059 "extensions": ["otf"]
47060 },
47061 "font/sfnt": {
47062 "source": "iana"
47063 },
47064 "font/ttf": {
47065 "source": "iana",
47066 "extensions": ["ttf"]
47067 },
47068 "font/woff": {
47069 "source": "iana",
47070 "extensions": ["woff"]
47071 },
47072 "font/woff2": {
47073 "source": "iana",
47074 "extensions": ["woff2"]
47075 },
47076 "image/aces": {
47077 "source": "iana",
47078 "extensions": ["exr"]
47079 },
47080 "image/apng": {
47081 "compressible": false,
47082 "extensions": ["apng"]
47083 },
47084 "image/avci": {
47085 "source": "iana"
47086 },
47087 "image/avcs": {
47088 "source": "iana"
47089 },
47090 "image/bmp": {
47091 "source": "iana",
47092 "compressible": true,
47093 "extensions": ["bmp"]
47094 },
47095 "image/cgm": {
47096 "source": "iana",
47097 "extensions": ["cgm"]
47098 },
47099 "image/dicom-rle": {
47100 "source": "iana",
47101 "extensions": ["drle"]
47102 },
47103 "image/emf": {
47104 "source": "iana",
47105 "extensions": ["emf"]
47106 },
47107 "image/fits": {
47108 "source": "iana",
47109 "extensions": ["fits"]
47110 },
47111 "image/g3fax": {
47112 "source": "iana",
47113 "extensions": ["g3"]
47114 },
47115 "image/gif": {
47116 "source": "iana",
47117 "compressible": false,
47118 "extensions": ["gif"]
47119 },
47120 "image/heic": {
47121 "source": "iana",
47122 "extensions": ["heic"]
47123 },
47124 "image/heic-sequence": {
47125 "source": "iana",
47126 "extensions": ["heics"]
47127 },
47128 "image/heif": {
47129 "source": "iana",
47130 "extensions": ["heif"]
47131 },
47132 "image/heif-sequence": {
47133 "source": "iana",
47134 "extensions": ["heifs"]
47135 },
47136 "image/ief": {
47137 "source": "iana",
47138 "extensions": ["ief"]
47139 },
47140 "image/jls": {
47141 "source": "iana",
47142 "extensions": ["jls"]
47143 },
47144 "image/jp2": {
47145 "source": "iana",
47146 "compressible": false,
47147 "extensions": ["jp2","jpg2"]
47148 },
47149 "image/jpeg": {
47150 "source": "iana",
47151 "compressible": false,
47152 "extensions": ["jpeg","jpg","jpe"]
47153 },
47154 "image/jpm": {
47155 "source": "iana",
47156 "compressible": false,
47157 "extensions": ["jpm"]
47158 },
47159 "image/jpx": {
47160 "source": "iana",
47161 "compressible": false,
47162 "extensions": ["jpx","jpf"]
47163 },
47164 "image/jxr": {
47165 "source": "iana",
47166 "extensions": ["jxr"]
47167 },
47168 "image/ktx": {
47169 "source": "iana",
47170 "extensions": ["ktx"]
47171 },
47172 "image/naplps": {
47173 "source": "iana"
47174 },
47175 "image/pjpeg": {
47176 "compressible": false
47177 },
47178 "image/png": {
47179 "source": "iana",
47180 "compressible": false,
47181 "extensions": ["png"]
47182 },
47183 "image/prs.btif": {
47184 "source": "iana",
47185 "extensions": ["btif"]
47186 },
47187 "image/prs.pti": {
47188 "source": "iana",
47189 "extensions": ["pti"]
47190 },
47191 "image/pwg-raster": {
47192 "source": "iana"
47193 },
47194 "image/sgi": {
47195 "source": "apache",
47196 "extensions": ["sgi"]
47197 },
47198 "image/svg+xml": {
47199 "source": "iana",
47200 "compressible": true,
47201 "extensions": ["svg","svgz"]
47202 },
47203 "image/t38": {
47204 "source": "iana",
47205 "extensions": ["t38"]
47206 },
47207 "image/tiff": {
47208 "source": "iana",
47209 "compressible": false,
47210 "extensions": ["tif","tiff"]
47211 },
47212 "image/tiff-fx": {
47213 "source": "iana",
47214 "extensions": ["tfx"]
47215 },
47216 "image/vnd.adobe.photoshop": {
47217 "source": "iana",
47218 "compressible": true,
47219 "extensions": ["psd"]
47220 },
47221 "image/vnd.airzip.accelerator.azv": {
47222 "source": "iana",
47223 "extensions": ["azv"]
47224 },
47225 "image/vnd.cns.inf2": {
47226 "source": "iana"
47227 },
47228 "image/vnd.dece.graphic": {
47229 "source": "iana",
47230 "extensions": ["uvi","uvvi","uvg","uvvg"]
47231 },
47232 "image/vnd.djvu": {
47233 "source": "iana",
47234 "extensions": ["djvu","djv"]
47235 },
47236 "image/vnd.dvb.subtitle": {
47237 "source": "iana",
47238 "extensions": ["sub"]
47239 },
47240 "image/vnd.dwg": {
47241 "source": "iana",
47242 "extensions": ["dwg"]
47243 },
47244 "image/vnd.dxf": {
47245 "source": "iana",
47246 "extensions": ["dxf"]
47247 },
47248 "image/vnd.fastbidsheet": {
47249 "source": "iana",
47250 "extensions": ["fbs"]
47251 },
47252 "image/vnd.fpx": {
47253 "source": "iana",
47254 "extensions": ["fpx"]
47255 },
47256 "image/vnd.fst": {
47257 "source": "iana",
47258 "extensions": ["fst"]
47259 },
47260 "image/vnd.fujixerox.edmics-mmr": {
47261 "source": "iana",
47262 "extensions": ["mmr"]
47263 },
47264 "image/vnd.fujixerox.edmics-rlc": {
47265 "source": "iana",
47266 "extensions": ["rlc"]
47267 },
47268 "image/vnd.globalgraphics.pgb": {
47269 "source": "iana"
47270 },
47271 "image/vnd.microsoft.icon": {
47272 "source": "iana",
47273 "extensions": ["ico"]
47274 },
47275 "image/vnd.mix": {
47276 "source": "iana"
47277 },
47278 "image/vnd.mozilla.apng": {
47279 "source": "iana"
47280 },
47281 "image/vnd.ms-modi": {
47282 "source": "iana",
47283 "extensions": ["mdi"]
47284 },
47285 "image/vnd.ms-photo": {
47286 "source": "apache",
47287 "extensions": ["wdp"]
47288 },
47289 "image/vnd.net-fpx": {
47290 "source": "iana",
47291 "extensions": ["npx"]
47292 },
47293 "image/vnd.radiance": {
47294 "source": "iana"
47295 },
47296 "image/vnd.sealed.png": {
47297 "source": "iana"
47298 },
47299 "image/vnd.sealedmedia.softseal.gif": {
47300 "source": "iana"
47301 },
47302 "image/vnd.sealedmedia.softseal.jpg": {
47303 "source": "iana"
47304 },
47305 "image/vnd.svf": {
47306 "source": "iana"
47307 },
47308 "image/vnd.tencent.tap": {
47309 "source": "iana",
47310 "extensions": ["tap"]
47311 },
47312 "image/vnd.valve.source.texture": {
47313 "source": "iana",
47314 "extensions": ["vtf"]
47315 },
47316 "image/vnd.wap.wbmp": {
47317 "source": "iana",
47318 "extensions": ["wbmp"]
47319 },
47320 "image/vnd.xiff": {
47321 "source": "iana",
47322 "extensions": ["xif"]
47323 },
47324 "image/vnd.zbrush.pcx": {
47325 "source": "iana",
47326 "extensions": ["pcx"]
47327 },
47328 "image/webp": {
47329 "source": "apache",
47330 "extensions": ["webp"]
47331 },
47332 "image/wmf": {
47333 "source": "iana",
47334 "extensions": ["wmf"]
47335 },
47336 "image/x-3ds": {
47337 "source": "apache",
47338 "extensions": ["3ds"]
47339 },
47340 "image/x-cmu-raster": {
47341 "source": "apache",
47342 "extensions": ["ras"]
47343 },
47344 "image/x-cmx": {
47345 "source": "apache",
47346 "extensions": ["cmx"]
47347 },
47348 "image/x-freehand": {
47349 "source": "apache",
47350 "extensions": ["fh","fhc","fh4","fh5","fh7"]
47351 },
47352 "image/x-icon": {
47353 "source": "apache",
47354 "compressible": true,
47355 "extensions": ["ico"]
47356 },
47357 "image/x-jng": {
47358 "source": "nginx",
47359 "extensions": ["jng"]
47360 },
47361 "image/x-mrsid-image": {
47362 "source": "apache",
47363 "extensions": ["sid"]
47364 },
47365 "image/x-ms-bmp": {
47366 "source": "nginx",
47367 "compressible": true,
47368 "extensions": ["bmp"]
47369 },
47370 "image/x-pcx": {
47371 "source": "apache",
47372 "extensions": ["pcx"]
47373 },
47374 "image/x-pict": {
47375 "source": "apache",
47376 "extensions": ["pic","pct"]
47377 },
47378 "image/x-portable-anymap": {
47379 "source": "apache",
47380 "extensions": ["pnm"]
47381 },
47382 "image/x-portable-bitmap": {
47383 "source": "apache",
47384 "extensions": ["pbm"]
47385 },
47386 "image/x-portable-graymap": {
47387 "source": "apache",
47388 "extensions": ["pgm"]
47389 },
47390 "image/x-portable-pixmap": {
47391 "source": "apache",
47392 "extensions": ["ppm"]
47393 },
47394 "image/x-rgb": {
47395 "source": "apache",
47396 "extensions": ["rgb"]
47397 },
47398 "image/x-tga": {
47399 "source": "apache",
47400 "extensions": ["tga"]
47401 },
47402 "image/x-xbitmap": {
47403 "source": "apache",
47404 "extensions": ["xbm"]
47405 },
47406 "image/x-xcf": {
47407 "compressible": false
47408 },
47409 "image/x-xpixmap": {
47410 "source": "apache",
47411 "extensions": ["xpm"]
47412 },
47413 "image/x-xwindowdump": {
47414 "source": "apache",
47415 "extensions": ["xwd"]
47416 },
47417 "message/cpim": {
47418 "source": "iana"
47419 },
47420 "message/delivery-status": {
47421 "source": "iana"
47422 },
47423 "message/disposition-notification": {
47424 "source": "iana",
47425 "extensions": [
47426 "disposition-notification"
47427 ]
47428 },
47429 "message/external-body": {
47430 "source": "iana"
47431 },
47432 "message/feedback-report": {
47433 "source": "iana"
47434 },
47435 "message/global": {
47436 "source": "iana",
47437 "extensions": ["u8msg"]
47438 },
47439 "message/global-delivery-status": {
47440 "source": "iana",
47441 "extensions": ["u8dsn"]
47442 },
47443 "message/global-disposition-notification": {
47444 "source": "iana",
47445 "extensions": ["u8mdn"]
47446 },
47447 "message/global-headers": {
47448 "source": "iana",
47449 "extensions": ["u8hdr"]
47450 },
47451 "message/http": {
47452 "source": "iana",
47453 "compressible": false
47454 },
47455 "message/imdn+xml": {
47456 "source": "iana",
47457 "compressible": true
47458 },
47459 "message/news": {
47460 "source": "iana"
47461 },
47462 "message/partial": {
47463 "source": "iana",
47464 "compressible": false
47465 },
47466 "message/rfc822": {
47467 "source": "iana",
47468 "compressible": true,
47469 "extensions": ["eml","mime"]
47470 },
47471 "message/s-http": {
47472 "source": "iana"
47473 },
47474 "message/sip": {
47475 "source": "iana"
47476 },
47477 "message/sipfrag": {
47478 "source": "iana"
47479 },
47480 "message/tracking-status": {
47481 "source": "iana"
47482 },
47483 "message/vnd.si.simp": {
47484 "source": "iana"
47485 },
47486 "message/vnd.wfa.wsc": {
47487 "source": "iana",
47488 "extensions": ["wsc"]
47489 },
47490 "model/3mf": {
47491 "source": "iana",
47492 "extensions": ["3mf"]
47493 },
47494 "model/gltf+json": {
47495 "source": "iana",
47496 "compressible": true,
47497 "extensions": ["gltf"]
47498 },
47499 "model/gltf-binary": {
47500 "source": "iana",
47501 "compressible": true,
47502 "extensions": ["glb"]
47503 },
47504 "model/iges": {
47505 "source": "iana",
47506 "compressible": false,
47507 "extensions": ["igs","iges"]
47508 },
47509 "model/mesh": {
47510 "source": "iana",
47511 "compressible": false,
47512 "extensions": ["msh","mesh","silo"]
47513 },
47514 "model/stl": {
47515 "source": "iana",
47516 "extensions": ["stl"]
47517 },
47518 "model/vnd.collada+xml": {
47519 "source": "iana",
47520 "compressible": true,
47521 "extensions": ["dae"]
47522 },
47523 "model/vnd.dwf": {
47524 "source": "iana",
47525 "extensions": ["dwf"]
47526 },
47527 "model/vnd.flatland.3dml": {
47528 "source": "iana"
47529 },
47530 "model/vnd.gdl": {
47531 "source": "iana",
47532 "extensions": ["gdl"]
47533 },
47534 "model/vnd.gs-gdl": {
47535 "source": "apache"
47536 },
47537 "model/vnd.gs.gdl": {
47538 "source": "iana"
47539 },
47540 "model/vnd.gtw": {
47541 "source": "iana",
47542 "extensions": ["gtw"]
47543 },
47544 "model/vnd.moml+xml": {
47545 "source": "iana",
47546 "compressible": true
47547 },
47548 "model/vnd.mts": {
47549 "source": "iana",
47550 "extensions": ["mts"]
47551 },
47552 "model/vnd.opengex": {
47553 "source": "iana",
47554 "extensions": ["ogex"]
47555 },
47556 "model/vnd.parasolid.transmit.binary": {
47557 "source": "iana",
47558 "extensions": ["x_b"]
47559 },
47560 "model/vnd.parasolid.transmit.text": {
47561 "source": "iana",
47562 "extensions": ["x_t"]
47563 },
47564 "model/vnd.rosette.annotated-data-model": {
47565 "source": "iana"
47566 },
47567 "model/vnd.usdz+zip": {
47568 "source": "iana",
47569 "compressible": false,
47570 "extensions": ["usdz"]
47571 },
47572 "model/vnd.valve.source.compiled-map": {
47573 "source": "iana",
47574 "extensions": ["bsp"]
47575 },
47576 "model/vnd.vtu": {
47577 "source": "iana",
47578 "extensions": ["vtu"]
47579 },
47580 "model/vrml": {
47581 "source": "iana",
47582 "compressible": false,
47583 "extensions": ["wrl","vrml"]
47584 },
47585 "model/x3d+binary": {
47586 "source": "apache",
47587 "compressible": false,
47588 "extensions": ["x3db","x3dbz"]
47589 },
47590 "model/x3d+fastinfoset": {
47591 "source": "iana",
47592 "extensions": ["x3db"]
47593 },
47594 "model/x3d+vrml": {
47595 "source": "apache",
47596 "compressible": false,
47597 "extensions": ["x3dv","x3dvz"]
47598 },
47599 "model/x3d+xml": {
47600 "source": "iana",
47601 "compressible": true,
47602 "extensions": ["x3d","x3dz"]
47603 },
47604 "model/x3d-vrml": {
47605 "source": "iana",
47606 "extensions": ["x3dv"]
47607 },
47608 "multipart/alternative": {
47609 "source": "iana",
47610 "compressible": false
47611 },
47612 "multipart/appledouble": {
47613 "source": "iana"
47614 },
47615 "multipart/byteranges": {
47616 "source": "iana"
47617 },
47618 "multipart/digest": {
47619 "source": "iana"
47620 },
47621 "multipart/encrypted": {
47622 "source": "iana",
47623 "compressible": false
47624 },
47625 "multipart/form-data": {
47626 "source": "iana",
47627 "compressible": false
47628 },
47629 "multipart/header-set": {
47630 "source": "iana"
47631 },
47632 "multipart/mixed": {
47633 "source": "iana",
47634 "compressible": false
47635 },
47636 "multipart/multilingual": {
47637 "source": "iana"
47638 },
47639 "multipart/parallel": {
47640 "source": "iana"
47641 },
47642 "multipart/related": {
47643 "source": "iana",
47644 "compressible": false
47645 },
47646 "multipart/report": {
47647 "source": "iana"
47648 },
47649 "multipart/signed": {
47650 "source": "iana",
47651 "compressible": false
47652 },
47653 "multipart/vnd.bint.med-plus": {
47654 "source": "iana"
47655 },
47656 "multipart/voice-message": {
47657 "source": "iana"
47658 },
47659 "multipart/x-mixed-replace": {
47660 "source": "iana"
47661 },
47662 "text/1d-interleaved-parityfec": {
47663 "source": "iana"
47664 },
47665 "text/cache-manifest": {
47666 "source": "iana",
47667 "compressible": true,
47668 "extensions": ["appcache","manifest"]
47669 },
47670 "text/calendar": {
47671 "source": "iana",
47672 "extensions": ["ics","ifb"]
47673 },
47674 "text/calender": {
47675 "compressible": true
47676 },
47677 "text/cmd": {
47678 "compressible": true
47679 },
47680 "text/coffeescript": {
47681 "extensions": ["coffee","litcoffee"]
47682 },
47683 "text/css": {
47684 "source": "iana",
47685 "charset": "UTF-8",
47686 "compressible": true,
47687 "extensions": ["css"]
47688 },
47689 "text/csv": {
47690 "source": "iana",
47691 "compressible": true,
47692 "extensions": ["csv"]
47693 },
47694 "text/csv-schema": {
47695 "source": "iana"
47696 },
47697 "text/directory": {
47698 "source": "iana"
47699 },
47700 "text/dns": {
47701 "source": "iana"
47702 },
47703 "text/ecmascript": {
47704 "source": "iana"
47705 },
47706 "text/encaprtp": {
47707 "source": "iana"
47708 },
47709 "text/enriched": {
47710 "source": "iana"
47711 },
47712 "text/fwdred": {
47713 "source": "iana"
47714 },
47715 "text/grammar-ref-list": {
47716 "source": "iana"
47717 },
47718 "text/html": {
47719 "source": "iana",
47720 "compressible": true,
47721 "extensions": ["html","htm","shtml"]
47722 },
47723 "text/jade": {
47724 "extensions": ["jade"]
47725 },
47726 "text/javascript": {
47727 "source": "iana",
47728 "compressible": true
47729 },
47730 "text/jcr-cnd": {
47731 "source": "iana"
47732 },
47733 "text/jsx": {
47734 "compressible": true,
47735 "extensions": ["jsx"]
47736 },
47737 "text/less": {
47738 "compressible": true,
47739 "extensions": ["less"]
47740 },
47741 "text/markdown": {
47742 "source": "iana",
47743 "compressible": true,
47744 "extensions": ["markdown","md"]
47745 },
47746 "text/mathml": {
47747 "source": "nginx",
47748 "extensions": ["mml"]
47749 },
47750 "text/mdx": {
47751 "compressible": true,
47752 "extensions": ["mdx"]
47753 },
47754 "text/mizar": {
47755 "source": "iana"
47756 },
47757 "text/n3": {
47758 "source": "iana",
47759 "compressible": true,
47760 "extensions": ["n3"]
47761 },
47762 "text/parameters": {
47763 "source": "iana"
47764 },
47765 "text/parityfec": {
47766 "source": "iana"
47767 },
47768 "text/plain": {
47769 "source": "iana",
47770 "compressible": true,
47771 "extensions": ["txt","text","conf","def","list","log","in","ini"]
47772 },
47773 "text/provenance-notation": {
47774 "source": "iana"
47775 },
47776 "text/prs.fallenstein.rst": {
47777 "source": "iana"
47778 },
47779 "text/prs.lines.tag": {
47780 "source": "iana",
47781 "extensions": ["dsc"]
47782 },
47783 "text/prs.prop.logic": {
47784 "source": "iana"
47785 },
47786 "text/raptorfec": {
47787 "source": "iana"
47788 },
47789 "text/red": {
47790 "source": "iana"
47791 },
47792 "text/rfc822-headers": {
47793 "source": "iana"
47794 },
47795 "text/richtext": {
47796 "source": "iana",
47797 "compressible": true,
47798 "extensions": ["rtx"]
47799 },
47800 "text/rtf": {
47801 "source": "iana",
47802 "compressible": true,
47803 "extensions": ["rtf"]
47804 },
47805 "text/rtp-enc-aescm128": {
47806 "source": "iana"
47807 },
47808 "text/rtploopback": {
47809 "source": "iana"
47810 },
47811 "text/rtx": {
47812 "source": "iana"
47813 },
47814 "text/sgml": {
47815 "source": "iana",
47816 "extensions": ["sgml","sgm"]
47817 },
47818 "text/shex": {
47819 "extensions": ["shex"]
47820 },
47821 "text/slim": {
47822 "extensions": ["slim","slm"]
47823 },
47824 "text/strings": {
47825 "source": "iana"
47826 },
47827 "text/stylus": {
47828 "extensions": ["stylus","styl"]
47829 },
47830 "text/t140": {
47831 "source": "iana"
47832 },
47833 "text/tab-separated-values": {
47834 "source": "iana",
47835 "compressible": true,
47836 "extensions": ["tsv"]
47837 },
47838 "text/troff": {
47839 "source": "iana",
47840 "extensions": ["t","tr","roff","man","me","ms"]
47841 },
47842 "text/turtle": {
47843 "source": "iana",
47844 "charset": "UTF-8",
47845 "extensions": ["ttl"]
47846 },
47847 "text/ulpfec": {
47848 "source": "iana"
47849 },
47850 "text/uri-list": {
47851 "source": "iana",
47852 "compressible": true,
47853 "extensions": ["uri","uris","urls"]
47854 },
47855 "text/vcard": {
47856 "source": "iana",
47857 "compressible": true,
47858 "extensions": ["vcard"]
47859 },
47860 "text/vnd.a": {
47861 "source": "iana"
47862 },
47863 "text/vnd.abc": {
47864 "source": "iana"
47865 },
47866 "text/vnd.ascii-art": {
47867 "source": "iana"
47868 },
47869 "text/vnd.curl": {
47870 "source": "iana",
47871 "extensions": ["curl"]
47872 },
47873 "text/vnd.curl.dcurl": {
47874 "source": "apache",
47875 "extensions": ["dcurl"]
47876 },
47877 "text/vnd.curl.mcurl": {
47878 "source": "apache",
47879 "extensions": ["mcurl"]
47880 },
47881 "text/vnd.curl.scurl": {
47882 "source": "apache",
47883 "extensions": ["scurl"]
47884 },
47885 "text/vnd.debian.copyright": {
47886 "source": "iana"
47887 },
47888 "text/vnd.dmclientscript": {
47889 "source": "iana"
47890 },
47891 "text/vnd.dvb.subtitle": {
47892 "source": "iana",
47893 "extensions": ["sub"]
47894 },
47895 "text/vnd.esmertec.theme-descriptor": {
47896 "source": "iana"
47897 },
47898 "text/vnd.fly": {
47899 "source": "iana",
47900 "extensions": ["fly"]
47901 },
47902 "text/vnd.fmi.flexstor": {
47903 "source": "iana",
47904 "extensions": ["flx"]
47905 },
47906 "text/vnd.gml": {
47907 "source": "iana"
47908 },
47909 "text/vnd.graphviz": {
47910 "source": "iana",
47911 "extensions": ["gv"]
47912 },
47913 "text/vnd.hgl": {
47914 "source": "iana"
47915 },
47916 "text/vnd.in3d.3dml": {
47917 "source": "iana",
47918 "extensions": ["3dml"]
47919 },
47920 "text/vnd.in3d.spot": {
47921 "source": "iana",
47922 "extensions": ["spot"]
47923 },
47924 "text/vnd.iptc.newsml": {
47925 "source": "iana"
47926 },
47927 "text/vnd.iptc.nitf": {
47928 "source": "iana"
47929 },
47930 "text/vnd.latex-z": {
47931 "source": "iana"
47932 },
47933 "text/vnd.motorola.reflex": {
47934 "source": "iana"
47935 },
47936 "text/vnd.ms-mediapackage": {
47937 "source": "iana"
47938 },
47939 "text/vnd.net2phone.commcenter.command": {
47940 "source": "iana"
47941 },
47942 "text/vnd.radisys.msml-basic-layout": {
47943 "source": "iana"
47944 },
47945 "text/vnd.senx.warpscript": {
47946 "source": "iana"
47947 },
47948 "text/vnd.si.uricatalogue": {
47949 "source": "iana"
47950 },
47951 "text/vnd.sun.j2me.app-descriptor": {
47952 "source": "iana",
47953 "extensions": ["jad"]
47954 },
47955 "text/vnd.trolltech.linguist": {
47956 "source": "iana"
47957 },
47958 "text/vnd.wap.si": {
47959 "source": "iana"
47960 },
47961 "text/vnd.wap.sl": {
47962 "source": "iana"
47963 },
47964 "text/vnd.wap.wml": {
47965 "source": "iana",
47966 "extensions": ["wml"]
47967 },
47968 "text/vnd.wap.wmlscript": {
47969 "source": "iana",
47970 "extensions": ["wmls"]
47971 },
47972 "text/vtt": {
47973 "charset": "UTF-8",
47974 "compressible": true,
47975 "extensions": ["vtt"]
47976 },
47977 "text/x-asm": {
47978 "source": "apache",
47979 "extensions": ["s","asm"]
47980 },
47981 "text/x-c": {
47982 "source": "apache",
47983 "extensions": ["c","cc","cxx","cpp","h","hh","dic"]
47984 },
47985 "text/x-component": {
47986 "source": "nginx",
47987 "extensions": ["htc"]
47988 },
47989 "text/x-fortran": {
47990 "source": "apache",
47991 "extensions": ["f","for","f77","f90"]
47992 },
47993 "text/x-gwt-rpc": {
47994 "compressible": true
47995 },
47996 "text/x-handlebars-template": {
47997 "extensions": ["hbs"]
47998 },
47999 "text/x-java-source": {
48000 "source": "apache",
48001 "extensions": ["java"]
48002 },
48003 "text/x-jquery-tmpl": {
48004 "compressible": true
48005 },
48006 "text/x-lua": {
48007 "extensions": ["lua"]
48008 },
48009 "text/x-markdown": {
48010 "compressible": true,
48011 "extensions": ["mkd"]
48012 },
48013 "text/x-nfo": {
48014 "source": "apache",
48015 "extensions": ["nfo"]
48016 },
48017 "text/x-opml": {
48018 "source": "apache",
48019 "extensions": ["opml"]
48020 },
48021 "text/x-org": {
48022 "compressible": true,
48023 "extensions": ["org"]
48024 },
48025 "text/x-pascal": {
48026 "source": "apache",
48027 "extensions": ["p","pas"]
48028 },
48029 "text/x-processing": {
48030 "compressible": true,
48031 "extensions": ["pde"]
48032 },
48033 "text/x-sass": {
48034 "extensions": ["sass"]
48035 },
48036 "text/x-scss": {
48037 "extensions": ["scss"]
48038 },
48039 "text/x-setext": {
48040 "source": "apache",
48041 "extensions": ["etx"]
48042 },
48043 "text/x-sfv": {
48044 "source": "apache",
48045 "extensions": ["sfv"]
48046 },
48047 "text/x-suse-ymp": {
48048 "compressible": true,
48049 "extensions": ["ymp"]
48050 },
48051 "text/x-uuencode": {
48052 "source": "apache",
48053 "extensions": ["uu"]
48054 },
48055 "text/x-vcalendar": {
48056 "source": "apache",
48057 "extensions": ["vcs"]
48058 },
48059 "text/x-vcard": {
48060 "source": "apache",
48061 "extensions": ["vcf"]
48062 },
48063 "text/xml": {
48064 "source": "iana",
48065 "compressible": true,
48066 "extensions": ["xml"]
48067 },
48068 "text/xml-external-parsed-entity": {
48069 "source": "iana"
48070 },
48071 "text/yaml": {
48072 "extensions": ["yaml","yml"]
48073 },
48074 "video/1d-interleaved-parityfec": {
48075 "source": "iana"
48076 },
48077 "video/3gpp": {
48078 "source": "iana",
48079 "extensions": ["3gp","3gpp"]
48080 },
48081 "video/3gpp-tt": {
48082 "source": "iana"
48083 },
48084 "video/3gpp2": {
48085 "source": "iana",
48086 "extensions": ["3g2"]
48087 },
48088 "video/bmpeg": {
48089 "source": "iana"
48090 },
48091 "video/bt656": {
48092 "source": "iana"
48093 },
48094 "video/celb": {
48095 "source": "iana"
48096 },
48097 "video/dv": {
48098 "source": "iana"
48099 },
48100 "video/encaprtp": {
48101 "source": "iana"
48102 },
48103 "video/h261": {
48104 "source": "iana",
48105 "extensions": ["h261"]
48106 },
48107 "video/h263": {
48108 "source": "iana",
48109 "extensions": ["h263"]
48110 },
48111 "video/h263-1998": {
48112 "source": "iana"
48113 },
48114 "video/h263-2000": {
48115 "source": "iana"
48116 },
48117 "video/h264": {
48118 "source": "iana",
48119 "extensions": ["h264"]
48120 },
48121 "video/h264-rcdo": {
48122 "source": "iana"
48123 },
48124 "video/h264-svc": {
48125 "source": "iana"
48126 },
48127 "video/h265": {
48128 "source": "iana"
48129 },
48130 "video/iso.segment": {
48131 "source": "iana"
48132 },
48133 "video/jpeg": {
48134 "source": "iana",
48135 "extensions": ["jpgv"]
48136 },
48137 "video/jpeg2000": {
48138 "source": "iana"
48139 },
48140 "video/jpm": {
48141 "source": "apache",
48142 "extensions": ["jpm","jpgm"]
48143 },
48144 "video/mj2": {
48145 "source": "iana",
48146 "extensions": ["mj2","mjp2"]
48147 },
48148 "video/mp1s": {
48149 "source": "iana"
48150 },
48151 "video/mp2p": {
48152 "source": "iana"
48153 },
48154 "video/mp2t": {
48155 "source": "iana",
48156 "extensions": ["ts"]
48157 },
48158 "video/mp4": {
48159 "source": "iana",
48160 "compressible": false,
48161 "extensions": ["mp4","mp4v","mpg4"]
48162 },
48163 "video/mp4v-es": {
48164 "source": "iana"
48165 },
48166 "video/mpeg": {
48167 "source": "iana",
48168 "compressible": false,
48169 "extensions": ["mpeg","mpg","mpe","m1v","m2v"]
48170 },
48171 "video/mpeg4-generic": {
48172 "source": "iana"
48173 },
48174 "video/mpv": {
48175 "source": "iana"
48176 },
48177 "video/nv": {
48178 "source": "iana"
48179 },
48180 "video/ogg": {
48181 "source": "iana",
48182 "compressible": false,
48183 "extensions": ["ogv"]
48184 },
48185 "video/parityfec": {
48186 "source": "iana"
48187 },
48188 "video/pointer": {
48189 "source": "iana"
48190 },
48191 "video/quicktime": {
48192 "source": "iana",
48193 "compressible": false,
48194 "extensions": ["qt","mov"]
48195 },
48196 "video/raptorfec": {
48197 "source": "iana"
48198 },
48199 "video/raw": {
48200 "source": "iana"
48201 },
48202 "video/rtp-enc-aescm128": {
48203 "source": "iana"
48204 },
48205 "video/rtploopback": {
48206 "source": "iana"
48207 },
48208 "video/rtx": {
48209 "source": "iana"
48210 },
48211 "video/smpte291": {
48212 "source": "iana"
48213 },
48214 "video/smpte292m": {
48215 "source": "iana"
48216 },
48217 "video/ulpfec": {
48218 "source": "iana"
48219 },
48220 "video/vc1": {
48221 "source": "iana"
48222 },
48223 "video/vc2": {
48224 "source": "iana"
48225 },
48226 "video/vnd.cctv": {
48227 "source": "iana"
48228 },
48229 "video/vnd.dece.hd": {
48230 "source": "iana",
48231 "extensions": ["uvh","uvvh"]
48232 },
48233 "video/vnd.dece.mobile": {
48234 "source": "iana",
48235 "extensions": ["uvm","uvvm"]
48236 },
48237 "video/vnd.dece.mp4": {
48238 "source": "iana"
48239 },
48240 "video/vnd.dece.pd": {
48241 "source": "iana",
48242 "extensions": ["uvp","uvvp"]
48243 },
48244 "video/vnd.dece.sd": {
48245 "source": "iana",
48246 "extensions": ["uvs","uvvs"]
48247 },
48248 "video/vnd.dece.video": {
48249 "source": "iana",
48250 "extensions": ["uvv","uvvv"]
48251 },
48252 "video/vnd.directv.mpeg": {
48253 "source": "iana"
48254 },
48255 "video/vnd.directv.mpeg-tts": {
48256 "source": "iana"
48257 },
48258 "video/vnd.dlna.mpeg-tts": {
48259 "source": "iana"
48260 },
48261 "video/vnd.dvb.file": {
48262 "source": "iana",
48263 "extensions": ["dvb"]
48264 },
48265 "video/vnd.fvt": {
48266 "source": "iana",
48267 "extensions": ["fvt"]
48268 },
48269 "video/vnd.hns.video": {
48270 "source": "iana"
48271 },
48272 "video/vnd.iptvforum.1dparityfec-1010": {
48273 "source": "iana"
48274 },
48275 "video/vnd.iptvforum.1dparityfec-2005": {
48276 "source": "iana"
48277 },
48278 "video/vnd.iptvforum.2dparityfec-1010": {
48279 "source": "iana"
48280 },
48281 "video/vnd.iptvforum.2dparityfec-2005": {
48282 "source": "iana"
48283 },
48284 "video/vnd.iptvforum.ttsavc": {
48285 "source": "iana"
48286 },
48287 "video/vnd.iptvforum.ttsmpeg2": {
48288 "source": "iana"
48289 },
48290 "video/vnd.motorola.video": {
48291 "source": "iana"
48292 },
48293 "video/vnd.motorola.videop": {
48294 "source": "iana"
48295 },
48296 "video/vnd.mpegurl": {
48297 "source": "iana",
48298 "extensions": ["mxu","m4u"]
48299 },
48300 "video/vnd.ms-playready.media.pyv": {
48301 "source": "iana",
48302 "extensions": ["pyv"]
48303 },
48304 "video/vnd.nokia.interleaved-multimedia": {
48305 "source": "iana"
48306 },
48307 "video/vnd.nokia.mp4vr": {
48308 "source": "iana"
48309 },
48310 "video/vnd.nokia.videovoip": {
48311 "source": "iana"
48312 },
48313 "video/vnd.objectvideo": {
48314 "source": "iana"
48315 },
48316 "video/vnd.radgamettools.bink": {
48317 "source": "iana"
48318 },
48319 "video/vnd.radgamettools.smacker": {
48320 "source": "iana"
48321 },
48322 "video/vnd.sealed.mpeg1": {
48323 "source": "iana"
48324 },
48325 "video/vnd.sealed.mpeg4": {
48326 "source": "iana"
48327 },
48328 "video/vnd.sealed.swf": {
48329 "source": "iana"
48330 },
48331 "video/vnd.sealedmedia.softseal.mov": {
48332 "source": "iana"
48333 },
48334 "video/vnd.uvvu.mp4": {
48335 "source": "iana",
48336 "extensions": ["uvu","uvvu"]
48337 },
48338 "video/vnd.vivo": {
48339 "source": "iana",
48340 "extensions": ["viv"]
48341 },
48342 "video/vp8": {
48343 "source": "iana"
48344 },
48345 "video/webm": {
48346 "source": "apache",
48347 "compressible": false,
48348 "extensions": ["webm"]
48349 },
48350 "video/x-f4v": {
48351 "source": "apache",
48352 "extensions": ["f4v"]
48353 },
48354 "video/x-fli": {
48355 "source": "apache",
48356 "extensions": ["fli"]
48357 },
48358 "video/x-flv": {
48359 "source": "apache",
48360 "compressible": false,
48361 "extensions": ["flv"]
48362 },
48363 "video/x-m4v": {
48364 "source": "apache",
48365 "extensions": ["m4v"]
48366 },
48367 "video/x-matroska": {
48368 "source": "apache",
48369 "compressible": false,
48370 "extensions": ["mkv","mk3d","mks"]
48371 },
48372 "video/x-mng": {
48373 "source": "apache",
48374 "extensions": ["mng"]
48375 },
48376 "video/x-ms-asf": {
48377 "source": "apache",
48378 "extensions": ["asf","asx"]
48379 },
48380 "video/x-ms-vob": {
48381 "source": "apache",
48382 "extensions": ["vob"]
48383 },
48384 "video/x-ms-wm": {
48385 "source": "apache",
48386 "extensions": ["wm"]
48387 },
48388 "video/x-ms-wmv": {
48389 "source": "apache",
48390 "compressible": false,
48391 "extensions": ["wmv"]
48392 },
48393 "video/x-ms-wmx": {
48394 "source": "apache",
48395 "extensions": ["wmx"]
48396 },
48397 "video/x-ms-wvx": {
48398 "source": "apache",
48399 "extensions": ["wvx"]
48400 },
48401 "video/x-msvideo": {
48402 "source": "apache",
48403 "extensions": ["avi"]
48404 },
48405 "video/x-sgi-movie": {
48406 "source": "apache",
48407 "extensions": ["movie"]
48408 },
48409 "video/x-smv": {
48410 "source": "apache",
48411 "extensions": ["smv"]
48412 },
48413 "x-conference/x-cooltalk": {
48414 "source": "apache",
48415 "extensions": ["ice"]
48416 },
48417 "x-shader/x-fragment": {
48418 "compressible": true
48419 },
48420 "x-shader/x-vertex": {
48421 "compressible": true
48422 }
48423}
48424
48425},{}],235:[function(require,module,exports){
48426/*!
48427 * mime-db
48428 * Copyright(c) 2014 Jonathan Ong
48429 * MIT Licensed
48430 */
48431
48432/**
48433 * Module exports.
48434 */
48435
48436module.exports = require('./db.json')
48437
48438},{"./db.json":234}],236:[function(require,module,exports){
48439/*!
48440 * mime-types
48441 * Copyright(c) 2014 Jonathan Ong
48442 * Copyright(c) 2015 Douglas Christopher Wilson
48443 * MIT Licensed
48444 */
48445
48446'use strict'
48447
48448/**
48449 * Module dependencies.
48450 * @private
48451 */
48452
48453var db = require('mime-db')
48454var extname = require('path').extname
48455
48456/**
48457 * Module variables.
48458 * @private
48459 */
48460
48461var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
48462var TEXT_TYPE_REGEXP = /^text\//i
48463
48464/**
48465 * Module exports.
48466 * @public
48467 */
48468
48469exports.charset = charset
48470exports.charsets = { lookup: charset }
48471exports.contentType = contentType
48472exports.extension = extension
48473exports.extensions = Object.create(null)
48474exports.lookup = lookup
48475exports.types = Object.create(null)
48476
48477// Populate the extensions/types maps
48478populateMaps(exports.extensions, exports.types)
48479
48480/**
48481 * Get the default charset for a MIME type.
48482 *
48483 * @param {string} type
48484 * @return {boolean|string}
48485 */
48486
48487function charset (type) {
48488 if (!type || typeof type !== 'string') {
48489 return false
48490 }
48491
48492 // TODO: use media-typer
48493 var match = EXTRACT_TYPE_REGEXP.exec(type)
48494 var mime = match && db[match[1].toLowerCase()]
48495
48496 if (mime && mime.charset) {
48497 return mime.charset
48498 }
48499
48500 // default text/* to utf-8
48501 if (match && TEXT_TYPE_REGEXP.test(match[1])) {
48502 return 'UTF-8'
48503 }
48504
48505 return false
48506}
48507
48508/**
48509 * Create a full Content-Type header given a MIME type or extension.
48510 *
48511 * @param {string} str
48512 * @return {boolean|string}
48513 */
48514
48515function contentType (str) {
48516 // TODO: should this even be in this module?
48517 if (!str || typeof str !== 'string') {
48518 return false
48519 }
48520
48521 var mime = str.indexOf('/') === -1
48522 ? exports.lookup(str)
48523 : str
48524
48525 if (!mime) {
48526 return false
48527 }
48528
48529 // TODO: use content-type or other module
48530 if (mime.indexOf('charset') === -1) {
48531 var charset = exports.charset(mime)
48532 if (charset) mime += '; charset=' + charset.toLowerCase()
48533 }
48534
48535 return mime
48536}
48537
48538/**
48539 * Get the default extension for a MIME type.
48540 *
48541 * @param {string} type
48542 * @return {boolean|string}
48543 */
48544
48545function extension (type) {
48546 if (!type || typeof type !== 'string') {
48547 return false
48548 }
48549
48550 // TODO: use media-typer
48551 var match = EXTRACT_TYPE_REGEXP.exec(type)
48552
48553 // get extensions
48554 var exts = match && exports.extensions[match[1].toLowerCase()]
48555
48556 if (!exts || !exts.length) {
48557 return false
48558 }
48559
48560 return exts[0]
48561}
48562
48563/**
48564 * Lookup the MIME type for a file path/extension.
48565 *
48566 * @param {string} path
48567 * @return {boolean|string}
48568 */
48569
48570function lookup (path) {
48571 if (!path || typeof path !== 'string') {
48572 return false
48573 }
48574
48575 // get the extension ("ext" or ".ext" or full path)
48576 var extension = extname('x.' + path)
48577 .toLowerCase()
48578 .substr(1)
48579
48580 if (!extension) {
48581 return false
48582 }
48583
48584 return exports.types[extension] || false
48585}
48586
48587/**
48588 * Populate the extensions and types maps.
48589 * @private
48590 */
48591
48592function populateMaps (extensions, types) {
48593 // source preference (least -> most)
48594 var preference = ['nginx', 'apache', undefined, 'iana']
48595
48596 Object.keys(db).forEach(function forEachMimeType (type) {
48597 var mime = db[type]
48598 var exts = mime.extensions
48599
48600 if (!exts || !exts.length) {
48601 return
48602 }
48603
48604 // mime -> extensions
48605 extensions[type] = exts
48606
48607 // extension -> mime
48608 for (var i = 0; i < exts.length; i++) {
48609 var extension = exts[i]
48610
48611 if (types[extension]) {
48612 var from = preference.indexOf(db[types[extension]].source)
48613 var to = preference.indexOf(mime.source)
48614
48615 if (types[extension] !== 'application/octet-stream' &&
48616 (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) {
48617 // skip the remapping
48618 continue
48619 }
48620 }
48621
48622 // set the extension -> mime
48623 types[extension] = type
48624 }
48625 })
48626}
48627
48628},{"mime-db":235,"path":257}],237:[function(require,module,exports){
48629module.exports = assert;
48630
48631function assert(val, msg) {
48632 if (!val)
48633 throw new Error(msg || 'Assertion failed');
48634}
48635
48636assert.equal = function assertEqual(l, r, msg) {
48637 if (l != r)
48638 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
48639};
48640
48641},{}],238:[function(require,module,exports){
48642'use strict';
48643
48644var utils = exports;
48645
48646function toArray(msg, enc) {
48647 if (Array.isArray(msg))
48648 return msg.slice();
48649 if (!msg)
48650 return [];
48651 var res = [];
48652 if (typeof msg !== 'string') {
48653 for (var i = 0; i < msg.length; i++)
48654 res[i] = msg[i] | 0;
48655 return res;
48656 }
48657 if (enc === 'hex') {
48658 msg = msg.replace(/[^a-z0-9]+/ig, '');
48659 if (msg.length % 2 !== 0)
48660 msg = '0' + msg;
48661 for (var i = 0; i < msg.length; i += 2)
48662 res.push(parseInt(msg[i] + msg[i + 1], 16));
48663 } else {
48664 for (var i = 0; i < msg.length; i++) {
48665 var c = msg.charCodeAt(i);
48666 var hi = c >> 8;
48667 var lo = c & 0xff;
48668 if (hi)
48669 res.push(hi, lo);
48670 else
48671 res.push(lo);
48672 }
48673 }
48674 return res;
48675}
48676utils.toArray = toArray;
48677
48678function zero2(word) {
48679 if (word.length === 1)
48680 return '0' + word;
48681 else
48682 return word;
48683}
48684utils.zero2 = zero2;
48685
48686function toHex(msg) {
48687 var res = '';
48688 for (var i = 0; i < msg.length; i++)
48689 res += zero2(msg[i].toString(16));
48690 return res;
48691}
48692utils.toHex = toHex;
48693
48694utils.encode = function encode(arr, enc) {
48695 if (enc === 'hex')
48696 return toHex(arr);
48697 else
48698 return arr;
48699};
48700
48701},{}],239:[function(require,module,exports){
48702var crypto = require('crypto')
48703
48704function sha (key, body, algorithm) {
48705 return crypto.createHmac(algorithm, key).update(body).digest('base64')
48706}
48707
48708function rsa (key, body) {
48709 return crypto.createSign('RSA-SHA1').update(body).sign(key, 'base64')
48710}
48711
48712function rfc3986 (str) {
48713 return encodeURIComponent(str)
48714 .replace(/!/g,'%21')
48715 .replace(/\*/g,'%2A')
48716 .replace(/\(/g,'%28')
48717 .replace(/\)/g,'%29')
48718 .replace(/'/g,'%27')
48719}
48720
48721// Maps object to bi-dimensional array
48722// Converts { foo: 'A', bar: [ 'b', 'B' ]} to
48723// [ ['foo', 'A'], ['bar', 'b'], ['bar', 'B'] ]
48724function map (obj) {
48725 var key, val, arr = []
48726 for (key in obj) {
48727 val = obj[key]
48728 if (Array.isArray(val))
48729 for (var i = 0; i < val.length; i++)
48730 arr.push([key, val[i]])
48731 else if (typeof val === 'object')
48732 for (var prop in val)
48733 arr.push([key + '[' + prop + ']', val[prop]])
48734 else
48735 arr.push([key, val])
48736 }
48737 return arr
48738}
48739
48740// Compare function for sort
48741function compare (a, b) {
48742 return a > b ? 1 : a < b ? -1 : 0
48743}
48744
48745function generateBase (httpMethod, base_uri, params) {
48746 // adapted from https://dev.twitter.com/docs/auth/oauth and
48747 // https://dev.twitter.com/docs/auth/creating-signature
48748
48749 // Parameter normalization
48750 // http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2
48751 var normalized = map(params)
48752 // 1. First, the name and value of each parameter are encoded
48753 .map(function (p) {
48754 return [ rfc3986(p[0]), rfc3986(p[1] || '') ]
48755 })
48756 // 2. The parameters are sorted by name, using ascending byte value
48757 // ordering. If two or more parameters share the same name, they
48758 // are sorted by their value.
48759 .sort(function (a, b) {
48760 return compare(a[0], b[0]) || compare(a[1], b[1])
48761 })
48762 // 3. The name of each parameter is concatenated to its corresponding
48763 // value using an "=" character (ASCII code 61) as a separator, even
48764 // if the value is empty.
48765 .map(function (p) { return p.join('=') })
48766 // 4. The sorted name/value pairs are concatenated together into a
48767 // single string by using an "&" character (ASCII code 38) as
48768 // separator.
48769 .join('&')
48770
48771 var base = [
48772 rfc3986(httpMethod ? httpMethod.toUpperCase() : 'GET'),
48773 rfc3986(base_uri),
48774 rfc3986(normalized)
48775 ].join('&')
48776
48777 return base
48778}
48779
48780function hmacsign (httpMethod, base_uri, params, consumer_secret, token_secret) {
48781 var base = generateBase(httpMethod, base_uri, params)
48782 var key = [
48783 consumer_secret || '',
48784 token_secret || ''
48785 ].map(rfc3986).join('&')
48786
48787 return sha(key, base, 'sha1')
48788}
48789
48790function hmacsign256 (httpMethod, base_uri, params, consumer_secret, token_secret) {
48791 var base = generateBase(httpMethod, base_uri, params)
48792 var key = [
48793 consumer_secret || '',
48794 token_secret || ''
48795 ].map(rfc3986).join('&')
48796
48797 return sha(key, base, 'sha256')
48798}
48799
48800function rsasign (httpMethod, base_uri, params, private_key, token_secret) {
48801 var base = generateBase(httpMethod, base_uri, params)
48802 var key = private_key || ''
48803
48804 return rsa(key, base)
48805}
48806
48807function plaintext (consumer_secret, token_secret) {
48808 var key = [
48809 consumer_secret || '',
48810 token_secret || ''
48811 ].map(rfc3986).join('&')
48812
48813 return key
48814}
48815
48816function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) {
48817 var method
48818 var skipArgs = 1
48819
48820 switch (signMethod) {
48821 case 'RSA-SHA1':
48822 method = rsasign
48823 break
48824 case 'HMAC-SHA1':
48825 method = hmacsign
48826 break
48827 case 'HMAC-SHA256':
48828 method = hmacsign256
48829 break
48830 case 'PLAINTEXT':
48831 method = plaintext
48832 skipArgs = 4
48833 break
48834 default:
48835 throw new Error('Signature method not supported: ' + signMethod)
48836 }
48837
48838 return method.apply(null, [].slice.call(arguments, skipArgs))
48839}
48840
48841exports.hmacsign = hmacsign
48842exports.hmacsign256 = hmacsign256
48843exports.rsasign = rsasign
48844exports.plaintext = plaintext
48845exports.sign = sign
48846exports.rfc3986 = rfc3986
48847exports.generateBase = generateBase
48848},{"crypto":126}],240:[function(require,module,exports){
48849exports.endianness = function () { return 'LE' };
48850
48851exports.hostname = function () {
48852 if (typeof location !== 'undefined') {
48853 return location.hostname
48854 }
48855 else return '';
48856};
48857
48858exports.loadavg = function () { return [] };
48859
48860exports.uptime = function () { return 0 };
48861
48862exports.freemem = function () {
48863 return Number.MAX_VALUE;
48864};
48865
48866exports.totalmem = function () {
48867 return Number.MAX_VALUE;
48868};
48869
48870exports.cpus = function () { return [] };
48871
48872exports.type = function () { return 'Browser' };
48873
48874exports.release = function () {
48875 if (typeof navigator !== 'undefined') {
48876 return navigator.appVersion;
48877 }
48878 return '';
48879};
48880
48881exports.networkInterfaces
48882= exports.getNetworkInterfaces
48883= function () { return {} };
48884
48885exports.arch = function () { return 'javascript' };
48886
48887exports.platform = function () { return 'browser' };
48888
48889exports.tmpdir = exports.tmpDir = function () {
48890 return '/tmp';
48891};
48892
48893exports.EOL = '\n';
48894
48895exports.homedir = function () {
48896 return '/'
48897};
48898
48899},{}],241:[function(require,module,exports){
48900'use strict';
48901
48902
48903var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
48904 (typeof Uint16Array !== 'undefined') &&
48905 (typeof Int32Array !== 'undefined');
48906
48907function _has(obj, key) {
48908 return Object.prototype.hasOwnProperty.call(obj, key);
48909}
48910
48911exports.assign = function (obj /*from1, from2, from3, ...*/) {
48912 var sources = Array.prototype.slice.call(arguments, 1);
48913 while (sources.length) {
48914 var source = sources.shift();
48915 if (!source) { continue; }
48916
48917 if (typeof source !== 'object') {
48918 throw new TypeError(source + 'must be non-object');
48919 }
48920
48921 for (var p in source) {
48922 if (_has(source, p)) {
48923 obj[p] = source[p];
48924 }
48925 }
48926 }
48927
48928 return obj;
48929};
48930
48931
48932// reduce buffer size, avoiding mem copy
48933exports.shrinkBuf = function (buf, size) {
48934 if (buf.length === size) { return buf; }
48935 if (buf.subarray) { return buf.subarray(0, size); }
48936 buf.length = size;
48937 return buf;
48938};
48939
48940
48941var fnTyped = {
48942 arraySet: function (dest, src, src_offs, len, dest_offs) {
48943 if (src.subarray && dest.subarray) {
48944 dest.set(src.subarray(src_offs, src_offs + len), dest_offs);
48945 return;
48946 }
48947 // Fallback to ordinary array
48948 for (var i = 0; i < len; i++) {
48949 dest[dest_offs + i] = src[src_offs + i];
48950 }
48951 },
48952 // Join array of chunks to single array.
48953 flattenChunks: function (chunks) {
48954 var i, l, len, pos, chunk, result;
48955
48956 // calculate data length
48957 len = 0;
48958 for (i = 0, l = chunks.length; i < l; i++) {
48959 len += chunks[i].length;
48960 }
48961
48962 // join chunks
48963 result = new Uint8Array(len);
48964 pos = 0;
48965 for (i = 0, l = chunks.length; i < l; i++) {
48966 chunk = chunks[i];
48967 result.set(chunk, pos);
48968 pos += chunk.length;
48969 }
48970
48971 return result;
48972 }
48973};
48974
48975var fnUntyped = {
48976 arraySet: function (dest, src, src_offs, len, dest_offs) {
48977 for (var i = 0; i < len; i++) {
48978 dest[dest_offs + i] = src[src_offs + i];
48979 }
48980 },
48981 // Join array of chunks to single array.
48982 flattenChunks: function (chunks) {
48983 return [].concat.apply([], chunks);
48984 }
48985};
48986
48987
48988// Enable/Disable typed arrays use, for testing
48989//
48990exports.setTyped = function (on) {
48991 if (on) {
48992 exports.Buf8 = Uint8Array;
48993 exports.Buf16 = Uint16Array;
48994 exports.Buf32 = Int32Array;
48995 exports.assign(exports, fnTyped);
48996 } else {
48997 exports.Buf8 = Array;
48998 exports.Buf16 = Array;
48999 exports.Buf32 = Array;
49000 exports.assign(exports, fnUntyped);
49001 }
49002};
49003
49004exports.setTyped(TYPED_OK);
49005
49006},{}],242:[function(require,module,exports){
49007'use strict';
49008
49009// Note: adler32 takes 12% for level 0 and 2% for level 6.
49010// It isn't worth it to make additional optimizations as in original.
49011// Small size is preferable.
49012
49013// (C) 1995-2013 Jean-loup Gailly and Mark Adler
49014// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
49015//
49016// This software is provided 'as-is', without any express or implied
49017// warranty. In no event will the authors be held liable for any damages
49018// arising from the use of this software.
49019//
49020// Permission is granted to anyone to use this software for any purpose,
49021// including commercial applications, and to alter it and redistribute it
49022// freely, subject to the following restrictions:
49023//
49024// 1. The origin of this software must not be misrepresented; you must not
49025// claim that you wrote the original software. If you use this software
49026// in a product, an acknowledgment in the product documentation would be
49027// appreciated but is not required.
49028// 2. Altered source versions must be plainly marked as such, and must not be
49029// misrepresented as being the original software.
49030// 3. This notice may not be removed or altered from any source distribution.
49031
49032function adler32(adler, buf, len, pos) {
49033 var s1 = (adler & 0xffff) |0,
49034 s2 = ((adler >>> 16) & 0xffff) |0,
49035 n = 0;
49036
49037 while (len !== 0) {
49038 // Set limit ~ twice less than 5552, to keep
49039 // s2 in 31-bits, because we force signed ints.
49040 // in other case %= will fail.
49041 n = len > 2000 ? 2000 : len;
49042 len -= n;
49043
49044 do {
49045 s1 = (s1 + buf[pos++]) |0;
49046 s2 = (s2 + s1) |0;
49047 } while (--n);
49048
49049 s1 %= 65521;
49050 s2 %= 65521;
49051 }
49052
49053 return (s1 | (s2 << 16)) |0;
49054}
49055
49056
49057module.exports = adler32;
49058
49059},{}],243:[function(require,module,exports){
49060'use strict';
49061
49062// (C) 1995-2013 Jean-loup Gailly and Mark Adler
49063// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
49064//
49065// This software is provided 'as-is', without any express or implied
49066// warranty. In no event will the authors be held liable for any damages
49067// arising from the use of this software.
49068//
49069// Permission is granted to anyone to use this software for any purpose,
49070// including commercial applications, and to alter it and redistribute it
49071// freely, subject to the following restrictions:
49072//
49073// 1. The origin of this software must not be misrepresented; you must not
49074// claim that you wrote the original software. If you use this software
49075// in a product, an acknowledgment in the product documentation would be
49076// appreciated but is not required.
49077// 2. Altered source versions must be plainly marked as such, and must not be
49078// misrepresented as being the original software.
49079// 3. This notice may not be removed or altered from any source distribution.
49080
49081module.exports = {
49082
49083 /* Allowed flush values; see deflate() and inflate() below for details */
49084 Z_NO_FLUSH: 0,
49085 Z_PARTIAL_FLUSH: 1,
49086 Z_SYNC_FLUSH: 2,
49087 Z_FULL_FLUSH: 3,
49088 Z_FINISH: 4,
49089 Z_BLOCK: 5,
49090 Z_TREES: 6,
49091
49092 /* Return codes for the compression/decompression functions. Negative values
49093 * are errors, positive values are used for special but normal events.
49094 */
49095 Z_OK: 0,
49096 Z_STREAM_END: 1,
49097 Z_NEED_DICT: 2,
49098 Z_ERRNO: -1,
49099 Z_STREAM_ERROR: -2,
49100 Z_DATA_ERROR: -3,
49101 //Z_MEM_ERROR: -4,
49102 Z_BUF_ERROR: -5,
49103 //Z_VERSION_ERROR: -6,
49104
49105 /* compression levels */
49106 Z_NO_COMPRESSION: 0,
49107 Z_BEST_SPEED: 1,
49108 Z_BEST_COMPRESSION: 9,
49109 Z_DEFAULT_COMPRESSION: -1,
49110
49111
49112 Z_FILTERED: 1,
49113 Z_HUFFMAN_ONLY: 2,
49114 Z_RLE: 3,
49115 Z_FIXED: 4,
49116 Z_DEFAULT_STRATEGY: 0,
49117
49118 /* Possible values of the data_type field (though see inflate()) */
49119 Z_BINARY: 0,
49120 Z_TEXT: 1,
49121 //Z_ASCII: 1, // = Z_TEXT (deprecated)
49122 Z_UNKNOWN: 2,
49123
49124 /* The deflate compression method */
49125 Z_DEFLATED: 8
49126 //Z_NULL: null // Use -1 or null inline, depending on var type
49127};
49128
49129},{}],244:[function(require,module,exports){
49130'use strict';
49131
49132// Note: we can't get significant speed boost here.
49133// So write code to minimize size - no pregenerated tables
49134// and array tools dependencies.
49135
49136// (C) 1995-2013 Jean-loup Gailly and Mark Adler
49137// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
49138//
49139// This software is provided 'as-is', without any express or implied
49140// warranty. In no event will the authors be held liable for any damages
49141// arising from the use of this software.
49142//
49143// Permission is granted to anyone to use this software for any purpose,
49144// including commercial applications, and to alter it and redistribute it
49145// freely, subject to the following restrictions:
49146//
49147// 1. The origin of this software must not be misrepresented; you must not
49148// claim that you wrote the original software. If you use this software
49149// in a product, an acknowledgment in the product documentation would be
49150// appreciated but is not required.
49151// 2. Altered source versions must be plainly marked as such, and must not be
49152// misrepresented as being the original software.
49153// 3. This notice may not be removed or altered from any source distribution.
49154
49155// Use ordinary array, since untyped makes no boost here
49156function makeTable() {
49157 var c, table = [];
49158
49159 for (var n = 0; n < 256; n++) {
49160 c = n;
49161 for (var k = 0; k < 8; k++) {
49162 c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
49163 }
49164 table[n] = c;
49165 }
49166
49167 return table;
49168}
49169
49170// Create table on load. Just 255 signed longs. Not a problem.
49171var crcTable = makeTable();
49172
49173
49174function crc32(crc, buf, len, pos) {
49175 var t = crcTable,
49176 end = pos + len;
49177
49178 crc ^= -1;
49179
49180 for (var i = pos; i < end; i++) {
49181 crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
49182 }
49183
49184 return (crc ^ (-1)); // >>> 0;
49185}
49186
49187
49188module.exports = crc32;
49189
49190},{}],245:[function(require,module,exports){
49191'use strict';
49192
49193// (C) 1995-2013 Jean-loup Gailly and Mark Adler
49194// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
49195//
49196// This software is provided 'as-is', without any express or implied
49197// warranty. In no event will the authors be held liable for any damages
49198// arising from the use of this software.
49199//
49200// Permission is granted to anyone to use this software for any purpose,
49201// including commercial applications, and to alter it and redistribute it
49202// freely, subject to the following restrictions:
49203//
49204// 1. The origin of this software must not be misrepresented; you must not
49205// claim that you wrote the original software. If you use this software
49206// in a product, an acknowledgment in the product documentation would be
49207// appreciated but is not required.
49208// 2. Altered source versions must be plainly marked as such, and must not be
49209// misrepresented as being the original software.
49210// 3. This notice may not be removed or altered from any source distribution.
49211
49212var utils = require('../utils/common');
49213var trees = require('./trees');
49214var adler32 = require('./adler32');
49215var crc32 = require('./crc32');
49216var msg = require('./messages');
49217
49218/* Public constants ==========================================================*/
49219/* ===========================================================================*/
49220
49221
49222/* Allowed flush values; see deflate() and inflate() below for details */
49223var Z_NO_FLUSH = 0;
49224var Z_PARTIAL_FLUSH = 1;
49225//var Z_SYNC_FLUSH = 2;
49226var Z_FULL_FLUSH = 3;
49227var Z_FINISH = 4;
49228var Z_BLOCK = 5;
49229//var Z_TREES = 6;
49230
49231
49232/* Return codes for the compression/decompression functions. Negative values
49233 * are errors, positive values are used for special but normal events.
49234 */
49235var Z_OK = 0;
49236var Z_STREAM_END = 1;
49237//var Z_NEED_DICT = 2;
49238//var Z_ERRNO = -1;
49239var Z_STREAM_ERROR = -2;
49240var Z_DATA_ERROR = -3;
49241//var Z_MEM_ERROR = -4;
49242var Z_BUF_ERROR = -5;
49243//var Z_VERSION_ERROR = -6;
49244
49245
49246/* compression levels */
49247//var Z_NO_COMPRESSION = 0;
49248//var Z_BEST_SPEED = 1;
49249//var Z_BEST_COMPRESSION = 9;
49250var Z_DEFAULT_COMPRESSION = -1;
49251
49252
49253var Z_FILTERED = 1;
49254var Z_HUFFMAN_ONLY = 2;
49255var Z_RLE = 3;
49256var Z_FIXED = 4;
49257var Z_DEFAULT_STRATEGY = 0;
49258
49259/* Possible values of the data_type field (though see inflate()) */
49260//var Z_BINARY = 0;
49261//var Z_TEXT = 1;
49262//var Z_ASCII = 1; // = Z_TEXT
49263var Z_UNKNOWN = 2;
49264
49265
49266/* The deflate compression method */
49267var Z_DEFLATED = 8;
49268
49269/*============================================================================*/
49270
49271
49272var MAX_MEM_LEVEL = 9;
49273/* Maximum value for memLevel in deflateInit2 */
49274var MAX_WBITS = 15;
49275/* 32K LZ77 window */
49276var DEF_MEM_LEVEL = 8;
49277
49278
49279var LENGTH_CODES = 29;
49280/* number of length codes, not counting the special END_BLOCK code */
49281var LITERALS = 256;
49282/* number of literal bytes 0..255 */
49283var L_CODES = LITERALS + 1 + LENGTH_CODES;
49284/* number of Literal or Length codes, including the END_BLOCK code */
49285var D_CODES = 30;
49286/* number of distance codes */
49287var BL_CODES = 19;
49288/* number of codes used to transfer the bit lengths */
49289var HEAP_SIZE = 2 * L_CODES + 1;
49290/* maximum heap size */
49291var MAX_BITS = 15;
49292/* All codes must not exceed MAX_BITS bits */
49293
49294var MIN_MATCH = 3;
49295var MAX_MATCH = 258;
49296var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
49297
49298var PRESET_DICT = 0x20;
49299
49300var INIT_STATE = 42;
49301var EXTRA_STATE = 69;
49302var NAME_STATE = 73;
49303var COMMENT_STATE = 91;
49304var HCRC_STATE = 103;
49305var BUSY_STATE = 113;
49306var FINISH_STATE = 666;
49307
49308var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
49309var BS_BLOCK_DONE = 2; /* block flush performed */
49310var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
49311var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
49312
49313var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
49314
49315function err(strm, errorCode) {
49316 strm.msg = msg[errorCode];
49317 return errorCode;
49318}
49319
49320function rank(f) {
49321 return ((f) << 1) - ((f) > 4 ? 9 : 0);
49322}
49323
49324function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
49325
49326
49327/* =========================================================================
49328 * Flush as much pending output as possible. All deflate() output goes
49329 * through this function so some applications may wish to modify it
49330 * to avoid allocating a large strm->output buffer and copying into it.
49331 * (See also read_buf()).
49332 */
49333function flush_pending(strm) {
49334 var s = strm.state;
49335
49336 //_tr_flush_bits(s);
49337 var len = s.pending;
49338 if (len > strm.avail_out) {
49339 len = strm.avail_out;
49340 }
49341 if (len === 0) { return; }
49342
49343 utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
49344 strm.next_out += len;
49345 s.pending_out += len;
49346 strm.total_out += len;
49347 strm.avail_out -= len;
49348 s.pending -= len;
49349 if (s.pending === 0) {
49350 s.pending_out = 0;
49351 }
49352}
49353
49354
49355function flush_block_only(s, last) {
49356 trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
49357 s.block_start = s.strstart;
49358 flush_pending(s.strm);
49359}
49360
49361
49362function put_byte(s, b) {
49363 s.pending_buf[s.pending++] = b;
49364}
49365
49366
49367/* =========================================================================
49368 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
49369 * IN assertion: the stream state is correct and there is enough room in
49370 * pending_buf.
49371 */
49372function putShortMSB(s, b) {
49373// put_byte(s, (Byte)(b >> 8));
49374// put_byte(s, (Byte)(b & 0xff));
49375 s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
49376 s.pending_buf[s.pending++] = b & 0xff;
49377}
49378
49379
49380/* ===========================================================================
49381 * Read a new buffer from the current input stream, update the adler32
49382 * and total number of bytes read. All deflate() input goes through
49383 * this function so some applications may wish to modify it to avoid
49384 * allocating a large strm->input buffer and copying from it.
49385 * (See also flush_pending()).
49386 */
49387function read_buf(strm, buf, start, size) {
49388 var len = strm.avail_in;
49389
49390 if (len > size) { len = size; }
49391 if (len === 0) { return 0; }
49392
49393 strm.avail_in -= len;
49394
49395 // zmemcpy(buf, strm->next_in, len);
49396 utils.arraySet(buf, strm.input, strm.next_in, len, start);
49397 if (strm.state.wrap === 1) {
49398 strm.adler = adler32(strm.adler, buf, len, start);
49399 }
49400
49401 else if (strm.state.wrap === 2) {
49402 strm.adler = crc32(strm.adler, buf, len, start);
49403 }
49404
49405 strm.next_in += len;
49406 strm.total_in += len;
49407
49408 return len;
49409}
49410
49411
49412/* ===========================================================================
49413 * Set match_start to the longest match starting at the given string and
49414 * return its length. Matches shorter or equal to prev_length are discarded,
49415 * in which case the result is equal to prev_length and match_start is
49416 * garbage.
49417 * IN assertions: cur_match is the head of the hash chain for the current
49418 * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
49419 * OUT assertion: the match length is not greater than s->lookahead.
49420 */
49421function longest_match(s, cur_match) {
49422 var chain_length = s.max_chain_length; /* max hash chain length */
49423 var scan = s.strstart; /* current string */
49424 var match; /* matched string */
49425 var len; /* length of current match */
49426 var best_len = s.prev_length; /* best match length so far */
49427 var nice_match = s.nice_match; /* stop if match long enough */
49428 var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
49429 s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
49430
49431 var _win = s.window; // shortcut
49432
49433 var wmask = s.w_mask;
49434 var prev = s.prev;
49435
49436 /* Stop when cur_match becomes <= limit. To simplify the code,
49437 * we prevent matches with the string of window index 0.
49438 */
49439
49440 var strend = s.strstart + MAX_MATCH;
49441 var scan_end1 = _win[scan + best_len - 1];
49442 var scan_end = _win[scan + best_len];
49443
49444 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
49445 * It is easy to get rid of this optimization if necessary.
49446 */
49447 // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
49448
49449 /* Do not waste too much time if we already have a good match: */
49450 if (s.prev_length >= s.good_match) {
49451 chain_length >>= 2;
49452 }
49453 /* Do not look for matches beyond the end of the input. This is necessary
49454 * to make deflate deterministic.
49455 */
49456 if (nice_match > s.lookahead) { nice_match = s.lookahead; }
49457
49458 // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
49459
49460 do {
49461 // Assert(cur_match < s->strstart, "no future");
49462 match = cur_match;
49463
49464 /* Skip to next match if the match length cannot increase
49465 * or if the match length is less than 2. Note that the checks below
49466 * for insufficient lookahead only occur occasionally for performance
49467 * reasons. Therefore uninitialized memory will be accessed, and
49468 * conditional jumps will be made that depend on those values.
49469 * However the length of the match is limited to the lookahead, so
49470 * the output of deflate is not affected by the uninitialized values.
49471 */
49472
49473 if (_win[match + best_len] !== scan_end ||
49474 _win[match + best_len - 1] !== scan_end1 ||
49475 _win[match] !== _win[scan] ||
49476 _win[++match] !== _win[scan + 1]) {
49477 continue;
49478 }
49479
49480 /* The check at best_len-1 can be removed because it will be made
49481 * again later. (This heuristic is not always a win.)
49482 * It is not necessary to compare scan[2] and match[2] since they
49483 * are always equal when the other bytes match, given that
49484 * the hash keys are equal and that HASH_BITS >= 8.
49485 */
49486 scan += 2;
49487 match++;
49488 // Assert(*scan == *match, "match[2]?");
49489
49490 /* We check for insufficient lookahead only every 8th comparison;
49491 * the 256th check will be made at strstart+258.
49492 */
49493 do {
49494 /*jshint noempty:false*/
49495 } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
49496 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
49497 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
49498 _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
49499 scan < strend);
49500
49501 // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
49502
49503 len = MAX_MATCH - (strend - scan);
49504 scan = strend - MAX_MATCH;
49505
49506 if (len > best_len) {
49507 s.match_start = cur_match;
49508 best_len = len;
49509 if (len >= nice_match) {
49510 break;
49511 }
49512 scan_end1 = _win[scan + best_len - 1];
49513 scan_end = _win[scan + best_len];
49514 }
49515 } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
49516
49517 if (best_len <= s.lookahead) {
49518 return best_len;
49519 }
49520 return s.lookahead;
49521}
49522
49523
49524/* ===========================================================================
49525 * Fill the window when the lookahead becomes insufficient.
49526 * Updates strstart and lookahead.
49527 *
49528 * IN assertion: lookahead < MIN_LOOKAHEAD
49529 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
49530 * At least one byte has been read, or avail_in == 0; reads are
49531 * performed for at least two bytes (required for the zip translate_eol
49532 * option -- not supported here).
49533 */
49534function fill_window(s) {
49535 var _w_size = s.w_size;
49536 var p, n, m, more, str;
49537
49538 //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
49539
49540 do {
49541 more = s.window_size - s.lookahead - s.strstart;
49542
49543 // JS ints have 32 bit, block below not needed
49544 /* Deal with !@#$% 64K limit: */
49545 //if (sizeof(int) <= 2) {
49546 // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
49547 // more = wsize;
49548 //
49549 // } else if (more == (unsigned)(-1)) {
49550 // /* Very unlikely, but possible on 16 bit machine if
49551 // * strstart == 0 && lookahead == 1 (input done a byte at time)
49552 // */
49553 // more--;
49554 // }
49555 //}
49556
49557
49558 /* If the window is almost full and there is insufficient lookahead,
49559 * move the upper half to the lower one to make room in the upper half.
49560 */
49561 if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
49562
49563 utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
49564 s.match_start -= _w_size;
49565 s.strstart -= _w_size;
49566 /* we now have strstart >= MAX_DIST */
49567 s.block_start -= _w_size;
49568
49569 /* Slide the hash table (could be avoided with 32 bit values
49570 at the expense of memory usage). We slide even when level == 0
49571 to keep the hash table consistent if we switch back to level > 0
49572 later. (Using level 0 permanently is not an optimal usage of
49573 zlib, so we don't care about this pathological case.)
49574 */
49575
49576 n = s.hash_size;
49577 p = n;
49578 do {
49579 m = s.head[--p];
49580 s.head[p] = (m >= _w_size ? m - _w_size : 0);
49581 } while (--n);
49582
49583 n = _w_size;
49584 p = n;
49585 do {
49586 m = s.prev[--p];
49587 s.prev[p] = (m >= _w_size ? m - _w_size : 0);
49588 /* If n is not on any hash chain, prev[n] is garbage but
49589 * its value will never be used.
49590 */
49591 } while (--n);
49592
49593 more += _w_size;
49594 }
49595 if (s.strm.avail_in === 0) {
49596 break;
49597 }
49598
49599 /* If there was no sliding:
49600 * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
49601 * more == window_size - lookahead - strstart
49602 * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
49603 * => more >= window_size - 2*WSIZE + 2
49604 * In the BIG_MEM or MMAP case (not yet supported),
49605 * window_size == input_size + MIN_LOOKAHEAD &&
49606 * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
49607 * Otherwise, window_size == 2*WSIZE so more >= 2.
49608 * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
49609 */
49610 //Assert(more >= 2, "more < 2");
49611 n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
49612 s.lookahead += n;
49613
49614 /* Initialize the hash value now that we have some input: */
49615 if (s.lookahead + s.insert >= MIN_MATCH) {
49616 str = s.strstart - s.insert;
49617 s.ins_h = s.window[str];
49618
49619 /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
49620 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
49621//#if MIN_MATCH != 3
49622// Call update_hash() MIN_MATCH-3 more times
49623//#endif
49624 while (s.insert) {
49625 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
49626 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
49627
49628 s.prev[str & s.w_mask] = s.head[s.ins_h];
49629 s.head[s.ins_h] = str;
49630 str++;
49631 s.insert--;
49632 if (s.lookahead + s.insert < MIN_MATCH) {
49633 break;
49634 }
49635 }
49636 }
49637 /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
49638 * but this is not important since only literal bytes will be emitted.
49639 */
49640
49641 } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
49642
49643 /* If the WIN_INIT bytes after the end of the current data have never been
49644 * written, then zero those bytes in order to avoid memory check reports of
49645 * the use of uninitialized (or uninitialised as Julian writes) bytes by
49646 * the longest match routines. Update the high water mark for the next
49647 * time through here. WIN_INIT is set to MAX_MATCH since the longest match
49648 * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
49649 */
49650// if (s.high_water < s.window_size) {
49651// var curr = s.strstart + s.lookahead;
49652// var init = 0;
49653//
49654// if (s.high_water < curr) {
49655// /* Previous high water mark below current data -- zero WIN_INIT
49656// * bytes or up to end of window, whichever is less.
49657// */
49658// init = s.window_size - curr;
49659// if (init > WIN_INIT)
49660// init = WIN_INIT;
49661// zmemzero(s->window + curr, (unsigned)init);
49662// s->high_water = curr + init;
49663// }
49664// else if (s->high_water < (ulg)curr + WIN_INIT) {
49665// /* High water mark at or above current data, but below current data
49666// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
49667// * to end of window, whichever is less.
49668// */
49669// init = (ulg)curr + WIN_INIT - s->high_water;
49670// if (init > s->window_size - s->high_water)
49671// init = s->window_size - s->high_water;
49672// zmemzero(s->window + s->high_water, (unsigned)init);
49673// s->high_water += init;
49674// }
49675// }
49676//
49677// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
49678// "not enough room for search");
49679}
49680
49681/* ===========================================================================
49682 * Copy without compression as much as possible from the input stream, return
49683 * the current block state.
49684 * This function does not insert new strings in the dictionary since
49685 * uncompressible data is probably not useful. This function is used
49686 * only for the level=0 compression option.
49687 * NOTE: this function should be optimized to avoid extra copying from
49688 * window to pending_buf.
49689 */
49690function deflate_stored(s, flush) {
49691 /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
49692 * to pending_buf_size, and each stored block has a 5 byte header:
49693 */
49694 var max_block_size = 0xffff;
49695
49696 if (max_block_size > s.pending_buf_size - 5) {
49697 max_block_size = s.pending_buf_size - 5;
49698 }
49699
49700 /* Copy as much as possible from input to output: */
49701 for (;;) {
49702 /* Fill the window as much as possible: */
49703 if (s.lookahead <= 1) {
49704
49705 //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
49706 // s->block_start >= (long)s->w_size, "slide too late");
49707// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
49708// s.block_start >= s.w_size)) {
49709// throw new Error("slide too late");
49710// }
49711
49712 fill_window(s);
49713 if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
49714 return BS_NEED_MORE;
49715 }
49716
49717 if (s.lookahead === 0) {
49718 break;
49719 }
49720 /* flush the current block */
49721 }
49722 //Assert(s->block_start >= 0L, "block gone");
49723// if (s.block_start < 0) throw new Error("block gone");
49724
49725 s.strstart += s.lookahead;
49726 s.lookahead = 0;
49727
49728 /* Emit a stored block if pending_buf will be full: */
49729 var max_start = s.block_start + max_block_size;
49730
49731 if (s.strstart === 0 || s.strstart >= max_start) {
49732 /* strstart == 0 is possible when wraparound on 16-bit machine */
49733 s.lookahead = s.strstart - max_start;
49734 s.strstart = max_start;
49735 /*** FLUSH_BLOCK(s, 0); ***/
49736 flush_block_only(s, false);
49737 if (s.strm.avail_out === 0) {
49738 return BS_NEED_MORE;
49739 }
49740 /***/
49741
49742
49743 }
49744 /* Flush if we may have to slide, otherwise block_start may become
49745 * negative and the data will be gone:
49746 */
49747 if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
49748 /*** FLUSH_BLOCK(s, 0); ***/
49749 flush_block_only(s, false);
49750 if (s.strm.avail_out === 0) {
49751 return BS_NEED_MORE;
49752 }
49753 /***/
49754 }
49755 }
49756
49757 s.insert = 0;
49758
49759 if (flush === Z_FINISH) {
49760 /*** FLUSH_BLOCK(s, 1); ***/
49761 flush_block_only(s, true);
49762 if (s.strm.avail_out === 0) {
49763 return BS_FINISH_STARTED;
49764 }
49765 /***/
49766 return BS_FINISH_DONE;
49767 }
49768
49769 if (s.strstart > s.block_start) {
49770 /*** FLUSH_BLOCK(s, 0); ***/
49771 flush_block_only(s, false);
49772 if (s.strm.avail_out === 0) {
49773 return BS_NEED_MORE;
49774 }
49775 /***/
49776 }
49777
49778 return BS_NEED_MORE;
49779}
49780
49781/* ===========================================================================
49782 * Compress as much as possible from the input stream, return the current
49783 * block state.
49784 * This function does not perform lazy evaluation of matches and inserts
49785 * new strings in the dictionary only for unmatched strings or for short
49786 * matches. It is used only for the fast compression options.
49787 */
49788function deflate_fast(s, flush) {
49789 var hash_head; /* head of the hash chain */
49790 var bflush; /* set if current block must be flushed */
49791
49792 for (;;) {
49793 /* Make sure that we always have enough lookahead, except
49794 * at the end of the input file. We need MAX_MATCH bytes
49795 * for the next match, plus MIN_MATCH bytes to insert the
49796 * string following the next match.
49797 */
49798 if (s.lookahead < MIN_LOOKAHEAD) {
49799 fill_window(s);
49800 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
49801 return BS_NEED_MORE;
49802 }
49803 if (s.lookahead === 0) {
49804 break; /* flush the current block */
49805 }
49806 }
49807
49808 /* Insert the string window[strstart .. strstart+2] in the
49809 * dictionary, and set hash_head to the head of the hash chain:
49810 */
49811 hash_head = 0/*NIL*/;
49812 if (s.lookahead >= MIN_MATCH) {
49813 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
49814 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
49815 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
49816 s.head[s.ins_h] = s.strstart;
49817 /***/
49818 }
49819
49820 /* Find the longest match, discarding those <= prev_length.
49821 * At this point we have always match_length < MIN_MATCH
49822 */
49823 if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
49824 /* To simplify the code, we prevent matches with the string
49825 * of window index 0 (in particular we have to avoid a match
49826 * of the string with itself at the start of the input file).
49827 */
49828 s.match_length = longest_match(s, hash_head);
49829 /* longest_match() sets match_start */
49830 }
49831 if (s.match_length >= MIN_MATCH) {
49832 // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
49833
49834 /*** _tr_tally_dist(s, s.strstart - s.match_start,
49835 s.match_length - MIN_MATCH, bflush); ***/
49836 bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
49837
49838 s.lookahead -= s.match_length;
49839
49840 /* Insert new strings in the hash table only if the match length
49841 * is not too large. This saves time but degrades compression.
49842 */
49843 if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
49844 s.match_length--; /* string at strstart already in table */
49845 do {
49846 s.strstart++;
49847 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
49848 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
49849 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
49850 s.head[s.ins_h] = s.strstart;
49851 /***/
49852 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
49853 * always MIN_MATCH bytes ahead.
49854 */
49855 } while (--s.match_length !== 0);
49856 s.strstart++;
49857 } else
49858 {
49859 s.strstart += s.match_length;
49860 s.match_length = 0;
49861 s.ins_h = s.window[s.strstart];
49862 /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
49863 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
49864
49865//#if MIN_MATCH != 3
49866// Call UPDATE_HASH() MIN_MATCH-3 more times
49867//#endif
49868 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
49869 * matter since it will be recomputed at next deflate call.
49870 */
49871 }
49872 } else {
49873 /* No match, output a literal byte */
49874 //Tracevv((stderr,"%c", s.window[s.strstart]));
49875 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
49876 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
49877
49878 s.lookahead--;
49879 s.strstart++;
49880 }
49881 if (bflush) {
49882 /*** FLUSH_BLOCK(s, 0); ***/
49883 flush_block_only(s, false);
49884 if (s.strm.avail_out === 0) {
49885 return BS_NEED_MORE;
49886 }
49887 /***/
49888 }
49889 }
49890 s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1);
49891 if (flush === Z_FINISH) {
49892 /*** FLUSH_BLOCK(s, 1); ***/
49893 flush_block_only(s, true);
49894 if (s.strm.avail_out === 0) {
49895 return BS_FINISH_STARTED;
49896 }
49897 /***/
49898 return BS_FINISH_DONE;
49899 }
49900 if (s.last_lit) {
49901 /*** FLUSH_BLOCK(s, 0); ***/
49902 flush_block_only(s, false);
49903 if (s.strm.avail_out === 0) {
49904 return BS_NEED_MORE;
49905 }
49906 /***/
49907 }
49908 return BS_BLOCK_DONE;
49909}
49910
49911/* ===========================================================================
49912 * Same as above, but achieves better compression. We use a lazy
49913 * evaluation for matches: a match is finally adopted only if there is
49914 * no better match at the next window position.
49915 */
49916function deflate_slow(s, flush) {
49917 var hash_head; /* head of hash chain */
49918 var bflush; /* set if current block must be flushed */
49919
49920 var max_insert;
49921
49922 /* Process the input block. */
49923 for (;;) {
49924 /* Make sure that we always have enough lookahead, except
49925 * at the end of the input file. We need MAX_MATCH bytes
49926 * for the next match, plus MIN_MATCH bytes to insert the
49927 * string following the next match.
49928 */
49929 if (s.lookahead < MIN_LOOKAHEAD) {
49930 fill_window(s);
49931 if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
49932 return BS_NEED_MORE;
49933 }
49934 if (s.lookahead === 0) { break; } /* flush the current block */
49935 }
49936
49937 /* Insert the string window[strstart .. strstart+2] in the
49938 * dictionary, and set hash_head to the head of the hash chain:
49939 */
49940 hash_head = 0/*NIL*/;
49941 if (s.lookahead >= MIN_MATCH) {
49942 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
49943 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
49944 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
49945 s.head[s.ins_h] = s.strstart;
49946 /***/
49947 }
49948
49949 /* Find the longest match, discarding those <= prev_length.
49950 */
49951 s.prev_length = s.match_length;
49952 s.prev_match = s.match_start;
49953 s.match_length = MIN_MATCH - 1;
49954
49955 if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
49956 s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
49957 /* To simplify the code, we prevent matches with the string
49958 * of window index 0 (in particular we have to avoid a match
49959 * of the string with itself at the start of the input file).
49960 */
49961 s.match_length = longest_match(s, hash_head);
49962 /* longest_match() sets match_start */
49963
49964 if (s.match_length <= 5 &&
49965 (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
49966
49967 /* If prev_match is also MIN_MATCH, match_start is garbage
49968 * but we will ignore the current match anyway.
49969 */
49970 s.match_length = MIN_MATCH - 1;
49971 }
49972 }
49973 /* If there was a match at the previous step and the current
49974 * match is not better, output the previous match:
49975 */
49976 if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
49977 max_insert = s.strstart + s.lookahead - MIN_MATCH;
49978 /* Do not insert strings in hash table beyond this. */
49979
49980 //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
49981
49982 /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
49983 s.prev_length - MIN_MATCH, bflush);***/
49984 bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH);
49985 /* Insert in hash table all strings up to the end of the match.
49986 * strstart-1 and strstart are already inserted. If there is not
49987 * enough lookahead, the last two strings are not inserted in
49988 * the hash table.
49989 */
49990 s.lookahead -= s.prev_length - 1;
49991 s.prev_length -= 2;
49992 do {
49993 if (++s.strstart <= max_insert) {
49994 /*** INSERT_STRING(s, s.strstart, hash_head); ***/
49995 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
49996 hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
49997 s.head[s.ins_h] = s.strstart;
49998 /***/
49999 }
50000 } while (--s.prev_length !== 0);
50001 s.match_available = 0;
50002 s.match_length = MIN_MATCH - 1;
50003 s.strstart++;
50004
50005 if (bflush) {
50006 /*** FLUSH_BLOCK(s, 0); ***/
50007 flush_block_only(s, false);
50008 if (s.strm.avail_out === 0) {
50009 return BS_NEED_MORE;
50010 }
50011 /***/
50012 }
50013
50014 } else if (s.match_available) {
50015 /* If there was no match at the previous position, output a
50016 * single literal. If there was a match but the current match
50017 * is longer, truncate the previous match to a single literal.
50018 */
50019 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
50020 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
50021 bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
50022
50023 if (bflush) {
50024 /*** FLUSH_BLOCK_ONLY(s, 0) ***/
50025 flush_block_only(s, false);
50026 /***/
50027 }
50028 s.strstart++;
50029 s.lookahead--;
50030 if (s.strm.avail_out === 0) {
50031 return BS_NEED_MORE;
50032 }
50033 } else {
50034 /* There is no previous match to compare with, wait for
50035 * the next step to decide.
50036 */
50037 s.match_available = 1;
50038 s.strstart++;
50039 s.lookahead--;
50040 }
50041 }
50042 //Assert (flush != Z_NO_FLUSH, "no flush?");
50043 if (s.match_available) {
50044 //Tracevv((stderr,"%c", s->window[s->strstart-1]));
50045 /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
50046 bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]);
50047
50048 s.match_available = 0;
50049 }
50050 s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1;
50051 if (flush === Z_FINISH) {
50052 /*** FLUSH_BLOCK(s, 1); ***/
50053 flush_block_only(s, true);
50054 if (s.strm.avail_out === 0) {
50055 return BS_FINISH_STARTED;
50056 }
50057 /***/
50058 return BS_FINISH_DONE;
50059 }
50060 if (s.last_lit) {
50061 /*** FLUSH_BLOCK(s, 0); ***/
50062 flush_block_only(s, false);
50063 if (s.strm.avail_out === 0) {
50064 return BS_NEED_MORE;
50065 }
50066 /***/
50067 }
50068
50069 return BS_BLOCK_DONE;
50070}
50071
50072
50073/* ===========================================================================
50074 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
50075 * one. Do not maintain a hash table. (It will be regenerated if this run of
50076 * deflate switches away from Z_RLE.)
50077 */
50078function deflate_rle(s, flush) {
50079 var bflush; /* set if current block must be flushed */
50080 var prev; /* byte at distance one to match */
50081 var scan, strend; /* scan goes up to strend for length of run */
50082
50083 var _win = s.window;
50084
50085 for (;;) {
50086 /* Make sure that we always have enough lookahead, except
50087 * at the end of the input file. We need MAX_MATCH bytes
50088 * for the longest run, plus one for the unrolled loop.
50089 */
50090 if (s.lookahead <= MAX_MATCH) {
50091 fill_window(s);
50092 if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
50093 return BS_NEED_MORE;
50094 }
50095 if (s.lookahead === 0) { break; } /* flush the current block */
50096 }
50097
50098 /* See how many times the previous byte repeats */
50099 s.match_length = 0;
50100 if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
50101 scan = s.strstart - 1;
50102 prev = _win[scan];
50103 if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
50104 strend = s.strstart + MAX_MATCH;
50105 do {
50106 /*jshint noempty:false*/
50107 } while (prev === _win[++scan] && prev === _win[++scan] &&
50108 prev === _win[++scan] && prev === _win[++scan] &&
50109 prev === _win[++scan] && prev === _win[++scan] &&
50110 prev === _win[++scan] && prev === _win[++scan] &&
50111 scan < strend);
50112 s.match_length = MAX_MATCH - (strend - scan);
50113 if (s.match_length > s.lookahead) {
50114 s.match_length = s.lookahead;
50115 }
50116 }
50117 //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
50118 }
50119
50120 /* Emit match if have run of MIN_MATCH or longer, else emit literal */
50121 if (s.match_length >= MIN_MATCH) {
50122 //check_match(s, s.strstart, s.strstart - 1, s.match_length);
50123
50124 /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
50125 bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
50126
50127 s.lookahead -= s.match_length;
50128 s.strstart += s.match_length;
50129 s.match_length = 0;
50130 } else {
50131 /* No match, output a literal byte */
50132 //Tracevv((stderr,"%c", s->window[s->strstart]));
50133 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
50134 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
50135
50136 s.lookahead--;
50137 s.strstart++;
50138 }
50139 if (bflush) {
50140 /*** FLUSH_BLOCK(s, 0); ***/
50141 flush_block_only(s, false);
50142 if (s.strm.avail_out === 0) {
50143 return BS_NEED_MORE;
50144 }
50145 /***/
50146 }
50147 }
50148 s.insert = 0;
50149 if (flush === Z_FINISH) {
50150 /*** FLUSH_BLOCK(s, 1); ***/
50151 flush_block_only(s, true);
50152 if (s.strm.avail_out === 0) {
50153 return BS_FINISH_STARTED;
50154 }
50155 /***/
50156 return BS_FINISH_DONE;
50157 }
50158 if (s.last_lit) {
50159 /*** FLUSH_BLOCK(s, 0); ***/
50160 flush_block_only(s, false);
50161 if (s.strm.avail_out === 0) {
50162 return BS_NEED_MORE;
50163 }
50164 /***/
50165 }
50166 return BS_BLOCK_DONE;
50167}
50168
50169/* ===========================================================================
50170 * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
50171 * (It will be regenerated if this run of deflate switches away from Huffman.)
50172 */
50173function deflate_huff(s, flush) {
50174 var bflush; /* set if current block must be flushed */
50175
50176 for (;;) {
50177 /* Make sure that we have a literal to write. */
50178 if (s.lookahead === 0) {
50179 fill_window(s);
50180 if (s.lookahead === 0) {
50181 if (flush === Z_NO_FLUSH) {
50182 return BS_NEED_MORE;
50183 }
50184 break; /* flush the current block */
50185 }
50186 }
50187
50188 /* Output a literal byte */
50189 s.match_length = 0;
50190 //Tracevv((stderr,"%c", s->window[s->strstart]));
50191 /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
50192 bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
50193 s.lookahead--;
50194 s.strstart++;
50195 if (bflush) {
50196 /*** FLUSH_BLOCK(s, 0); ***/
50197 flush_block_only(s, false);
50198 if (s.strm.avail_out === 0) {
50199 return BS_NEED_MORE;
50200 }
50201 /***/
50202 }
50203 }
50204 s.insert = 0;
50205 if (flush === Z_FINISH) {
50206 /*** FLUSH_BLOCK(s, 1); ***/
50207 flush_block_only(s, true);
50208 if (s.strm.avail_out === 0) {
50209 return BS_FINISH_STARTED;
50210 }
50211 /***/
50212 return BS_FINISH_DONE;
50213 }
50214 if (s.last_lit) {
50215 /*** FLUSH_BLOCK(s, 0); ***/
50216 flush_block_only(s, false);
50217 if (s.strm.avail_out === 0) {
50218 return BS_NEED_MORE;
50219 }
50220 /***/
50221 }
50222 return BS_BLOCK_DONE;
50223}
50224
50225/* Values for max_lazy_match, good_match and max_chain_length, depending on
50226 * the desired pack level (0..9). The values given below have been tuned to
50227 * exclude worst case performance for pathological files. Better values may be
50228 * found for specific files.
50229 */
50230function Config(good_length, max_lazy, nice_length, max_chain, func) {
50231 this.good_length = good_length;
50232 this.max_lazy = max_lazy;
50233 this.nice_length = nice_length;
50234 this.max_chain = max_chain;
50235 this.func = func;
50236}
50237
50238var configuration_table;
50239
50240configuration_table = [
50241 /* good lazy nice chain */
50242 new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
50243 new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
50244 new Config(4, 5, 16, 8, deflate_fast), /* 2 */
50245 new Config(4, 6, 32, 32, deflate_fast), /* 3 */
50246
50247 new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
50248 new Config(8, 16, 32, 32, deflate_slow), /* 5 */
50249 new Config(8, 16, 128, 128, deflate_slow), /* 6 */
50250 new Config(8, 32, 128, 256, deflate_slow), /* 7 */
50251 new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
50252 new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
50253];
50254
50255
50256/* ===========================================================================
50257 * Initialize the "longest match" routines for a new zlib stream
50258 */
50259function lm_init(s) {
50260 s.window_size = 2 * s.w_size;
50261
50262 /*** CLEAR_HASH(s); ***/
50263 zero(s.head); // Fill with NIL (= 0);
50264
50265 /* Set the default configuration parameters:
50266 */
50267 s.max_lazy_match = configuration_table[s.level].max_lazy;
50268 s.good_match = configuration_table[s.level].good_length;
50269 s.nice_match = configuration_table[s.level].nice_length;
50270 s.max_chain_length = configuration_table[s.level].max_chain;
50271
50272 s.strstart = 0;
50273 s.block_start = 0;
50274 s.lookahead = 0;
50275 s.insert = 0;
50276 s.match_length = s.prev_length = MIN_MATCH - 1;
50277 s.match_available = 0;
50278 s.ins_h = 0;
50279}
50280
50281
50282function DeflateState() {
50283 this.strm = null; /* pointer back to this zlib stream */
50284 this.status = 0; /* as the name implies */
50285 this.pending_buf = null; /* output still pending */
50286 this.pending_buf_size = 0; /* size of pending_buf */
50287 this.pending_out = 0; /* next pending byte to output to the stream */
50288 this.pending = 0; /* nb of bytes in the pending buffer */
50289 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
50290 this.gzhead = null; /* gzip header information to write */
50291 this.gzindex = 0; /* where in extra, name, or comment */
50292 this.method = Z_DEFLATED; /* can only be DEFLATED */
50293 this.last_flush = -1; /* value of flush param for previous deflate call */
50294
50295 this.w_size = 0; /* LZ77 window size (32K by default) */
50296 this.w_bits = 0; /* log2(w_size) (8..16) */
50297 this.w_mask = 0; /* w_size - 1 */
50298
50299 this.window = null;
50300 /* Sliding window. Input bytes are read into the second half of the window,
50301 * and move to the first half later to keep a dictionary of at least wSize
50302 * bytes. With this organization, matches are limited to a distance of
50303 * wSize-MAX_MATCH bytes, but this ensures that IO is always
50304 * performed with a length multiple of the block size.
50305 */
50306
50307 this.window_size = 0;
50308 /* Actual size of window: 2*wSize, except when the user input buffer
50309 * is directly used as sliding window.
50310 */
50311
50312 this.prev = null;
50313 /* Link to older string with same hash index. To limit the size of this
50314 * array to 64K, this link is maintained only for the last 32K strings.
50315 * An index in this array is thus a window index modulo 32K.
50316 */
50317
50318 this.head = null; /* Heads of the hash chains or NIL. */
50319
50320 this.ins_h = 0; /* hash index of string to be inserted */
50321 this.hash_size = 0; /* number of elements in hash table */
50322 this.hash_bits = 0; /* log2(hash_size) */
50323 this.hash_mask = 0; /* hash_size-1 */
50324
50325 this.hash_shift = 0;
50326 /* Number of bits by which ins_h must be shifted at each input
50327 * step. It must be such that after MIN_MATCH steps, the oldest
50328 * byte no longer takes part in the hash key, that is:
50329 * hash_shift * MIN_MATCH >= hash_bits
50330 */
50331
50332 this.block_start = 0;
50333 /* Window position at the beginning of the current output block. Gets
50334 * negative when the window is moved backwards.
50335 */
50336
50337 this.match_length = 0; /* length of best match */
50338 this.prev_match = 0; /* previous match */
50339 this.match_available = 0; /* set if previous match exists */
50340 this.strstart = 0; /* start of string to insert */
50341 this.match_start = 0; /* start of matching string */
50342 this.lookahead = 0; /* number of valid bytes ahead in window */
50343
50344 this.prev_length = 0;
50345 /* Length of the best match at previous step. Matches not greater than this
50346 * are discarded. This is used in the lazy match evaluation.
50347 */
50348
50349 this.max_chain_length = 0;
50350 /* To speed up deflation, hash chains are never searched beyond this
50351 * length. A higher limit improves compression ratio but degrades the
50352 * speed.
50353 */
50354
50355 this.max_lazy_match = 0;
50356 /* Attempt to find a better match only when the current match is strictly
50357 * smaller than this value. This mechanism is used only for compression
50358 * levels >= 4.
50359 */
50360 // That's alias to max_lazy_match, don't use directly
50361 //this.max_insert_length = 0;
50362 /* Insert new strings in the hash table only if the match length is not
50363 * greater than this length. This saves time but degrades compression.
50364 * max_insert_length is used only for compression levels <= 3.
50365 */
50366
50367 this.level = 0; /* compression level (1..9) */
50368 this.strategy = 0; /* favor or force Huffman coding*/
50369
50370 this.good_match = 0;
50371 /* Use a faster search when the previous match is longer than this */
50372
50373 this.nice_match = 0; /* Stop searching when current match exceeds this */
50374
50375 /* used by trees.c: */
50376
50377 /* Didn't use ct_data typedef below to suppress compiler warning */
50378
50379 // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
50380 // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
50381 // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
50382
50383 // Use flat array of DOUBLE size, with interleaved fata,
50384 // because JS does not support effective
50385 this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
50386 this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2);
50387 this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2);
50388 zero(this.dyn_ltree);
50389 zero(this.dyn_dtree);
50390 zero(this.bl_tree);
50391
50392 this.l_desc = null; /* desc. for literal tree */
50393 this.d_desc = null; /* desc. for distance tree */
50394 this.bl_desc = null; /* desc. for bit length tree */
50395
50396 //ush bl_count[MAX_BITS+1];
50397 this.bl_count = new utils.Buf16(MAX_BITS + 1);
50398 /* number of codes at each bit length for an optimal tree */
50399
50400 //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
50401 this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */
50402 zero(this.heap);
50403
50404 this.heap_len = 0; /* number of elements in the heap */
50405 this.heap_max = 0; /* element of largest frequency */
50406 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
50407 * The same heap array is used to build all trees.
50408 */
50409
50410 this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1];
50411 zero(this.depth);
50412 /* Depth of each subtree used as tie breaker for trees of equal frequency
50413 */
50414
50415 this.l_buf = 0; /* buffer index for literals or lengths */
50416
50417 this.lit_bufsize = 0;
50418 /* Size of match buffer for literals/lengths. There are 4 reasons for
50419 * limiting lit_bufsize to 64K:
50420 * - frequencies can be kept in 16 bit counters
50421 * - if compression is not successful for the first block, all input
50422 * data is still in the window so we can still emit a stored block even
50423 * when input comes from standard input. (This can also be done for
50424 * all blocks if lit_bufsize is not greater than 32K.)
50425 * - if compression is not successful for a file smaller than 64K, we can
50426 * even emit a stored file instead of a stored block (saving 5 bytes).
50427 * This is applicable only for zip (not gzip or zlib).
50428 * - creating new Huffman trees less frequently may not provide fast
50429 * adaptation to changes in the input data statistics. (Take for
50430 * example a binary file with poorly compressible code followed by
50431 * a highly compressible string table.) Smaller buffer sizes give
50432 * fast adaptation but have of course the overhead of transmitting
50433 * trees more frequently.
50434 * - I can't count above 4
50435 */
50436
50437 this.last_lit = 0; /* running index in l_buf */
50438
50439 this.d_buf = 0;
50440 /* Buffer index for distances. To simplify the code, d_buf and l_buf have
50441 * the same number of elements. To use different lengths, an extra flag
50442 * array would be necessary.
50443 */
50444
50445 this.opt_len = 0; /* bit length of current block with optimal trees */
50446 this.static_len = 0; /* bit length of current block with static trees */
50447 this.matches = 0; /* number of string matches in current block */
50448 this.insert = 0; /* bytes at end of window left to insert */
50449
50450
50451 this.bi_buf = 0;
50452 /* Output buffer. bits are inserted starting at the bottom (least
50453 * significant bits).
50454 */
50455 this.bi_valid = 0;
50456 /* Number of valid bits in bi_buf. All bits above the last valid bit
50457 * are always zero.
50458 */
50459
50460 // Used for window memory init. We safely ignore it for JS. That makes
50461 // sense only for pointers and memory check tools.
50462 //this.high_water = 0;
50463 /* High water mark offset in window for initialized bytes -- bytes above
50464 * this are set to zero in order to avoid memory check warnings when
50465 * longest match routines access bytes past the input. This is then
50466 * updated to the new high water mark.
50467 */
50468}
50469
50470
50471function deflateResetKeep(strm) {
50472 var s;
50473
50474 if (!strm || !strm.state) {
50475 return err(strm, Z_STREAM_ERROR);
50476 }
50477
50478 strm.total_in = strm.total_out = 0;
50479 strm.data_type = Z_UNKNOWN;
50480
50481 s = strm.state;
50482 s.pending = 0;
50483 s.pending_out = 0;
50484
50485 if (s.wrap < 0) {
50486 s.wrap = -s.wrap;
50487 /* was made negative by deflate(..., Z_FINISH); */
50488 }
50489 s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
50490 strm.adler = (s.wrap === 2) ?
50491 0 // crc32(0, Z_NULL, 0)
50492 :
50493 1; // adler32(0, Z_NULL, 0)
50494 s.last_flush = Z_NO_FLUSH;
50495 trees._tr_init(s);
50496 return Z_OK;
50497}
50498
50499
50500function deflateReset(strm) {
50501 var ret = deflateResetKeep(strm);
50502 if (ret === Z_OK) {
50503 lm_init(strm.state);
50504 }
50505 return ret;
50506}
50507
50508
50509function deflateSetHeader(strm, head) {
50510 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
50511 if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
50512 strm.state.gzhead = head;
50513 return Z_OK;
50514}
50515
50516
50517function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
50518 if (!strm) { // === Z_NULL
50519 return Z_STREAM_ERROR;
50520 }
50521 var wrap = 1;
50522
50523 if (level === Z_DEFAULT_COMPRESSION) {
50524 level = 6;
50525 }
50526
50527 if (windowBits < 0) { /* suppress zlib wrapper */
50528 wrap = 0;
50529 windowBits = -windowBits;
50530 }
50531
50532 else if (windowBits > 15) {
50533 wrap = 2; /* write gzip wrapper instead */
50534 windowBits -= 16;
50535 }
50536
50537
50538 if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
50539 windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
50540 strategy < 0 || strategy > Z_FIXED) {
50541 return err(strm, Z_STREAM_ERROR);
50542 }
50543
50544
50545 if (windowBits === 8) {
50546 windowBits = 9;
50547 }
50548 /* until 256-byte window bug fixed */
50549
50550 var s = new DeflateState();
50551
50552 strm.state = s;
50553 s.strm = strm;
50554
50555 s.wrap = wrap;
50556 s.gzhead = null;
50557 s.w_bits = windowBits;
50558 s.w_size = 1 << s.w_bits;
50559 s.w_mask = s.w_size - 1;
50560
50561 s.hash_bits = memLevel + 7;
50562 s.hash_size = 1 << s.hash_bits;
50563 s.hash_mask = s.hash_size - 1;
50564 s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
50565
50566 s.window = new utils.Buf8(s.w_size * 2);
50567 s.head = new utils.Buf16(s.hash_size);
50568 s.prev = new utils.Buf16(s.w_size);
50569
50570 // Don't need mem init magic for JS.
50571 //s.high_water = 0; /* nothing written to s->window yet */
50572
50573 s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
50574
50575 s.pending_buf_size = s.lit_bufsize * 4;
50576
50577 //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
50578 //s->pending_buf = (uchf *) overlay;
50579 s.pending_buf = new utils.Buf8(s.pending_buf_size);
50580
50581 // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)
50582 //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
50583 s.d_buf = 1 * s.lit_bufsize;
50584
50585 //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
50586 s.l_buf = (1 + 2) * s.lit_bufsize;
50587
50588 s.level = level;
50589 s.strategy = strategy;
50590 s.method = method;
50591
50592 return deflateReset(strm);
50593}
50594
50595function deflateInit(strm, level) {
50596 return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
50597}
50598
50599
50600function deflate(strm, flush) {
50601 var old_flush, s;
50602 var beg, val; // for gzip header write only
50603
50604 if (!strm || !strm.state ||
50605 flush > Z_BLOCK || flush < 0) {
50606 return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
50607 }
50608
50609 s = strm.state;
50610
50611 if (!strm.output ||
50612 (!strm.input && strm.avail_in !== 0) ||
50613 (s.status === FINISH_STATE && flush !== Z_FINISH)) {
50614 return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
50615 }
50616
50617 s.strm = strm; /* just in case */
50618 old_flush = s.last_flush;
50619 s.last_flush = flush;
50620
50621 /* Write the header */
50622 if (s.status === INIT_STATE) {
50623
50624 if (s.wrap === 2) { // GZIP header
50625 strm.adler = 0; //crc32(0L, Z_NULL, 0);
50626 put_byte(s, 31);
50627 put_byte(s, 139);
50628 put_byte(s, 8);
50629 if (!s.gzhead) { // s->gzhead == Z_NULL
50630 put_byte(s, 0);
50631 put_byte(s, 0);
50632 put_byte(s, 0);
50633 put_byte(s, 0);
50634 put_byte(s, 0);
50635 put_byte(s, s.level === 9 ? 2 :
50636 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
50637 4 : 0));
50638 put_byte(s, OS_CODE);
50639 s.status = BUSY_STATE;
50640 }
50641 else {
50642 put_byte(s, (s.gzhead.text ? 1 : 0) +
50643 (s.gzhead.hcrc ? 2 : 0) +
50644 (!s.gzhead.extra ? 0 : 4) +
50645 (!s.gzhead.name ? 0 : 8) +
50646 (!s.gzhead.comment ? 0 : 16)
50647 );
50648 put_byte(s, s.gzhead.time & 0xff);
50649 put_byte(s, (s.gzhead.time >> 8) & 0xff);
50650 put_byte(s, (s.gzhead.time >> 16) & 0xff);
50651 put_byte(s, (s.gzhead.time >> 24) & 0xff);
50652 put_byte(s, s.level === 9 ? 2 :
50653 (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
50654 4 : 0));
50655 put_byte(s, s.gzhead.os & 0xff);
50656 if (s.gzhead.extra && s.gzhead.extra.length) {
50657 put_byte(s, s.gzhead.extra.length & 0xff);
50658 put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
50659 }
50660 if (s.gzhead.hcrc) {
50661 strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
50662 }
50663 s.gzindex = 0;
50664 s.status = EXTRA_STATE;
50665 }
50666 }
50667 else // DEFLATE header
50668 {
50669 var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
50670 var level_flags = -1;
50671
50672 if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
50673 level_flags = 0;
50674 } else if (s.level < 6) {
50675 level_flags = 1;
50676 } else if (s.level === 6) {
50677 level_flags = 2;
50678 } else {
50679 level_flags = 3;
50680 }
50681 header |= (level_flags << 6);
50682 if (s.strstart !== 0) { header |= PRESET_DICT; }
50683 header += 31 - (header % 31);
50684
50685 s.status = BUSY_STATE;
50686 putShortMSB(s, header);
50687
50688 /* Save the adler32 of the preset dictionary: */
50689 if (s.strstart !== 0) {
50690 putShortMSB(s, strm.adler >>> 16);
50691 putShortMSB(s, strm.adler & 0xffff);
50692 }
50693 strm.adler = 1; // adler32(0L, Z_NULL, 0);
50694 }
50695 }
50696
50697//#ifdef GZIP
50698 if (s.status === EXTRA_STATE) {
50699 if (s.gzhead.extra/* != Z_NULL*/) {
50700 beg = s.pending; /* start of bytes to update crc */
50701
50702 while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
50703 if (s.pending === s.pending_buf_size) {
50704 if (s.gzhead.hcrc && s.pending > beg) {
50705 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50706 }
50707 flush_pending(strm);
50708 beg = s.pending;
50709 if (s.pending === s.pending_buf_size) {
50710 break;
50711 }
50712 }
50713 put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
50714 s.gzindex++;
50715 }
50716 if (s.gzhead.hcrc && s.pending > beg) {
50717 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50718 }
50719 if (s.gzindex === s.gzhead.extra.length) {
50720 s.gzindex = 0;
50721 s.status = NAME_STATE;
50722 }
50723 }
50724 else {
50725 s.status = NAME_STATE;
50726 }
50727 }
50728 if (s.status === NAME_STATE) {
50729 if (s.gzhead.name/* != Z_NULL*/) {
50730 beg = s.pending; /* start of bytes to update crc */
50731 //int val;
50732
50733 do {
50734 if (s.pending === s.pending_buf_size) {
50735 if (s.gzhead.hcrc && s.pending > beg) {
50736 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50737 }
50738 flush_pending(strm);
50739 beg = s.pending;
50740 if (s.pending === s.pending_buf_size) {
50741 val = 1;
50742 break;
50743 }
50744 }
50745 // JS specific: little magic to add zero terminator to end of string
50746 if (s.gzindex < s.gzhead.name.length) {
50747 val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
50748 } else {
50749 val = 0;
50750 }
50751 put_byte(s, val);
50752 } while (val !== 0);
50753
50754 if (s.gzhead.hcrc && s.pending > beg) {
50755 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50756 }
50757 if (val === 0) {
50758 s.gzindex = 0;
50759 s.status = COMMENT_STATE;
50760 }
50761 }
50762 else {
50763 s.status = COMMENT_STATE;
50764 }
50765 }
50766 if (s.status === COMMENT_STATE) {
50767 if (s.gzhead.comment/* != Z_NULL*/) {
50768 beg = s.pending; /* start of bytes to update crc */
50769 //int val;
50770
50771 do {
50772 if (s.pending === s.pending_buf_size) {
50773 if (s.gzhead.hcrc && s.pending > beg) {
50774 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50775 }
50776 flush_pending(strm);
50777 beg = s.pending;
50778 if (s.pending === s.pending_buf_size) {
50779 val = 1;
50780 break;
50781 }
50782 }
50783 // JS specific: little magic to add zero terminator to end of string
50784 if (s.gzindex < s.gzhead.comment.length) {
50785 val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
50786 } else {
50787 val = 0;
50788 }
50789 put_byte(s, val);
50790 } while (val !== 0);
50791
50792 if (s.gzhead.hcrc && s.pending > beg) {
50793 strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
50794 }
50795 if (val === 0) {
50796 s.status = HCRC_STATE;
50797 }
50798 }
50799 else {
50800 s.status = HCRC_STATE;
50801 }
50802 }
50803 if (s.status === HCRC_STATE) {
50804 if (s.gzhead.hcrc) {
50805 if (s.pending + 2 > s.pending_buf_size) {
50806 flush_pending(strm);
50807 }
50808 if (s.pending + 2 <= s.pending_buf_size) {
50809 put_byte(s, strm.adler & 0xff);
50810 put_byte(s, (strm.adler >> 8) & 0xff);
50811 strm.adler = 0; //crc32(0L, Z_NULL, 0);
50812 s.status = BUSY_STATE;
50813 }
50814 }
50815 else {
50816 s.status = BUSY_STATE;
50817 }
50818 }
50819//#endif
50820
50821 /* Flush as much pending output as possible */
50822 if (s.pending !== 0) {
50823 flush_pending(strm);
50824 if (strm.avail_out === 0) {
50825 /* Since avail_out is 0, deflate will be called again with
50826 * more output space, but possibly with both pending and
50827 * avail_in equal to zero. There won't be anything to do,
50828 * but this is not an error situation so make sure we
50829 * return OK instead of BUF_ERROR at next call of deflate:
50830 */
50831 s.last_flush = -1;
50832 return Z_OK;
50833 }
50834
50835 /* Make sure there is something to do and avoid duplicate consecutive
50836 * flushes. For repeated and useless calls with Z_FINISH, we keep
50837 * returning Z_STREAM_END instead of Z_BUF_ERROR.
50838 */
50839 } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
50840 flush !== Z_FINISH) {
50841 return err(strm, Z_BUF_ERROR);
50842 }
50843
50844 /* User must not provide more input after the first FINISH: */
50845 if (s.status === FINISH_STATE && strm.avail_in !== 0) {
50846 return err(strm, Z_BUF_ERROR);
50847 }
50848
50849 /* Start a new block or continue the current one.
50850 */
50851 if (strm.avail_in !== 0 || s.lookahead !== 0 ||
50852 (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
50853 var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
50854 (s.strategy === Z_RLE ? deflate_rle(s, flush) :
50855 configuration_table[s.level].func(s, flush));
50856
50857 if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
50858 s.status = FINISH_STATE;
50859 }
50860 if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
50861 if (strm.avail_out === 0) {
50862 s.last_flush = -1;
50863 /* avoid BUF_ERROR next call, see above */
50864 }
50865 return Z_OK;
50866 /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
50867 * of deflate should use the same flush parameter to make sure
50868 * that the flush is complete. So we don't have to output an
50869 * empty block here, this will be done at next call. This also
50870 * ensures that for a very small output buffer, we emit at most
50871 * one empty block.
50872 */
50873 }
50874 if (bstate === BS_BLOCK_DONE) {
50875 if (flush === Z_PARTIAL_FLUSH) {
50876 trees._tr_align(s);
50877 }
50878 else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
50879
50880 trees._tr_stored_block(s, 0, 0, false);
50881 /* For a full flush, this empty block will be recognized
50882 * as a special marker by inflate_sync().
50883 */
50884 if (flush === Z_FULL_FLUSH) {
50885 /*** CLEAR_HASH(s); ***/ /* forget history */
50886 zero(s.head); // Fill with NIL (= 0);
50887
50888 if (s.lookahead === 0) {
50889 s.strstart = 0;
50890 s.block_start = 0;
50891 s.insert = 0;
50892 }
50893 }
50894 }
50895 flush_pending(strm);
50896 if (strm.avail_out === 0) {
50897 s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
50898 return Z_OK;
50899 }
50900 }
50901 }
50902 //Assert(strm->avail_out > 0, "bug2");
50903 //if (strm.avail_out <= 0) { throw new Error("bug2");}
50904
50905 if (flush !== Z_FINISH) { return Z_OK; }
50906 if (s.wrap <= 0) { return Z_STREAM_END; }
50907
50908 /* Write the trailer */
50909 if (s.wrap === 2) {
50910 put_byte(s, strm.adler & 0xff);
50911 put_byte(s, (strm.adler >> 8) & 0xff);
50912 put_byte(s, (strm.adler >> 16) & 0xff);
50913 put_byte(s, (strm.adler >> 24) & 0xff);
50914 put_byte(s, strm.total_in & 0xff);
50915 put_byte(s, (strm.total_in >> 8) & 0xff);
50916 put_byte(s, (strm.total_in >> 16) & 0xff);
50917 put_byte(s, (strm.total_in >> 24) & 0xff);
50918 }
50919 else
50920 {
50921 putShortMSB(s, strm.adler >>> 16);
50922 putShortMSB(s, strm.adler & 0xffff);
50923 }
50924
50925 flush_pending(strm);
50926 /* If avail_out is zero, the application will call deflate again
50927 * to flush the rest.
50928 */
50929 if (s.wrap > 0) { s.wrap = -s.wrap; }
50930 /* write the trailer only once! */
50931 return s.pending !== 0 ? Z_OK : Z_STREAM_END;
50932}
50933
50934function deflateEnd(strm) {
50935 var status;
50936
50937 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
50938 return Z_STREAM_ERROR;
50939 }
50940
50941 status = strm.state.status;
50942 if (status !== INIT_STATE &&
50943 status !== EXTRA_STATE &&
50944 status !== NAME_STATE &&
50945 status !== COMMENT_STATE &&
50946 status !== HCRC_STATE &&
50947 status !== BUSY_STATE &&
50948 status !== FINISH_STATE
50949 ) {
50950 return err(strm, Z_STREAM_ERROR);
50951 }
50952
50953 strm.state = null;
50954
50955 return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
50956}
50957
50958
50959/* =========================================================================
50960 * Initializes the compression dictionary from the given byte
50961 * sequence without producing any compressed output.
50962 */
50963function deflateSetDictionary(strm, dictionary) {
50964 var dictLength = dictionary.length;
50965
50966 var s;
50967 var str, n;
50968 var wrap;
50969 var avail;
50970 var next;
50971 var input;
50972 var tmpDict;
50973
50974 if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
50975 return Z_STREAM_ERROR;
50976 }
50977
50978 s = strm.state;
50979 wrap = s.wrap;
50980
50981 if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {
50982 return Z_STREAM_ERROR;
50983 }
50984
50985 /* when using zlib wrappers, compute Adler-32 for provided dictionary */
50986 if (wrap === 1) {
50987 /* adler32(strm->adler, dictionary, dictLength); */
50988 strm.adler = adler32(strm.adler, dictionary, dictLength, 0);
50989 }
50990
50991 s.wrap = 0; /* avoid computing Adler-32 in read_buf */
50992
50993 /* if dictionary would fill window, just replace the history */
50994 if (dictLength >= s.w_size) {
50995 if (wrap === 0) { /* already empty otherwise */
50996 /*** CLEAR_HASH(s); ***/
50997 zero(s.head); // Fill with NIL (= 0);
50998 s.strstart = 0;
50999 s.block_start = 0;
51000 s.insert = 0;
51001 }
51002 /* use the tail */
51003 // dictionary = dictionary.slice(dictLength - s.w_size);
51004 tmpDict = new utils.Buf8(s.w_size);
51005 utils.arraySet(tmpDict, dictionary, dictLength - s.w_size, s.w_size, 0);
51006 dictionary = tmpDict;
51007 dictLength = s.w_size;
51008 }
51009 /* insert dictionary into window and hash */
51010 avail = strm.avail_in;
51011 next = strm.next_in;
51012 input = strm.input;
51013 strm.avail_in = dictLength;
51014 strm.next_in = 0;
51015 strm.input = dictionary;
51016 fill_window(s);
51017 while (s.lookahead >= MIN_MATCH) {
51018 str = s.strstart;
51019 n = s.lookahead - (MIN_MATCH - 1);
51020 do {
51021 /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
51022 s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask;
51023
51024 s.prev[str & s.w_mask] = s.head[s.ins_h];
51025
51026 s.head[s.ins_h] = str;
51027 str++;
51028 } while (--n);
51029 s.strstart = str;
51030 s.lookahead = MIN_MATCH - 1;
51031 fill_window(s);
51032 }
51033 s.strstart += s.lookahead;
51034 s.block_start = s.strstart;
51035 s.insert = s.lookahead;
51036 s.lookahead = 0;
51037 s.match_length = s.prev_length = MIN_MATCH - 1;
51038 s.match_available = 0;
51039 strm.next_in = next;
51040 strm.input = input;
51041 strm.avail_in = avail;
51042 s.wrap = wrap;
51043 return Z_OK;
51044}
51045
51046
51047exports.deflateInit = deflateInit;
51048exports.deflateInit2 = deflateInit2;
51049exports.deflateReset = deflateReset;
51050exports.deflateResetKeep = deflateResetKeep;
51051exports.deflateSetHeader = deflateSetHeader;
51052exports.deflate = deflate;
51053exports.deflateEnd = deflateEnd;
51054exports.deflateSetDictionary = deflateSetDictionary;
51055exports.deflateInfo = 'pako deflate (from Nodeca project)';
51056
51057/* Not implemented
51058exports.deflateBound = deflateBound;
51059exports.deflateCopy = deflateCopy;
51060exports.deflateParams = deflateParams;
51061exports.deflatePending = deflatePending;
51062exports.deflatePrime = deflatePrime;
51063exports.deflateTune = deflateTune;
51064*/
51065
51066},{"../utils/common":241,"./adler32":242,"./crc32":244,"./messages":249,"./trees":250}],246:[function(require,module,exports){
51067'use strict';
51068
51069// (C) 1995-2013 Jean-loup Gailly and Mark Adler
51070// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
51071//
51072// This software is provided 'as-is', without any express or implied
51073// warranty. In no event will the authors be held liable for any damages
51074// arising from the use of this software.
51075//
51076// Permission is granted to anyone to use this software for any purpose,
51077// including commercial applications, and to alter it and redistribute it
51078// freely, subject to the following restrictions:
51079//
51080// 1. The origin of this software must not be misrepresented; you must not
51081// claim that you wrote the original software. If you use this software
51082// in a product, an acknowledgment in the product documentation would be
51083// appreciated but is not required.
51084// 2. Altered source versions must be plainly marked as such, and must not be
51085// misrepresented as being the original software.
51086// 3. This notice may not be removed or altered from any source distribution.
51087
51088// See state defs from inflate.js
51089var BAD = 30; /* got a data error -- remain here until reset */
51090var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
51091
51092/*
51093 Decode literal, length, and distance codes and write out the resulting
51094 literal and match bytes until either not enough input or output is
51095 available, an end-of-block is encountered, or a data error is encountered.
51096 When large enough input and output buffers are supplied to inflate(), for
51097 example, a 16K input buffer and a 64K output buffer, more than 95% of the
51098 inflate execution time is spent in this routine.
51099
51100 Entry assumptions:
51101
51102 state.mode === LEN
51103 strm.avail_in >= 6
51104 strm.avail_out >= 258
51105 start >= strm.avail_out
51106 state.bits < 8
51107
51108 On return, state.mode is one of:
51109
51110 LEN -- ran out of enough output space or enough available input
51111 TYPE -- reached end of block code, inflate() to interpret next block
51112 BAD -- error in block data
51113
51114 Notes:
51115
51116 - The maximum input bits used by a length/distance pair is 15 bits for the
51117 length code, 5 bits for the length extra, 15 bits for the distance code,
51118 and 13 bits for the distance extra. This totals 48 bits, or six bytes.
51119 Therefore if strm.avail_in >= 6, then there is enough input to avoid
51120 checking for available input while decoding.
51121
51122 - The maximum bytes that a single length/distance pair can output is 258
51123 bytes, which is the maximum length that can be coded. inflate_fast()
51124 requires strm.avail_out >= 258 for each loop to avoid checking for
51125 output space.
51126 */
51127module.exports = function inflate_fast(strm, start) {
51128 var state;
51129 var _in; /* local strm.input */
51130 var last; /* have enough input while in < last */
51131 var _out; /* local strm.output */
51132 var beg; /* inflate()'s initial strm.output */
51133 var end; /* while out < end, enough space available */
51134//#ifdef INFLATE_STRICT
51135 var dmax; /* maximum distance from zlib header */
51136//#endif
51137 var wsize; /* window size or zero if not using window */
51138 var whave; /* valid bytes in the window */
51139 var wnext; /* window write index */
51140 // Use `s_window` instead `window`, avoid conflict with instrumentation tools
51141 var s_window; /* allocated sliding window, if wsize != 0 */
51142 var hold; /* local strm.hold */
51143 var bits; /* local strm.bits */
51144 var lcode; /* local strm.lencode */
51145 var dcode; /* local strm.distcode */
51146 var lmask; /* mask for first level of length codes */
51147 var dmask; /* mask for first level of distance codes */
51148 var here; /* retrieved table entry */
51149 var op; /* code bits, operation, extra bits, or */
51150 /* window position, window bytes to copy */
51151 var len; /* match length, unused bytes */
51152 var dist; /* match distance */
51153 var from; /* where to copy match from */
51154 var from_source;
51155
51156
51157 var input, output; // JS specific, because we have no pointers
51158
51159 /* copy state to local variables */
51160 state = strm.state;
51161 //here = state.here;
51162 _in = strm.next_in;
51163 input = strm.input;
51164 last = _in + (strm.avail_in - 5);
51165 _out = strm.next_out;
51166 output = strm.output;
51167 beg = _out - (start - strm.avail_out);
51168 end = _out + (strm.avail_out - 257);
51169//#ifdef INFLATE_STRICT
51170 dmax = state.dmax;
51171//#endif
51172 wsize = state.wsize;
51173 whave = state.whave;
51174 wnext = state.wnext;
51175 s_window = state.window;
51176 hold = state.hold;
51177 bits = state.bits;
51178 lcode = state.lencode;
51179 dcode = state.distcode;
51180 lmask = (1 << state.lenbits) - 1;
51181 dmask = (1 << state.distbits) - 1;
51182
51183
51184 /* decode literals and length/distances until end-of-block or not enough
51185 input data or output space */
51186
51187 top:
51188 do {
51189 if (bits < 15) {
51190 hold += input[_in++] << bits;
51191 bits += 8;
51192 hold += input[_in++] << bits;
51193 bits += 8;
51194 }
51195
51196 here = lcode[hold & lmask];
51197
51198 dolen:
51199 for (;;) { // Goto emulation
51200 op = here >>> 24/*here.bits*/;
51201 hold >>>= op;
51202 bits -= op;
51203 op = (here >>> 16) & 0xff/*here.op*/;
51204 if (op === 0) { /* literal */
51205 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
51206 // "inflate: literal '%c'\n" :
51207 // "inflate: literal 0x%02x\n", here.val));
51208 output[_out++] = here & 0xffff/*here.val*/;
51209 }
51210 else if (op & 16) { /* length base */
51211 len = here & 0xffff/*here.val*/;
51212 op &= 15; /* number of extra bits */
51213 if (op) {
51214 if (bits < op) {
51215 hold += input[_in++] << bits;
51216 bits += 8;
51217 }
51218 len += hold & ((1 << op) - 1);
51219 hold >>>= op;
51220 bits -= op;
51221 }
51222 //Tracevv((stderr, "inflate: length %u\n", len));
51223 if (bits < 15) {
51224 hold += input[_in++] << bits;
51225 bits += 8;
51226 hold += input[_in++] << bits;
51227 bits += 8;
51228 }
51229 here = dcode[hold & dmask];
51230
51231 dodist:
51232 for (;;) { // goto emulation
51233 op = here >>> 24/*here.bits*/;
51234 hold >>>= op;
51235 bits -= op;
51236 op = (here >>> 16) & 0xff/*here.op*/;
51237
51238 if (op & 16) { /* distance base */
51239 dist = here & 0xffff/*here.val*/;
51240 op &= 15; /* number of extra bits */
51241 if (bits < op) {
51242 hold += input[_in++] << bits;
51243 bits += 8;
51244 if (bits < op) {
51245 hold += input[_in++] << bits;
51246 bits += 8;
51247 }
51248 }
51249 dist += hold & ((1 << op) - 1);
51250//#ifdef INFLATE_STRICT
51251 if (dist > dmax) {
51252 strm.msg = 'invalid distance too far back';
51253 state.mode = BAD;
51254 break top;
51255 }
51256//#endif
51257 hold >>>= op;
51258 bits -= op;
51259 //Tracevv((stderr, "inflate: distance %u\n", dist));
51260 op = _out - beg; /* max distance in output */
51261 if (dist > op) { /* see if copy from window */
51262 op = dist - op; /* distance back in window */
51263 if (op > whave) {
51264 if (state.sane) {
51265 strm.msg = 'invalid distance too far back';
51266 state.mode = BAD;
51267 break top;
51268 }
51269
51270// (!) This block is disabled in zlib defaults,
51271// don't enable it for binary compatibility
51272//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
51273// if (len <= op - whave) {
51274// do {
51275// output[_out++] = 0;
51276// } while (--len);
51277// continue top;
51278// }
51279// len -= op - whave;
51280// do {
51281// output[_out++] = 0;
51282// } while (--op > whave);
51283// if (op === 0) {
51284// from = _out - dist;
51285// do {
51286// output[_out++] = output[from++];
51287// } while (--len);
51288// continue top;
51289// }
51290//#endif
51291 }
51292 from = 0; // window index
51293 from_source = s_window;
51294 if (wnext === 0) { /* very common case */
51295 from += wsize - op;
51296 if (op < len) { /* some from window */
51297 len -= op;
51298 do {
51299 output[_out++] = s_window[from++];
51300 } while (--op);
51301 from = _out - dist; /* rest from output */
51302 from_source = output;
51303 }
51304 }
51305 else if (wnext < op) { /* wrap around window */
51306 from += wsize + wnext - op;
51307 op -= wnext;
51308 if (op < len) { /* some from end of window */
51309 len -= op;
51310 do {
51311 output[_out++] = s_window[from++];
51312 } while (--op);
51313 from = 0;
51314 if (wnext < len) { /* some from start of window */
51315 op = wnext;
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 }
51325 else { /* contiguous in window */
51326 from += wnext - op;
51327 if (op < len) { /* some from window */
51328 len -= op;
51329 do {
51330 output[_out++] = s_window[from++];
51331 } while (--op);
51332 from = _out - dist; /* rest from output */
51333 from_source = output;
51334 }
51335 }
51336 while (len > 2) {
51337 output[_out++] = from_source[from++];
51338 output[_out++] = from_source[from++];
51339 output[_out++] = from_source[from++];
51340 len -= 3;
51341 }
51342 if (len) {
51343 output[_out++] = from_source[from++];
51344 if (len > 1) {
51345 output[_out++] = from_source[from++];
51346 }
51347 }
51348 }
51349 else {
51350 from = _out - dist; /* copy direct from output */
51351 do { /* minimum length is three */
51352 output[_out++] = output[from++];
51353 output[_out++] = output[from++];
51354 output[_out++] = output[from++];
51355 len -= 3;
51356 } while (len > 2);
51357 if (len) {
51358 output[_out++] = output[from++];
51359 if (len > 1) {
51360 output[_out++] = output[from++];
51361 }
51362 }
51363 }
51364 }
51365 else if ((op & 64) === 0) { /* 2nd level distance code */
51366 here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
51367 continue dodist;
51368 }
51369 else {
51370 strm.msg = 'invalid distance code';
51371 state.mode = BAD;
51372 break top;
51373 }
51374
51375 break; // need to emulate goto via "continue"
51376 }
51377 }
51378 else if ((op & 64) === 0) { /* 2nd level length code */
51379 here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
51380 continue dolen;
51381 }
51382 else if (op & 32) { /* end-of-block */
51383 //Tracevv((stderr, "inflate: end of block\n"));
51384 state.mode = TYPE;
51385 break top;
51386 }
51387 else {
51388 strm.msg = 'invalid literal/length code';
51389 state.mode = BAD;
51390 break top;
51391 }
51392
51393 break; // need to emulate goto via "continue"
51394 }
51395 } while (_in < last && _out < end);
51396
51397 /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
51398 len = bits >> 3;
51399 _in -= len;
51400 bits -= len << 3;
51401 hold &= (1 << bits) - 1;
51402
51403 /* update state and return */
51404 strm.next_in = _in;
51405 strm.next_out = _out;
51406 strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
51407 strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
51408 state.hold = hold;
51409 state.bits = bits;
51410 return;
51411};
51412
51413},{}],247:[function(require,module,exports){
51414'use strict';
51415
51416// (C) 1995-2013 Jean-loup Gailly and Mark Adler
51417// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
51418//
51419// This software is provided 'as-is', without any express or implied
51420// warranty. In no event will the authors be held liable for any damages
51421// arising from the use of this software.
51422//
51423// Permission is granted to anyone to use this software for any purpose,
51424// including commercial applications, and to alter it and redistribute it
51425// freely, subject to the following restrictions:
51426//
51427// 1. The origin of this software must not be misrepresented; you must not
51428// claim that you wrote the original software. If you use this software
51429// in a product, an acknowledgment in the product documentation would be
51430// appreciated but is not required.
51431// 2. Altered source versions must be plainly marked as such, and must not be
51432// misrepresented as being the original software.
51433// 3. This notice may not be removed or altered from any source distribution.
51434
51435var utils = require('../utils/common');
51436var adler32 = require('./adler32');
51437var crc32 = require('./crc32');
51438var inflate_fast = require('./inffast');
51439var inflate_table = require('./inftrees');
51440
51441var CODES = 0;
51442var LENS = 1;
51443var DISTS = 2;
51444
51445/* Public constants ==========================================================*/
51446/* ===========================================================================*/
51447
51448
51449/* Allowed flush values; see deflate() and inflate() below for details */
51450//var Z_NO_FLUSH = 0;
51451//var Z_PARTIAL_FLUSH = 1;
51452//var Z_SYNC_FLUSH = 2;
51453//var Z_FULL_FLUSH = 3;
51454var Z_FINISH = 4;
51455var Z_BLOCK = 5;
51456var Z_TREES = 6;
51457
51458
51459/* Return codes for the compression/decompression functions. Negative values
51460 * are errors, positive values are used for special but normal events.
51461 */
51462var Z_OK = 0;
51463var Z_STREAM_END = 1;
51464var Z_NEED_DICT = 2;
51465//var Z_ERRNO = -1;
51466var Z_STREAM_ERROR = -2;
51467var Z_DATA_ERROR = -3;
51468var Z_MEM_ERROR = -4;
51469var Z_BUF_ERROR = -5;
51470//var Z_VERSION_ERROR = -6;
51471
51472/* The deflate compression method */
51473var Z_DEFLATED = 8;
51474
51475
51476/* STATES ====================================================================*/
51477/* ===========================================================================*/
51478
51479
51480var HEAD = 1; /* i: waiting for magic header */
51481var FLAGS = 2; /* i: waiting for method and flags (gzip) */
51482var TIME = 3; /* i: waiting for modification time (gzip) */
51483var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
51484var EXLEN = 5; /* i: waiting for extra length (gzip) */
51485var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
51486var NAME = 7; /* i: waiting for end of file name (gzip) */
51487var COMMENT = 8; /* i: waiting for end of comment (gzip) */
51488var HCRC = 9; /* i: waiting for header crc (gzip) */
51489var DICTID = 10; /* i: waiting for dictionary check value */
51490var DICT = 11; /* waiting for inflateSetDictionary() call */
51491var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
51492var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
51493var STORED = 14; /* i: waiting for stored size (length and complement) */
51494var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
51495var COPY = 16; /* i/o: waiting for input or output to copy stored block */
51496var TABLE = 17; /* i: waiting for dynamic block table lengths */
51497var LENLENS = 18; /* i: waiting for code length code lengths */
51498var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
51499var LEN_ = 20; /* i: same as LEN below, but only first time in */
51500var LEN = 21; /* i: waiting for length/lit/eob code */
51501var LENEXT = 22; /* i: waiting for length extra bits */
51502var DIST = 23; /* i: waiting for distance code */
51503var DISTEXT = 24; /* i: waiting for distance extra bits */
51504var MATCH = 25; /* o: waiting for output space to copy string */
51505var LIT = 26; /* o: waiting for output space to write literal */
51506var CHECK = 27; /* i: waiting for 32-bit check value */
51507var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
51508var DONE = 29; /* finished check, done -- remain here until reset */
51509var BAD = 30; /* got a data error -- remain here until reset */
51510var MEM = 31; /* got an inflate() memory error -- remain here until reset */
51511var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
51512
51513/* ===========================================================================*/
51514
51515
51516
51517var ENOUGH_LENS = 852;
51518var ENOUGH_DISTS = 592;
51519//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
51520
51521var MAX_WBITS = 15;
51522/* 32K LZ77 window */
51523var DEF_WBITS = MAX_WBITS;
51524
51525
51526function zswap32(q) {
51527 return (((q >>> 24) & 0xff) +
51528 ((q >>> 8) & 0xff00) +
51529 ((q & 0xff00) << 8) +
51530 ((q & 0xff) << 24));
51531}
51532
51533
51534function InflateState() {
51535 this.mode = 0; /* current inflate mode */
51536 this.last = false; /* true if processing last block */
51537 this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
51538 this.havedict = false; /* true if dictionary provided */
51539 this.flags = 0; /* gzip header method and flags (0 if zlib) */
51540 this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
51541 this.check = 0; /* protected copy of check value */
51542 this.total = 0; /* protected copy of output count */
51543 // TODO: may be {}
51544 this.head = null; /* where to save gzip header information */
51545
51546 /* sliding window */
51547 this.wbits = 0; /* log base 2 of requested window size */
51548 this.wsize = 0; /* window size or zero if not using window */
51549 this.whave = 0; /* valid bytes in the window */
51550 this.wnext = 0; /* window write index */
51551 this.window = null; /* allocated sliding window, if needed */
51552
51553 /* bit accumulator */
51554 this.hold = 0; /* input bit accumulator */
51555 this.bits = 0; /* number of bits in "in" */
51556
51557 /* for string and stored block copying */
51558 this.length = 0; /* literal or length of data to copy */
51559 this.offset = 0; /* distance back to copy string from */
51560
51561 /* for table and code decoding */
51562 this.extra = 0; /* extra bits needed */
51563
51564 /* fixed and dynamic code tables */
51565 this.lencode = null; /* starting table for length/literal codes */
51566 this.distcode = null; /* starting table for distance codes */
51567 this.lenbits = 0; /* index bits for lencode */
51568 this.distbits = 0; /* index bits for distcode */
51569
51570 /* dynamic table building */
51571 this.ncode = 0; /* number of code length code lengths */
51572 this.nlen = 0; /* number of length code lengths */
51573 this.ndist = 0; /* number of distance code lengths */
51574 this.have = 0; /* number of code lengths in lens[] */
51575 this.next = null; /* next available space in codes[] */
51576
51577 this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
51578 this.work = new utils.Buf16(288); /* work area for code table building */
51579
51580 /*
51581 because we don't have pointers in js, we use lencode and distcode directly
51582 as buffers so we don't need codes
51583 */
51584 //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
51585 this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
51586 this.distdyn = null; /* dynamic table for distance codes (JS specific) */
51587 this.sane = 0; /* if false, allow invalid distance too far */
51588 this.back = 0; /* bits back of last unprocessed length/lit */
51589 this.was = 0; /* initial length of match */
51590}
51591
51592function inflateResetKeep(strm) {
51593 var state;
51594
51595 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
51596 state = strm.state;
51597 strm.total_in = strm.total_out = state.total = 0;
51598 strm.msg = ''; /*Z_NULL*/
51599 if (state.wrap) { /* to support ill-conceived Java test suite */
51600 strm.adler = state.wrap & 1;
51601 }
51602 state.mode = HEAD;
51603 state.last = 0;
51604 state.havedict = 0;
51605 state.dmax = 32768;
51606 state.head = null/*Z_NULL*/;
51607 state.hold = 0;
51608 state.bits = 0;
51609 //state.lencode = state.distcode = state.next = state.codes;
51610 state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
51611 state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
51612
51613 state.sane = 1;
51614 state.back = -1;
51615 //Tracev((stderr, "inflate: reset\n"));
51616 return Z_OK;
51617}
51618
51619function inflateReset(strm) {
51620 var state;
51621
51622 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
51623 state = strm.state;
51624 state.wsize = 0;
51625 state.whave = 0;
51626 state.wnext = 0;
51627 return inflateResetKeep(strm);
51628
51629}
51630
51631function inflateReset2(strm, windowBits) {
51632 var wrap;
51633 var state;
51634
51635 /* get the state */
51636 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
51637 state = strm.state;
51638
51639 /* extract wrap request from windowBits parameter */
51640 if (windowBits < 0) {
51641 wrap = 0;
51642 windowBits = -windowBits;
51643 }
51644 else {
51645 wrap = (windowBits >> 4) + 1;
51646 if (windowBits < 48) {
51647 windowBits &= 15;
51648 }
51649 }
51650
51651 /* set number of window bits, free window if different */
51652 if (windowBits && (windowBits < 8 || windowBits > 15)) {
51653 return Z_STREAM_ERROR;
51654 }
51655 if (state.window !== null && state.wbits !== windowBits) {
51656 state.window = null;
51657 }
51658
51659 /* update state and reset the rest of it */
51660 state.wrap = wrap;
51661 state.wbits = windowBits;
51662 return inflateReset(strm);
51663}
51664
51665function inflateInit2(strm, windowBits) {
51666 var ret;
51667 var state;
51668
51669 if (!strm) { return Z_STREAM_ERROR; }
51670 //strm.msg = Z_NULL; /* in case we return an error */
51671
51672 state = new InflateState();
51673
51674 //if (state === Z_NULL) return Z_MEM_ERROR;
51675 //Tracev((stderr, "inflate: allocated\n"));
51676 strm.state = state;
51677 state.window = null/*Z_NULL*/;
51678 ret = inflateReset2(strm, windowBits);
51679 if (ret !== Z_OK) {
51680 strm.state = null/*Z_NULL*/;
51681 }
51682 return ret;
51683}
51684
51685function inflateInit(strm) {
51686 return inflateInit2(strm, DEF_WBITS);
51687}
51688
51689
51690/*
51691 Return state with length and distance decoding tables and index sizes set to
51692 fixed code decoding. Normally this returns fixed tables from inffixed.h.
51693 If BUILDFIXED is defined, then instead this routine builds the tables the
51694 first time it's called, and returns those tables the first time and
51695 thereafter. This reduces the size of the code by about 2K bytes, in
51696 exchange for a little execution time. However, BUILDFIXED should not be
51697 used for threaded applications, since the rewriting of the tables and virgin
51698 may not be thread-safe.
51699 */
51700var virgin = true;
51701
51702var lenfix, distfix; // We have no pointers in JS, so keep tables separate
51703
51704function fixedtables(state) {
51705 /* build fixed huffman tables if first call (may not be thread safe) */
51706 if (virgin) {
51707 var sym;
51708
51709 lenfix = new utils.Buf32(512);
51710 distfix = new utils.Buf32(32);
51711
51712 /* literal/length table */
51713 sym = 0;
51714 while (sym < 144) { state.lens[sym++] = 8; }
51715 while (sym < 256) { state.lens[sym++] = 9; }
51716 while (sym < 280) { state.lens[sym++] = 7; }
51717 while (sym < 288) { state.lens[sym++] = 8; }
51718
51719 inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });
51720
51721 /* distance table */
51722 sym = 0;
51723 while (sym < 32) { state.lens[sym++] = 5; }
51724
51725 inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });
51726
51727 /* do this just once */
51728 virgin = false;
51729 }
51730
51731 state.lencode = lenfix;
51732 state.lenbits = 9;
51733 state.distcode = distfix;
51734 state.distbits = 5;
51735}
51736
51737
51738/*
51739 Update the window with the last wsize (normally 32K) bytes written before
51740 returning. If window does not exist yet, create it. This is only called
51741 when a window is already in use, or when output has been written during this
51742 inflate call, but the end of the deflate stream has not been reached yet.
51743 It is also called to create a window for dictionary data when a dictionary
51744 is loaded.
51745
51746 Providing output buffers larger than 32K to inflate() should provide a speed
51747 advantage, since only the last 32K of output is copied to the sliding window
51748 upon return from inflate(), and since all distances after the first 32K of
51749 output will fall in the output data, making match copies simpler and faster.
51750 The advantage may be dependent on the size of the processor's data caches.
51751 */
51752function updatewindow(strm, src, end, copy) {
51753 var dist;
51754 var state = strm.state;
51755
51756 /* if it hasn't been done already, allocate space for the window */
51757 if (state.window === null) {
51758 state.wsize = 1 << state.wbits;
51759 state.wnext = 0;
51760 state.whave = 0;
51761
51762 state.window = new utils.Buf8(state.wsize);
51763 }
51764
51765 /* copy state->wsize or less output bytes into the circular window */
51766 if (copy >= state.wsize) {
51767 utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0);
51768 state.wnext = 0;
51769 state.whave = state.wsize;
51770 }
51771 else {
51772 dist = state.wsize - state.wnext;
51773 if (dist > copy) {
51774 dist = copy;
51775 }
51776 //zmemcpy(state->window + state->wnext, end - copy, dist);
51777 utils.arraySet(state.window, src, end - copy, dist, state.wnext);
51778 copy -= dist;
51779 if (copy) {
51780 //zmemcpy(state->window, end - copy, copy);
51781 utils.arraySet(state.window, src, end - copy, copy, 0);
51782 state.wnext = copy;
51783 state.whave = state.wsize;
51784 }
51785 else {
51786 state.wnext += dist;
51787 if (state.wnext === state.wsize) { state.wnext = 0; }
51788 if (state.whave < state.wsize) { state.whave += dist; }
51789 }
51790 }
51791 return 0;
51792}
51793
51794function inflate(strm, flush) {
51795 var state;
51796 var input, output; // input/output buffers
51797 var next; /* next input INDEX */
51798 var put; /* next output INDEX */
51799 var have, left; /* available input and output */
51800 var hold; /* bit buffer */
51801 var bits; /* bits in bit buffer */
51802 var _in, _out; /* save starting available input and output */
51803 var copy; /* number of stored or match bytes to copy */
51804 var from; /* where to copy match bytes from */
51805 var from_source;
51806 var here = 0; /* current decoding table entry */
51807 var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
51808 //var last; /* parent table entry */
51809 var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
51810 var len; /* length to copy for repeats, bits to drop */
51811 var ret; /* return code */
51812 var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
51813 var opts;
51814
51815 var n; // temporary var for NEED_BITS
51816
51817 var order = /* permutation of code lengths */
51818 [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ];
51819
51820
51821 if (!strm || !strm.state || !strm.output ||
51822 (!strm.input && strm.avail_in !== 0)) {
51823 return Z_STREAM_ERROR;
51824 }
51825
51826 state = strm.state;
51827 if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
51828
51829
51830 //--- LOAD() ---
51831 put = strm.next_out;
51832 output = strm.output;
51833 left = strm.avail_out;
51834 next = strm.next_in;
51835 input = strm.input;
51836 have = strm.avail_in;
51837 hold = state.hold;
51838 bits = state.bits;
51839 //---
51840
51841 _in = have;
51842 _out = left;
51843 ret = Z_OK;
51844
51845 inf_leave: // goto emulation
51846 for (;;) {
51847 switch (state.mode) {
51848 case HEAD:
51849 if (state.wrap === 0) {
51850 state.mode = TYPEDO;
51851 break;
51852 }
51853 //=== NEEDBITS(16);
51854 while (bits < 16) {
51855 if (have === 0) { break inf_leave; }
51856 have--;
51857 hold += input[next++] << bits;
51858 bits += 8;
51859 }
51860 //===//
51861 if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
51862 state.check = 0/*crc32(0L, Z_NULL, 0)*/;
51863 //=== CRC2(state.check, hold);
51864 hbuf[0] = hold & 0xff;
51865 hbuf[1] = (hold >>> 8) & 0xff;
51866 state.check = crc32(state.check, hbuf, 2, 0);
51867 //===//
51868
51869 //=== INITBITS();
51870 hold = 0;
51871 bits = 0;
51872 //===//
51873 state.mode = FLAGS;
51874 break;
51875 }
51876 state.flags = 0; /* expect zlib header */
51877 if (state.head) {
51878 state.head.done = false;
51879 }
51880 if (!(state.wrap & 1) || /* check if zlib header allowed */
51881 (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
51882 strm.msg = 'incorrect header check';
51883 state.mode = BAD;
51884 break;
51885 }
51886 if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
51887 strm.msg = 'unknown compression method';
51888 state.mode = BAD;
51889 break;
51890 }
51891 //--- DROPBITS(4) ---//
51892 hold >>>= 4;
51893 bits -= 4;
51894 //---//
51895 len = (hold & 0x0f)/*BITS(4)*/ + 8;
51896 if (state.wbits === 0) {
51897 state.wbits = len;
51898 }
51899 else if (len > state.wbits) {
51900 strm.msg = 'invalid window size';
51901 state.mode = BAD;
51902 break;
51903 }
51904 state.dmax = 1 << len;
51905 //Tracev((stderr, "inflate: zlib header ok\n"));
51906 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
51907 state.mode = hold & 0x200 ? DICTID : TYPE;
51908 //=== INITBITS();
51909 hold = 0;
51910 bits = 0;
51911 //===//
51912 break;
51913 case FLAGS:
51914 //=== NEEDBITS(16); */
51915 while (bits < 16) {
51916 if (have === 0) { break inf_leave; }
51917 have--;
51918 hold += input[next++] << bits;
51919 bits += 8;
51920 }
51921 //===//
51922 state.flags = hold;
51923 if ((state.flags & 0xff) !== Z_DEFLATED) {
51924 strm.msg = 'unknown compression method';
51925 state.mode = BAD;
51926 break;
51927 }
51928 if (state.flags & 0xe000) {
51929 strm.msg = 'unknown header flags set';
51930 state.mode = BAD;
51931 break;
51932 }
51933 if (state.head) {
51934 state.head.text = ((hold >> 8) & 1);
51935 }
51936 if (state.flags & 0x0200) {
51937 //=== CRC2(state.check, hold);
51938 hbuf[0] = hold & 0xff;
51939 hbuf[1] = (hold >>> 8) & 0xff;
51940 state.check = crc32(state.check, hbuf, 2, 0);
51941 //===//
51942 }
51943 //=== INITBITS();
51944 hold = 0;
51945 bits = 0;
51946 //===//
51947 state.mode = TIME;
51948 /* falls through */
51949 case TIME:
51950 //=== NEEDBITS(32); */
51951 while (bits < 32) {
51952 if (have === 0) { break inf_leave; }
51953 have--;
51954 hold += input[next++] << bits;
51955 bits += 8;
51956 }
51957 //===//
51958 if (state.head) {
51959 state.head.time = hold;
51960 }
51961 if (state.flags & 0x0200) {
51962 //=== CRC4(state.check, hold)
51963 hbuf[0] = hold & 0xff;
51964 hbuf[1] = (hold >>> 8) & 0xff;
51965 hbuf[2] = (hold >>> 16) & 0xff;
51966 hbuf[3] = (hold >>> 24) & 0xff;
51967 state.check = crc32(state.check, hbuf, 4, 0);
51968 //===
51969 }
51970 //=== INITBITS();
51971 hold = 0;
51972 bits = 0;
51973 //===//
51974 state.mode = OS;
51975 /* falls through */
51976 case OS:
51977 //=== NEEDBITS(16); */
51978 while (bits < 16) {
51979 if (have === 0) { break inf_leave; }
51980 have--;
51981 hold += input[next++] << bits;
51982 bits += 8;
51983 }
51984 //===//
51985 if (state.head) {
51986 state.head.xflags = (hold & 0xff);
51987 state.head.os = (hold >> 8);
51988 }
51989 if (state.flags & 0x0200) {
51990 //=== CRC2(state.check, hold);
51991 hbuf[0] = hold & 0xff;
51992 hbuf[1] = (hold >>> 8) & 0xff;
51993 state.check = crc32(state.check, hbuf, 2, 0);
51994 //===//
51995 }
51996 //=== INITBITS();
51997 hold = 0;
51998 bits = 0;
51999 //===//
52000 state.mode = EXLEN;
52001 /* falls through */
52002 case EXLEN:
52003 if (state.flags & 0x0400) {
52004 //=== NEEDBITS(16); */
52005 while (bits < 16) {
52006 if (have === 0) { break inf_leave; }
52007 have--;
52008 hold += input[next++] << bits;
52009 bits += 8;
52010 }
52011 //===//
52012 state.length = hold;
52013 if (state.head) {
52014 state.head.extra_len = hold;
52015 }
52016 if (state.flags & 0x0200) {
52017 //=== CRC2(state.check, hold);
52018 hbuf[0] = hold & 0xff;
52019 hbuf[1] = (hold >>> 8) & 0xff;
52020 state.check = crc32(state.check, hbuf, 2, 0);
52021 //===//
52022 }
52023 //=== INITBITS();
52024 hold = 0;
52025 bits = 0;
52026 //===//
52027 }
52028 else if (state.head) {
52029 state.head.extra = null/*Z_NULL*/;
52030 }
52031 state.mode = EXTRA;
52032 /* falls through */
52033 case EXTRA:
52034 if (state.flags & 0x0400) {
52035 copy = state.length;
52036 if (copy > have) { copy = have; }
52037 if (copy) {
52038 if (state.head) {
52039 len = state.head.extra_len - state.length;
52040 if (!state.head.extra) {
52041 // Use untyped array for more convenient processing later
52042 state.head.extra = new Array(state.head.extra_len);
52043 }
52044 utils.arraySet(
52045 state.head.extra,
52046 input,
52047 next,
52048 // extra field is limited to 65536 bytes
52049 // - no need for additional size check
52050 copy,
52051 /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
52052 len
52053 );
52054 //zmemcpy(state.head.extra + len, next,
52055 // len + copy > state.head.extra_max ?
52056 // state.head.extra_max - len : copy);
52057 }
52058 if (state.flags & 0x0200) {
52059 state.check = crc32(state.check, input, copy, next);
52060 }
52061 have -= copy;
52062 next += copy;
52063 state.length -= copy;
52064 }
52065 if (state.length) { break inf_leave; }
52066 }
52067 state.length = 0;
52068 state.mode = NAME;
52069 /* falls through */
52070 case NAME:
52071 if (state.flags & 0x0800) {
52072 if (have === 0) { break inf_leave; }
52073 copy = 0;
52074 do {
52075 // TODO: 2 or 1 bytes?
52076 len = input[next + copy++];
52077 /* use constant limit because in js we should not preallocate memory */
52078 if (state.head && len &&
52079 (state.length < 65536 /*state.head.name_max*/)) {
52080 state.head.name += String.fromCharCode(len);
52081 }
52082 } while (len && copy < have);
52083
52084 if (state.flags & 0x0200) {
52085 state.check = crc32(state.check, input, copy, next);
52086 }
52087 have -= copy;
52088 next += copy;
52089 if (len) { break inf_leave; }
52090 }
52091 else if (state.head) {
52092 state.head.name = null;
52093 }
52094 state.length = 0;
52095 state.mode = COMMENT;
52096 /* falls through */
52097 case COMMENT:
52098 if (state.flags & 0x1000) {
52099 if (have === 0) { break inf_leave; }
52100 copy = 0;
52101 do {
52102 len = input[next + copy++];
52103 /* use constant limit because in js we should not preallocate memory */
52104 if (state.head && len &&
52105 (state.length < 65536 /*state.head.comm_max*/)) {
52106 state.head.comment += String.fromCharCode(len);
52107 }
52108 } while (len && copy < have);
52109 if (state.flags & 0x0200) {
52110 state.check = crc32(state.check, input, copy, next);
52111 }
52112 have -= copy;
52113 next += copy;
52114 if (len) { break inf_leave; }
52115 }
52116 else if (state.head) {
52117 state.head.comment = null;
52118 }
52119 state.mode = HCRC;
52120 /* falls through */
52121 case HCRC:
52122 if (state.flags & 0x0200) {
52123 //=== NEEDBITS(16); */
52124 while (bits < 16) {
52125 if (have === 0) { break inf_leave; }
52126 have--;
52127 hold += input[next++] << bits;
52128 bits += 8;
52129 }
52130 //===//
52131 if (hold !== (state.check & 0xffff)) {
52132 strm.msg = 'header crc mismatch';
52133 state.mode = BAD;
52134 break;
52135 }
52136 //=== INITBITS();
52137 hold = 0;
52138 bits = 0;
52139 //===//
52140 }
52141 if (state.head) {
52142 state.head.hcrc = ((state.flags >> 9) & 1);
52143 state.head.done = true;
52144 }
52145 strm.adler = state.check = 0;
52146 state.mode = TYPE;
52147 break;
52148 case DICTID:
52149 //=== NEEDBITS(32); */
52150 while (bits < 32) {
52151 if (have === 0) { break inf_leave; }
52152 have--;
52153 hold += input[next++] << bits;
52154 bits += 8;
52155 }
52156 //===//
52157 strm.adler = state.check = zswap32(hold);
52158 //=== INITBITS();
52159 hold = 0;
52160 bits = 0;
52161 //===//
52162 state.mode = DICT;
52163 /* falls through */
52164 case DICT:
52165 if (state.havedict === 0) {
52166 //--- RESTORE() ---
52167 strm.next_out = put;
52168 strm.avail_out = left;
52169 strm.next_in = next;
52170 strm.avail_in = have;
52171 state.hold = hold;
52172 state.bits = bits;
52173 //---
52174 return Z_NEED_DICT;
52175 }
52176 strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
52177 state.mode = TYPE;
52178 /* falls through */
52179 case TYPE:
52180 if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
52181 /* falls through */
52182 case TYPEDO:
52183 if (state.last) {
52184 //--- BYTEBITS() ---//
52185 hold >>>= bits & 7;
52186 bits -= bits & 7;
52187 //---//
52188 state.mode = CHECK;
52189 break;
52190 }
52191 //=== NEEDBITS(3); */
52192 while (bits < 3) {
52193 if (have === 0) { break inf_leave; }
52194 have--;
52195 hold += input[next++] << bits;
52196 bits += 8;
52197 }
52198 //===//
52199 state.last = (hold & 0x01)/*BITS(1)*/;
52200 //--- DROPBITS(1) ---//
52201 hold >>>= 1;
52202 bits -= 1;
52203 //---//
52204
52205 switch ((hold & 0x03)/*BITS(2)*/) {
52206 case 0: /* stored block */
52207 //Tracev((stderr, "inflate: stored block%s\n",
52208 // state.last ? " (last)" : ""));
52209 state.mode = STORED;
52210 break;
52211 case 1: /* fixed block */
52212 fixedtables(state);
52213 //Tracev((stderr, "inflate: fixed codes block%s\n",
52214 // state.last ? " (last)" : ""));
52215 state.mode = LEN_; /* decode codes */
52216 if (flush === Z_TREES) {
52217 //--- DROPBITS(2) ---//
52218 hold >>>= 2;
52219 bits -= 2;
52220 //---//
52221 break inf_leave;
52222 }
52223 break;
52224 case 2: /* dynamic block */
52225 //Tracev((stderr, "inflate: dynamic codes block%s\n",
52226 // state.last ? " (last)" : ""));
52227 state.mode = TABLE;
52228 break;
52229 case 3:
52230 strm.msg = 'invalid block type';
52231 state.mode = BAD;
52232 }
52233 //--- DROPBITS(2) ---//
52234 hold >>>= 2;
52235 bits -= 2;
52236 //---//
52237 break;
52238 case STORED:
52239 //--- BYTEBITS() ---// /* go to byte boundary */
52240 hold >>>= bits & 7;
52241 bits -= bits & 7;
52242 //---//
52243 //=== NEEDBITS(32); */
52244 while (bits < 32) {
52245 if (have === 0) { break inf_leave; }
52246 have--;
52247 hold += input[next++] << bits;
52248 bits += 8;
52249 }
52250 //===//
52251 if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
52252 strm.msg = 'invalid stored block lengths';
52253 state.mode = BAD;
52254 break;
52255 }
52256 state.length = hold & 0xffff;
52257 //Tracev((stderr, "inflate: stored length %u\n",
52258 // state.length));
52259 //=== INITBITS();
52260 hold = 0;
52261 bits = 0;
52262 //===//
52263 state.mode = COPY_;
52264 if (flush === Z_TREES) { break inf_leave; }
52265 /* falls through */
52266 case COPY_:
52267 state.mode = COPY;
52268 /* falls through */
52269 case COPY:
52270 copy = state.length;
52271 if (copy) {
52272 if (copy > have) { copy = have; }
52273 if (copy > left) { copy = left; }
52274 if (copy === 0) { break inf_leave; }
52275 //--- zmemcpy(put, next, copy); ---
52276 utils.arraySet(output, input, next, copy, put);
52277 //---//
52278 have -= copy;
52279 next += copy;
52280 left -= copy;
52281 put += copy;
52282 state.length -= copy;
52283 break;
52284 }
52285 //Tracev((stderr, "inflate: stored end\n"));
52286 state.mode = TYPE;
52287 break;
52288 case TABLE:
52289 //=== NEEDBITS(14); */
52290 while (bits < 14) {
52291 if (have === 0) { break inf_leave; }
52292 have--;
52293 hold += input[next++] << bits;
52294 bits += 8;
52295 }
52296 //===//
52297 state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
52298 //--- DROPBITS(5) ---//
52299 hold >>>= 5;
52300 bits -= 5;
52301 //---//
52302 state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
52303 //--- DROPBITS(5) ---//
52304 hold >>>= 5;
52305 bits -= 5;
52306 //---//
52307 state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
52308 //--- DROPBITS(4) ---//
52309 hold >>>= 4;
52310 bits -= 4;
52311 //---//
52312//#ifndef PKZIP_BUG_WORKAROUND
52313 if (state.nlen > 286 || state.ndist > 30) {
52314 strm.msg = 'too many length or distance symbols';
52315 state.mode = BAD;
52316 break;
52317 }
52318//#endif
52319 //Tracev((stderr, "inflate: table sizes ok\n"));
52320 state.have = 0;
52321 state.mode = LENLENS;
52322 /* falls through */
52323 case LENLENS:
52324 while (state.have < state.ncode) {
52325 //=== NEEDBITS(3);
52326 while (bits < 3) {
52327 if (have === 0) { break inf_leave; }
52328 have--;
52329 hold += input[next++] << bits;
52330 bits += 8;
52331 }
52332 //===//
52333 state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
52334 //--- DROPBITS(3) ---//
52335 hold >>>= 3;
52336 bits -= 3;
52337 //---//
52338 }
52339 while (state.have < 19) {
52340 state.lens[order[state.have++]] = 0;
52341 }
52342 // We have separate tables & no pointers. 2 commented lines below not needed.
52343 //state.next = state.codes;
52344 //state.lencode = state.next;
52345 // Switch to use dynamic table
52346 state.lencode = state.lendyn;
52347 state.lenbits = 7;
52348
52349 opts = { bits: state.lenbits };
52350 ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
52351 state.lenbits = opts.bits;
52352
52353 if (ret) {
52354 strm.msg = 'invalid code lengths set';
52355 state.mode = BAD;
52356 break;
52357 }
52358 //Tracev((stderr, "inflate: code lengths ok\n"));
52359 state.have = 0;
52360 state.mode = CODELENS;
52361 /* falls through */
52362 case CODELENS:
52363 while (state.have < state.nlen + state.ndist) {
52364 for (;;) {
52365 here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
52366 here_bits = here >>> 24;
52367 here_op = (here >>> 16) & 0xff;
52368 here_val = here & 0xffff;
52369
52370 if ((here_bits) <= bits) { break; }
52371 //--- PULLBYTE() ---//
52372 if (have === 0) { break inf_leave; }
52373 have--;
52374 hold += input[next++] << bits;
52375 bits += 8;
52376 //---//
52377 }
52378 if (here_val < 16) {
52379 //--- DROPBITS(here.bits) ---//
52380 hold >>>= here_bits;
52381 bits -= here_bits;
52382 //---//
52383 state.lens[state.have++] = here_val;
52384 }
52385 else {
52386 if (here_val === 16) {
52387 //=== NEEDBITS(here.bits + 2);
52388 n = here_bits + 2;
52389 while (bits < n) {
52390 if (have === 0) { break inf_leave; }
52391 have--;
52392 hold += input[next++] << bits;
52393 bits += 8;
52394 }
52395 //===//
52396 //--- DROPBITS(here.bits) ---//
52397 hold >>>= here_bits;
52398 bits -= here_bits;
52399 //---//
52400 if (state.have === 0) {
52401 strm.msg = 'invalid bit length repeat';
52402 state.mode = BAD;
52403 break;
52404 }
52405 len = state.lens[state.have - 1];
52406 copy = 3 + (hold & 0x03);//BITS(2);
52407 //--- DROPBITS(2) ---//
52408 hold >>>= 2;
52409 bits -= 2;
52410 //---//
52411 }
52412 else if (here_val === 17) {
52413 //=== NEEDBITS(here.bits + 3);
52414 n = here_bits + 3;
52415 while (bits < n) {
52416 if (have === 0) { break inf_leave; }
52417 have--;
52418 hold += input[next++] << bits;
52419 bits += 8;
52420 }
52421 //===//
52422 //--- DROPBITS(here.bits) ---//
52423 hold >>>= here_bits;
52424 bits -= here_bits;
52425 //---//
52426 len = 0;
52427 copy = 3 + (hold & 0x07);//BITS(3);
52428 //--- DROPBITS(3) ---//
52429 hold >>>= 3;
52430 bits -= 3;
52431 //---//
52432 }
52433 else {
52434 //=== NEEDBITS(here.bits + 7);
52435 n = here_bits + 7;
52436 while (bits < n) {
52437 if (have === 0) { break inf_leave; }
52438 have--;
52439 hold += input[next++] << bits;
52440 bits += 8;
52441 }
52442 //===//
52443 //--- DROPBITS(here.bits) ---//
52444 hold >>>= here_bits;
52445 bits -= here_bits;
52446 //---//
52447 len = 0;
52448 copy = 11 + (hold & 0x7f);//BITS(7);
52449 //--- DROPBITS(7) ---//
52450 hold >>>= 7;
52451 bits -= 7;
52452 //---//
52453 }
52454 if (state.have + copy > state.nlen + state.ndist) {
52455 strm.msg = 'invalid bit length repeat';
52456 state.mode = BAD;
52457 break;
52458 }
52459 while (copy--) {
52460 state.lens[state.have++] = len;
52461 }
52462 }
52463 }
52464
52465 /* handle error breaks in while */
52466 if (state.mode === BAD) { break; }
52467
52468 /* check for end-of-block code (better have one) */
52469 if (state.lens[256] === 0) {
52470 strm.msg = 'invalid code -- missing end-of-block';
52471 state.mode = BAD;
52472 break;
52473 }
52474
52475 /* build code tables -- note: do not change the lenbits or distbits
52476 values here (9 and 6) without reading the comments in inftrees.h
52477 concerning the ENOUGH constants, which depend on those values */
52478 state.lenbits = 9;
52479
52480 opts = { bits: state.lenbits };
52481 ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
52482 // We have separate tables & no pointers. 2 commented lines below not needed.
52483 // state.next_index = opts.table_index;
52484 state.lenbits = opts.bits;
52485 // state.lencode = state.next;
52486
52487 if (ret) {
52488 strm.msg = 'invalid literal/lengths set';
52489 state.mode = BAD;
52490 break;
52491 }
52492
52493 state.distbits = 6;
52494 //state.distcode.copy(state.codes);
52495 // Switch to use dynamic table
52496 state.distcode = state.distdyn;
52497 opts = { bits: state.distbits };
52498 ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
52499 // We have separate tables & no pointers. 2 commented lines below not needed.
52500 // state.next_index = opts.table_index;
52501 state.distbits = opts.bits;
52502 // state.distcode = state.next;
52503
52504 if (ret) {
52505 strm.msg = 'invalid distances set';
52506 state.mode = BAD;
52507 break;
52508 }
52509 //Tracev((stderr, 'inflate: codes ok\n'));
52510 state.mode = LEN_;
52511 if (flush === Z_TREES) { break inf_leave; }
52512 /* falls through */
52513 case LEN_:
52514 state.mode = LEN;
52515 /* falls through */
52516 case LEN:
52517 if (have >= 6 && left >= 258) {
52518 //--- RESTORE() ---
52519 strm.next_out = put;
52520 strm.avail_out = left;
52521 strm.next_in = next;
52522 strm.avail_in = have;
52523 state.hold = hold;
52524 state.bits = bits;
52525 //---
52526 inflate_fast(strm, _out);
52527 //--- LOAD() ---
52528 put = strm.next_out;
52529 output = strm.output;
52530 left = strm.avail_out;
52531 next = strm.next_in;
52532 input = strm.input;
52533 have = strm.avail_in;
52534 hold = state.hold;
52535 bits = state.bits;
52536 //---
52537
52538 if (state.mode === TYPE) {
52539 state.back = -1;
52540 }
52541 break;
52542 }
52543 state.back = 0;
52544 for (;;) {
52545 here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/
52546 here_bits = here >>> 24;
52547 here_op = (here >>> 16) & 0xff;
52548 here_val = here & 0xffff;
52549
52550 if (here_bits <= bits) { break; }
52551 //--- PULLBYTE() ---//
52552 if (have === 0) { break inf_leave; }
52553 have--;
52554 hold += input[next++] << bits;
52555 bits += 8;
52556 //---//
52557 }
52558 if (here_op && (here_op & 0xf0) === 0) {
52559 last_bits = here_bits;
52560 last_op = here_op;
52561 last_val = here_val;
52562 for (;;) {
52563 here = state.lencode[last_val +
52564 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
52565 here_bits = here >>> 24;
52566 here_op = (here >>> 16) & 0xff;
52567 here_val = here & 0xffff;
52568
52569 if ((last_bits + here_bits) <= bits) { break; }
52570 //--- PULLBYTE() ---//
52571 if (have === 0) { break inf_leave; }
52572 have--;
52573 hold += input[next++] << bits;
52574 bits += 8;
52575 //---//
52576 }
52577 //--- DROPBITS(last.bits) ---//
52578 hold >>>= last_bits;
52579 bits -= last_bits;
52580 //---//
52581 state.back += last_bits;
52582 }
52583 //--- DROPBITS(here.bits) ---//
52584 hold >>>= here_bits;
52585 bits -= here_bits;
52586 //---//
52587 state.back += here_bits;
52588 state.length = here_val;
52589 if (here_op === 0) {
52590 //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
52591 // "inflate: literal '%c'\n" :
52592 // "inflate: literal 0x%02x\n", here.val));
52593 state.mode = LIT;
52594 break;
52595 }
52596 if (here_op & 32) {
52597 //Tracevv((stderr, "inflate: end of block\n"));
52598 state.back = -1;
52599 state.mode = TYPE;
52600 break;
52601 }
52602 if (here_op & 64) {
52603 strm.msg = 'invalid literal/length code';
52604 state.mode = BAD;
52605 break;
52606 }
52607 state.extra = here_op & 15;
52608 state.mode = LENEXT;
52609 /* falls through */
52610 case LENEXT:
52611 if (state.extra) {
52612 //=== NEEDBITS(state.extra);
52613 n = state.extra;
52614 while (bits < n) {
52615 if (have === 0) { break inf_leave; }
52616 have--;
52617 hold += input[next++] << bits;
52618 bits += 8;
52619 }
52620 //===//
52621 state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
52622 //--- DROPBITS(state.extra) ---//
52623 hold >>>= state.extra;
52624 bits -= state.extra;
52625 //---//
52626 state.back += state.extra;
52627 }
52628 //Tracevv((stderr, "inflate: length %u\n", state.length));
52629 state.was = state.length;
52630 state.mode = DIST;
52631 /* falls through */
52632 case DIST:
52633 for (;;) {
52634 here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/
52635 here_bits = here >>> 24;
52636 here_op = (here >>> 16) & 0xff;
52637 here_val = here & 0xffff;
52638
52639 if ((here_bits) <= bits) { break; }
52640 //--- PULLBYTE() ---//
52641 if (have === 0) { break inf_leave; }
52642 have--;
52643 hold += input[next++] << bits;
52644 bits += 8;
52645 //---//
52646 }
52647 if ((here_op & 0xf0) === 0) {
52648 last_bits = here_bits;
52649 last_op = here_op;
52650 last_val = here_val;
52651 for (;;) {
52652 here = state.distcode[last_val +
52653 ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];
52654 here_bits = here >>> 24;
52655 here_op = (here >>> 16) & 0xff;
52656 here_val = here & 0xffff;
52657
52658 if ((last_bits + here_bits) <= bits) { break; }
52659 //--- PULLBYTE() ---//
52660 if (have === 0) { break inf_leave; }
52661 have--;
52662 hold += input[next++] << bits;
52663 bits += 8;
52664 //---//
52665 }
52666 //--- DROPBITS(last.bits) ---//
52667 hold >>>= last_bits;
52668 bits -= last_bits;
52669 //---//
52670 state.back += last_bits;
52671 }
52672 //--- DROPBITS(here.bits) ---//
52673 hold >>>= here_bits;
52674 bits -= here_bits;
52675 //---//
52676 state.back += here_bits;
52677 if (here_op & 64) {
52678 strm.msg = 'invalid distance code';
52679 state.mode = BAD;
52680 break;
52681 }
52682 state.offset = here_val;
52683 state.extra = (here_op) & 15;
52684 state.mode = DISTEXT;
52685 /* falls through */
52686 case DISTEXT:
52687 if (state.extra) {
52688 //=== NEEDBITS(state.extra);
52689 n = state.extra;
52690 while (bits < n) {
52691 if (have === 0) { break inf_leave; }
52692 have--;
52693 hold += input[next++] << bits;
52694 bits += 8;
52695 }
52696 //===//
52697 state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;
52698 //--- DROPBITS(state.extra) ---//
52699 hold >>>= state.extra;
52700 bits -= state.extra;
52701 //---//
52702 state.back += state.extra;
52703 }
52704//#ifdef INFLATE_STRICT
52705 if (state.offset > state.dmax) {
52706 strm.msg = 'invalid distance too far back';
52707 state.mode = BAD;
52708 break;
52709 }
52710//#endif
52711 //Tracevv((stderr, "inflate: distance %u\n", state.offset));
52712 state.mode = MATCH;
52713 /* falls through */
52714 case MATCH:
52715 if (left === 0) { break inf_leave; }
52716 copy = _out - left;
52717 if (state.offset > copy) { /* copy from window */
52718 copy = state.offset - copy;
52719 if (copy > state.whave) {
52720 if (state.sane) {
52721 strm.msg = 'invalid distance too far back';
52722 state.mode = BAD;
52723 break;
52724 }
52725// (!) This block is disabled in zlib defaults,
52726// don't enable it for binary compatibility
52727//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
52728// Trace((stderr, "inflate.c too far\n"));
52729// copy -= state.whave;
52730// if (copy > state.length) { copy = state.length; }
52731// if (copy > left) { copy = left; }
52732// left -= copy;
52733// state.length -= copy;
52734// do {
52735// output[put++] = 0;
52736// } while (--copy);
52737// if (state.length === 0) { state.mode = LEN; }
52738// break;
52739//#endif
52740 }
52741 if (copy > state.wnext) {
52742 copy -= state.wnext;
52743 from = state.wsize - copy;
52744 }
52745 else {
52746 from = state.wnext - copy;
52747 }
52748 if (copy > state.length) { copy = state.length; }
52749 from_source = state.window;
52750 }
52751 else { /* copy from output */
52752 from_source = output;
52753 from = put - state.offset;
52754 copy = state.length;
52755 }
52756 if (copy > left) { copy = left; }
52757 left -= copy;
52758 state.length -= copy;
52759 do {
52760 output[put++] = from_source[from++];
52761 } while (--copy);
52762 if (state.length === 0) { state.mode = LEN; }
52763 break;
52764 case LIT:
52765 if (left === 0) { break inf_leave; }
52766 output[put++] = state.length;
52767 left--;
52768 state.mode = LEN;
52769 break;
52770 case CHECK:
52771 if (state.wrap) {
52772 //=== NEEDBITS(32);
52773 while (bits < 32) {
52774 if (have === 0) { break inf_leave; }
52775 have--;
52776 // Use '|' instead of '+' to make sure that result is signed
52777 hold |= input[next++] << bits;
52778 bits += 8;
52779 }
52780 //===//
52781 _out -= left;
52782 strm.total_out += _out;
52783 state.total += _out;
52784 if (_out) {
52785 strm.adler = state.check =
52786 /*UPDATE(state.check, put - _out, _out);*/
52787 (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
52788
52789 }
52790 _out = left;
52791 // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too
52792 if ((state.flags ? hold : zswap32(hold)) !== state.check) {
52793 strm.msg = 'incorrect data check';
52794 state.mode = BAD;
52795 break;
52796 }
52797 //=== INITBITS();
52798 hold = 0;
52799 bits = 0;
52800 //===//
52801 //Tracev((stderr, "inflate: check matches trailer\n"));
52802 }
52803 state.mode = LENGTH;
52804 /* falls through */
52805 case LENGTH:
52806 if (state.wrap && state.flags) {
52807 //=== NEEDBITS(32);
52808 while (bits < 32) {
52809 if (have === 0) { break inf_leave; }
52810 have--;
52811 hold += input[next++] << bits;
52812 bits += 8;
52813 }
52814 //===//
52815 if (hold !== (state.total & 0xffffffff)) {
52816 strm.msg = 'incorrect length check';
52817 state.mode = BAD;
52818 break;
52819 }
52820 //=== INITBITS();
52821 hold = 0;
52822 bits = 0;
52823 //===//
52824 //Tracev((stderr, "inflate: length matches trailer\n"));
52825 }
52826 state.mode = DONE;
52827 /* falls through */
52828 case DONE:
52829 ret = Z_STREAM_END;
52830 break inf_leave;
52831 case BAD:
52832 ret = Z_DATA_ERROR;
52833 break inf_leave;
52834 case MEM:
52835 return Z_MEM_ERROR;
52836 case SYNC:
52837 /* falls through */
52838 default:
52839 return Z_STREAM_ERROR;
52840 }
52841 }
52842
52843 // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
52844
52845 /*
52846 Return from inflate(), updating the total counts and the check value.
52847 If there was no progress during the inflate() call, return a buffer
52848 error. Call updatewindow() to create and/or update the window state.
52849 Note: a memory error from inflate() is non-recoverable.
52850 */
52851
52852 //--- RESTORE() ---
52853 strm.next_out = put;
52854 strm.avail_out = left;
52855 strm.next_in = next;
52856 strm.avail_in = have;
52857 state.hold = hold;
52858 state.bits = bits;
52859 //---
52860
52861 if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
52862 (state.mode < CHECK || flush !== Z_FINISH))) {
52863 if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
52864 state.mode = MEM;
52865 return Z_MEM_ERROR;
52866 }
52867 }
52868 _in -= strm.avail_in;
52869 _out -= strm.avail_out;
52870 strm.total_in += _in;
52871 strm.total_out += _out;
52872 state.total += _out;
52873 if (state.wrap && _out) {
52874 strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
52875 (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
52876 }
52877 strm.data_type = state.bits + (state.last ? 64 : 0) +
52878 (state.mode === TYPE ? 128 : 0) +
52879 (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
52880 if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
52881 ret = Z_BUF_ERROR;
52882 }
52883 return ret;
52884}
52885
52886function inflateEnd(strm) {
52887
52888 if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
52889 return Z_STREAM_ERROR;
52890 }
52891
52892 var state = strm.state;
52893 if (state.window) {
52894 state.window = null;
52895 }
52896 strm.state = null;
52897 return Z_OK;
52898}
52899
52900function inflateGetHeader(strm, head) {
52901 var state;
52902
52903 /* check state */
52904 if (!strm || !strm.state) { return Z_STREAM_ERROR; }
52905 state = strm.state;
52906 if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
52907
52908 /* save header structure */
52909 state.head = head;
52910 head.done = false;
52911 return Z_OK;
52912}
52913
52914function inflateSetDictionary(strm, dictionary) {
52915 var dictLength = dictionary.length;
52916
52917 var state;
52918 var dictid;
52919 var ret;
52920
52921 /* check state */
52922 if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR; }
52923 state = strm.state;
52924
52925 if (state.wrap !== 0 && state.mode !== DICT) {
52926 return Z_STREAM_ERROR;
52927 }
52928
52929 /* check for correct dictionary identifier */
52930 if (state.mode === DICT) {
52931 dictid = 1; /* adler32(0, null, 0)*/
52932 /* dictid = adler32(dictid, dictionary, dictLength); */
52933 dictid = adler32(dictid, dictionary, dictLength, 0);
52934 if (dictid !== state.check) {
52935 return Z_DATA_ERROR;
52936 }
52937 }
52938 /* copy dictionary to window using updatewindow(), which will amend the
52939 existing dictionary if appropriate */
52940 ret = updatewindow(strm, dictionary, dictLength, dictLength);
52941 if (ret) {
52942 state.mode = MEM;
52943 return Z_MEM_ERROR;
52944 }
52945 state.havedict = 1;
52946 // Tracev((stderr, "inflate: dictionary set\n"));
52947 return Z_OK;
52948}
52949
52950exports.inflateReset = inflateReset;
52951exports.inflateReset2 = inflateReset2;
52952exports.inflateResetKeep = inflateResetKeep;
52953exports.inflateInit = inflateInit;
52954exports.inflateInit2 = inflateInit2;
52955exports.inflate = inflate;
52956exports.inflateEnd = inflateEnd;
52957exports.inflateGetHeader = inflateGetHeader;
52958exports.inflateSetDictionary = inflateSetDictionary;
52959exports.inflateInfo = 'pako inflate (from Nodeca project)';
52960
52961/* Not implemented
52962exports.inflateCopy = inflateCopy;
52963exports.inflateGetDictionary = inflateGetDictionary;
52964exports.inflateMark = inflateMark;
52965exports.inflatePrime = inflatePrime;
52966exports.inflateSync = inflateSync;
52967exports.inflateSyncPoint = inflateSyncPoint;
52968exports.inflateUndermine = inflateUndermine;
52969*/
52970
52971},{"../utils/common":241,"./adler32":242,"./crc32":244,"./inffast":246,"./inftrees":248}],248:[function(require,module,exports){
52972'use strict';
52973
52974// (C) 1995-2013 Jean-loup Gailly and Mark Adler
52975// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
52976//
52977// This software is provided 'as-is', without any express or implied
52978// warranty. In no event will the authors be held liable for any damages
52979// arising from the use of this software.
52980//
52981// Permission is granted to anyone to use this software for any purpose,
52982// including commercial applications, and to alter it and redistribute it
52983// freely, subject to the following restrictions:
52984//
52985// 1. The origin of this software must not be misrepresented; you must not
52986// claim that you wrote the original software. If you use this software
52987// in a product, an acknowledgment in the product documentation would be
52988// appreciated but is not required.
52989// 2. Altered source versions must be plainly marked as such, and must not be
52990// misrepresented as being the original software.
52991// 3. This notice may not be removed or altered from any source distribution.
52992
52993var utils = require('../utils/common');
52994
52995var MAXBITS = 15;
52996var ENOUGH_LENS = 852;
52997var ENOUGH_DISTS = 592;
52998//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
52999
53000var CODES = 0;
53001var LENS = 1;
53002var DISTS = 2;
53003
53004var lbase = [ /* Length codes 257..285 base */
53005 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
53006 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
53007];
53008
53009var lext = [ /* Length codes 257..285 extra */
53010 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
53011 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
53012];
53013
53014var dbase = [ /* Distance codes 0..29 base */
53015 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
53016 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
53017 8193, 12289, 16385, 24577, 0, 0
53018];
53019
53020var dext = [ /* Distance codes 0..29 extra */
53021 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
53022 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
53023 28, 28, 29, 29, 64, 64
53024];
53025
53026module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
53027{
53028 var bits = opts.bits;
53029 //here = opts.here; /* table entry for duplication */
53030
53031 var len = 0; /* a code's length in bits */
53032 var sym = 0; /* index of code symbols */
53033 var min = 0, max = 0; /* minimum and maximum code lengths */
53034 var root = 0; /* number of index bits for root table */
53035 var curr = 0; /* number of index bits for current table */
53036 var drop = 0; /* code bits to drop for sub-table */
53037 var left = 0; /* number of prefix codes available */
53038 var used = 0; /* code entries in table used */
53039 var huff = 0; /* Huffman code */
53040 var incr; /* for incrementing code, index */
53041 var fill; /* index for replicating entries */
53042 var low; /* low bits for current root entry */
53043 var mask; /* mask for low root bits */
53044 var next; /* next available space in table */
53045 var base = null; /* base value table to use */
53046 var base_index = 0;
53047// var shoextra; /* extra bits table to use */
53048 var end; /* use base and extra for symbol > end */
53049 var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */
53050 var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */
53051 var extra = null;
53052 var extra_index = 0;
53053
53054 var here_bits, here_op, here_val;
53055
53056 /*
53057 Process a set of code lengths to create a canonical Huffman code. The
53058 code lengths are lens[0..codes-1]. Each length corresponds to the
53059 symbols 0..codes-1. The Huffman code is generated by first sorting the
53060 symbols by length from short to long, and retaining the symbol order
53061 for codes with equal lengths. Then the code starts with all zero bits
53062 for the first code of the shortest length, and the codes are integer
53063 increments for the same length, and zeros are appended as the length
53064 increases. For the deflate format, these bits are stored backwards
53065 from their more natural integer increment ordering, and so when the
53066 decoding tables are built in the large loop below, the integer codes
53067 are incremented backwards.
53068
53069 This routine assumes, but does not check, that all of the entries in
53070 lens[] are in the range 0..MAXBITS. The caller must assure this.
53071 1..MAXBITS is interpreted as that code length. zero means that that
53072 symbol does not occur in this code.
53073
53074 The codes are sorted by computing a count of codes for each length,
53075 creating from that a table of starting indices for each length in the
53076 sorted table, and then entering the symbols in order in the sorted
53077 table. The sorted table is work[], with that space being provided by
53078 the caller.
53079
53080 The length counts are used for other purposes as well, i.e. finding
53081 the minimum and maximum length codes, determining if there are any
53082 codes at all, checking for a valid set of lengths, and looking ahead
53083 at length counts to determine sub-table sizes when building the
53084 decoding tables.
53085 */
53086
53087 /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
53088 for (len = 0; len <= MAXBITS; len++) {
53089 count[len] = 0;
53090 }
53091 for (sym = 0; sym < codes; sym++) {
53092 count[lens[lens_index + sym]]++;
53093 }
53094
53095 /* bound code lengths, force root to be within code lengths */
53096 root = bits;
53097 for (max = MAXBITS; max >= 1; max--) {
53098 if (count[max] !== 0) { break; }
53099 }
53100 if (root > max) {
53101 root = max;
53102 }
53103 if (max === 0) { /* no symbols to code at all */
53104 //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
53105 //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
53106 //table.val[opts.table_index++] = 0; //here.val = (var short)0;
53107 table[table_index++] = (1 << 24) | (64 << 16) | 0;
53108
53109
53110 //table.op[opts.table_index] = 64;
53111 //table.bits[opts.table_index] = 1;
53112 //table.val[opts.table_index++] = 0;
53113 table[table_index++] = (1 << 24) | (64 << 16) | 0;
53114
53115 opts.bits = 1;
53116 return 0; /* no symbols, but wait for decoding to report error */
53117 }
53118 for (min = 1; min < max; min++) {
53119 if (count[min] !== 0) { break; }
53120 }
53121 if (root < min) {
53122 root = min;
53123 }
53124
53125 /* check for an over-subscribed or incomplete set of lengths */
53126 left = 1;
53127 for (len = 1; len <= MAXBITS; len++) {
53128 left <<= 1;
53129 left -= count[len];
53130 if (left < 0) {
53131 return -1;
53132 } /* over-subscribed */
53133 }
53134 if (left > 0 && (type === CODES || max !== 1)) {
53135 return -1; /* incomplete set */
53136 }
53137
53138 /* generate offsets into symbol table for each length for sorting */
53139 offs[1] = 0;
53140 for (len = 1; len < MAXBITS; len++) {
53141 offs[len + 1] = offs[len] + count[len];
53142 }
53143
53144 /* sort symbols by length, by symbol order within each length */
53145 for (sym = 0; sym < codes; sym++) {
53146 if (lens[lens_index + sym] !== 0) {
53147 work[offs[lens[lens_index + sym]]++] = sym;
53148 }
53149 }
53150
53151 /*
53152 Create and fill in decoding tables. In this loop, the table being
53153 filled is at next and has curr index bits. The code being used is huff
53154 with length len. That code is converted to an index by dropping drop
53155 bits off of the bottom. For codes where len is less than drop + curr,
53156 those top drop + curr - len bits are incremented through all values to
53157 fill the table with replicated entries.
53158
53159 root is the number of index bits for the root table. When len exceeds
53160 root, sub-tables are created pointed to by the root entry with an index
53161 of the low root bits of huff. This is saved in low to check for when a
53162 new sub-table should be started. drop is zero when the root table is
53163 being filled, and drop is root when sub-tables are being filled.
53164
53165 When a new sub-table is needed, it is necessary to look ahead in the
53166 code lengths to determine what size sub-table is needed. The length
53167 counts are used for this, and so count[] is decremented as codes are
53168 entered in the tables.
53169
53170 used keeps track of how many table entries have been allocated from the
53171 provided *table space. It is checked for LENS and DIST tables against
53172 the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
53173 the initial root table size constants. See the comments in inftrees.h
53174 for more information.
53175
53176 sym increments through all symbols, and the loop terminates when
53177 all codes of length max, i.e. all codes, have been processed. This
53178 routine permits incomplete codes, so another loop after this one fills
53179 in the rest of the decoding tables with invalid code markers.
53180 */
53181
53182 /* set up for code type */
53183 // poor man optimization - use if-else instead of switch,
53184 // to avoid deopts in old v8
53185 if (type === CODES) {
53186 base = extra = work; /* dummy value--not used */
53187 end = 19;
53188
53189 } else if (type === LENS) {
53190 base = lbase;
53191 base_index -= 257;
53192 extra = lext;
53193 extra_index -= 257;
53194 end = 256;
53195
53196 } else { /* DISTS */
53197 base = dbase;
53198 extra = dext;
53199 end = -1;
53200 }
53201
53202 /* initialize opts for loop */
53203 huff = 0; /* starting code */
53204 sym = 0; /* starting code symbol */
53205 len = min; /* starting code length */
53206 next = table_index; /* current table to fill in */
53207 curr = root; /* current table index bits */
53208 drop = 0; /* current bits to drop from code for index */
53209 low = -1; /* trigger new sub-table when len > root */
53210 used = 1 << root; /* use root table entries */
53211 mask = used - 1; /* mask for comparing low */
53212
53213 /* check available table space */
53214 if ((type === LENS && used > ENOUGH_LENS) ||
53215 (type === DISTS && used > ENOUGH_DISTS)) {
53216 return 1;
53217 }
53218
53219 /* process all codes and make table entries */
53220 for (;;) {
53221 /* create table entry */
53222 here_bits = len - drop;
53223 if (work[sym] < end) {
53224 here_op = 0;
53225 here_val = work[sym];
53226 }
53227 else if (work[sym] > end) {
53228 here_op = extra[extra_index + work[sym]];
53229 here_val = base[base_index + work[sym]];
53230 }
53231 else {
53232 here_op = 32 + 64; /* end of block */
53233 here_val = 0;
53234 }
53235
53236 /* replicate for those indices with low len bits equal to huff */
53237 incr = 1 << (len - drop);
53238 fill = 1 << curr;
53239 min = fill; /* save offset to next table */
53240 do {
53241 fill -= incr;
53242 table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
53243 } while (fill !== 0);
53244
53245 /* backwards increment the len-bit code huff */
53246 incr = 1 << (len - 1);
53247 while (huff & incr) {
53248 incr >>= 1;
53249 }
53250 if (incr !== 0) {
53251 huff &= incr - 1;
53252 huff += incr;
53253 } else {
53254 huff = 0;
53255 }
53256
53257 /* go to next symbol, update count, len */
53258 sym++;
53259 if (--count[len] === 0) {
53260 if (len === max) { break; }
53261 len = lens[lens_index + work[sym]];
53262 }
53263
53264 /* create new sub-table if needed */
53265 if (len > root && (huff & mask) !== low) {
53266 /* if first time, transition to sub-tables */
53267 if (drop === 0) {
53268 drop = root;
53269 }
53270
53271 /* increment past last table */
53272 next += min; /* here min is 1 << curr */
53273
53274 /* determine length of next table */
53275 curr = len - drop;
53276 left = 1 << curr;
53277 while (curr + drop < max) {
53278 left -= count[curr + drop];
53279 if (left <= 0) { break; }
53280 curr++;
53281 left <<= 1;
53282 }
53283
53284 /* check for enough space */
53285 used += 1 << curr;
53286 if ((type === LENS && used > ENOUGH_LENS) ||
53287 (type === DISTS && used > ENOUGH_DISTS)) {
53288 return 1;
53289 }
53290
53291 /* point entry in root table to sub-table */
53292 low = huff & mask;
53293 /*table.op[low] = curr;
53294 table.bits[low] = root;
53295 table.val[low] = next - opts.table_index;*/
53296 table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
53297 }
53298 }
53299
53300 /* fill in remaining table entry if code is incomplete (guaranteed to have
53301 at most one remaining entry, since if the code is incomplete, the
53302 maximum code length that was allowed to get this far is one bit) */
53303 if (huff !== 0) {
53304 //table.op[next + huff] = 64; /* invalid code marker */
53305 //table.bits[next + huff] = len - drop;
53306 //table.val[next + huff] = 0;
53307 table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
53308 }
53309
53310 /* set return parameters */
53311 //opts.table_index += used;
53312 opts.bits = root;
53313 return 0;
53314};
53315
53316},{"../utils/common":241}],249:[function(require,module,exports){
53317'use strict';
53318
53319// (C) 1995-2013 Jean-loup Gailly and Mark Adler
53320// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
53321//
53322// This software is provided 'as-is', without any express or implied
53323// warranty. In no event will the authors be held liable for any damages
53324// arising from the use of this software.
53325//
53326// Permission is granted to anyone to use this software for any purpose,
53327// including commercial applications, and to alter it and redistribute it
53328// freely, subject to the following restrictions:
53329//
53330// 1. The origin of this software must not be misrepresented; you must not
53331// claim that you wrote the original software. If you use this software
53332// in a product, an acknowledgment in the product documentation would be
53333// appreciated but is not required.
53334// 2. Altered source versions must be plainly marked as such, and must not be
53335// misrepresented as being the original software.
53336// 3. This notice may not be removed or altered from any source distribution.
53337
53338module.exports = {
53339 2: 'need dictionary', /* Z_NEED_DICT 2 */
53340 1: 'stream end', /* Z_STREAM_END 1 */
53341 0: '', /* Z_OK 0 */
53342 '-1': 'file error', /* Z_ERRNO (-1) */
53343 '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
53344 '-3': 'data error', /* Z_DATA_ERROR (-3) */
53345 '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
53346 '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
53347 '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
53348};
53349
53350},{}],250:[function(require,module,exports){
53351'use strict';
53352
53353// (C) 1995-2013 Jean-loup Gailly and Mark Adler
53354// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
53355//
53356// This software is provided 'as-is', without any express or implied
53357// warranty. In no event will the authors be held liable for any damages
53358// arising from the use of this software.
53359//
53360// Permission is granted to anyone to use this software for any purpose,
53361// including commercial applications, and to alter it and redistribute it
53362// freely, subject to the following restrictions:
53363//
53364// 1. The origin of this software must not be misrepresented; you must not
53365// claim that you wrote the original software. If you use this software
53366// in a product, an acknowledgment in the product documentation would be
53367// appreciated but is not required.
53368// 2. Altered source versions must be plainly marked as such, and must not be
53369// misrepresented as being the original software.
53370// 3. This notice may not be removed or altered from any source distribution.
53371
53372/* eslint-disable space-unary-ops */
53373
53374var utils = require('../utils/common');
53375
53376/* Public constants ==========================================================*/
53377/* ===========================================================================*/
53378
53379
53380//var Z_FILTERED = 1;
53381//var Z_HUFFMAN_ONLY = 2;
53382//var Z_RLE = 3;
53383var Z_FIXED = 4;
53384//var Z_DEFAULT_STRATEGY = 0;
53385
53386/* Possible values of the data_type field (though see inflate()) */
53387var Z_BINARY = 0;
53388var Z_TEXT = 1;
53389//var Z_ASCII = 1; // = Z_TEXT
53390var Z_UNKNOWN = 2;
53391
53392/*============================================================================*/
53393
53394
53395function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
53396
53397// From zutil.h
53398
53399var STORED_BLOCK = 0;
53400var STATIC_TREES = 1;
53401var DYN_TREES = 2;
53402/* The three kinds of block type */
53403
53404var MIN_MATCH = 3;
53405var MAX_MATCH = 258;
53406/* The minimum and maximum match lengths */
53407
53408// From deflate.h
53409/* ===========================================================================
53410 * Internal compression state.
53411 */
53412
53413var LENGTH_CODES = 29;
53414/* number of length codes, not counting the special END_BLOCK code */
53415
53416var LITERALS = 256;
53417/* number of literal bytes 0..255 */
53418
53419var L_CODES = LITERALS + 1 + LENGTH_CODES;
53420/* number of Literal or Length codes, including the END_BLOCK code */
53421
53422var D_CODES = 30;
53423/* number of distance codes */
53424
53425var BL_CODES = 19;
53426/* number of codes used to transfer the bit lengths */
53427
53428var HEAP_SIZE = 2 * L_CODES + 1;
53429/* maximum heap size */
53430
53431var MAX_BITS = 15;
53432/* All codes must not exceed MAX_BITS bits */
53433
53434var Buf_size = 16;
53435/* size of bit buffer in bi_buf */
53436
53437
53438/* ===========================================================================
53439 * Constants
53440 */
53441
53442var MAX_BL_BITS = 7;
53443/* Bit length codes must not exceed MAX_BL_BITS bits */
53444
53445var END_BLOCK = 256;
53446/* end of block literal code */
53447
53448var REP_3_6 = 16;
53449/* repeat previous bit length 3-6 times (2 bits of repeat count) */
53450
53451var REPZ_3_10 = 17;
53452/* repeat a zero length 3-10 times (3 bits of repeat count) */
53453
53454var REPZ_11_138 = 18;
53455/* repeat a zero length 11-138 times (7 bits of repeat count) */
53456
53457/* eslint-disable comma-spacing,array-bracket-spacing */
53458var extra_lbits = /* extra bits for each length code */
53459 [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];
53460
53461var extra_dbits = /* extra bits for each distance code */
53462 [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];
53463
53464var extra_blbits = /* extra bits for each bit length code */
53465 [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
53466
53467var bl_order =
53468 [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
53469/* eslint-enable comma-spacing,array-bracket-spacing */
53470
53471/* The lengths of the bit length codes are sent in order of decreasing
53472 * probability, to avoid transmitting the lengths for unused bit length codes.
53473 */
53474
53475/* ===========================================================================
53476 * Local data. These are initialized only once.
53477 */
53478
53479// We pre-fill arrays with 0 to avoid uninitialized gaps
53480
53481var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
53482
53483// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1
53484var static_ltree = new Array((L_CODES + 2) * 2);
53485zero(static_ltree);
53486/* The static literal tree. Since the bit lengths are imposed, there is no
53487 * need for the L_CODES extra codes used during heap construction. However
53488 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
53489 * below).
53490 */
53491
53492var static_dtree = new Array(D_CODES * 2);
53493zero(static_dtree);
53494/* The static distance tree. (Actually a trivial tree since all codes use
53495 * 5 bits.)
53496 */
53497
53498var _dist_code = new Array(DIST_CODE_LEN);
53499zero(_dist_code);
53500/* Distance codes. The first 256 values correspond to the distances
53501 * 3 .. 258, the last 256 values correspond to the top 8 bits of
53502 * the 15 bit distances.
53503 */
53504
53505var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);
53506zero(_length_code);
53507/* length code for each normalized match length (0 == MIN_MATCH) */
53508
53509var base_length = new Array(LENGTH_CODES);
53510zero(base_length);
53511/* First normalized length for each code (0 = MIN_MATCH) */
53512
53513var base_dist = new Array(D_CODES);
53514zero(base_dist);
53515/* First normalized distance for each code (0 = distance of 1) */
53516
53517
53518function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {
53519
53520 this.static_tree = static_tree; /* static tree or NULL */
53521 this.extra_bits = extra_bits; /* extra bits for each code or NULL */
53522 this.extra_base = extra_base; /* base index for extra_bits */
53523 this.elems = elems; /* max number of elements in the tree */
53524 this.max_length = max_length; /* max bit length for the codes */
53525
53526 // show if `static_tree` has data or dummy - needed for monomorphic objects
53527 this.has_stree = static_tree && static_tree.length;
53528}
53529
53530
53531var static_l_desc;
53532var static_d_desc;
53533var static_bl_desc;
53534
53535
53536function TreeDesc(dyn_tree, stat_desc) {
53537 this.dyn_tree = dyn_tree; /* the dynamic tree */
53538 this.max_code = 0; /* largest code with non zero frequency */
53539 this.stat_desc = stat_desc; /* the corresponding static tree */
53540}
53541
53542
53543
53544function d_code(dist) {
53545 return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
53546}
53547
53548
53549/* ===========================================================================
53550 * Output a short LSB first on the stream.
53551 * IN assertion: there is enough room in pendingBuf.
53552 */
53553function put_short(s, w) {
53554// put_byte(s, (uch)((w) & 0xff));
53555// put_byte(s, (uch)((ush)(w) >> 8));
53556 s.pending_buf[s.pending++] = (w) & 0xff;
53557 s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
53558}
53559
53560
53561/* ===========================================================================
53562 * Send a value on a given number of bits.
53563 * IN assertion: length <= 16 and value fits in length bits.
53564 */
53565function send_bits(s, value, length) {
53566 if (s.bi_valid > (Buf_size - length)) {
53567 s.bi_buf |= (value << s.bi_valid) & 0xffff;
53568 put_short(s, s.bi_buf);
53569 s.bi_buf = value >> (Buf_size - s.bi_valid);
53570 s.bi_valid += length - Buf_size;
53571 } else {
53572 s.bi_buf |= (value << s.bi_valid) & 0xffff;
53573 s.bi_valid += length;
53574 }
53575}
53576
53577
53578function send_code(s, c, tree) {
53579 send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);
53580}
53581
53582
53583/* ===========================================================================
53584 * Reverse the first len bits of a code, using straightforward code (a faster
53585 * method would use a table)
53586 * IN assertion: 1 <= len <= 15
53587 */
53588function bi_reverse(code, len) {
53589 var res = 0;
53590 do {
53591 res |= code & 1;
53592 code >>>= 1;
53593 res <<= 1;
53594 } while (--len > 0);
53595 return res >>> 1;
53596}
53597
53598
53599/* ===========================================================================
53600 * Flush the bit buffer, keeping at most 7 bits in it.
53601 */
53602function bi_flush(s) {
53603 if (s.bi_valid === 16) {
53604 put_short(s, s.bi_buf);
53605 s.bi_buf = 0;
53606 s.bi_valid = 0;
53607
53608 } else if (s.bi_valid >= 8) {
53609 s.pending_buf[s.pending++] = s.bi_buf & 0xff;
53610 s.bi_buf >>= 8;
53611 s.bi_valid -= 8;
53612 }
53613}
53614
53615
53616/* ===========================================================================
53617 * Compute the optimal bit lengths for a tree and update the total bit length
53618 * for the current block.
53619 * IN assertion: the fields freq and dad are set, heap[heap_max] and
53620 * above are the tree nodes sorted by increasing frequency.
53621 * OUT assertions: the field len is set to the optimal bit length, the
53622 * array bl_count contains the frequencies for each bit length.
53623 * The length opt_len is updated; static_len is also updated if stree is
53624 * not null.
53625 */
53626function gen_bitlen(s, desc)
53627// deflate_state *s;
53628// tree_desc *desc; /* the tree descriptor */
53629{
53630 var tree = desc.dyn_tree;
53631 var max_code = desc.max_code;
53632 var stree = desc.stat_desc.static_tree;
53633 var has_stree = desc.stat_desc.has_stree;
53634 var extra = desc.stat_desc.extra_bits;
53635 var base = desc.stat_desc.extra_base;
53636 var max_length = desc.stat_desc.max_length;
53637 var h; /* heap index */
53638 var n, m; /* iterate over the tree elements */
53639 var bits; /* bit length */
53640 var xbits; /* extra bits */
53641 var f; /* frequency */
53642 var overflow = 0; /* number of elements with bit length too large */
53643
53644 for (bits = 0; bits <= MAX_BITS; bits++) {
53645 s.bl_count[bits] = 0;
53646 }
53647
53648 /* In a first pass, compute the optimal bit lengths (which may
53649 * overflow in the case of the bit length tree).
53650 */
53651 tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */
53652
53653 for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
53654 n = s.heap[h];
53655 bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
53656 if (bits > max_length) {
53657 bits = max_length;
53658 overflow++;
53659 }
53660 tree[n * 2 + 1]/*.Len*/ = bits;
53661 /* We overwrite tree[n].Dad which is no longer needed */
53662
53663 if (n > max_code) { continue; } /* not a leaf node */
53664
53665 s.bl_count[bits]++;
53666 xbits = 0;
53667 if (n >= base) {
53668 xbits = extra[n - base];
53669 }
53670 f = tree[n * 2]/*.Freq*/;
53671 s.opt_len += f * (bits + xbits);
53672 if (has_stree) {
53673 s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);
53674 }
53675 }
53676 if (overflow === 0) { return; }
53677
53678 // Trace((stderr,"\nbit length overflow\n"));
53679 /* This happens for example on obj2 and pic of the Calgary corpus */
53680
53681 /* Find the first bit length which could increase: */
53682 do {
53683 bits = max_length - 1;
53684 while (s.bl_count[bits] === 0) { bits--; }
53685 s.bl_count[bits]--; /* move one leaf down the tree */
53686 s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
53687 s.bl_count[max_length]--;
53688 /* The brother of the overflow item also moves one step up,
53689 * but this does not affect bl_count[max_length]
53690 */
53691 overflow -= 2;
53692 } while (overflow > 0);
53693
53694 /* Now recompute all bit lengths, scanning in increasing frequency.
53695 * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
53696 * lengths instead of fixing only the wrong ones. This idea is taken
53697 * from 'ar' written by Haruhiko Okumura.)
53698 */
53699 for (bits = max_length; bits !== 0; bits--) {
53700 n = s.bl_count[bits];
53701 while (n !== 0) {
53702 m = s.heap[--h];
53703 if (m > max_code) { continue; }
53704 if (tree[m * 2 + 1]/*.Len*/ !== bits) {
53705 // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
53706 s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;
53707 tree[m * 2 + 1]/*.Len*/ = bits;
53708 }
53709 n--;
53710 }
53711 }
53712}
53713
53714
53715/* ===========================================================================
53716 * Generate the codes for a given tree and bit counts (which need not be
53717 * optimal).
53718 * IN assertion: the array bl_count contains the bit length statistics for
53719 * the given tree and the field len is set for all tree elements.
53720 * OUT assertion: the field code is set for all tree elements of non
53721 * zero code length.
53722 */
53723function gen_codes(tree, max_code, bl_count)
53724// ct_data *tree; /* the tree to decorate */
53725// int max_code; /* largest code with non zero frequency */
53726// ushf *bl_count; /* number of codes at each bit length */
53727{
53728 var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */
53729 var code = 0; /* running code value */
53730 var bits; /* bit index */
53731 var n; /* code index */
53732
53733 /* The distribution counts are first used to generate the code values
53734 * without bit reversal.
53735 */
53736 for (bits = 1; bits <= MAX_BITS; bits++) {
53737 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
53738 }
53739 /* Check that the bit counts in bl_count are consistent. The last code
53740 * must be all ones.
53741 */
53742 //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
53743 // "inconsistent bit counts");
53744 //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
53745
53746 for (n = 0; n <= max_code; n++) {
53747 var len = tree[n * 2 + 1]/*.Len*/;
53748 if (len === 0) { continue; }
53749 /* Now reverse the bits */
53750 tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len);
53751
53752 //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
53753 // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
53754 }
53755}
53756
53757
53758/* ===========================================================================
53759 * Initialize the various 'constant' tables.
53760 */
53761function tr_static_init() {
53762 var n; /* iterates over tree elements */
53763 var bits; /* bit counter */
53764 var length; /* length value */
53765 var code; /* code value */
53766 var dist; /* distance index */
53767 var bl_count = new Array(MAX_BITS + 1);
53768 /* number of codes at each bit length for an optimal tree */
53769
53770 // do check in _tr_init()
53771 //if (static_init_done) return;
53772
53773 /* For some embedded targets, global variables are not initialized: */
53774/*#ifdef NO_INIT_GLOBAL_POINTERS
53775 static_l_desc.static_tree = static_ltree;
53776 static_l_desc.extra_bits = extra_lbits;
53777 static_d_desc.static_tree = static_dtree;
53778 static_d_desc.extra_bits = extra_dbits;
53779 static_bl_desc.extra_bits = extra_blbits;
53780#endif*/
53781
53782 /* Initialize the mapping length (0..255) -> length code (0..28) */
53783 length = 0;
53784 for (code = 0; code < LENGTH_CODES - 1; code++) {
53785 base_length[code] = length;
53786 for (n = 0; n < (1 << extra_lbits[code]); n++) {
53787 _length_code[length++] = code;
53788 }
53789 }
53790 //Assert (length == 256, "tr_static_init: length != 256");
53791 /* Note that the length 255 (match length 258) can be represented
53792 * in two different ways: code 284 + 5 bits or code 285, so we
53793 * overwrite length_code[255] to use the best encoding:
53794 */
53795 _length_code[length - 1] = code;
53796
53797 /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
53798 dist = 0;
53799 for (code = 0; code < 16; code++) {
53800 base_dist[code] = dist;
53801 for (n = 0; n < (1 << extra_dbits[code]); n++) {
53802 _dist_code[dist++] = code;
53803 }
53804 }
53805 //Assert (dist == 256, "tr_static_init: dist != 256");
53806 dist >>= 7; /* from now on, all distances are divided by 128 */
53807 for (; code < D_CODES; code++) {
53808 base_dist[code] = dist << 7;
53809 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
53810 _dist_code[256 + dist++] = code;
53811 }
53812 }
53813 //Assert (dist == 256, "tr_static_init: 256+dist != 512");
53814
53815 /* Construct the codes of the static literal tree */
53816 for (bits = 0; bits <= MAX_BITS; bits++) {
53817 bl_count[bits] = 0;
53818 }
53819
53820 n = 0;
53821 while (n <= 143) {
53822 static_ltree[n * 2 + 1]/*.Len*/ = 8;
53823 n++;
53824 bl_count[8]++;
53825 }
53826 while (n <= 255) {
53827 static_ltree[n * 2 + 1]/*.Len*/ = 9;
53828 n++;
53829 bl_count[9]++;
53830 }
53831 while (n <= 279) {
53832 static_ltree[n * 2 + 1]/*.Len*/ = 7;
53833 n++;
53834 bl_count[7]++;
53835 }
53836 while (n <= 287) {
53837 static_ltree[n * 2 + 1]/*.Len*/ = 8;
53838 n++;
53839 bl_count[8]++;
53840 }
53841 /* Codes 286 and 287 do not exist, but we must include them in the
53842 * tree construction to get a canonical Huffman tree (longest code
53843 * all ones)
53844 */
53845 gen_codes(static_ltree, L_CODES + 1, bl_count);
53846
53847 /* The static distance tree is trivial: */
53848 for (n = 0; n < D_CODES; n++) {
53849 static_dtree[n * 2 + 1]/*.Len*/ = 5;
53850 static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);
53851 }
53852
53853 // Now data ready and we can init static trees
53854 static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
53855 static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
53856 static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
53857
53858 //static_init_done = true;
53859}
53860
53861
53862/* ===========================================================================
53863 * Initialize a new block.
53864 */
53865function init_block(s) {
53866 var n; /* iterates over tree elements */
53867
53868 /* Initialize the trees. */
53869 for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }
53870 for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }
53871 for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }
53872
53873 s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;
53874 s.opt_len = s.static_len = 0;
53875 s.last_lit = s.matches = 0;
53876}
53877
53878
53879/* ===========================================================================
53880 * Flush the bit buffer and align the output on a byte boundary
53881 */
53882function bi_windup(s)
53883{
53884 if (s.bi_valid > 8) {
53885 put_short(s, s.bi_buf);
53886 } else if (s.bi_valid > 0) {
53887 //put_byte(s, (Byte)s->bi_buf);
53888 s.pending_buf[s.pending++] = s.bi_buf;
53889 }
53890 s.bi_buf = 0;
53891 s.bi_valid = 0;
53892}
53893
53894/* ===========================================================================
53895 * Copy a stored block, storing first the length and its
53896 * one's complement if requested.
53897 */
53898function copy_block(s, buf, len, header)
53899//DeflateState *s;
53900//charf *buf; /* the input data */
53901//unsigned len; /* its length */
53902//int header; /* true if block header must be written */
53903{
53904 bi_windup(s); /* align on byte boundary */
53905
53906 if (header) {
53907 put_short(s, len);
53908 put_short(s, ~len);
53909 }
53910// while (len--) {
53911// put_byte(s, *buf++);
53912// }
53913 utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
53914 s.pending += len;
53915}
53916
53917/* ===========================================================================
53918 * Compares to subtrees, using the tree depth as tie breaker when
53919 * the subtrees have equal frequency. This minimizes the worst case length.
53920 */
53921function smaller(tree, n, m, depth) {
53922 var _n2 = n * 2;
53923 var _m2 = m * 2;
53924 return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
53925 (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
53926}
53927
53928/* ===========================================================================
53929 * Restore the heap property by moving down the tree starting at node k,
53930 * exchanging a node with the smallest of its two sons if necessary, stopping
53931 * when the heap property is re-established (each father smaller than its
53932 * two sons).
53933 */
53934function pqdownheap(s, tree, k)
53935// deflate_state *s;
53936// ct_data *tree; /* the tree to restore */
53937// int k; /* node to move down */
53938{
53939 var v = s.heap[k];
53940 var j = k << 1; /* left son of k */
53941 while (j <= s.heap_len) {
53942 /* Set j to the smallest of the two sons: */
53943 if (j < s.heap_len &&
53944 smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {
53945 j++;
53946 }
53947 /* Exit if v is smaller than both sons */
53948 if (smaller(tree, v, s.heap[j], s.depth)) { break; }
53949
53950 /* Exchange v with the smallest son */
53951 s.heap[k] = s.heap[j];
53952 k = j;
53953
53954 /* And continue down the tree, setting j to the left son of k */
53955 j <<= 1;
53956 }
53957 s.heap[k] = v;
53958}
53959
53960
53961// inlined manually
53962// var SMALLEST = 1;
53963
53964/* ===========================================================================
53965 * Send the block data compressed using the given Huffman trees
53966 */
53967function compress_block(s, ltree, dtree)
53968// deflate_state *s;
53969// const ct_data *ltree; /* literal tree */
53970// const ct_data *dtree; /* distance tree */
53971{
53972 var dist; /* distance of matched string */
53973 var lc; /* match length or unmatched char (if dist == 0) */
53974 var lx = 0; /* running index in l_buf */
53975 var code; /* the code to send */
53976 var extra; /* number of extra bits to send */
53977
53978 if (s.last_lit !== 0) {
53979 do {
53980 dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);
53981 lc = s.pending_buf[s.l_buf + lx];
53982 lx++;
53983
53984 if (dist === 0) {
53985 send_code(s, lc, ltree); /* send a literal byte */
53986 //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
53987 } else {
53988 /* Here, lc is the match length - MIN_MATCH */
53989 code = _length_code[lc];
53990 send_code(s, code + LITERALS + 1, ltree); /* send the length code */
53991 extra = extra_lbits[code];
53992 if (extra !== 0) {
53993 lc -= base_length[code];
53994 send_bits(s, lc, extra); /* send the extra length bits */
53995 }
53996 dist--; /* dist is now the match distance - 1 */
53997 code = d_code(dist);
53998 //Assert (code < D_CODES, "bad d_code");
53999
54000 send_code(s, code, dtree); /* send the distance code */
54001 extra = extra_dbits[code];
54002 if (extra !== 0) {
54003 dist -= base_dist[code];
54004 send_bits(s, dist, extra); /* send the extra distance bits */
54005 }
54006 } /* literal or match pair ? */
54007
54008 /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
54009 //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
54010 // "pendingBuf overflow");
54011
54012 } while (lx < s.last_lit);
54013 }
54014
54015 send_code(s, END_BLOCK, ltree);
54016}
54017
54018
54019/* ===========================================================================
54020 * Construct one Huffman tree and assigns the code bit strings and lengths.
54021 * Update the total bit length for the current block.
54022 * IN assertion: the field freq is set for all tree elements.
54023 * OUT assertions: the fields len and code are set to the optimal bit length
54024 * and corresponding code. The length opt_len is updated; static_len is
54025 * also updated if stree is not null. The field max_code is set.
54026 */
54027function build_tree(s, desc)
54028// deflate_state *s;
54029// tree_desc *desc; /* the tree descriptor */
54030{
54031 var tree = desc.dyn_tree;
54032 var stree = desc.stat_desc.static_tree;
54033 var has_stree = desc.stat_desc.has_stree;
54034 var elems = desc.stat_desc.elems;
54035 var n, m; /* iterate over heap elements */
54036 var max_code = -1; /* largest code with non zero frequency */
54037 var node; /* new node being created */
54038
54039 /* Construct the initial heap, with least frequent element in
54040 * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
54041 * heap[0] is not used.
54042 */
54043 s.heap_len = 0;
54044 s.heap_max = HEAP_SIZE;
54045
54046 for (n = 0; n < elems; n++) {
54047 if (tree[n * 2]/*.Freq*/ !== 0) {
54048 s.heap[++s.heap_len] = max_code = n;
54049 s.depth[n] = 0;
54050
54051 } else {
54052 tree[n * 2 + 1]/*.Len*/ = 0;
54053 }
54054 }
54055
54056 /* The pkzip format requires that at least one distance code exists,
54057 * and that at least one bit should be sent even if there is only one
54058 * possible code. So to avoid special checks later on we force at least
54059 * two codes of non zero frequency.
54060 */
54061 while (s.heap_len < 2) {
54062 node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
54063 tree[node * 2]/*.Freq*/ = 1;
54064 s.depth[node] = 0;
54065 s.opt_len--;
54066
54067 if (has_stree) {
54068 s.static_len -= stree[node * 2 + 1]/*.Len*/;
54069 }
54070 /* node is 0 or 1 so it does not have extra bits */
54071 }
54072 desc.max_code = max_code;
54073
54074 /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
54075 * establish sub-heaps of increasing lengths:
54076 */
54077 for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
54078
54079 /* Construct the Huffman tree by repeatedly combining the least two
54080 * frequent nodes.
54081 */
54082 node = elems; /* next internal node of the tree */
54083 do {
54084 //pqremove(s, tree, n); /* n = node of least frequency */
54085 /*** pqremove ***/
54086 n = s.heap[1/*SMALLEST*/];
54087 s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
54088 pqdownheap(s, tree, 1/*SMALLEST*/);
54089 /***/
54090
54091 m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
54092
54093 s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
54094 s.heap[--s.heap_max] = m;
54095
54096 /* Create a new node father of n and m */
54097 tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
54098 s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
54099 tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;
54100
54101 /* and insert the new node in the heap */
54102 s.heap[1/*SMALLEST*/] = node++;
54103 pqdownheap(s, tree, 1/*SMALLEST*/);
54104
54105 } while (s.heap_len >= 2);
54106
54107 s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
54108
54109 /* At this point, the fields freq and dad are set. We can now
54110 * generate the bit lengths.
54111 */
54112 gen_bitlen(s, desc);
54113
54114 /* The field len is now set, we can generate the bit codes */
54115 gen_codes(tree, max_code, s.bl_count);
54116}
54117
54118
54119/* ===========================================================================
54120 * Scan a literal or distance tree to determine the frequencies of the codes
54121 * in the bit length tree.
54122 */
54123function scan_tree(s, tree, max_code)
54124// deflate_state *s;
54125// ct_data *tree; /* the tree to be scanned */
54126// int max_code; /* and its largest code of non zero frequency */
54127{
54128 var n; /* iterates over all tree elements */
54129 var prevlen = -1; /* last emitted length */
54130 var curlen; /* length of current code */
54131
54132 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
54133
54134 var count = 0; /* repeat count of the current code */
54135 var max_count = 7; /* max repeat count */
54136 var min_count = 4; /* min repeat count */
54137
54138 if (nextlen === 0) {
54139 max_count = 138;
54140 min_count = 3;
54141 }
54142 tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */
54143
54144 for (n = 0; n <= max_code; n++) {
54145 curlen = nextlen;
54146 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
54147
54148 if (++count < max_count && curlen === nextlen) {
54149 continue;
54150
54151 } else if (count < min_count) {
54152 s.bl_tree[curlen * 2]/*.Freq*/ += count;
54153
54154 } else if (curlen !== 0) {
54155
54156 if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
54157 s.bl_tree[REP_3_6 * 2]/*.Freq*/++;
54158
54159 } else if (count <= 10) {
54160 s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;
54161
54162 } else {
54163 s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;
54164 }
54165
54166 count = 0;
54167 prevlen = curlen;
54168
54169 if (nextlen === 0) {
54170 max_count = 138;
54171 min_count = 3;
54172
54173 } else if (curlen === nextlen) {
54174 max_count = 6;
54175 min_count = 3;
54176
54177 } else {
54178 max_count = 7;
54179 min_count = 4;
54180 }
54181 }
54182}
54183
54184
54185/* ===========================================================================
54186 * Send a literal or distance tree in compressed form, using the codes in
54187 * bl_tree.
54188 */
54189function send_tree(s, tree, max_code)
54190// deflate_state *s;
54191// ct_data *tree; /* the tree to be scanned */
54192// int max_code; /* and its largest code of non zero frequency */
54193{
54194 var n; /* iterates over all tree elements */
54195 var prevlen = -1; /* last emitted length */
54196 var curlen; /* length of current code */
54197
54198 var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */
54199
54200 var count = 0; /* repeat count of the current code */
54201 var max_count = 7; /* max repeat count */
54202 var min_count = 4; /* min repeat count */
54203
54204 /* tree[max_code+1].Len = -1; */ /* guard already set */
54205 if (nextlen === 0) {
54206 max_count = 138;
54207 min_count = 3;
54208 }
54209
54210 for (n = 0; n <= max_code; n++) {
54211 curlen = nextlen;
54212 nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;
54213
54214 if (++count < max_count && curlen === nextlen) {
54215 continue;
54216
54217 } else if (count < min_count) {
54218 do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
54219
54220 } else if (curlen !== 0) {
54221 if (curlen !== prevlen) {
54222 send_code(s, curlen, s.bl_tree);
54223 count--;
54224 }
54225 //Assert(count >= 3 && count <= 6, " 3_6?");
54226 send_code(s, REP_3_6, s.bl_tree);
54227 send_bits(s, count - 3, 2);
54228
54229 } else if (count <= 10) {
54230 send_code(s, REPZ_3_10, s.bl_tree);
54231 send_bits(s, count - 3, 3);
54232
54233 } else {
54234 send_code(s, REPZ_11_138, s.bl_tree);
54235 send_bits(s, count - 11, 7);
54236 }
54237
54238 count = 0;
54239 prevlen = curlen;
54240 if (nextlen === 0) {
54241 max_count = 138;
54242 min_count = 3;
54243
54244 } else if (curlen === nextlen) {
54245 max_count = 6;
54246 min_count = 3;
54247
54248 } else {
54249 max_count = 7;
54250 min_count = 4;
54251 }
54252 }
54253}
54254
54255
54256/* ===========================================================================
54257 * Construct the Huffman tree for the bit lengths and return the index in
54258 * bl_order of the last bit length code to send.
54259 */
54260function build_bl_tree(s) {
54261 var max_blindex; /* index of last bit length code of non zero freq */
54262
54263 /* Determine the bit length frequencies for literal and distance trees */
54264 scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
54265 scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
54266
54267 /* Build the bit length tree: */
54268 build_tree(s, s.bl_desc);
54269 /* opt_len now includes the length of the tree representations, except
54270 * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
54271 */
54272
54273 /* Determine the number of bit length codes to send. The pkzip format
54274 * requires that at least 4 bit length codes be sent. (appnote.txt says
54275 * 3 but the actual value used is 4.)
54276 */
54277 for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
54278 if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {
54279 break;
54280 }
54281 }
54282 /* Update opt_len to include the bit length tree and counts */
54283 s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
54284 //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
54285 // s->opt_len, s->static_len));
54286
54287 return max_blindex;
54288}
54289
54290
54291/* ===========================================================================
54292 * Send the header for a block using dynamic Huffman trees: the counts, the
54293 * lengths of the bit length codes, the literal tree and the distance tree.
54294 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
54295 */
54296function send_all_trees(s, lcodes, dcodes, blcodes)
54297// deflate_state *s;
54298// int lcodes, dcodes, blcodes; /* number of codes for each tree */
54299{
54300 var rank; /* index in bl_order */
54301
54302 //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
54303 //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
54304 // "too many codes");
54305 //Tracev((stderr, "\nbl counts: "));
54306 send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */
54307 send_bits(s, dcodes - 1, 5);
54308 send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */
54309 for (rank = 0; rank < blcodes; rank++) {
54310 //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
54311 send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);
54312 }
54313 //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
54314
54315 send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */
54316 //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
54317
54318 send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */
54319 //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
54320}
54321
54322
54323/* ===========================================================================
54324 * Check if the data type is TEXT or BINARY, using the following algorithm:
54325 * - TEXT if the two conditions below are satisfied:
54326 * a) There are no non-portable control characters belonging to the
54327 * "black list" (0..6, 14..25, 28..31).
54328 * b) There is at least one printable character belonging to the
54329 * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
54330 * - BINARY otherwise.
54331 * - The following partially-portable control characters form a
54332 * "gray list" that is ignored in this detection algorithm:
54333 * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
54334 * IN assertion: the fields Freq of dyn_ltree are set.
54335 */
54336function detect_data_type(s) {
54337 /* black_mask is the bit mask of black-listed bytes
54338 * set bits 0..6, 14..25, and 28..31
54339 * 0xf3ffc07f = binary 11110011111111111100000001111111
54340 */
54341 var black_mask = 0xf3ffc07f;
54342 var n;
54343
54344 /* Check for non-textual ("black-listed") bytes. */
54345 for (n = 0; n <= 31; n++, black_mask >>>= 1) {
54346 if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {
54347 return Z_BINARY;
54348 }
54349 }
54350
54351 /* Check for textual ("white-listed") bytes. */
54352 if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
54353 s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
54354 return Z_TEXT;
54355 }
54356 for (n = 32; n < LITERALS; n++) {
54357 if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
54358 return Z_TEXT;
54359 }
54360 }
54361
54362 /* There are no "black-listed" or "white-listed" bytes:
54363 * this stream either is empty or has tolerated ("gray-listed") bytes only.
54364 */
54365 return Z_BINARY;
54366}
54367
54368
54369var static_init_done = false;
54370
54371/* ===========================================================================
54372 * Initialize the tree data structures for a new zlib stream.
54373 */
54374function _tr_init(s)
54375{
54376
54377 if (!static_init_done) {
54378 tr_static_init();
54379 static_init_done = true;
54380 }
54381
54382 s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
54383 s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
54384 s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
54385
54386 s.bi_buf = 0;
54387 s.bi_valid = 0;
54388
54389 /* Initialize the first block of the first file: */
54390 init_block(s);
54391}
54392
54393
54394/* ===========================================================================
54395 * Send a stored block
54396 */
54397function _tr_stored_block(s, buf, stored_len, last)
54398//DeflateState *s;
54399//charf *buf; /* input block */
54400//ulg stored_len; /* length of input block */
54401//int last; /* one if this is the last block for a file */
54402{
54403 send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */
54404 copy_block(s, buf, stored_len, true); /* with header */
54405}
54406
54407
54408/* ===========================================================================
54409 * Send one empty static block to give enough lookahead for inflate.
54410 * This takes 10 bits, of which 7 may remain in the bit buffer.
54411 */
54412function _tr_align(s) {
54413 send_bits(s, STATIC_TREES << 1, 3);
54414 send_code(s, END_BLOCK, static_ltree);
54415 bi_flush(s);
54416}
54417
54418
54419/* ===========================================================================
54420 * Determine the best encoding for the current block: dynamic trees, static
54421 * trees or store, and output the encoded block to the zip file.
54422 */
54423function _tr_flush_block(s, buf, stored_len, last)
54424//DeflateState *s;
54425//charf *buf; /* input block, or NULL if too old */
54426//ulg stored_len; /* length of input block */
54427//int last; /* one if this is the last block for a file */
54428{
54429 var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
54430 var max_blindex = 0; /* index of last bit length code of non zero freq */
54431
54432 /* Build the Huffman trees unless a stored block is forced */
54433 if (s.level > 0) {
54434
54435 /* Check if the file is binary or text */
54436 if (s.strm.data_type === Z_UNKNOWN) {
54437 s.strm.data_type = detect_data_type(s);
54438 }
54439
54440 /* Construct the literal and distance trees */
54441 build_tree(s, s.l_desc);
54442 // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
54443 // s->static_len));
54444
54445 build_tree(s, s.d_desc);
54446 // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
54447 // s->static_len));
54448 /* At this point, opt_len and static_len are the total bit lengths of
54449 * the compressed block data, excluding the tree representations.
54450 */
54451
54452 /* Build the bit length tree for the above two trees, and get the index
54453 * in bl_order of the last bit length code to send.
54454 */
54455 max_blindex = build_bl_tree(s);
54456
54457 /* Determine the best encoding. Compute the block lengths in bytes. */
54458 opt_lenb = (s.opt_len + 3 + 7) >>> 3;
54459 static_lenb = (s.static_len + 3 + 7) >>> 3;
54460
54461 // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
54462 // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
54463 // s->last_lit));
54464
54465 if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
54466
54467 } else {
54468 // Assert(buf != (char*)0, "lost buf");
54469 opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
54470 }
54471
54472 if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {
54473 /* 4: two words for the lengths */
54474
54475 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
54476 * Otherwise we can't have processed more than WSIZE input bytes since
54477 * the last block flush, because compression would have been
54478 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
54479 * transform a block into a stored block.
54480 */
54481 _tr_stored_block(s, buf, stored_len, last);
54482
54483 } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
54484
54485 send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);
54486 compress_block(s, static_ltree, static_dtree);
54487
54488 } else {
54489 send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);
54490 send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);
54491 compress_block(s, s.dyn_ltree, s.dyn_dtree);
54492 }
54493 // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
54494 /* The above check is made mod 2^32, for files larger than 512 MB
54495 * and uLong implemented on 32 bits.
54496 */
54497 init_block(s);
54498
54499 if (last) {
54500 bi_windup(s);
54501 }
54502 // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
54503 // s->compressed_len-7*last));
54504}
54505
54506/* ===========================================================================
54507 * Save the match info and tally the frequency counts. Return true if
54508 * the current block must be flushed.
54509 */
54510function _tr_tally(s, dist, lc)
54511// deflate_state *s;
54512// unsigned dist; /* distance of matched string */
54513// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
54514{
54515 //var out_length, in_length, dcode;
54516
54517 s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
54518 s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
54519
54520 s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
54521 s.last_lit++;
54522
54523 if (dist === 0) {
54524 /* lc is the unmatched char */
54525 s.dyn_ltree[lc * 2]/*.Freq*/++;
54526 } else {
54527 s.matches++;
54528 /* Here, lc is the match length - MIN_MATCH */
54529 dist--; /* dist = match distance - 1 */
54530 //Assert((ush)dist < (ush)MAX_DIST(s) &&
54531 // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
54532 // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
54533
54534 s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;
54535 s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
54536 }
54537
54538// (!) This block is disabled in zlib defaults,
54539// don't enable it for binary compatibility
54540
54541//#ifdef TRUNCATE_BLOCK
54542// /* Try to guess if it is profitable to stop the current block here */
54543// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
54544// /* Compute an upper bound for the compressed length */
54545// out_length = s.last_lit*8;
54546// in_length = s.strstart - s.block_start;
54547//
54548// for (dcode = 0; dcode < D_CODES; dcode++) {
54549// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
54550// }
54551// out_length >>>= 3;
54552// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
54553// // s->last_lit, in_length, out_length,
54554// // 100L - out_length*100L/in_length));
54555// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
54556// return true;
54557// }
54558// }
54559//#endif
54560
54561 return (s.last_lit === s.lit_bufsize - 1);
54562 /* We avoid equality with lit_bufsize because of wraparound at 64K
54563 * on 16 bit machines and because stored blocks are restricted to
54564 * 64K-1 bytes.
54565 */
54566}
54567
54568exports._tr_init = _tr_init;
54569exports._tr_stored_block = _tr_stored_block;
54570exports._tr_flush_block = _tr_flush_block;
54571exports._tr_tally = _tr_tally;
54572exports._tr_align = _tr_align;
54573
54574},{"../utils/common":241}],251:[function(require,module,exports){
54575'use strict';
54576
54577// (C) 1995-2013 Jean-loup Gailly and Mark Adler
54578// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin
54579//
54580// This software is provided 'as-is', without any express or implied
54581// warranty. In no event will the authors be held liable for any damages
54582// arising from the use of this software.
54583//
54584// Permission is granted to anyone to use this software for any purpose,
54585// including commercial applications, and to alter it and redistribute it
54586// freely, subject to the following restrictions:
54587//
54588// 1. The origin of this software must not be misrepresented; you must not
54589// claim that you wrote the original software. If you use this software
54590// in a product, an acknowledgment in the product documentation would be
54591// appreciated but is not required.
54592// 2. Altered source versions must be plainly marked as such, and must not be
54593// misrepresented as being the original software.
54594// 3. This notice may not be removed or altered from any source distribution.
54595
54596function ZStream() {
54597 /* next input byte */
54598 this.input = null; // JS specific, because we have no pointers
54599 this.next_in = 0;
54600 /* number of bytes available at input */
54601 this.avail_in = 0;
54602 /* total number of input bytes read so far */
54603 this.total_in = 0;
54604 /* next output byte should be put there */
54605 this.output = null; // JS specific, because we have no pointers
54606 this.next_out = 0;
54607 /* remaining free space at output */
54608 this.avail_out = 0;
54609 /* total number of bytes output so far */
54610 this.total_out = 0;
54611 /* last error message, NULL if no error */
54612 this.msg = ''/*Z_NULL*/;
54613 /* not visible by applications */
54614 this.state = null;
54615 /* best guess about the data type: binary or text */
54616 this.data_type = 2/*Z_UNKNOWN*/;
54617 /* adler32 value of the uncompressed data */
54618 this.adler = 0;
54619}
54620
54621module.exports = ZStream;
54622
54623},{}],252:[function(require,module,exports){
54624module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
54625"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
54626"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
54627"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
54628"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
54629"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
54630"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
54631"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
54632"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
54633"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
54634"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
54635"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
54636}
54637},{}],253:[function(require,module,exports){
54638// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
54639// Fedor, you are amazing.
54640'use strict'
54641
54642var asn1 = require('asn1.js')
54643
54644exports.certificate = require('./certificate')
54645
54646var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
54647 this.seq().obj(
54648 this.key('version').int(),
54649 this.key('modulus').int(),
54650 this.key('publicExponent').int(),
54651 this.key('privateExponent').int(),
54652 this.key('prime1').int(),
54653 this.key('prime2').int(),
54654 this.key('exponent1').int(),
54655 this.key('exponent2').int(),
54656 this.key('coefficient').int()
54657 )
54658})
54659exports.RSAPrivateKey = RSAPrivateKey
54660
54661var RSAPublicKey = asn1.define('RSAPublicKey', function () {
54662 this.seq().obj(
54663 this.key('modulus').int(),
54664 this.key('publicExponent').int()
54665 )
54666})
54667exports.RSAPublicKey = RSAPublicKey
54668
54669var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
54670 this.seq().obj(
54671 this.key('algorithm').use(AlgorithmIdentifier),
54672 this.key('subjectPublicKey').bitstr()
54673 )
54674})
54675exports.PublicKey = PublicKey
54676
54677var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
54678 this.seq().obj(
54679 this.key('algorithm').objid(),
54680 this.key('none').null_().optional(),
54681 this.key('curve').objid().optional(),
54682 this.key('params').seq().obj(
54683 this.key('p').int(),
54684 this.key('q').int(),
54685 this.key('g').int()
54686 ).optional()
54687 )
54688})
54689
54690var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
54691 this.seq().obj(
54692 this.key('version').int(),
54693 this.key('algorithm').use(AlgorithmIdentifier),
54694 this.key('subjectPrivateKey').octstr()
54695 )
54696})
54697exports.PrivateKey = PrivateKeyInfo
54698var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
54699 this.seq().obj(
54700 this.key('algorithm').seq().obj(
54701 this.key('id').objid(),
54702 this.key('decrypt').seq().obj(
54703 this.key('kde').seq().obj(
54704 this.key('id').objid(),
54705 this.key('kdeparams').seq().obj(
54706 this.key('salt').octstr(),
54707 this.key('iters').int()
54708 )
54709 ),
54710 this.key('cipher').seq().obj(
54711 this.key('algo').objid(),
54712 this.key('iv').octstr()
54713 )
54714 )
54715 ),
54716 this.key('subjectPrivateKey').octstr()
54717 )
54718})
54719
54720exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
54721
54722var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
54723 this.seq().obj(
54724 this.key('version').int(),
54725 this.key('p').int(),
54726 this.key('q').int(),
54727 this.key('g').int(),
54728 this.key('pub_key').int(),
54729 this.key('priv_key').int()
54730 )
54731})
54732exports.DSAPrivateKey = DSAPrivateKey
54733
54734exports.DSAparam = asn1.define('DSAparam', function () {
54735 this.int()
54736})
54737
54738var ECPrivateKey = asn1.define('ECPrivateKey', function () {
54739 this.seq().obj(
54740 this.key('version').int(),
54741 this.key('privateKey').octstr(),
54742 this.key('parameters').optional().explicit(0).use(ECParameters),
54743 this.key('publicKey').optional().explicit(1).bitstr()
54744 )
54745})
54746exports.ECPrivateKey = ECPrivateKey
54747
54748var ECParameters = asn1.define('ECParameters', function () {
54749 this.choice({
54750 namedCurve: this.objid()
54751 })
54752})
54753
54754exports.signature = asn1.define('signature', function () {
54755 this.seq().obj(
54756 this.key('r').int(),
54757 this.key('s').int()
54758 )
54759})
54760
54761},{"./certificate":254,"asn1.js":47}],254:[function(require,module,exports){
54762// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
54763// thanks to @Rantanen
54764
54765'use strict'
54766
54767var asn = require('asn1.js')
54768
54769var Time = asn.define('Time', function () {
54770 this.choice({
54771 utcTime: this.utctime(),
54772 generalTime: this.gentime()
54773 })
54774})
54775
54776var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
54777 this.seq().obj(
54778 this.key('type').objid(),
54779 this.key('value').any()
54780 )
54781})
54782
54783var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
54784 this.seq().obj(
54785 this.key('algorithm').objid(),
54786 this.key('parameters').optional(),
54787 this.key('curve').objid().optional()
54788 )
54789})
54790
54791var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
54792 this.seq().obj(
54793 this.key('algorithm').use(AlgorithmIdentifier),
54794 this.key('subjectPublicKey').bitstr()
54795 )
54796})
54797
54798var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
54799 this.setof(AttributeTypeValue)
54800})
54801
54802var RDNSequence = asn.define('RDNSequence', function () {
54803 this.seqof(RelativeDistinguishedName)
54804})
54805
54806var Name = asn.define('Name', function () {
54807 this.choice({
54808 rdnSequence: this.use(RDNSequence)
54809 })
54810})
54811
54812var Validity = asn.define('Validity', function () {
54813 this.seq().obj(
54814 this.key('notBefore').use(Time),
54815 this.key('notAfter').use(Time)
54816 )
54817})
54818
54819var Extension = asn.define('Extension', function () {
54820 this.seq().obj(
54821 this.key('extnID').objid(),
54822 this.key('critical').bool().def(false),
54823 this.key('extnValue').octstr()
54824 )
54825})
54826
54827var TBSCertificate = asn.define('TBSCertificate', function () {
54828 this.seq().obj(
54829 this.key('version').explicit(0).int().optional(),
54830 this.key('serialNumber').int(),
54831 this.key('signature').use(AlgorithmIdentifier),
54832 this.key('issuer').use(Name),
54833 this.key('validity').use(Validity),
54834 this.key('subject').use(Name),
54835 this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
54836 this.key('issuerUniqueID').implicit(1).bitstr().optional(),
54837 this.key('subjectUniqueID').implicit(2).bitstr().optional(),
54838 this.key('extensions').explicit(3).seqof(Extension).optional()
54839 )
54840})
54841
54842var X509Certificate = asn.define('X509Certificate', function () {
54843 this.seq().obj(
54844 this.key('tbsCertificate').use(TBSCertificate),
54845 this.key('signatureAlgorithm').use(AlgorithmIdentifier),
54846 this.key('signatureValue').bitstr()
54847 )
54848})
54849
54850module.exports = X509Certificate
54851
54852},{"asn1.js":47}],255:[function(require,module,exports){
54853// adapted from https://github.com/apatil/pemstrip
54854var 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
54855var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m
54856var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r\+\/\=]+)-----END \1-----$/m
54857var evp = require('evp_bytestokey')
54858var ciphers = require('browserify-aes')
54859var Buffer = require('safe-buffer').Buffer
54860module.exports = function (okey, password) {
54861 var key = okey.toString()
54862 var match = key.match(findProc)
54863 var decrypted
54864 if (!match) {
54865 var match2 = key.match(fullRegex)
54866 decrypted = new Buffer(match2[2].replace(/[\r\n]/g, ''), 'base64')
54867 } else {
54868 var suite = 'aes' + match[1]
54869 var iv = Buffer.from(match[2], 'hex')
54870 var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64')
54871 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
54872 var out = []
54873 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
54874 out.push(cipher.update(cipherText))
54875 out.push(cipher.final())
54876 decrypted = Buffer.concat(out)
54877 }
54878 var tag = key.match(startRegex)[1]
54879 return {
54880 tag: tag,
54881 data: decrypted
54882 }
54883}
54884
54885},{"browserify-aes":85,"evp_bytestokey":160,"safe-buffer":325}],256:[function(require,module,exports){
54886var asn1 = require('./asn1')
54887var aesid = require('./aesid.json')
54888var fixProc = require('./fixProc')
54889var ciphers = require('browserify-aes')
54890var compat = require('pbkdf2')
54891var Buffer = require('safe-buffer').Buffer
54892module.exports = parseKeys
54893
54894function parseKeys (buffer) {
54895 var password
54896 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
54897 password = buffer.passphrase
54898 buffer = buffer.key
54899 }
54900 if (typeof buffer === 'string') {
54901 buffer = Buffer.from(buffer)
54902 }
54903
54904 var stripped = fixProc(buffer, password)
54905
54906 var type = stripped.tag
54907 var data = stripped.data
54908 var subtype, ndata
54909 switch (type) {
54910 case 'CERTIFICATE':
54911 ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
54912 // falls through
54913 case 'PUBLIC KEY':
54914 if (!ndata) {
54915 ndata = asn1.PublicKey.decode(data, 'der')
54916 }
54917 subtype = ndata.algorithm.algorithm.join('.')
54918 switch (subtype) {
54919 case '1.2.840.113549.1.1.1':
54920 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
54921 case '1.2.840.10045.2.1':
54922 ndata.subjectPrivateKey = ndata.subjectPublicKey
54923 return {
54924 type: 'ec',
54925 data: ndata
54926 }
54927 case '1.2.840.10040.4.1':
54928 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
54929 return {
54930 type: 'dsa',
54931 data: ndata.algorithm.params
54932 }
54933 default: throw new Error('unknown key id ' + subtype)
54934 }
54935 throw new Error('unknown key type ' + type)
54936 case 'ENCRYPTED PRIVATE KEY':
54937 data = asn1.EncryptedPrivateKey.decode(data, 'der')
54938 data = decrypt(data, password)
54939 // falls through
54940 case 'PRIVATE KEY':
54941 ndata = asn1.PrivateKey.decode(data, 'der')
54942 subtype = ndata.algorithm.algorithm.join('.')
54943 switch (subtype) {
54944 case '1.2.840.113549.1.1.1':
54945 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
54946 case '1.2.840.10045.2.1':
54947 return {
54948 curve: ndata.algorithm.curve,
54949 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
54950 }
54951 case '1.2.840.10040.4.1':
54952 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
54953 return {
54954 type: 'dsa',
54955 params: ndata.algorithm.params
54956 }
54957 default: throw new Error('unknown key id ' + subtype)
54958 }
54959 throw new Error('unknown key type ' + type)
54960 case 'RSA PUBLIC KEY':
54961 return asn1.RSAPublicKey.decode(data, 'der')
54962 case 'RSA PRIVATE KEY':
54963 return asn1.RSAPrivateKey.decode(data, 'der')
54964 case 'DSA PRIVATE KEY':
54965 return {
54966 type: 'dsa',
54967 params: asn1.DSAPrivateKey.decode(data, 'der')
54968 }
54969 case 'EC PRIVATE KEY':
54970 data = asn1.ECPrivateKey.decode(data, 'der')
54971 return {
54972 curve: data.parameters.value,
54973 privateKey: data.privateKey
54974 }
54975 default: throw new Error('unknown key type ' + type)
54976 }
54977}
54978parseKeys.signature = asn1.signature
54979function decrypt (data, password) {
54980 var salt = data.algorithm.decrypt.kde.kdeparams.salt
54981 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
54982 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
54983 var iv = data.algorithm.decrypt.cipher.iv
54984 var cipherText = data.subjectPrivateKey
54985 var keylen = parseInt(algo.split('-')[1], 10) / 8
54986 var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1')
54987 var cipher = ciphers.createDecipheriv(algo, key, iv)
54988 var out = []
54989 out.push(cipher.update(cipherText))
54990 out.push(cipher.final())
54991 return Buffer.concat(out)
54992}
54993
54994},{"./aesid.json":252,"./asn1":253,"./fixProc":255,"browserify-aes":85,"pbkdf2":258,"safe-buffer":325}],257:[function(require,module,exports){
54995(function (process){
54996// .dirname, .basename, and .extname methods are extracted from Node.js v8.11.1,
54997// backported and transplited with Babel, with backwards-compat fixes
54998
54999// Copyright Joyent, Inc. and other Node contributors.
55000//
55001// Permission is hereby granted, free of charge, to any person obtaining a
55002// copy of this software and associated documentation files (the
55003// "Software"), to deal in the Software without restriction, including
55004// without limitation the rights to use, copy, modify, merge, publish,
55005// distribute, sublicense, and/or sell copies of the Software, and to permit
55006// persons to whom the Software is furnished to do so, subject to the
55007// following conditions:
55008//
55009// The above copyright notice and this permission notice shall be included
55010// in all copies or substantial portions of the Software.
55011//
55012// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
55013// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
55014// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
55015// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
55016// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
55017// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
55018// USE OR OTHER DEALINGS IN THE SOFTWARE.
55019
55020// resolves . and .. elements in a path array with directory names there
55021// must be no slashes, empty elements, or device names (c:\) in the array
55022// (so also no leading and trailing slashes - it does not distinguish
55023// relative and absolute paths)
55024function normalizeArray(parts, allowAboveRoot) {
55025 // if the path tries to go above the root, `up` ends up > 0
55026 var up = 0;
55027 for (var i = parts.length - 1; i >= 0; i--) {
55028 var last = parts[i];
55029 if (last === '.') {
55030 parts.splice(i, 1);
55031 } else if (last === '..') {
55032 parts.splice(i, 1);
55033 up++;
55034 } else if (up) {
55035 parts.splice(i, 1);
55036 up--;
55037 }
55038 }
55039
55040 // if the path is allowed to go above the root, restore leading ..s
55041 if (allowAboveRoot) {
55042 for (; up--; up) {
55043 parts.unshift('..');
55044 }
55045 }
55046
55047 return parts;
55048}
55049
55050// path.resolve([from ...], to)
55051// posix version
55052exports.resolve = function() {
55053 var resolvedPath = '',
55054 resolvedAbsolute = false;
55055
55056 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
55057 var path = (i >= 0) ? arguments[i] : process.cwd();
55058
55059 // Skip empty and invalid entries
55060 if (typeof path !== 'string') {
55061 throw new TypeError('Arguments to path.resolve must be strings');
55062 } else if (!path) {
55063 continue;
55064 }
55065
55066 resolvedPath = path + '/' + resolvedPath;
55067 resolvedAbsolute = path.charAt(0) === '/';
55068 }
55069
55070 // At this point the path should be resolved to a full absolute path, but
55071 // handle relative paths to be safe (might happen when process.cwd() fails)
55072
55073 // Normalize the path
55074 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
55075 return !!p;
55076 }), !resolvedAbsolute).join('/');
55077
55078 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
55079};
55080
55081// path.normalize(path)
55082// posix version
55083exports.normalize = function(path) {
55084 var isAbsolute = exports.isAbsolute(path),
55085 trailingSlash = substr(path, -1) === '/';
55086
55087 // Normalize the path
55088 path = normalizeArray(filter(path.split('/'), function(p) {
55089 return !!p;
55090 }), !isAbsolute).join('/');
55091
55092 if (!path && !isAbsolute) {
55093 path = '.';
55094 }
55095 if (path && trailingSlash) {
55096 path += '/';
55097 }
55098
55099 return (isAbsolute ? '/' : '') + path;
55100};
55101
55102// posix version
55103exports.isAbsolute = function(path) {
55104 return path.charAt(0) === '/';
55105};
55106
55107// posix version
55108exports.join = function() {
55109 var paths = Array.prototype.slice.call(arguments, 0);
55110 return exports.normalize(filter(paths, function(p, index) {
55111 if (typeof p !== 'string') {
55112 throw new TypeError('Arguments to path.join must be strings');
55113 }
55114 return p;
55115 }).join('/'));
55116};
55117
55118
55119// path.relative(from, to)
55120// posix version
55121exports.relative = function(from, to) {
55122 from = exports.resolve(from).substr(1);
55123 to = exports.resolve(to).substr(1);
55124
55125 function trim(arr) {
55126 var start = 0;
55127 for (; start < arr.length; start++) {
55128 if (arr[start] !== '') break;
55129 }
55130
55131 var end = arr.length - 1;
55132 for (; end >= 0; end--) {
55133 if (arr[end] !== '') break;
55134 }
55135
55136 if (start > end) return [];
55137 return arr.slice(start, end - start + 1);
55138 }
55139
55140 var fromParts = trim(from.split('/'));
55141 var toParts = trim(to.split('/'));
55142
55143 var length = Math.min(fromParts.length, toParts.length);
55144 var samePartsLength = length;
55145 for (var i = 0; i < length; i++) {
55146 if (fromParts[i] !== toParts[i]) {
55147 samePartsLength = i;
55148 break;
55149 }
55150 }
55151
55152 var outputParts = [];
55153 for (var i = samePartsLength; i < fromParts.length; i++) {
55154 outputParts.push('..');
55155 }
55156
55157 outputParts = outputParts.concat(toParts.slice(samePartsLength));
55158
55159 return outputParts.join('/');
55160};
55161
55162exports.sep = '/';
55163exports.delimiter = ':';
55164
55165exports.dirname = function (path) {
55166 if (typeof path !== 'string') path = path + '';
55167 if (path.length === 0) return '.';
55168 var code = path.charCodeAt(0);
55169 var hasRoot = code === 47 /*/*/;
55170 var end = -1;
55171 var matchedSlash = true;
55172 for (var i = path.length - 1; i >= 1; --i) {
55173 code = path.charCodeAt(i);
55174 if (code === 47 /*/*/) {
55175 if (!matchedSlash) {
55176 end = i;
55177 break;
55178 }
55179 } else {
55180 // We saw the first non-path separator
55181 matchedSlash = false;
55182 }
55183 }
55184
55185 if (end === -1) return hasRoot ? '/' : '.';
55186 if (hasRoot && end === 1) {
55187 // return '//';
55188 // Backwards-compat fix:
55189 return '/';
55190 }
55191 return path.slice(0, end);
55192};
55193
55194function basename(path) {
55195 if (typeof path !== 'string') path = path + '';
55196
55197 var start = 0;
55198 var end = -1;
55199 var matchedSlash = true;
55200 var i;
55201
55202 for (i = path.length - 1; i >= 0; --i) {
55203 if (path.charCodeAt(i) === 47 /*/*/) {
55204 // If we reached a path separator that was not part of a set of path
55205 // separators at the end of the string, stop now
55206 if (!matchedSlash) {
55207 start = i + 1;
55208 break;
55209 }
55210 } else if (end === -1) {
55211 // We saw the first non-path separator, mark this as the end of our
55212 // path component
55213 matchedSlash = false;
55214 end = i + 1;
55215 }
55216 }
55217
55218 if (end === -1) return '';
55219 return path.slice(start, end);
55220}
55221
55222// Uses a mixed approach for backwards-compatibility, as ext behavior changed
55223// in new Node.js versions, so only basename() above is backported here
55224exports.basename = function (path, ext) {
55225 var f = basename(path);
55226 if (ext && f.substr(-1 * ext.length) === ext) {
55227 f = f.substr(0, f.length - ext.length);
55228 }
55229 return f;
55230};
55231
55232exports.extname = function (path) {
55233 if (typeof path !== 'string') path = path + '';
55234 var startDot = -1;
55235 var startPart = 0;
55236 var end = -1;
55237 var matchedSlash = true;
55238 // Track the state of characters (if any) we see before our first dot and
55239 // after any path separator we find
55240 var preDotState = 0;
55241 for (var i = path.length - 1; i >= 0; --i) {
55242 var code = path.charCodeAt(i);
55243 if (code === 47 /*/*/) {
55244 // If we reached a path separator that was not part of a set of path
55245 // separators at the end of the string, stop now
55246 if (!matchedSlash) {
55247 startPart = i + 1;
55248 break;
55249 }
55250 continue;
55251 }
55252 if (end === -1) {
55253 // We saw the first non-path separator, mark this as the end of our
55254 // extension
55255 matchedSlash = false;
55256 end = i + 1;
55257 }
55258 if (code === 46 /*.*/) {
55259 // If this is our first dot, mark it as the start of our extension
55260 if (startDot === -1)
55261 startDot = i;
55262 else if (preDotState !== 1)
55263 preDotState = 1;
55264 } else if (startDot !== -1) {
55265 // We saw a non-dot and non-path separator before our dot, so we should
55266 // have a good chance at having a non-empty extension
55267 preDotState = -1;
55268 }
55269 }
55270
55271 if (startDot === -1 || end === -1 ||
55272 // We saw a non-dot character immediately before the dot
55273 preDotState === 0 ||
55274 // The (right-most) trimmed path component is exactly '..'
55275 preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
55276 return '';
55277 }
55278 return path.slice(startDot, end);
55279};
55280
55281function filter (xs, f) {
55282 if (xs.filter) return xs.filter(f);
55283 var res = [];
55284 for (var i = 0; i < xs.length; i++) {
55285 if (f(xs[i], i, xs)) res.push(xs[i]);
55286 }
55287 return res;
55288}
55289
55290// String.prototype.substr - negative index don't work in IE8
55291var substr = 'ab'.substr(-1) === 'b'
55292 ? function (str, start, len) { return str.substr(start, len) }
55293 : function (str, start, len) {
55294 if (start < 0) start = str.length + start;
55295 return str.substr(start, len);
55296 }
55297;
55298
55299}).call(this,require('_process'))
55300},{"_process":265}],258:[function(require,module,exports){
55301exports.pbkdf2 = require('./lib/async')
55302exports.pbkdf2Sync = require('./lib/sync')
55303
55304},{"./lib/async":259,"./lib/sync":262}],259:[function(require,module,exports){
55305(function (process,global){
55306var checkParameters = require('./precondition')
55307var defaultEncoding = require('./default-encoding')
55308var sync = require('./sync')
55309var Buffer = require('safe-buffer').Buffer
55310
55311var ZERO_BUF
55312var subtle = global.crypto && global.crypto.subtle
55313var toBrowser = {
55314 'sha': 'SHA-1',
55315 'sha-1': 'SHA-1',
55316 'sha1': 'SHA-1',
55317 'sha256': 'SHA-256',
55318 'sha-256': 'SHA-256',
55319 'sha384': 'SHA-384',
55320 'sha-384': 'SHA-384',
55321 'sha-512': 'SHA-512',
55322 'sha512': 'SHA-512'
55323}
55324var checks = []
55325function checkNative (algo) {
55326 if (global.process && !global.process.browser) {
55327 return Promise.resolve(false)
55328 }
55329 if (!subtle || !subtle.importKey || !subtle.deriveBits) {
55330 return Promise.resolve(false)
55331 }
55332 if (checks[algo] !== undefined) {
55333 return checks[algo]
55334 }
55335 ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
55336 var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
55337 .then(function () {
55338 return true
55339 }).catch(function () {
55340 return false
55341 })
55342 checks[algo] = prom
55343 return prom
55344}
55345
55346function browserPbkdf2 (password, salt, iterations, length, algo) {
55347 return subtle.importKey(
55348 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits']
55349 ).then(function (key) {
55350 return subtle.deriveBits({
55351 name: 'PBKDF2',
55352 salt: salt,
55353 iterations: iterations,
55354 hash: {
55355 name: algo
55356 }
55357 }, key, length << 3)
55358 }).then(function (res) {
55359 return Buffer.from(res)
55360 })
55361}
55362
55363function resolvePromise (promise, callback) {
55364 promise.then(function (out) {
55365 process.nextTick(function () {
55366 callback(null, out)
55367 })
55368 }, function (e) {
55369 process.nextTick(function () {
55370 callback(e)
55371 })
55372 })
55373}
55374module.exports = function (password, salt, iterations, keylen, digest, callback) {
55375 if (typeof digest === 'function') {
55376 callback = digest
55377 digest = undefined
55378 }
55379
55380 digest = digest || 'sha1'
55381 var algo = toBrowser[digest.toLowerCase()]
55382
55383 if (!algo || typeof global.Promise !== 'function') {
55384 return process.nextTick(function () {
55385 var out
55386 try {
55387 out = sync(password, salt, iterations, keylen, digest)
55388 } catch (e) {
55389 return callback(e)
55390 }
55391 callback(null, out)
55392 })
55393 }
55394
55395 checkParameters(password, salt, iterations, keylen)
55396 if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
55397 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
55398 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
55399
55400 resolvePromise(checkNative(algo).then(function (resp) {
55401 if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)
55402
55403 return sync(password, salt, iterations, keylen, digest)
55404 }), callback)
55405}
55406
55407}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
55408},{"./default-encoding":260,"./precondition":261,"./sync":262,"_process":265,"safe-buffer":325}],260:[function(require,module,exports){
55409(function (process){
55410var defaultEncoding
55411/* istanbul ignore next */
55412if (process.browser) {
55413 defaultEncoding = 'utf-8'
55414} else {
55415 var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
55416
55417 defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
55418}
55419module.exports = defaultEncoding
55420
55421}).call(this,require('_process'))
55422},{"_process":265}],261:[function(require,module,exports){
55423(function (Buffer){
55424var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
55425
55426function checkBuffer (buf, name) {
55427 if (typeof buf !== 'string' && !Buffer.isBuffer(buf)) {
55428 throw new TypeError(name + ' must be a buffer or string')
55429 }
55430}
55431
55432module.exports = function (password, salt, iterations, keylen) {
55433 checkBuffer(password, 'Password')
55434 checkBuffer(salt, 'Salt')
55435
55436 if (typeof iterations !== 'number') {
55437 throw new TypeError('Iterations not a number')
55438 }
55439
55440 if (iterations < 0) {
55441 throw new TypeError('Bad iterations')
55442 }
55443
55444 if (typeof keylen !== 'number') {
55445 throw new TypeError('Key length not a number')
55446 }
55447
55448 if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
55449 throw new TypeError('Bad key length')
55450 }
55451}
55452
55453}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
55454},{"../../is-buffer/index.js":211}],262:[function(require,module,exports){
55455var md5 = require('create-hash/md5')
55456var RIPEMD160 = require('ripemd160')
55457var sha = require('sha.js')
55458
55459var checkParameters = require('./precondition')
55460var defaultEncoding = require('./default-encoding')
55461var Buffer = require('safe-buffer').Buffer
55462var ZEROS = Buffer.alloc(128)
55463var sizes = {
55464 md5: 16,
55465 sha1: 20,
55466 sha224: 28,
55467 sha256: 32,
55468 sha384: 48,
55469 sha512: 64,
55470 rmd160: 20,
55471 ripemd160: 20
55472}
55473
55474function Hmac (alg, key, saltLen) {
55475 var hash = getDigest(alg)
55476 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
55477
55478 if (key.length > blocksize) {
55479 key = hash(key)
55480 } else if (key.length < blocksize) {
55481 key = Buffer.concat([key, ZEROS], blocksize)
55482 }
55483
55484 var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
55485 var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
55486 for (var i = 0; i < blocksize; i++) {
55487 ipad[i] = key[i] ^ 0x36
55488 opad[i] = key[i] ^ 0x5C
55489 }
55490
55491 var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
55492 ipad.copy(ipad1, 0, 0, blocksize)
55493 this.ipad1 = ipad1
55494 this.ipad2 = ipad
55495 this.opad = opad
55496 this.alg = alg
55497 this.blocksize = blocksize
55498 this.hash = hash
55499 this.size = sizes[alg]
55500}
55501
55502Hmac.prototype.run = function (data, ipad) {
55503 data.copy(ipad, this.blocksize)
55504 var h = this.hash(ipad)
55505 h.copy(this.opad, this.blocksize)
55506 return this.hash(this.opad)
55507}
55508
55509function getDigest (alg) {
55510 function shaFunc (data) {
55511 return sha(alg).update(data).digest()
55512 }
55513 function rmd160Func (data) {
55514 return new RIPEMD160().update(data).digest()
55515 }
55516
55517 if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func
55518 if (alg === 'md5') return md5
55519 return shaFunc
55520}
55521
55522function pbkdf2 (password, salt, iterations, keylen, digest) {
55523 checkParameters(password, salt, iterations, keylen)
55524
55525 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
55526 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
55527
55528 digest = digest || 'sha1'
55529
55530 var hmac = new Hmac(digest, password, salt.length)
55531
55532 var DK = Buffer.allocUnsafe(keylen)
55533 var block1 = Buffer.allocUnsafe(salt.length + 4)
55534 salt.copy(block1, 0, 0, salt.length)
55535
55536 var destPos = 0
55537 var hLen = sizes[digest]
55538 var l = Math.ceil(keylen / hLen)
55539
55540 for (var i = 1; i <= l; i++) {
55541 block1.writeUInt32BE(i, salt.length)
55542
55543 var T = hmac.run(block1, hmac.ipad1)
55544 var U = T
55545
55546 for (var j = 1; j < iterations; j++) {
55547 U = hmac.run(U, hmac.ipad2)
55548 for (var k = 0; k < hLen; k++) T[k] ^= U[k]
55549 }
55550
55551 T.copy(DK, destPos)
55552 destPos += hLen
55553 }
55554
55555 return DK
55556}
55557
55558module.exports = pbkdf2
55559
55560},{"./default-encoding":260,"./precondition":261,"create-hash/md5":123,"ripemd160":324,"safe-buffer":325,"sha.js":328}],263:[function(require,module,exports){
55561(function (process){
55562// Generated by CoffeeScript 1.12.2
55563(function() {
55564 var getNanoSeconds, hrtime, loadTime, moduleLoadTime, nodeLoadTime, upTime;
55565
55566 if ((typeof performance !== "undefined" && performance !== null) && performance.now) {
55567 module.exports = function() {
55568 return performance.now();
55569 };
55570 } else if ((typeof process !== "undefined" && process !== null) && process.hrtime) {
55571 module.exports = function() {
55572 return (getNanoSeconds() - nodeLoadTime) / 1e6;
55573 };
55574 hrtime = process.hrtime;
55575 getNanoSeconds = function() {
55576 var hr;
55577 hr = hrtime();
55578 return hr[0] * 1e9 + hr[1];
55579 };
55580 moduleLoadTime = getNanoSeconds();
55581 upTime = process.uptime() * 1e9;
55582 nodeLoadTime = moduleLoadTime - upTime;
55583 } else if (Date.now) {
55584 module.exports = function() {
55585 return Date.now() - loadTime;
55586 };
55587 loadTime = Date.now();
55588 } else {
55589 module.exports = function() {
55590 return new Date().getTime() - loadTime;
55591 };
55592 loadTime = new Date().getTime();
55593 }
55594
55595}).call(this);
55596
55597
55598
55599}).call(this,require('_process'))
55600},{"_process":265}],264:[function(require,module,exports){
55601(function (process){
55602'use strict';
55603
55604if (!process.version ||
55605 process.version.indexOf('v0.') === 0 ||
55606 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
55607 module.exports = { nextTick: nextTick };
55608} else {
55609 module.exports = process
55610}
55611
55612function nextTick(fn, arg1, arg2, arg3) {
55613 if (typeof fn !== 'function') {
55614 throw new TypeError('"callback" argument must be a function');
55615 }
55616 var len = arguments.length;
55617 var args, i;
55618 switch (len) {
55619 case 0:
55620 case 1:
55621 return process.nextTick(fn);
55622 case 2:
55623 return process.nextTick(function afterTickOne() {
55624 fn.call(null, arg1);
55625 });
55626 case 3:
55627 return process.nextTick(function afterTickTwo() {
55628 fn.call(null, arg1, arg2);
55629 });
55630 case 4:
55631 return process.nextTick(function afterTickThree() {
55632 fn.call(null, arg1, arg2, arg3);
55633 });
55634 default:
55635 args = new Array(len - 1);
55636 i = 0;
55637 while (i < args.length) {
55638 args[i++] = arguments[i];
55639 }
55640 return process.nextTick(function afterTick() {
55641 fn.apply(null, args);
55642 });
55643 }
55644}
55645
55646
55647}).call(this,require('_process'))
55648},{"_process":265}],265:[function(require,module,exports){
55649// shim for using process in browser
55650var process = module.exports = {};
55651
55652// cached from whatever global is present so that test runners that stub it
55653// don't break things. But we need to wrap it in a try catch in case it is
55654// wrapped in strict mode code which doesn't define any globals. It's inside a
55655// function because try/catches deoptimize in certain engines.
55656
55657var cachedSetTimeout;
55658var cachedClearTimeout;
55659
55660function defaultSetTimout() {
55661 throw new Error('setTimeout has not been defined');
55662}
55663function defaultClearTimeout () {
55664 throw new Error('clearTimeout has not been defined');
55665}
55666(function () {
55667 try {
55668 if (typeof setTimeout === 'function') {
55669 cachedSetTimeout = setTimeout;
55670 } else {
55671 cachedSetTimeout = defaultSetTimout;
55672 }
55673 } catch (e) {
55674 cachedSetTimeout = defaultSetTimout;
55675 }
55676 try {
55677 if (typeof clearTimeout === 'function') {
55678 cachedClearTimeout = clearTimeout;
55679 } else {
55680 cachedClearTimeout = defaultClearTimeout;
55681 }
55682 } catch (e) {
55683 cachedClearTimeout = defaultClearTimeout;
55684 }
55685} ())
55686function runTimeout(fun) {
55687 if (cachedSetTimeout === setTimeout) {
55688 //normal enviroments in sane situations
55689 return setTimeout(fun, 0);
55690 }
55691 // if setTimeout wasn't available but was latter defined
55692 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
55693 cachedSetTimeout = setTimeout;
55694 return setTimeout(fun, 0);
55695 }
55696 try {
55697 // when when somebody has screwed with setTimeout but no I.E. maddness
55698 return cachedSetTimeout(fun, 0);
55699 } catch(e){
55700 try {
55701 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
55702 return cachedSetTimeout.call(null, fun, 0);
55703 } catch(e){
55704 // 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
55705 return cachedSetTimeout.call(this, fun, 0);
55706 }
55707 }
55708
55709
55710}
55711function runClearTimeout(marker) {
55712 if (cachedClearTimeout === clearTimeout) {
55713 //normal enviroments in sane situations
55714 return clearTimeout(marker);
55715 }
55716 // if clearTimeout wasn't available but was latter defined
55717 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
55718 cachedClearTimeout = clearTimeout;
55719 return clearTimeout(marker);
55720 }
55721 try {
55722 // when when somebody has screwed with setTimeout but no I.E. maddness
55723 return cachedClearTimeout(marker);
55724 } catch (e){
55725 try {
55726 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
55727 return cachedClearTimeout.call(null, marker);
55728 } catch (e){
55729 // 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.
55730 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
55731 return cachedClearTimeout.call(this, marker);
55732 }
55733 }
55734
55735
55736
55737}
55738var queue = [];
55739var draining = false;
55740var currentQueue;
55741var queueIndex = -1;
55742
55743function cleanUpNextTick() {
55744 if (!draining || !currentQueue) {
55745 return;
55746 }
55747 draining = false;
55748 if (currentQueue.length) {
55749 queue = currentQueue.concat(queue);
55750 } else {
55751 queueIndex = -1;
55752 }
55753 if (queue.length) {
55754 drainQueue();
55755 }
55756}
55757
55758function drainQueue() {
55759 if (draining) {
55760 return;
55761 }
55762 var timeout = runTimeout(cleanUpNextTick);
55763 draining = true;
55764
55765 var len = queue.length;
55766 while(len) {
55767 currentQueue = queue;
55768 queue = [];
55769 while (++queueIndex < len) {
55770 if (currentQueue) {
55771 currentQueue[queueIndex].run();
55772 }
55773 }
55774 queueIndex = -1;
55775 len = queue.length;
55776 }
55777 currentQueue = null;
55778 draining = false;
55779 runClearTimeout(timeout);
55780}
55781
55782process.nextTick = function (fun) {
55783 var args = new Array(arguments.length - 1);
55784 if (arguments.length > 1) {
55785 for (var i = 1; i < arguments.length; i++) {
55786 args[i - 1] = arguments[i];
55787 }
55788 }
55789 queue.push(new Item(fun, args));
55790 if (queue.length === 1 && !draining) {
55791 runTimeout(drainQueue);
55792 }
55793};
55794
55795// v8 likes predictible objects
55796function Item(fun, array) {
55797 this.fun = fun;
55798 this.array = array;
55799}
55800Item.prototype.run = function () {
55801 this.fun.apply(null, this.array);
55802};
55803process.title = 'browser';
55804process.browser = true;
55805process.env = {};
55806process.argv = [];
55807process.version = ''; // empty string to avoid regexp issues
55808process.versions = {};
55809
55810function noop() {}
55811
55812process.on = noop;
55813process.addListener = noop;
55814process.once = noop;
55815process.off = noop;
55816process.removeListener = noop;
55817process.removeAllListeners = noop;
55818process.emit = noop;
55819process.prependListener = noop;
55820process.prependOnceListener = noop;
55821
55822process.listeners = function (name) { return [] }
55823
55824process.binding = function (name) {
55825 throw new Error('process.binding is not supported');
55826};
55827
55828process.cwd = function () { return '/' };
55829process.chdir = function (dir) {
55830 throw new Error('process.chdir is not supported');
55831};
55832process.umask = function() { return 0; };
55833
55834},{}],266:[function(require,module,exports){
55835module.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"]
55836},{}],267:[function(require,module,exports){
55837/*eslint no-var:0, prefer-arrow-callback: 0, object-shorthand: 0 */
55838'use strict';
55839
55840
55841var Punycode = require('punycode');
55842
55843
55844var internals = {};
55845
55846
55847//
55848// Read rules from file.
55849//
55850internals.rules = require('./data/rules.json').map(function (rule) {
55851
55852 return {
55853 rule: rule,
55854 suffix: rule.replace(/^(\*\.|\!)/, ''),
55855 punySuffix: -1,
55856 wildcard: rule.charAt(0) === '*',
55857 exception: rule.charAt(0) === '!'
55858 };
55859});
55860
55861
55862//
55863// Check is given string ends with `suffix`.
55864//
55865internals.endsWith = function (str, suffix) {
55866
55867 return str.indexOf(suffix, str.length - suffix.length) !== -1;
55868};
55869
55870
55871//
55872// Find rule for a given domain.
55873//
55874internals.findRule = function (domain) {
55875
55876 var punyDomain = Punycode.toASCII(domain);
55877 return internals.rules.reduce(function (memo, rule) {
55878
55879 if (rule.punySuffix === -1){
55880 rule.punySuffix = Punycode.toASCII(rule.suffix);
55881 }
55882 if (!internals.endsWith(punyDomain, '.' + rule.punySuffix) && punyDomain !== rule.punySuffix) {
55883 return memo;
55884 }
55885 // This has been commented out as it never seems to run. This is because
55886 // sub tlds always appear after their parents and we never find a shorter
55887 // match.
55888 //if (memo) {
55889 // var memoSuffix = Punycode.toASCII(memo.suffix);
55890 // if (memoSuffix.length >= punySuffix.length) {
55891 // return memo;
55892 // }
55893 //}
55894 return rule;
55895 }, null);
55896};
55897
55898
55899//
55900// Error codes and messages.
55901//
55902exports.errorCodes = {
55903 DOMAIN_TOO_SHORT: 'Domain name too short.',
55904 DOMAIN_TOO_LONG: 'Domain name too long. It should be no more than 255 chars.',
55905 LABEL_STARTS_WITH_DASH: 'Domain name label can not start with a dash.',
55906 LABEL_ENDS_WITH_DASH: 'Domain name label can not end with a dash.',
55907 LABEL_TOO_LONG: 'Domain name label should be at most 63 chars long.',
55908 LABEL_TOO_SHORT: 'Domain name label should be at least 1 character long.',
55909 LABEL_INVALID_CHARS: 'Domain name label can only contain alphanumeric characters or dashes.'
55910};
55911
55912
55913//
55914// Validate domain name and throw if not valid.
55915//
55916// From wikipedia:
55917//
55918// Hostnames are composed of series of labels concatenated with dots, as are all
55919// domain names. Each label must be between 1 and 63 characters long, and the
55920// entire hostname (including the delimiting dots) has a maximum of 255 chars.
55921//
55922// Allowed chars:
55923//
55924// * `a-z`
55925// * `0-9`
55926// * `-` but not as a starting or ending character
55927// * `.` as a separator for the textual portions of a domain name
55928//
55929// * http://en.wikipedia.org/wiki/Domain_name
55930// * http://en.wikipedia.org/wiki/Hostname
55931//
55932internals.validate = function (input) {
55933
55934 // Before we can validate we need to take care of IDNs with unicode chars.
55935 var ascii = Punycode.toASCII(input);
55936
55937 if (ascii.length < 1) {
55938 return 'DOMAIN_TOO_SHORT';
55939 }
55940 if (ascii.length > 255) {
55941 return 'DOMAIN_TOO_LONG';
55942 }
55943
55944 // Check each part's length and allowed chars.
55945 var labels = ascii.split('.');
55946 var label;
55947
55948 for (var i = 0; i < labels.length; ++i) {
55949 label = labels[i];
55950 if (!label.length) {
55951 return 'LABEL_TOO_SHORT';
55952 }
55953 if (label.length > 63) {
55954 return 'LABEL_TOO_LONG';
55955 }
55956 if (label.charAt(0) === '-') {
55957 return 'LABEL_STARTS_WITH_DASH';
55958 }
55959 if (label.charAt(label.length - 1) === '-') {
55960 return 'LABEL_ENDS_WITH_DASH';
55961 }
55962 if (!/^[a-z0-9\-]+$/.test(label)) {
55963 return 'LABEL_INVALID_CHARS';
55964 }
55965 }
55966};
55967
55968
55969//
55970// Public API
55971//
55972
55973
55974//
55975// Parse domain.
55976//
55977exports.parse = function (input) {
55978
55979 if (typeof input !== 'string') {
55980 throw new TypeError('Domain name must be a string.');
55981 }
55982
55983 // Force domain to lowercase.
55984 var domain = input.slice(0).toLowerCase();
55985
55986 // Handle FQDN.
55987 // TODO: Simply remove trailing dot?
55988 if (domain.charAt(domain.length - 1) === '.') {
55989 domain = domain.slice(0, domain.length - 1);
55990 }
55991
55992 // Validate and sanitise input.
55993 var error = internals.validate(domain);
55994 if (error) {
55995 return {
55996 input: input,
55997 error: {
55998 message: exports.errorCodes[error],
55999 code: error
56000 }
56001 };
56002 }
56003
56004 var parsed = {
56005 input: input,
56006 tld: null,
56007 sld: null,
56008 domain: null,
56009 subdomain: null,
56010 listed: false
56011 };
56012
56013 var domainParts = domain.split('.');
56014
56015 // Non-Internet TLD
56016 if (domainParts[domainParts.length - 1] === 'local') {
56017 return parsed;
56018 }
56019
56020 var handlePunycode = function () {
56021
56022 if (!/xn--/.test(domain)) {
56023 return parsed;
56024 }
56025 if (parsed.domain) {
56026 parsed.domain = Punycode.toASCII(parsed.domain);
56027 }
56028 if (parsed.subdomain) {
56029 parsed.subdomain = Punycode.toASCII(parsed.subdomain);
56030 }
56031 return parsed;
56032 };
56033
56034 var rule = internals.findRule(domain);
56035
56036 // Unlisted tld.
56037 if (!rule) {
56038 if (domainParts.length < 2) {
56039 return parsed;
56040 }
56041 parsed.tld = domainParts.pop();
56042 parsed.sld = domainParts.pop();
56043 parsed.domain = [parsed.sld, parsed.tld].join('.');
56044 if (domainParts.length) {
56045 parsed.subdomain = domainParts.pop();
56046 }
56047 return handlePunycode();
56048 }
56049
56050 // At this point we know the public suffix is listed.
56051 parsed.listed = true;
56052
56053 var tldParts = rule.suffix.split('.');
56054 var privateParts = domainParts.slice(0, domainParts.length - tldParts.length);
56055
56056 if (rule.exception) {
56057 privateParts.push(tldParts.shift());
56058 }
56059
56060 parsed.tld = tldParts.join('.');
56061
56062 if (!privateParts.length) {
56063 return handlePunycode();
56064 }
56065
56066 if (rule.wildcard) {
56067 tldParts.unshift(privateParts.pop());
56068 parsed.tld = tldParts.join('.');
56069 }
56070
56071 if (!privateParts.length) {
56072 return handlePunycode();
56073 }
56074
56075 parsed.sld = privateParts.pop();
56076 parsed.domain = [parsed.sld, parsed.tld].join('.');
56077
56078 if (privateParts.length) {
56079 parsed.subdomain = privateParts.join('.');
56080 }
56081
56082 return handlePunycode();
56083};
56084
56085
56086//
56087// Get domain.
56088//
56089exports.get = function (domain) {
56090
56091 if (!domain) {
56092 return null;
56093 }
56094 return exports.parse(domain).domain || null;
56095};
56096
56097
56098//
56099// Check whether domain belongs to a known public suffix.
56100//
56101exports.isValid = function (domain) {
56102
56103 var parsed = exports.parse(domain);
56104 return Boolean(parsed.domain && parsed.listed);
56105};
56106
56107},{"./data/rules.json":266,"punycode":274}],268:[function(require,module,exports){
56108exports.publicEncrypt = require('./publicEncrypt')
56109exports.privateDecrypt = require('./privateDecrypt')
56110
56111exports.privateEncrypt = function privateEncrypt (key, buf) {
56112 return exports.publicEncrypt(key, buf, true)
56113}
56114
56115exports.publicDecrypt = function publicDecrypt (key, buf) {
56116 return exports.privateDecrypt(key, buf, true)
56117}
56118
56119},{"./privateDecrypt":270,"./publicEncrypt":271}],269:[function(require,module,exports){
56120var createHash = require('create-hash')
56121var Buffer = require('safe-buffer').Buffer
56122
56123module.exports = function (seed, len) {
56124 var t = Buffer.alloc(0)
56125 var i = 0
56126 var c
56127 while (t.length < len) {
56128 c = i2ops(i++)
56129 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])
56130 }
56131 return t.slice(0, len)
56132}
56133
56134function i2ops (c) {
56135 var out = Buffer.allocUnsafe(4)
56136 out.writeUInt32BE(c, 0)
56137 return out
56138}
56139
56140},{"create-hash":122,"safe-buffer":325}],270:[function(require,module,exports){
56141var parseKeys = require('parse-asn1')
56142var mgf = require('./mgf')
56143var xor = require('./xor')
56144var BN = require('bn.js')
56145var crt = require('browserify-rsa')
56146var createHash = require('create-hash')
56147var withPublic = require('./withPublic')
56148var Buffer = require('safe-buffer').Buffer
56149
56150module.exports = function privateDecrypt (privateKey, enc, reverse) {
56151 var padding
56152 if (privateKey.padding) {
56153 padding = privateKey.padding
56154 } else if (reverse) {
56155 padding = 1
56156 } else {
56157 padding = 4
56158 }
56159
56160 var key = parseKeys(privateKey)
56161 var k = key.modulus.byteLength()
56162 if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
56163 throw new Error('decryption error')
56164 }
56165 var msg
56166 if (reverse) {
56167 msg = withPublic(new BN(enc), key)
56168 } else {
56169 msg = crt(enc, key)
56170 }
56171 var zBuffer = Buffer.alloc(k - msg.length)
56172 msg = Buffer.concat([zBuffer, msg], k)
56173 if (padding === 4) {
56174 return oaep(key, msg)
56175 } else if (padding === 1) {
56176 return pkcs1(key, msg, reverse)
56177 } else if (padding === 3) {
56178 return msg
56179 } else {
56180 throw new Error('unknown padding')
56181 }
56182}
56183
56184function oaep (key, msg) {
56185 var k = key.modulus.byteLength()
56186 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
56187 var hLen = iHash.length
56188 if (msg[0] !== 0) {
56189 throw new Error('decryption error')
56190 }
56191 var maskedSeed = msg.slice(1, hLen + 1)
56192 var maskedDb = msg.slice(hLen + 1)
56193 var seed = xor(maskedSeed, mgf(maskedDb, hLen))
56194 var db = xor(maskedDb, mgf(seed, k - hLen - 1))
56195 if (compare(iHash, db.slice(0, hLen))) {
56196 throw new Error('decryption error')
56197 }
56198 var i = hLen
56199 while (db[i] === 0) {
56200 i++
56201 }
56202 if (db[i++] !== 1) {
56203 throw new Error('decryption error')
56204 }
56205 return db.slice(i)
56206}
56207
56208function pkcs1 (key, msg, reverse) {
56209 var p1 = msg.slice(0, 2)
56210 var i = 2
56211 var status = 0
56212 while (msg[i++] !== 0) {
56213 if (i >= msg.length) {
56214 status++
56215 break
56216 }
56217 }
56218 var ps = msg.slice(2, i - 1)
56219
56220 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
56221 status++
56222 }
56223 if (ps.length < 8) {
56224 status++
56225 }
56226 if (status) {
56227 throw new Error('decryption error')
56228 }
56229 return msg.slice(i)
56230}
56231function compare (a, b) {
56232 a = Buffer.from(a)
56233 b = Buffer.from(b)
56234 var dif = 0
56235 var len = a.length
56236 if (a.length !== b.length) {
56237 dif++
56238 len = Math.min(a.length, b.length)
56239 }
56240 var i = -1
56241 while (++i < len) {
56242 dif += (a[i] ^ b[i])
56243 }
56244 return dif
56245}
56246
56247},{"./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){
56248var parseKeys = require('parse-asn1')
56249var randomBytes = require('randombytes')
56250var createHash = require('create-hash')
56251var mgf = require('./mgf')
56252var xor = require('./xor')
56253var BN = require('bn.js')
56254var withPublic = require('./withPublic')
56255var crt = require('browserify-rsa')
56256var Buffer = require('safe-buffer').Buffer
56257
56258module.exports = function publicEncrypt (publicKey, msg, reverse) {
56259 var padding
56260 if (publicKey.padding) {
56261 padding = publicKey.padding
56262 } else if (reverse) {
56263 padding = 1
56264 } else {
56265 padding = 4
56266 }
56267 var key = parseKeys(publicKey)
56268 var paddedMsg
56269 if (padding === 4) {
56270 paddedMsg = oaep(key, msg)
56271 } else if (padding === 1) {
56272 paddedMsg = pkcs1(key, msg, reverse)
56273 } else if (padding === 3) {
56274 paddedMsg = new BN(msg)
56275 if (paddedMsg.cmp(key.modulus) >= 0) {
56276 throw new Error('data too long for modulus')
56277 }
56278 } else {
56279 throw new Error('unknown padding')
56280 }
56281 if (reverse) {
56282 return crt(paddedMsg, key)
56283 } else {
56284 return withPublic(paddedMsg, key)
56285 }
56286}
56287
56288function oaep (key, msg) {
56289 var k = key.modulus.byteLength()
56290 var mLen = msg.length
56291 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
56292 var hLen = iHash.length
56293 var hLen2 = 2 * hLen
56294 if (mLen > k - hLen2 - 2) {
56295 throw new Error('message too long')
56296 }
56297 var ps = Buffer.alloc(k - mLen - hLen2 - 2)
56298 var dblen = k - hLen - 1
56299 var seed = randomBytes(hLen)
56300 var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))
56301 var maskedSeed = xor(seed, mgf(maskedDb, hLen))
56302 return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))
56303}
56304function pkcs1 (key, msg, reverse) {
56305 var mLen = msg.length
56306 var k = key.modulus.byteLength()
56307 if (mLen > k - 11) {
56308 throw new Error('message too long')
56309 }
56310 var ps
56311 if (reverse) {
56312 ps = Buffer.alloc(k - mLen - 3, 0xff)
56313 } else {
56314 ps = nonZero(k - mLen - 3)
56315 }
56316 return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))
56317}
56318function nonZero (len) {
56319 var out = Buffer.allocUnsafe(len)
56320 var i = 0
56321 var cache = randomBytes(len * 2)
56322 var cur = 0
56323 var num
56324 while (i < len) {
56325 if (cur === cache.length) {
56326 cache = randomBytes(len * 2)
56327 cur = 0
56328 }
56329 num = cache[cur++]
56330 if (num) {
56331 out[i++] = num
56332 }
56333 }
56334 return out
56335}
56336
56337},{"./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){
56338var BN = require('bn.js')
56339var Buffer = require('safe-buffer').Buffer
56340
56341function withPublic (paddedMsg, key) {
56342 return Buffer.from(paddedMsg
56343 .toRed(BN.mont(key.modulus))
56344 .redPow(new BN(key.publicExponent))
56345 .fromRed()
56346 .toArray())
56347}
56348
56349module.exports = withPublic
56350
56351},{"bn.js":80,"safe-buffer":325}],273:[function(require,module,exports){
56352module.exports = function xor (a, b) {
56353 var len = a.length
56354 var i = -1
56355 while (++i < len) {
56356 a[i] ^= b[i]
56357 }
56358 return a
56359}
56360
56361},{}],274:[function(require,module,exports){
56362(function (global){
56363/*! https://mths.be/punycode v1.4.1 by @mathias */
56364;(function(root) {
56365
56366 /** Detect free variables */
56367 var freeExports = typeof exports == 'object' && exports &&
56368 !exports.nodeType && exports;
56369 var freeModule = typeof module == 'object' && module &&
56370 !module.nodeType && module;
56371 var freeGlobal = typeof global == 'object' && global;
56372 if (
56373 freeGlobal.global === freeGlobal ||
56374 freeGlobal.window === freeGlobal ||
56375 freeGlobal.self === freeGlobal
56376 ) {
56377 root = freeGlobal;
56378 }
56379
56380 /**
56381 * The `punycode` object.
56382 * @name punycode
56383 * @type Object
56384 */
56385 var punycode,
56386
56387 /** Highest positive signed 32-bit float value */
56388 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
56389
56390 /** Bootstring parameters */
56391 base = 36,
56392 tMin = 1,
56393 tMax = 26,
56394 skew = 38,
56395 damp = 700,
56396 initialBias = 72,
56397 initialN = 128, // 0x80
56398 delimiter = '-', // '\x2D'
56399
56400 /** Regular expressions */
56401 regexPunycode = /^xn--/,
56402 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
56403 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
56404
56405 /** Error messages */
56406 errors = {
56407 'overflow': 'Overflow: input needs wider integers to process',
56408 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
56409 'invalid-input': 'Invalid input'
56410 },
56411
56412 /** Convenience shortcuts */
56413 baseMinusTMin = base - tMin,
56414 floor = Math.floor,
56415 stringFromCharCode = String.fromCharCode,
56416
56417 /** Temporary variable */
56418 key;
56419
56420 /*--------------------------------------------------------------------------*/
56421
56422 /**
56423 * A generic error utility function.
56424 * @private
56425 * @param {String} type The error type.
56426 * @returns {Error} Throws a `RangeError` with the applicable error message.
56427 */
56428 function error(type) {
56429 throw new RangeError(errors[type]);
56430 }
56431
56432 /**
56433 * A generic `Array#map` utility function.
56434 * @private
56435 * @param {Array} array The array to iterate over.
56436 * @param {Function} callback The function that gets called for every array
56437 * item.
56438 * @returns {Array} A new array of values returned by the callback function.
56439 */
56440 function map(array, fn) {
56441 var length = array.length;
56442 var result = [];
56443 while (length--) {
56444 result[length] = fn(array[length]);
56445 }
56446 return result;
56447 }
56448
56449 /**
56450 * A simple `Array#map`-like wrapper to work with domain name strings or email
56451 * addresses.
56452 * @private
56453 * @param {String} domain The domain name or email address.
56454 * @param {Function} callback The function that gets called for every
56455 * character.
56456 * @returns {Array} A new string of characters returned by the callback
56457 * function.
56458 */
56459 function mapDomain(string, fn) {
56460 var parts = string.split('@');
56461 var result = '';
56462 if (parts.length > 1) {
56463 // In email addresses, only the domain name should be punycoded. Leave
56464 // the local part (i.e. everything up to `@`) intact.
56465 result = parts[0] + '@';
56466 string = parts[1];
56467 }
56468 // Avoid `split(regex)` for IE8 compatibility. See #17.
56469 string = string.replace(regexSeparators, '\x2E');
56470 var labels = string.split('.');
56471 var encoded = map(labels, fn).join('.');
56472 return result + encoded;
56473 }
56474
56475 /**
56476 * Creates an array containing the numeric code points of each Unicode
56477 * character in the string. While JavaScript uses UCS-2 internally,
56478 * this function will convert a pair of surrogate halves (each of which
56479 * UCS-2 exposes as separate characters) into a single code point,
56480 * matching UTF-16.
56481 * @see `punycode.ucs2.encode`
56482 * @see <https://mathiasbynens.be/notes/javascript-encoding>
56483 * @memberOf punycode.ucs2
56484 * @name decode
56485 * @param {String} string The Unicode input string (UCS-2).
56486 * @returns {Array} The new array of code points.
56487 */
56488 function ucs2decode(string) {
56489 var output = [],
56490 counter = 0,
56491 length = string.length,
56492 value,
56493 extra;
56494 while (counter < length) {
56495 value = string.charCodeAt(counter++);
56496 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
56497 // high surrogate, and there is a next character
56498 extra = string.charCodeAt(counter++);
56499 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
56500 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
56501 } else {
56502 // unmatched surrogate; only append this code unit, in case the next
56503 // code unit is the high surrogate of a surrogate pair
56504 output.push(value);
56505 counter--;
56506 }
56507 } else {
56508 output.push(value);
56509 }
56510 }
56511 return output;
56512 }
56513
56514 /**
56515 * Creates a string based on an array of numeric code points.
56516 * @see `punycode.ucs2.decode`
56517 * @memberOf punycode.ucs2
56518 * @name encode
56519 * @param {Array} codePoints The array of numeric code points.
56520 * @returns {String} The new Unicode string (UCS-2).
56521 */
56522 function ucs2encode(array) {
56523 return map(array, function(value) {
56524 var output = '';
56525 if (value > 0xFFFF) {
56526 value -= 0x10000;
56527 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
56528 value = 0xDC00 | value & 0x3FF;
56529 }
56530 output += stringFromCharCode(value);
56531 return output;
56532 }).join('');
56533 }
56534
56535 /**
56536 * Converts a basic code point into a digit/integer.
56537 * @see `digitToBasic()`
56538 * @private
56539 * @param {Number} codePoint The basic numeric code point value.
56540 * @returns {Number} The numeric value of a basic code point (for use in
56541 * representing integers) in the range `0` to `base - 1`, or `base` if
56542 * the code point does not represent a value.
56543 */
56544 function basicToDigit(codePoint) {
56545 if (codePoint - 48 < 10) {
56546 return codePoint - 22;
56547 }
56548 if (codePoint - 65 < 26) {
56549 return codePoint - 65;
56550 }
56551 if (codePoint - 97 < 26) {
56552 return codePoint - 97;
56553 }
56554 return base;
56555 }
56556
56557 /**
56558 * Converts a digit/integer into a basic code point.
56559 * @see `basicToDigit()`
56560 * @private
56561 * @param {Number} digit The numeric value of a basic code point.
56562 * @returns {Number} The basic code point whose value (when used for
56563 * representing integers) is `digit`, which needs to be in the range
56564 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
56565 * used; else, the lowercase form is used. The behavior is undefined
56566 * if `flag` is non-zero and `digit` has no uppercase form.
56567 */
56568 function digitToBasic(digit, flag) {
56569 // 0..25 map to ASCII a..z or A..Z
56570 // 26..35 map to ASCII 0..9
56571 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
56572 }
56573
56574 /**
56575 * Bias adaptation function as per section 3.4 of RFC 3492.
56576 * https://tools.ietf.org/html/rfc3492#section-3.4
56577 * @private
56578 */
56579 function adapt(delta, numPoints, firstTime) {
56580 var k = 0;
56581 delta = firstTime ? floor(delta / damp) : delta >> 1;
56582 delta += floor(delta / numPoints);
56583 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
56584 delta = floor(delta / baseMinusTMin);
56585 }
56586 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
56587 }
56588
56589 /**
56590 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
56591 * symbols.
56592 * @memberOf punycode
56593 * @param {String} input The Punycode string of ASCII-only symbols.
56594 * @returns {String} The resulting string of Unicode symbols.
56595 */
56596 function decode(input) {
56597 // Don't use UCS-2
56598 var output = [],
56599 inputLength = input.length,
56600 out,
56601 i = 0,
56602 n = initialN,
56603 bias = initialBias,
56604 basic,
56605 j,
56606 index,
56607 oldi,
56608 w,
56609 k,
56610 digit,
56611 t,
56612 /** Cached calculation results */
56613 baseMinusT;
56614
56615 // Handle the basic code points: let `basic` be the number of input code
56616 // points before the last delimiter, or `0` if there is none, then copy
56617 // the first basic code points to the output.
56618
56619 basic = input.lastIndexOf(delimiter);
56620 if (basic < 0) {
56621 basic = 0;
56622 }
56623
56624 for (j = 0; j < basic; ++j) {
56625 // if it's not a basic code point
56626 if (input.charCodeAt(j) >= 0x80) {
56627 error('not-basic');
56628 }
56629 output.push(input.charCodeAt(j));
56630 }
56631
56632 // Main decoding loop: start just after the last delimiter if any basic code
56633 // points were copied; start at the beginning otherwise.
56634
56635 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
56636
56637 // `index` is the index of the next character to be consumed.
56638 // Decode a generalized variable-length integer into `delta`,
56639 // which gets added to `i`. The overflow checking is easier
56640 // if we increase `i` as we go, then subtract off its starting
56641 // value at the end to obtain `delta`.
56642 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
56643
56644 if (index >= inputLength) {
56645 error('invalid-input');
56646 }
56647
56648 digit = basicToDigit(input.charCodeAt(index++));
56649
56650 if (digit >= base || digit > floor((maxInt - i) / w)) {
56651 error('overflow');
56652 }
56653
56654 i += digit * w;
56655 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
56656
56657 if (digit < t) {
56658 break;
56659 }
56660
56661 baseMinusT = base - t;
56662 if (w > floor(maxInt / baseMinusT)) {
56663 error('overflow');
56664 }
56665
56666 w *= baseMinusT;
56667
56668 }
56669
56670 out = output.length + 1;
56671 bias = adapt(i - oldi, out, oldi == 0);
56672
56673 // `i` was supposed to wrap around from `out` to `0`,
56674 // incrementing `n` each time, so we'll fix that now:
56675 if (floor(i / out) > maxInt - n) {
56676 error('overflow');
56677 }
56678
56679 n += floor(i / out);
56680 i %= out;
56681
56682 // Insert `n` at position `i` of the output
56683 output.splice(i++, 0, n);
56684
56685 }
56686
56687 return ucs2encode(output);
56688 }
56689
56690 /**
56691 * Converts a string of Unicode symbols (e.g. a domain name label) to a
56692 * Punycode string of ASCII-only symbols.
56693 * @memberOf punycode
56694 * @param {String} input The string of Unicode symbols.
56695 * @returns {String} The resulting Punycode string of ASCII-only symbols.
56696 */
56697 function encode(input) {
56698 var n,
56699 delta,
56700 handledCPCount,
56701 basicLength,
56702 bias,
56703 j,
56704 m,
56705 q,
56706 k,
56707 t,
56708 currentValue,
56709 output = [],
56710 /** `inputLength` will hold the number of code points in `input`. */
56711 inputLength,
56712 /** Cached calculation results */
56713 handledCPCountPlusOne,
56714 baseMinusT,
56715 qMinusT;
56716
56717 // Convert the input in UCS-2 to Unicode
56718 input = ucs2decode(input);
56719
56720 // Cache the length
56721 inputLength = input.length;
56722
56723 // Initialize the state
56724 n = initialN;
56725 delta = 0;
56726 bias = initialBias;
56727
56728 // Handle the basic code points
56729 for (j = 0; j < inputLength; ++j) {
56730 currentValue = input[j];
56731 if (currentValue < 0x80) {
56732 output.push(stringFromCharCode(currentValue));
56733 }
56734 }
56735
56736 handledCPCount = basicLength = output.length;
56737
56738 // `handledCPCount` is the number of code points that have been handled;
56739 // `basicLength` is the number of basic code points.
56740
56741 // Finish the basic string - if it is not empty - with a delimiter
56742 if (basicLength) {
56743 output.push(delimiter);
56744 }
56745
56746 // Main encoding loop:
56747 while (handledCPCount < inputLength) {
56748
56749 // All non-basic code points < n have been handled already. Find the next
56750 // larger one:
56751 for (m = maxInt, j = 0; j < inputLength; ++j) {
56752 currentValue = input[j];
56753 if (currentValue >= n && currentValue < m) {
56754 m = currentValue;
56755 }
56756 }
56757
56758 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
56759 // but guard against overflow
56760 handledCPCountPlusOne = handledCPCount + 1;
56761 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
56762 error('overflow');
56763 }
56764
56765 delta += (m - n) * handledCPCountPlusOne;
56766 n = m;
56767
56768 for (j = 0; j < inputLength; ++j) {
56769 currentValue = input[j];
56770
56771 if (currentValue < n && ++delta > maxInt) {
56772 error('overflow');
56773 }
56774
56775 if (currentValue == n) {
56776 // Represent delta as a generalized variable-length integer
56777 for (q = delta, k = base; /* no condition */; k += base) {
56778 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
56779 if (q < t) {
56780 break;
56781 }
56782 qMinusT = q - t;
56783 baseMinusT = base - t;
56784 output.push(
56785 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
56786 );
56787 q = floor(qMinusT / baseMinusT);
56788 }
56789
56790 output.push(stringFromCharCode(digitToBasic(q, 0)));
56791 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
56792 delta = 0;
56793 ++handledCPCount;
56794 }
56795 }
56796
56797 ++delta;
56798 ++n;
56799
56800 }
56801 return output.join('');
56802 }
56803
56804 /**
56805 * Converts a Punycode string representing a domain name or an email address
56806 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
56807 * it doesn't matter if you call it on a string that has already been
56808 * converted to Unicode.
56809 * @memberOf punycode
56810 * @param {String} input The Punycoded domain name or email address to
56811 * convert to Unicode.
56812 * @returns {String} The Unicode representation of the given Punycode
56813 * string.
56814 */
56815 function toUnicode(input) {
56816 return mapDomain(input, function(string) {
56817 return regexPunycode.test(string)
56818 ? decode(string.slice(4).toLowerCase())
56819 : string;
56820 });
56821 }
56822
56823 /**
56824 * Converts a Unicode string representing a domain name or an email address to
56825 * Punycode. Only the non-ASCII parts of the domain name will be converted,
56826 * i.e. it doesn't matter if you call it with a domain that's already in
56827 * ASCII.
56828 * @memberOf punycode
56829 * @param {String} input The domain name or email address to convert, as a
56830 * Unicode string.
56831 * @returns {String} The Punycode representation of the given domain name or
56832 * email address.
56833 */
56834 function toASCII(input) {
56835 return mapDomain(input, function(string) {
56836 return regexNonASCII.test(string)
56837 ? 'xn--' + encode(string)
56838 : string;
56839 });
56840 }
56841
56842 /*--------------------------------------------------------------------------*/
56843
56844 /** Define the public API */
56845 punycode = {
56846 /**
56847 * A string representing the current Punycode.js version number.
56848 * @memberOf punycode
56849 * @type String
56850 */
56851 'version': '1.4.1',
56852 /**
56853 * An object of methods to convert from JavaScript's internal character
56854 * representation (UCS-2) to Unicode code points, and back.
56855 * @see <https://mathiasbynens.be/notes/javascript-encoding>
56856 * @memberOf punycode
56857 * @type Object
56858 */
56859 'ucs2': {
56860 'decode': ucs2decode,
56861 'encode': ucs2encode
56862 },
56863 'decode': decode,
56864 'encode': encode,
56865 'toASCII': toASCII,
56866 'toUnicode': toUnicode
56867 };
56868
56869 /** Expose `punycode` */
56870 // Some AMD build optimizers, like r.js, check for specific condition patterns
56871 // like the following:
56872 if (
56873 typeof define == 'function' &&
56874 typeof define.amd == 'object' &&
56875 define.amd
56876 ) {
56877 define('punycode', function() {
56878 return punycode;
56879 });
56880 } else if (freeExports && freeModule) {
56881 if (module.exports == freeExports) {
56882 // in Node.js, io.js, or RingoJS v0.8.0+
56883 freeModule.exports = punycode;
56884 } else {
56885 // in Narwhal or RingoJS v0.7.0-
56886 for (key in punycode) {
56887 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
56888 }
56889 }
56890 } else {
56891 // in Rhino or a web browser
56892 root.punycode = punycode;
56893 }
56894
56895}(this));
56896
56897}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
56898},{}],275:[function(require,module,exports){
56899// Copyright Joyent, Inc. and other Node contributors.
56900//
56901// Permission is hereby granted, free of charge, to any person obtaining a
56902// copy of this software and associated documentation files (the
56903// "Software"), to deal in the Software without restriction, including
56904// without limitation the rights to use, copy, modify, merge, publish,
56905// distribute, sublicense, and/or sell copies of the Software, and to permit
56906// persons to whom the Software is furnished to do so, subject to the
56907// following conditions:
56908//
56909// The above copyright notice and this permission notice shall be included
56910// in all copies or substantial portions of the Software.
56911//
56912// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
56913// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
56914// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
56915// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
56916// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
56917// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
56918// USE OR OTHER DEALINGS IN THE SOFTWARE.
56919
56920'use strict';
56921
56922// If obj.hasOwnProperty has been overridden, then calling
56923// obj.hasOwnProperty(prop) will break.
56924// See: https://github.com/joyent/node/issues/1707
56925function hasOwnProperty(obj, prop) {
56926 return Object.prototype.hasOwnProperty.call(obj, prop);
56927}
56928
56929module.exports = function(qs, sep, eq, options) {
56930 sep = sep || '&';
56931 eq = eq || '=';
56932 var obj = {};
56933
56934 if (typeof qs !== 'string' || qs.length === 0) {
56935 return obj;
56936 }
56937
56938 var regexp = /\+/g;
56939 qs = qs.split(sep);
56940
56941 var maxKeys = 1000;
56942 if (options && typeof options.maxKeys === 'number') {
56943 maxKeys = options.maxKeys;
56944 }
56945
56946 var len = qs.length;
56947 // maxKeys <= 0 means that we should not limit keys count
56948 if (maxKeys > 0 && len > maxKeys) {
56949 len = maxKeys;
56950 }
56951
56952 for (var i = 0; i < len; ++i) {
56953 var x = qs[i].replace(regexp, '%20'),
56954 idx = x.indexOf(eq),
56955 kstr, vstr, k, v;
56956
56957 if (idx >= 0) {
56958 kstr = x.substr(0, idx);
56959 vstr = x.substr(idx + 1);
56960 } else {
56961 kstr = x;
56962 vstr = '';
56963 }
56964
56965 k = decodeURIComponent(kstr);
56966 v = decodeURIComponent(vstr);
56967
56968 if (!hasOwnProperty(obj, k)) {
56969 obj[k] = v;
56970 } else if (isArray(obj[k])) {
56971 obj[k].push(v);
56972 } else {
56973 obj[k] = [obj[k], v];
56974 }
56975 }
56976
56977 return obj;
56978};
56979
56980var isArray = Array.isArray || function (xs) {
56981 return Object.prototype.toString.call(xs) === '[object Array]';
56982};
56983
56984},{}],276:[function(require,module,exports){
56985// Copyright Joyent, Inc. and other Node contributors.
56986//
56987// Permission is hereby granted, free of charge, to any person obtaining a
56988// copy of this software and associated documentation files (the
56989// "Software"), to deal in the Software without restriction, including
56990// without limitation the rights to use, copy, modify, merge, publish,
56991// distribute, sublicense, and/or sell copies of the Software, and to permit
56992// persons to whom the Software is furnished to do so, subject to the
56993// following conditions:
56994//
56995// The above copyright notice and this permission notice shall be included
56996// in all copies or substantial portions of the Software.
56997//
56998// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
56999// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
57000// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
57001// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
57002// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
57003// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
57004// USE OR OTHER DEALINGS IN THE SOFTWARE.
57005
57006'use strict';
57007
57008var stringifyPrimitive = function(v) {
57009 switch (typeof v) {
57010 case 'string':
57011 return v;
57012
57013 case 'boolean':
57014 return v ? 'true' : 'false';
57015
57016 case 'number':
57017 return isFinite(v) ? v : '';
57018
57019 default:
57020 return '';
57021 }
57022};
57023
57024module.exports = function(obj, sep, eq, name) {
57025 sep = sep || '&';
57026 eq = eq || '=';
57027 if (obj === null) {
57028 obj = undefined;
57029 }
57030
57031 if (typeof obj === 'object') {
57032 return map(objectKeys(obj), function(k) {
57033 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
57034 if (isArray(obj[k])) {
57035 return map(obj[k], function(v) {
57036 return ks + encodeURIComponent(stringifyPrimitive(v));
57037 }).join(sep);
57038 } else {
57039 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
57040 }
57041 }).join(sep);
57042
57043 }
57044
57045 if (!name) return '';
57046 return encodeURIComponent(stringifyPrimitive(name)) + eq +
57047 encodeURIComponent(stringifyPrimitive(obj));
57048};
57049
57050var isArray = Array.isArray || function (xs) {
57051 return Object.prototype.toString.call(xs) === '[object Array]';
57052};
57053
57054function map (xs, f) {
57055 if (xs.map) return xs.map(f);
57056 var res = [];
57057 for (var i = 0; i < xs.length; i++) {
57058 res.push(f(xs[i], i));
57059 }
57060 return res;
57061}
57062
57063var objectKeys = Object.keys || function (obj) {
57064 var res = [];
57065 for (var key in obj) {
57066 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
57067 }
57068 return res;
57069};
57070
57071},{}],277:[function(require,module,exports){
57072'use strict';
57073
57074exports.decode = exports.parse = require('./decode');
57075exports.encode = exports.stringify = require('./encode');
57076
57077},{"./decode":275,"./encode":276}],278:[function(require,module,exports){
57078(function (process,global){
57079'use strict'
57080
57081// limit of Crypto.getRandomValues()
57082// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
57083var MAX_BYTES = 65536
57084
57085// Node supports requesting up to this number of bytes
57086// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
57087var MAX_UINT32 = 4294967295
57088
57089function oldBrowser () {
57090 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
57091}
57092
57093var Buffer = require('safe-buffer').Buffer
57094var crypto = global.crypto || global.msCrypto
57095
57096if (crypto && crypto.getRandomValues) {
57097 module.exports = randomBytes
57098} else {
57099 module.exports = oldBrowser
57100}
57101
57102function randomBytes (size, cb) {
57103 // phantomjs needs to throw
57104 if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
57105
57106 var bytes = Buffer.allocUnsafe(size)
57107
57108 if (size > 0) { // getRandomValues fails on IE if size == 0
57109 if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
57110 // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
57111 for (var generated = 0; generated < size; generated += MAX_BYTES) {
57112 // buffer.slice automatically checks if the end is past the end of
57113 // the buffer so we don't have to here
57114 crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
57115 }
57116 } else {
57117 crypto.getRandomValues(bytes)
57118 }
57119 }
57120
57121 if (typeof cb === 'function') {
57122 return process.nextTick(function () {
57123 cb(null, bytes)
57124 })
57125 }
57126
57127 return bytes
57128}
57129
57130}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
57131},{"_process":265,"safe-buffer":325}],279:[function(require,module,exports){
57132(function (process,global){
57133'use strict'
57134
57135function oldBrowser () {
57136 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
57137}
57138var safeBuffer = require('safe-buffer')
57139var randombytes = require('randombytes')
57140var Buffer = safeBuffer.Buffer
57141var kBufferMaxLength = safeBuffer.kMaxLength
57142var crypto = global.crypto || global.msCrypto
57143var kMaxUint32 = Math.pow(2, 32) - 1
57144function assertOffset (offset, length) {
57145 if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
57146 throw new TypeError('offset must be a number')
57147 }
57148
57149 if (offset > kMaxUint32 || offset < 0) {
57150 throw new TypeError('offset must be a uint32')
57151 }
57152
57153 if (offset > kBufferMaxLength || offset > length) {
57154 throw new RangeError('offset out of range')
57155 }
57156}
57157
57158function assertSize (size, offset, length) {
57159 if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
57160 throw new TypeError('size must be a number')
57161 }
57162
57163 if (size > kMaxUint32 || size < 0) {
57164 throw new TypeError('size must be a uint32')
57165 }
57166
57167 if (size + offset > length || size > kBufferMaxLength) {
57168 throw new RangeError('buffer too small')
57169 }
57170}
57171if ((crypto && crypto.getRandomValues) || !process.browser) {
57172 exports.randomFill = randomFill
57173 exports.randomFillSync = randomFillSync
57174} else {
57175 exports.randomFill = oldBrowser
57176 exports.randomFillSync = oldBrowser
57177}
57178function randomFill (buf, offset, size, cb) {
57179 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
57180 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
57181 }
57182
57183 if (typeof offset === 'function') {
57184 cb = offset
57185 offset = 0
57186 size = buf.length
57187 } else if (typeof size === 'function') {
57188 cb = size
57189 size = buf.length - offset
57190 } else if (typeof cb !== 'function') {
57191 throw new TypeError('"cb" argument must be a function')
57192 }
57193 assertOffset(offset, buf.length)
57194 assertSize(size, offset, buf.length)
57195 return actualFill(buf, offset, size, cb)
57196}
57197
57198function actualFill (buf, offset, size, cb) {
57199 if (process.browser) {
57200 var ourBuf = buf.buffer
57201 var uint = new Uint8Array(ourBuf, offset, size)
57202 crypto.getRandomValues(uint)
57203 if (cb) {
57204 process.nextTick(function () {
57205 cb(null, buf)
57206 })
57207 return
57208 }
57209 return buf
57210 }
57211 if (cb) {
57212 randombytes(size, function (err, bytes) {
57213 if (err) {
57214 return cb(err)
57215 }
57216 bytes.copy(buf, offset)
57217 cb(null, buf)
57218 })
57219 return
57220 }
57221 var bytes = randombytes(size)
57222 bytes.copy(buf, offset)
57223 return buf
57224}
57225function randomFillSync (buf, offset, size) {
57226 if (typeof offset === 'undefined') {
57227 offset = 0
57228 }
57229 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
57230 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
57231 }
57232
57233 assertOffset(offset, buf.length)
57234
57235 if (size === undefined) size = buf.length - offset
57236
57237 assertSize(size, offset, buf.length)
57238
57239 return actualFill(buf, offset, size)
57240}
57241
57242}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
57243},{"_process":265,"randombytes":278,"safe-buffer":325}],280:[function(require,module,exports){
57244module.exports = require('./lib/_stream_duplex.js');
57245
57246},{"./lib/_stream_duplex.js":281}],281:[function(require,module,exports){
57247// Copyright Joyent, Inc. and other Node contributors.
57248//
57249// Permission is hereby granted, free of charge, to any person obtaining a
57250// copy of this software and associated documentation files (the
57251// "Software"), to deal in the Software without restriction, including
57252// without limitation the rights to use, copy, modify, merge, publish,
57253// distribute, sublicense, and/or sell copies of the Software, and to permit
57254// persons to whom the Software is furnished to do so, subject to the
57255// following conditions:
57256//
57257// The above copyright notice and this permission notice shall be included
57258// in all copies or substantial portions of the Software.
57259//
57260// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
57261// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
57262// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
57263// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
57264// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
57265// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
57266// USE OR OTHER DEALINGS IN THE SOFTWARE.
57267
57268// a duplex stream is just a stream that is both readable and writable.
57269// Since JS doesn't have multiple prototypal inheritance, this class
57270// prototypally inherits from Readable, and then parasitically from
57271// Writable.
57272
57273'use strict';
57274
57275/*<replacement>*/
57276
57277var pna = require('process-nextick-args');
57278/*</replacement>*/
57279
57280/*<replacement>*/
57281var objectKeys = Object.keys || function (obj) {
57282 var keys = [];
57283 for (var key in obj) {
57284 keys.push(key);
57285 }return keys;
57286};
57287/*</replacement>*/
57288
57289module.exports = Duplex;
57290
57291/*<replacement>*/
57292var util = require('core-util-is');
57293util.inherits = require('inherits');
57294/*</replacement>*/
57295
57296var Readable = require('./_stream_readable');
57297var Writable = require('./_stream_writable');
57298
57299util.inherits(Duplex, Readable);
57300
57301{
57302 // avoid scope creep, the keys array can then be collected
57303 var keys = objectKeys(Writable.prototype);
57304 for (var v = 0; v < keys.length; v++) {
57305 var method = keys[v];
57306 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
57307 }
57308}
57309
57310function Duplex(options) {
57311 if (!(this instanceof Duplex)) return new Duplex(options);
57312
57313 Readable.call(this, options);
57314 Writable.call(this, options);
57315
57316 if (options && options.readable === false) this.readable = false;
57317
57318 if (options && options.writable === false) this.writable = false;
57319
57320 this.allowHalfOpen = true;
57321 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
57322
57323 this.once('end', onend);
57324}
57325
57326Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
57327 // making it explicit this property is not enumerable
57328 // because otherwise some prototype manipulation in
57329 // userland will fail
57330 enumerable: false,
57331 get: function () {
57332 return this._writableState.highWaterMark;
57333 }
57334});
57335
57336// the no-half-open enforcer
57337function onend() {
57338 // if we allow half-open state, or if the writable side ended,
57339 // then we're ok.
57340 if (this.allowHalfOpen || this._writableState.ended) return;
57341
57342 // no more data can be written.
57343 // But allow more writes to happen in this tick.
57344 pna.nextTick(onEndNT, this);
57345}
57346
57347function onEndNT(self) {
57348 self.end();
57349}
57350
57351Object.defineProperty(Duplex.prototype, 'destroyed', {
57352 get: function () {
57353 if (this._readableState === undefined || this._writableState === undefined) {
57354 return false;
57355 }
57356 return this._readableState.destroyed && this._writableState.destroyed;
57357 },
57358 set: function (value) {
57359 // we ignore the value if the stream
57360 // has not been initialized yet
57361 if (this._readableState === undefined || this._writableState === undefined) {
57362 return;
57363 }
57364
57365 // backward compatibility, the user is explicitly
57366 // managing destroyed
57367 this._readableState.destroyed = value;
57368 this._writableState.destroyed = value;
57369 }
57370});
57371
57372Duplex.prototype._destroy = function (err, cb) {
57373 this.push(null);
57374 this.end();
57375
57376 pna.nextTick(cb, err);
57377};
57378},{"./_stream_readable":283,"./_stream_writable":285,"core-util-is":120,"inherits":210,"process-nextick-args":264}],282:[function(require,module,exports){
57379// Copyright Joyent, Inc. and other Node contributors.
57380//
57381// Permission is hereby granted, free of charge, to any person obtaining a
57382// copy of this software and associated documentation files (the
57383// "Software"), to deal in the Software without restriction, including
57384// without limitation the rights to use, copy, modify, merge, publish,
57385// distribute, sublicense, and/or sell copies of the Software, and to permit
57386// persons to whom the Software is furnished to do so, subject to the
57387// following conditions:
57388//
57389// The above copyright notice and this permission notice shall be included
57390// in all copies or substantial portions of the Software.
57391//
57392// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
57393// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
57394// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
57395// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
57396// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
57397// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
57398// USE OR OTHER DEALINGS IN THE SOFTWARE.
57399
57400// a passthrough stream.
57401// basically just the most minimal sort of Transform stream.
57402// Every written chunk gets output as-is.
57403
57404'use strict';
57405
57406module.exports = PassThrough;
57407
57408var Transform = require('./_stream_transform');
57409
57410/*<replacement>*/
57411var util = require('core-util-is');
57412util.inherits = require('inherits');
57413/*</replacement>*/
57414
57415util.inherits(PassThrough, Transform);
57416
57417function PassThrough(options) {
57418 if (!(this instanceof PassThrough)) return new PassThrough(options);
57419
57420 Transform.call(this, options);
57421}
57422
57423PassThrough.prototype._transform = function (chunk, encoding, cb) {
57424 cb(null, chunk);
57425};
57426},{"./_stream_transform":284,"core-util-is":120,"inherits":210}],283:[function(require,module,exports){
57427(function (process,global){
57428// Copyright Joyent, Inc. and other Node contributors.
57429//
57430// Permission is hereby granted, free of charge, to any person obtaining a
57431// copy of this software and associated documentation files (the
57432// "Software"), to deal in the Software without restriction, including
57433// without limitation the rights to use, copy, modify, merge, publish,
57434// distribute, sublicense, and/or sell copies of the Software, and to permit
57435// persons to whom the Software is furnished to do so, subject to the
57436// following conditions:
57437//
57438// The above copyright notice and this permission notice shall be included
57439// in all copies or substantial portions of the Software.
57440//
57441// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
57442// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
57443// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
57444// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
57445// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
57446// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
57447// USE OR OTHER DEALINGS IN THE SOFTWARE.
57448
57449'use strict';
57450
57451/*<replacement>*/
57452
57453var pna = require('process-nextick-args');
57454/*</replacement>*/
57455
57456module.exports = Readable;
57457
57458/*<replacement>*/
57459var isArray = require('isarray');
57460/*</replacement>*/
57461
57462/*<replacement>*/
57463var Duplex;
57464/*</replacement>*/
57465
57466Readable.ReadableState = ReadableState;
57467
57468/*<replacement>*/
57469var EE = require('events').EventEmitter;
57470
57471var EElistenerCount = function (emitter, type) {
57472 return emitter.listeners(type).length;
57473};
57474/*</replacement>*/
57475
57476/*<replacement>*/
57477var Stream = require('./internal/streams/stream');
57478/*</replacement>*/
57479
57480/*<replacement>*/
57481
57482var Buffer = require('safe-buffer').Buffer;
57483var OurUint8Array = global.Uint8Array || function () {};
57484function _uint8ArrayToBuffer(chunk) {
57485 return Buffer.from(chunk);
57486}
57487function _isUint8Array(obj) {
57488 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
57489}
57490
57491/*</replacement>*/
57492
57493/*<replacement>*/
57494var util = require('core-util-is');
57495util.inherits = require('inherits');
57496/*</replacement>*/
57497
57498/*<replacement>*/
57499var debugUtil = require('util');
57500var debug = void 0;
57501if (debugUtil && debugUtil.debuglog) {
57502 debug = debugUtil.debuglog('stream');
57503} else {
57504 debug = function () {};
57505}
57506/*</replacement>*/
57507
57508var BufferList = require('./internal/streams/BufferList');
57509var destroyImpl = require('./internal/streams/destroy');
57510var StringDecoder;
57511
57512util.inherits(Readable, Stream);
57513
57514var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
57515
57516function prependListener(emitter, event, fn) {
57517 // Sadly this is not cacheable as some libraries bundle their own
57518 // event emitter implementation with them.
57519 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
57520
57521 // This is a hack to make sure that our error handler is attached before any
57522 // userland ones. NEVER DO THIS. This is here only because this code needs
57523 // to continue to work with older versions of Node.js that do not include
57524 // the prependListener() method. The goal is to eventually remove this hack.
57525 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]];
57526}
57527
57528function ReadableState(options, stream) {
57529 Duplex = Duplex || require('./_stream_duplex');
57530
57531 options = options || {};
57532
57533 // Duplex streams are both readable and writable, but share
57534 // the same options object.
57535 // However, some cases require setting options to different
57536 // values for the readable and the writable sides of the duplex stream.
57537 // These options can be provided separately as readableXXX and writableXXX.
57538 var isDuplex = stream instanceof Duplex;
57539
57540 // object stream flag. Used to make read(n) ignore n and to
57541 // make all the buffer merging and length checks go away
57542 this.objectMode = !!options.objectMode;
57543
57544 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
57545
57546 // the point at which it stops calling _read() to fill the buffer
57547 // Note: 0 is a valid value, means "don't call _read preemptively ever"
57548 var hwm = options.highWaterMark;
57549 var readableHwm = options.readableHighWaterMark;
57550 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
57551
57552 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
57553
57554 // cast to ints.
57555 this.highWaterMark = Math.floor(this.highWaterMark);
57556
57557 // A linked list is used to store data chunks instead of an array because the
57558 // linked list can remove elements from the beginning faster than
57559 // array.shift()
57560 this.buffer = new BufferList();
57561 this.length = 0;
57562 this.pipes = null;
57563 this.pipesCount = 0;
57564 this.flowing = null;
57565 this.ended = false;
57566 this.endEmitted = false;
57567 this.reading = false;
57568
57569 // a flag to be able to tell if the event 'readable'/'data' is emitted
57570 // immediately, or on a later tick. We set this to true at first, because
57571 // any actions that shouldn't happen until "later" should generally also
57572 // not happen before the first read call.
57573 this.sync = true;
57574
57575 // whenever we return null, then we set a flag to say
57576 // that we're awaiting a 'readable' event emission.
57577 this.needReadable = false;
57578 this.emittedReadable = false;
57579 this.readableListening = false;
57580 this.resumeScheduled = false;
57581
57582 // has it been destroyed
57583 this.destroyed = false;
57584
57585 // Crypto is kind of old and crusty. Historically, its default string
57586 // encoding is 'binary' so we have to make this configurable.
57587 // Everything else in the universe uses 'utf8', though.
57588 this.defaultEncoding = options.defaultEncoding || 'utf8';
57589
57590 // the number of writers that are awaiting a drain event in .pipe()s
57591 this.awaitDrain = 0;
57592
57593 // if true, a maybeReadMore has been scheduled
57594 this.readingMore = false;
57595
57596 this.decoder = null;
57597 this.encoding = null;
57598 if (options.encoding) {
57599 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
57600 this.decoder = new StringDecoder(options.encoding);
57601 this.encoding = options.encoding;
57602 }
57603}
57604
57605function Readable(options) {
57606 Duplex = Duplex || require('./_stream_duplex');
57607
57608 if (!(this instanceof Readable)) return new Readable(options);
57609
57610 this._readableState = new ReadableState(options, this);
57611
57612 // legacy
57613 this.readable = true;
57614
57615 if (options) {
57616 if (typeof options.read === 'function') this._read = options.read;
57617
57618 if (typeof options.destroy === 'function') this._destroy = options.destroy;
57619 }
57620
57621 Stream.call(this);
57622}
57623
57624Object.defineProperty(Readable.prototype, 'destroyed', {
57625 get: function () {
57626 if (this._readableState === undefined) {
57627 return false;
57628 }
57629 return this._readableState.destroyed;
57630 },
57631 set: function (value) {
57632 // we ignore the value if the stream
57633 // has not been initialized yet
57634 if (!this._readableState) {
57635 return;
57636 }
57637
57638 // backward compatibility, the user is explicitly
57639 // managing destroyed
57640 this._readableState.destroyed = value;
57641 }
57642});
57643
57644Readable.prototype.destroy = destroyImpl.destroy;
57645Readable.prototype._undestroy = destroyImpl.undestroy;
57646Readable.prototype._destroy = function (err, cb) {
57647 this.push(null);
57648 cb(err);
57649};
57650
57651// Manually shove something into the read() buffer.
57652// This returns true if the highWaterMark has not been hit yet,
57653// similar to how Writable.write() returns true if you should
57654// write() some more.
57655Readable.prototype.push = function (chunk, encoding) {
57656 var state = this._readableState;
57657 var skipChunkCheck;
57658
57659 if (!state.objectMode) {
57660 if (typeof chunk === 'string') {
57661 encoding = encoding || state.defaultEncoding;
57662 if (encoding !== state.encoding) {
57663 chunk = Buffer.from(chunk, encoding);
57664 encoding = '';
57665 }
57666 skipChunkCheck = true;
57667 }
57668 } else {
57669 skipChunkCheck = true;
57670 }
57671
57672 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
57673};
57674
57675// Unshift should *always* be something directly out of read()
57676Readable.prototype.unshift = function (chunk) {
57677 return readableAddChunk(this, chunk, null, true, false);
57678};
57679
57680function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
57681 var state = stream._readableState;
57682 if (chunk === null) {
57683 state.reading = false;
57684 onEofChunk(stream, state);
57685 } else {
57686 var er;
57687 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
57688 if (er) {
57689 stream.emit('error', er);
57690 } else if (state.objectMode || chunk && chunk.length > 0) {
57691 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
57692 chunk = _uint8ArrayToBuffer(chunk);
57693 }
57694
57695 if (addToFront) {
57696 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
57697 } else if (state.ended) {
57698 stream.emit('error', new Error('stream.push() after EOF'));
57699 } else {
57700 state.reading = false;
57701 if (state.decoder && !encoding) {
57702 chunk = state.decoder.write(chunk);
57703 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
57704 } else {
57705 addChunk(stream, state, chunk, false);
57706 }
57707 }
57708 } else if (!addToFront) {
57709 state.reading = false;
57710 }
57711 }
57712
57713 return needMoreData(state);
57714}
57715
57716function addChunk(stream, state, chunk, addToFront) {
57717 if (state.flowing && state.length === 0 && !state.sync) {
57718 stream.emit('data', chunk);
57719 stream.read(0);
57720 } else {
57721 // update the buffer info.
57722 state.length += state.objectMode ? 1 : chunk.length;
57723 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
57724
57725 if (state.needReadable) emitReadable(stream);
57726 }
57727 maybeReadMore(stream, state);
57728}
57729
57730function chunkInvalid(state, chunk) {
57731 var er;
57732 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
57733 er = new TypeError('Invalid non-string/buffer chunk');
57734 }
57735 return er;
57736}
57737
57738// if it's past the high water mark, we can push in some more.
57739// Also, if we have no data yet, we can stand some
57740// more bytes. This is to work around cases where hwm=0,
57741// such as the repl. Also, if the push() triggered a
57742// readable event, and the user called read(largeNumber) such that
57743// needReadable was set, then we ought to push more, so that another
57744// 'readable' event will be triggered.
57745function needMoreData(state) {
57746 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
57747}
57748
57749Readable.prototype.isPaused = function () {
57750 return this._readableState.flowing === false;
57751};
57752
57753// backwards compatibility.
57754Readable.prototype.setEncoding = function (enc) {
57755 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
57756 this._readableState.decoder = new StringDecoder(enc);
57757 this._readableState.encoding = enc;
57758 return this;
57759};
57760
57761// Don't raise the hwm > 8MB
57762var MAX_HWM = 0x800000;
57763function computeNewHighWaterMark(n) {
57764 if (n >= MAX_HWM) {
57765 n = MAX_HWM;
57766 } else {
57767 // Get the next highest power of 2 to prevent increasing hwm excessively in
57768 // tiny amounts
57769 n--;
57770 n |= n >>> 1;
57771 n |= n >>> 2;
57772 n |= n >>> 4;
57773 n |= n >>> 8;
57774 n |= n >>> 16;
57775 n++;
57776 }
57777 return n;
57778}
57779
57780// This function is designed to be inlinable, so please take care when making
57781// changes to the function body.
57782function howMuchToRead(n, state) {
57783 if (n <= 0 || state.length === 0 && state.ended) return 0;
57784 if (state.objectMode) return 1;
57785 if (n !== n) {
57786 // Only flow one buffer at a time
57787 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
57788 }
57789 // If we're asking for more than the current hwm, then raise the hwm.
57790 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
57791 if (n <= state.length) return n;
57792 // Don't have enough
57793 if (!state.ended) {
57794 state.needReadable = true;
57795 return 0;
57796 }
57797 return state.length;
57798}
57799
57800// you can override either this method, or the async _read(n) below.
57801Readable.prototype.read = function (n) {
57802 debug('read', n);
57803 n = parseInt(n, 10);
57804 var state = this._readableState;
57805 var nOrig = n;
57806
57807 if (n !== 0) state.emittedReadable = false;
57808
57809 // if we're doing read(0) to trigger a readable event, but we
57810 // already have a bunch of data in the buffer, then just trigger
57811 // the 'readable' event and move on.
57812 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
57813 debug('read: emitReadable', state.length, state.ended);
57814 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
57815 return null;
57816 }
57817
57818 n = howMuchToRead(n, state);
57819
57820 // if we've ended, and we're now clear, then finish it up.
57821 if (n === 0 && state.ended) {
57822 if (state.length === 0) endReadable(this);
57823 return null;
57824 }
57825
57826 // All the actual chunk generation logic needs to be
57827 // *below* the call to _read. The reason is that in certain
57828 // synthetic stream cases, such as passthrough streams, _read
57829 // may be a completely synchronous operation which may change
57830 // the state of the read buffer, providing enough data when
57831 // before there was *not* enough.
57832 //
57833 // So, the steps are:
57834 // 1. Figure out what the state of things will be after we do
57835 // a read from the buffer.
57836 //
57837 // 2. If that resulting state will trigger a _read, then call _read.
57838 // Note that this may be asynchronous, or synchronous. Yes, it is
57839 // deeply ugly to write APIs this way, but that still doesn't mean
57840 // that the Readable class should behave improperly, as streams are
57841 // designed to be sync/async agnostic.
57842 // Take note if the _read call is sync or async (ie, if the read call
57843 // has returned yet), so that we know whether or not it's safe to emit
57844 // 'readable' etc.
57845 //
57846 // 3. Actually pull the requested chunks out of the buffer and return.
57847
57848 // if we need a readable event, then we need to do some reading.
57849 var doRead = state.needReadable;
57850 debug('need readable', doRead);
57851
57852 // if we currently have less than the highWaterMark, then also read some
57853 if (state.length === 0 || state.length - n < state.highWaterMark) {
57854 doRead = true;
57855 debug('length less than watermark', doRead);
57856 }
57857
57858 // however, if we've ended, then there's no point, and if we're already
57859 // reading, then it's unnecessary.
57860 if (state.ended || state.reading) {
57861 doRead = false;
57862 debug('reading or ended', doRead);
57863 } else if (doRead) {
57864 debug('do read');
57865 state.reading = true;
57866 state.sync = true;
57867 // if the length is currently zero, then we *need* a readable event.
57868 if (state.length === 0) state.needReadable = true;
57869 // call internal read method
57870 this._read(state.highWaterMark);
57871 state.sync = false;
57872 // If _read pushed data synchronously, then `reading` will be false,
57873 // and we need to re-evaluate how much data we can return to the user.
57874 if (!state.reading) n = howMuchToRead(nOrig, state);
57875 }
57876
57877 var ret;
57878 if (n > 0) ret = fromList(n, state);else ret = null;
57879
57880 if (ret === null) {
57881 state.needReadable = true;
57882 n = 0;
57883 } else {
57884 state.length -= n;
57885 }
57886
57887 if (state.length === 0) {
57888 // If we have nothing in the buffer, then we want to know
57889 // as soon as we *do* get something into the buffer.
57890 if (!state.ended) state.needReadable = true;
57891
57892 // If we tried to read() past the EOF, then emit end on the next tick.
57893 if (nOrig !== n && state.ended) endReadable(this);
57894 }
57895
57896 if (ret !== null) this.emit('data', ret);
57897
57898 return ret;
57899};
57900
57901function onEofChunk(stream, state) {
57902 if (state.ended) return;
57903 if (state.decoder) {
57904 var chunk = state.decoder.end();
57905 if (chunk && chunk.length) {
57906 state.buffer.push(chunk);
57907 state.length += state.objectMode ? 1 : chunk.length;
57908 }
57909 }
57910 state.ended = true;
57911
57912 // emit 'readable' now to make sure it gets picked up.
57913 emitReadable(stream);
57914}
57915
57916// Don't emit readable right away in sync mode, because this can trigger
57917// another read() call => stack overflow. This way, it might trigger
57918// a nextTick recursion warning, but that's not so bad.
57919function emitReadable(stream) {
57920 var state = stream._readableState;
57921 state.needReadable = false;
57922 if (!state.emittedReadable) {
57923 debug('emitReadable', state.flowing);
57924 state.emittedReadable = true;
57925 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
57926 }
57927}
57928
57929function emitReadable_(stream) {
57930 debug('emit readable');
57931 stream.emit('readable');
57932 flow(stream);
57933}
57934
57935// at this point, the user has presumably seen the 'readable' event,
57936// and called read() to consume some data. that may have triggered
57937// in turn another _read(n) call, in which case reading = true if
57938// it's in progress.
57939// However, if we're not ended, or reading, and the length < hwm,
57940// then go ahead and try to read some more preemptively.
57941function maybeReadMore(stream, state) {
57942 if (!state.readingMore) {
57943 state.readingMore = true;
57944 pna.nextTick(maybeReadMore_, stream, state);
57945 }
57946}
57947
57948function maybeReadMore_(stream, state) {
57949 var len = state.length;
57950 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
57951 debug('maybeReadMore read 0');
57952 stream.read(0);
57953 if (len === state.length)
57954 // didn't get any data, stop spinning.
57955 break;else len = state.length;
57956 }
57957 state.readingMore = false;
57958}
57959
57960// abstract method. to be overridden in specific implementation classes.
57961// call cb(er, data) where data is <= n in length.
57962// for virtual (non-string, non-buffer) streams, "length" is somewhat
57963// arbitrary, and perhaps not very meaningful.
57964Readable.prototype._read = function (n) {
57965 this.emit('error', new Error('_read() is not implemented'));
57966};
57967
57968Readable.prototype.pipe = function (dest, pipeOpts) {
57969 var src = this;
57970 var state = this._readableState;
57971
57972 switch (state.pipesCount) {
57973 case 0:
57974 state.pipes = dest;
57975 break;
57976 case 1:
57977 state.pipes = [state.pipes, dest];
57978 break;
57979 default:
57980 state.pipes.push(dest);
57981 break;
57982 }
57983 state.pipesCount += 1;
57984 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
57985
57986 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
57987
57988 var endFn = doEnd ? onend : unpipe;
57989 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
57990
57991 dest.on('unpipe', onunpipe);
57992 function onunpipe(readable, unpipeInfo) {
57993 debug('onunpipe');
57994 if (readable === src) {
57995 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
57996 unpipeInfo.hasUnpiped = true;
57997 cleanup();
57998 }
57999 }
58000 }
58001
58002 function onend() {
58003 debug('onend');
58004 dest.end();
58005 }
58006
58007 // when the dest drains, it reduces the awaitDrain counter
58008 // on the source. This would be more elegant with a .once()
58009 // handler in flow(), but adding and removing repeatedly is
58010 // too slow.
58011 var ondrain = pipeOnDrain(src);
58012 dest.on('drain', ondrain);
58013
58014 var cleanedUp = false;
58015 function cleanup() {
58016 debug('cleanup');
58017 // cleanup event handlers once the pipe is broken
58018 dest.removeListener('close', onclose);
58019 dest.removeListener('finish', onfinish);
58020 dest.removeListener('drain', ondrain);
58021 dest.removeListener('error', onerror);
58022 dest.removeListener('unpipe', onunpipe);
58023 src.removeListener('end', onend);
58024 src.removeListener('end', unpipe);
58025 src.removeListener('data', ondata);
58026
58027 cleanedUp = true;
58028
58029 // if the reader is waiting for a drain event from this
58030 // specific writer, then it would cause it to never start
58031 // flowing again.
58032 // So, if this is awaiting a drain, then we just call it now.
58033 // If we don't know, then assume that we are waiting for one.
58034 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
58035 }
58036
58037 // If the user pushes more data while we're writing to dest then we'll end up
58038 // in ondata again. However, we only want to increase awaitDrain once because
58039 // dest will only emit one 'drain' event for the multiple writes.
58040 // => Introduce a guard on increasing awaitDrain.
58041 var increasedAwaitDrain = false;
58042 src.on('data', ondata);
58043 function ondata(chunk) {
58044 debug('ondata');
58045 increasedAwaitDrain = false;
58046 var ret = dest.write(chunk);
58047 if (false === ret && !increasedAwaitDrain) {
58048 // If the user unpiped during `dest.write()`, it is possible
58049 // to get stuck in a permanently paused state if that write
58050 // also returned false.
58051 // => Check whether `dest` is still a piping destination.
58052 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
58053 debug('false write response, pause', src._readableState.awaitDrain);
58054 src._readableState.awaitDrain++;
58055 increasedAwaitDrain = true;
58056 }
58057 src.pause();
58058 }
58059 }
58060
58061 // if the dest has an error, then stop piping into it.
58062 // however, don't suppress the throwing behavior for this.
58063 function onerror(er) {
58064 debug('onerror', er);
58065 unpipe();
58066 dest.removeListener('error', onerror);
58067 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
58068 }
58069
58070 // Make sure our error handler is attached before userland ones.
58071 prependListener(dest, 'error', onerror);
58072
58073 // Both close and finish should trigger unpipe, but only once.
58074 function onclose() {
58075 dest.removeListener('finish', onfinish);
58076 unpipe();
58077 }
58078 dest.once('close', onclose);
58079 function onfinish() {
58080 debug('onfinish');
58081 dest.removeListener('close', onclose);
58082 unpipe();
58083 }
58084 dest.once('finish', onfinish);
58085
58086 function unpipe() {
58087 debug('unpipe');
58088 src.unpipe(dest);
58089 }
58090
58091 // tell the dest that it's being piped to
58092 dest.emit('pipe', src);
58093
58094 // start the flow if it hasn't been started already.
58095 if (!state.flowing) {
58096 debug('pipe resume');
58097 src.resume();
58098 }
58099
58100 return dest;
58101};
58102
58103function pipeOnDrain(src) {
58104 return function () {
58105 var state = src._readableState;
58106 debug('pipeOnDrain', state.awaitDrain);
58107 if (state.awaitDrain) state.awaitDrain--;
58108 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
58109 state.flowing = true;
58110 flow(src);
58111 }
58112 };
58113}
58114
58115Readable.prototype.unpipe = function (dest) {
58116 var state = this._readableState;
58117 var unpipeInfo = { hasUnpiped: false };
58118
58119 // if we're not piping anywhere, then do nothing.
58120 if (state.pipesCount === 0) return this;
58121
58122 // just one destination. most common case.
58123 if (state.pipesCount === 1) {
58124 // passed in one, but it's not the right one.
58125 if (dest && dest !== state.pipes) return this;
58126
58127 if (!dest) dest = state.pipes;
58128
58129 // got a match.
58130 state.pipes = null;
58131 state.pipesCount = 0;
58132 state.flowing = false;
58133 if (dest) dest.emit('unpipe', this, unpipeInfo);
58134 return this;
58135 }
58136
58137 // slow case. multiple pipe destinations.
58138
58139 if (!dest) {
58140 // remove all.
58141 var dests = state.pipes;
58142 var len = state.pipesCount;
58143 state.pipes = null;
58144 state.pipesCount = 0;
58145 state.flowing = false;
58146
58147 for (var i = 0; i < len; i++) {
58148 dests[i].emit('unpipe', this, unpipeInfo);
58149 }return this;
58150 }
58151
58152 // try to find the right one.
58153 var index = indexOf(state.pipes, dest);
58154 if (index === -1) return this;
58155
58156 state.pipes.splice(index, 1);
58157 state.pipesCount -= 1;
58158 if (state.pipesCount === 1) state.pipes = state.pipes[0];
58159
58160 dest.emit('unpipe', this, unpipeInfo);
58161
58162 return this;
58163};
58164
58165// set up data events if they are asked for
58166// Ensure readable listeners eventually get something
58167Readable.prototype.on = function (ev, fn) {
58168 var res = Stream.prototype.on.call(this, ev, fn);
58169
58170 if (ev === 'data') {
58171 // Start flowing on next tick if stream isn't explicitly paused
58172 if (this._readableState.flowing !== false) this.resume();
58173 } else if (ev === 'readable') {
58174 var state = this._readableState;
58175 if (!state.endEmitted && !state.readableListening) {
58176 state.readableListening = state.needReadable = true;
58177 state.emittedReadable = false;
58178 if (!state.reading) {
58179 pna.nextTick(nReadingNextTick, this);
58180 } else if (state.length) {
58181 emitReadable(this);
58182 }
58183 }
58184 }
58185
58186 return res;
58187};
58188Readable.prototype.addListener = Readable.prototype.on;
58189
58190function nReadingNextTick(self) {
58191 debug('readable nexttick read 0');
58192 self.read(0);
58193}
58194
58195// pause() and resume() are remnants of the legacy readable stream API
58196// If the user uses them, then switch into old mode.
58197Readable.prototype.resume = function () {
58198 var state = this._readableState;
58199 if (!state.flowing) {
58200 debug('resume');
58201 state.flowing = true;
58202 resume(this, state);
58203 }
58204 return this;
58205};
58206
58207function resume(stream, state) {
58208 if (!state.resumeScheduled) {
58209 state.resumeScheduled = true;
58210 pna.nextTick(resume_, stream, state);
58211 }
58212}
58213
58214function resume_(stream, state) {
58215 if (!state.reading) {
58216 debug('resume read 0');
58217 stream.read(0);
58218 }
58219
58220 state.resumeScheduled = false;
58221 state.awaitDrain = 0;
58222 stream.emit('resume');
58223 flow(stream);
58224 if (state.flowing && !state.reading) stream.read(0);
58225}
58226
58227Readable.prototype.pause = function () {
58228 debug('call pause flowing=%j', this._readableState.flowing);
58229 if (false !== this._readableState.flowing) {
58230 debug('pause');
58231 this._readableState.flowing = false;
58232 this.emit('pause');
58233 }
58234 return this;
58235};
58236
58237function flow(stream) {
58238 var state = stream._readableState;
58239 debug('flow', state.flowing);
58240 while (state.flowing && stream.read() !== null) {}
58241}
58242
58243// wrap an old-style stream as the async data source.
58244// This is *not* part of the readable stream interface.
58245// It is an ugly unfortunate mess of history.
58246Readable.prototype.wrap = function (stream) {
58247 var _this = this;
58248
58249 var state = this._readableState;
58250 var paused = false;
58251
58252 stream.on('end', function () {
58253 debug('wrapped end');
58254 if (state.decoder && !state.ended) {
58255 var chunk = state.decoder.end();
58256 if (chunk && chunk.length) _this.push(chunk);
58257 }
58258
58259 _this.push(null);
58260 });
58261
58262 stream.on('data', function (chunk) {
58263 debug('wrapped data');
58264 if (state.decoder) chunk = state.decoder.write(chunk);
58265
58266 // don't skip over falsy values in objectMode
58267 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
58268
58269 var ret = _this.push(chunk);
58270 if (!ret) {
58271 paused = true;
58272 stream.pause();
58273 }
58274 });
58275
58276 // proxy all the other methods.
58277 // important when wrapping filters and duplexes.
58278 for (var i in stream) {
58279 if (this[i] === undefined && typeof stream[i] === 'function') {
58280 this[i] = function (method) {
58281 return function () {
58282 return stream[method].apply(stream, arguments);
58283 };
58284 }(i);
58285 }
58286 }
58287
58288 // proxy certain important events.
58289 for (var n = 0; n < kProxyEvents.length; n++) {
58290 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
58291 }
58292
58293 // when we try to consume some more bytes, simply unpause the
58294 // underlying stream.
58295 this._read = function (n) {
58296 debug('wrapped _read', n);
58297 if (paused) {
58298 paused = false;
58299 stream.resume();
58300 }
58301 };
58302
58303 return this;
58304};
58305
58306Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
58307 // making it explicit this property is not enumerable
58308 // because otherwise some prototype manipulation in
58309 // userland will fail
58310 enumerable: false,
58311 get: function () {
58312 return this._readableState.highWaterMark;
58313 }
58314});
58315
58316// exposed for testing purposes only.
58317Readable._fromList = fromList;
58318
58319// Pluck off n bytes from an array of buffers.
58320// Length is the combined lengths of all the buffers in the list.
58321// This function is designed to be inlinable, so please take care when making
58322// changes to the function body.
58323function fromList(n, state) {
58324 // nothing buffered
58325 if (state.length === 0) return null;
58326
58327 var ret;
58328 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
58329 // read it all, truncate the list
58330 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);
58331 state.buffer.clear();
58332 } else {
58333 // read part of list
58334 ret = fromListPartial(n, state.buffer, state.decoder);
58335 }
58336
58337 return ret;
58338}
58339
58340// Extracts only enough buffered data to satisfy the amount requested.
58341// This function is designed to be inlinable, so please take care when making
58342// changes to the function body.
58343function fromListPartial(n, list, hasStrings) {
58344 var ret;
58345 if (n < list.head.data.length) {
58346 // slice is the same for buffers and strings
58347 ret = list.head.data.slice(0, n);
58348 list.head.data = list.head.data.slice(n);
58349 } else if (n === list.head.data.length) {
58350 // first chunk is a perfect match
58351 ret = list.shift();
58352 } else {
58353 // result spans more than one buffer
58354 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
58355 }
58356 return ret;
58357}
58358
58359// Copies a specified amount of characters from the list of buffered data
58360// chunks.
58361// This function is designed to be inlinable, so please take care when making
58362// changes to the function body.
58363function copyFromBufferString(n, list) {
58364 var p = list.head;
58365 var c = 1;
58366 var ret = p.data;
58367 n -= ret.length;
58368 while (p = p.next) {
58369 var str = p.data;
58370 var nb = n > str.length ? str.length : n;
58371 if (nb === str.length) ret += str;else ret += str.slice(0, n);
58372 n -= nb;
58373 if (n === 0) {
58374 if (nb === str.length) {
58375 ++c;
58376 if (p.next) list.head = p.next;else list.head = list.tail = null;
58377 } else {
58378 list.head = p;
58379 p.data = str.slice(nb);
58380 }
58381 break;
58382 }
58383 ++c;
58384 }
58385 list.length -= c;
58386 return ret;
58387}
58388
58389// Copies a specified amount of bytes from the list of buffered data chunks.
58390// This function is designed to be inlinable, so please take care when making
58391// changes to the function body.
58392function copyFromBuffer(n, list) {
58393 var ret = Buffer.allocUnsafe(n);
58394 var p = list.head;
58395 var c = 1;
58396 p.data.copy(ret);
58397 n -= p.data.length;
58398 while (p = p.next) {
58399 var buf = p.data;
58400 var nb = n > buf.length ? buf.length : n;
58401 buf.copy(ret, ret.length - n, 0, nb);
58402 n -= nb;
58403 if (n === 0) {
58404 if (nb === buf.length) {
58405 ++c;
58406 if (p.next) list.head = p.next;else list.head = list.tail = null;
58407 } else {
58408 list.head = p;
58409 p.data = buf.slice(nb);
58410 }
58411 break;
58412 }
58413 ++c;
58414 }
58415 list.length -= c;
58416 return ret;
58417}
58418
58419function endReadable(stream) {
58420 var state = stream._readableState;
58421
58422 // If we get here before consuming all the bytes, then that is a
58423 // bug in node. Should never happen.
58424 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
58425
58426 if (!state.endEmitted) {
58427 state.ended = true;
58428 pna.nextTick(endReadableNT, state, stream);
58429 }
58430}
58431
58432function endReadableNT(state, stream) {
58433 // Check that we didn't get one last unshift.
58434 if (!state.endEmitted && state.length === 0) {
58435 state.endEmitted = true;
58436 stream.readable = false;
58437 stream.emit('end');
58438 }
58439}
58440
58441function indexOf(xs, x) {
58442 for (var i = 0, l = xs.length; i < l; i++) {
58443 if (xs[i] === x) return i;
58444 }
58445 return -1;
58446}
58447}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
58448},{"./_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){
58449// Copyright Joyent, Inc. and other Node contributors.
58450//
58451// Permission is hereby granted, free of charge, to any person obtaining a
58452// copy of this software and associated documentation files (the
58453// "Software"), to deal in the Software without restriction, including
58454// without limitation the rights to use, copy, modify, merge, publish,
58455// distribute, sublicense, and/or sell copies of the Software, and to permit
58456// persons to whom the Software is furnished to do so, subject to the
58457// following conditions:
58458//
58459// The above copyright notice and this permission notice shall be included
58460// in all copies or substantial portions of the Software.
58461//
58462// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
58463// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
58464// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
58465// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
58466// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
58467// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
58468// USE OR OTHER DEALINGS IN THE SOFTWARE.
58469
58470// a transform stream is a readable/writable stream where you do
58471// something with the data. Sometimes it's called a "filter",
58472// but that's not a great name for it, since that implies a thing where
58473// some bits pass through, and others are simply ignored. (That would
58474// be a valid example of a transform, of course.)
58475//
58476// While the output is causally related to the input, it's not a
58477// necessarily symmetric or synchronous transformation. For example,
58478// a zlib stream might take multiple plain-text writes(), and then
58479// emit a single compressed chunk some time in the future.
58480//
58481// Here's how this works:
58482//
58483// The Transform stream has all the aspects of the readable and writable
58484// stream classes. When you write(chunk), that calls _write(chunk,cb)
58485// internally, and returns false if there's a lot of pending writes
58486// buffered up. When you call read(), that calls _read(n) until
58487// there's enough pending readable data buffered up.
58488//
58489// In a transform stream, the written data is placed in a buffer. When
58490// _read(n) is called, it transforms the queued up data, calling the
58491// buffered _write cb's as it consumes chunks. If consuming a single
58492// written chunk would result in multiple output chunks, then the first
58493// outputted bit calls the readcb, and subsequent chunks just go into
58494// the read buffer, and will cause it to emit 'readable' if necessary.
58495//
58496// This way, back-pressure is actually determined by the reading side,
58497// since _read has to be called to start processing a new chunk. However,
58498// a pathological inflate type of transform can cause excessive buffering
58499// here. For example, imagine a stream where every byte of input is
58500// interpreted as an integer from 0-255, and then results in that many
58501// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
58502// 1kb of data being output. In this case, you could write a very small
58503// amount of input, and end up with a very large amount of output. In
58504// such a pathological inflating mechanism, there'd be no way to tell
58505// the system to stop doing the transform. A single 4MB write could
58506// cause the system to run out of memory.
58507//
58508// However, even in such a pathological case, only a single written chunk
58509// would be consumed, and then the rest would wait (un-transformed) until
58510// the results of the previous transformed chunk were consumed.
58511
58512'use strict';
58513
58514module.exports = Transform;
58515
58516var Duplex = require('./_stream_duplex');
58517
58518/*<replacement>*/
58519var util = require('core-util-is');
58520util.inherits = require('inherits');
58521/*</replacement>*/
58522
58523util.inherits(Transform, Duplex);
58524
58525function afterTransform(er, data) {
58526 var ts = this._transformState;
58527 ts.transforming = false;
58528
58529 var cb = ts.writecb;
58530
58531 if (!cb) {
58532 return this.emit('error', new Error('write callback called multiple times'));
58533 }
58534
58535 ts.writechunk = null;
58536 ts.writecb = null;
58537
58538 if (data != null) // single equals check for both `null` and `undefined`
58539 this.push(data);
58540
58541 cb(er);
58542
58543 var rs = this._readableState;
58544 rs.reading = false;
58545 if (rs.needReadable || rs.length < rs.highWaterMark) {
58546 this._read(rs.highWaterMark);
58547 }
58548}
58549
58550function Transform(options) {
58551 if (!(this instanceof Transform)) return new Transform(options);
58552
58553 Duplex.call(this, options);
58554
58555 this._transformState = {
58556 afterTransform: afterTransform.bind(this),
58557 needTransform: false,
58558 transforming: false,
58559 writecb: null,
58560 writechunk: null,
58561 writeencoding: null
58562 };
58563
58564 // start out asking for a readable event once data is transformed.
58565 this._readableState.needReadable = true;
58566
58567 // we have implemented the _read method, and done the other things
58568 // that Readable wants before the first _read call, so unset the
58569 // sync guard flag.
58570 this._readableState.sync = false;
58571
58572 if (options) {
58573 if (typeof options.transform === 'function') this._transform = options.transform;
58574
58575 if (typeof options.flush === 'function') this._flush = options.flush;
58576 }
58577
58578 // When the writable side finishes, then flush out anything remaining.
58579 this.on('prefinish', prefinish);
58580}
58581
58582function prefinish() {
58583 var _this = this;
58584
58585 if (typeof this._flush === 'function') {
58586 this._flush(function (er, data) {
58587 done(_this, er, data);
58588 });
58589 } else {
58590 done(this, null, null);
58591 }
58592}
58593
58594Transform.prototype.push = function (chunk, encoding) {
58595 this._transformState.needTransform = false;
58596 return Duplex.prototype.push.call(this, chunk, encoding);
58597};
58598
58599// This is the part where you do stuff!
58600// override this function in implementation classes.
58601// 'chunk' is an input chunk.
58602//
58603// Call `push(newChunk)` to pass along transformed output
58604// to the readable side. You may call 'push' zero or more times.
58605//
58606// Call `cb(err)` when you are done with this chunk. If you pass
58607// an error, then that'll put the hurt on the whole operation. If you
58608// never call cb(), then you'll never get another chunk.
58609Transform.prototype._transform = function (chunk, encoding, cb) {
58610 throw new Error('_transform() is not implemented');
58611};
58612
58613Transform.prototype._write = function (chunk, encoding, cb) {
58614 var ts = this._transformState;
58615 ts.writecb = cb;
58616 ts.writechunk = chunk;
58617 ts.writeencoding = encoding;
58618 if (!ts.transforming) {
58619 var rs = this._readableState;
58620 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
58621 }
58622};
58623
58624// Doesn't matter what the args are here.
58625// _transform does all the work.
58626// That we got here means that the readable side wants more data.
58627Transform.prototype._read = function (n) {
58628 var ts = this._transformState;
58629
58630 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
58631 ts.transforming = true;
58632 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
58633 } else {
58634 // mark that we need a transform, so that any data that comes in
58635 // will get processed, now that we've asked for it.
58636 ts.needTransform = true;
58637 }
58638};
58639
58640Transform.prototype._destroy = function (err, cb) {
58641 var _this2 = this;
58642
58643 Duplex.prototype._destroy.call(this, err, function (err2) {
58644 cb(err2);
58645 _this2.emit('close');
58646 });
58647};
58648
58649function done(stream, er, data) {
58650 if (er) return stream.emit('error', er);
58651
58652 if (data != null) // single equals check for both `null` and `undefined`
58653 stream.push(data);
58654
58655 // if there's nothing in the write buffer, then that means
58656 // that nothing more will ever be provided
58657 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
58658
58659 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
58660
58661 return stream.push(null);
58662}
58663},{"./_stream_duplex":281,"core-util-is":120,"inherits":210}],285:[function(require,module,exports){
58664(function (process,global,setImmediate){
58665// Copyright Joyent, Inc. and other Node contributors.
58666//
58667// Permission is hereby granted, free of charge, to any person obtaining a
58668// copy of this software and associated documentation files (the
58669// "Software"), to deal in the Software without restriction, including
58670// without limitation the rights to use, copy, modify, merge, publish,
58671// distribute, sublicense, and/or sell copies of the Software, and to permit
58672// persons to whom the Software is furnished to do so, subject to the
58673// following conditions:
58674//
58675// The above copyright notice and this permission notice shall be included
58676// in all copies or substantial portions of the Software.
58677//
58678// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
58679// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
58680// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
58681// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
58682// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
58683// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
58684// USE OR OTHER DEALINGS IN THE SOFTWARE.
58685
58686// A bit simpler than readable streams.
58687// Implement an async ._write(chunk, encoding, cb), and it'll handle all
58688// the drain event emission and buffering.
58689
58690'use strict';
58691
58692/*<replacement>*/
58693
58694var pna = require('process-nextick-args');
58695/*</replacement>*/
58696
58697module.exports = Writable;
58698
58699/* <replacement> */
58700function WriteReq(chunk, encoding, cb) {
58701 this.chunk = chunk;
58702 this.encoding = encoding;
58703 this.callback = cb;
58704 this.next = null;
58705}
58706
58707// It seems a linked list but it is not
58708// there will be only 2 of these for each stream
58709function CorkedRequest(state) {
58710 var _this = this;
58711
58712 this.next = null;
58713 this.entry = null;
58714 this.finish = function () {
58715 onCorkedFinish(_this, state);
58716 };
58717}
58718/* </replacement> */
58719
58720/*<replacement>*/
58721var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
58722/*</replacement>*/
58723
58724/*<replacement>*/
58725var Duplex;
58726/*</replacement>*/
58727
58728Writable.WritableState = WritableState;
58729
58730/*<replacement>*/
58731var util = require('core-util-is');
58732util.inherits = require('inherits');
58733/*</replacement>*/
58734
58735/*<replacement>*/
58736var internalUtil = {
58737 deprecate: require('util-deprecate')
58738};
58739/*</replacement>*/
58740
58741/*<replacement>*/
58742var Stream = require('./internal/streams/stream');
58743/*</replacement>*/
58744
58745/*<replacement>*/
58746
58747var Buffer = require('safe-buffer').Buffer;
58748var OurUint8Array = global.Uint8Array || function () {};
58749function _uint8ArrayToBuffer(chunk) {
58750 return Buffer.from(chunk);
58751}
58752function _isUint8Array(obj) {
58753 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
58754}
58755
58756/*</replacement>*/
58757
58758var destroyImpl = require('./internal/streams/destroy');
58759
58760util.inherits(Writable, Stream);
58761
58762function nop() {}
58763
58764function WritableState(options, stream) {
58765 Duplex = Duplex || require('./_stream_duplex');
58766
58767 options = options || {};
58768
58769 // Duplex streams are both readable and writable, but share
58770 // the same options object.
58771 // However, some cases require setting options to different
58772 // values for the readable and the writable sides of the duplex stream.
58773 // These options can be provided separately as readableXXX and writableXXX.
58774 var isDuplex = stream instanceof Duplex;
58775
58776 // object stream flag to indicate whether or not this stream
58777 // contains buffers or objects.
58778 this.objectMode = !!options.objectMode;
58779
58780 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
58781
58782 // the point at which write() starts returning false
58783 // Note: 0 is a valid value, means that we always return false if
58784 // the entire buffer is not flushed immediately on write()
58785 var hwm = options.highWaterMark;
58786 var writableHwm = options.writableHighWaterMark;
58787 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
58788
58789 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
58790
58791 // cast to ints.
58792 this.highWaterMark = Math.floor(this.highWaterMark);
58793
58794 // if _final has been called
58795 this.finalCalled = false;
58796
58797 // drain event flag.
58798 this.needDrain = false;
58799 // at the start of calling end()
58800 this.ending = false;
58801 // when end() has been called, and returned
58802 this.ended = false;
58803 // when 'finish' is emitted
58804 this.finished = false;
58805
58806 // has it been destroyed
58807 this.destroyed = false;
58808
58809 // should we decode strings into buffers before passing to _write?
58810 // this is here so that some node-core streams can optimize string
58811 // handling at a lower level.
58812 var noDecode = options.decodeStrings === false;
58813 this.decodeStrings = !noDecode;
58814
58815 // Crypto is kind of old and crusty. Historically, its default string
58816 // encoding is 'binary' so we have to make this configurable.
58817 // Everything else in the universe uses 'utf8', though.
58818 this.defaultEncoding = options.defaultEncoding || 'utf8';
58819
58820 // not an actual buffer we keep track of, but a measurement
58821 // of how much we're waiting to get pushed to some underlying
58822 // socket or file.
58823 this.length = 0;
58824
58825 // a flag to see when we're in the middle of a write.
58826 this.writing = false;
58827
58828 // when true all writes will be buffered until .uncork() call
58829 this.corked = 0;
58830
58831 // a flag to be able to tell if the onwrite cb is called immediately,
58832 // or on a later tick. We set this to true at first, because any
58833 // actions that shouldn't happen until "later" should generally also
58834 // not happen before the first write call.
58835 this.sync = true;
58836
58837 // a flag to know if we're processing previously buffered items, which
58838 // may call the _write() callback in the same tick, so that we don't
58839 // end up in an overlapped onwrite situation.
58840 this.bufferProcessing = false;
58841
58842 // the callback that's passed to _write(chunk,cb)
58843 this.onwrite = function (er) {
58844 onwrite(stream, er);
58845 };
58846
58847 // the callback that the user supplies to write(chunk,encoding,cb)
58848 this.writecb = null;
58849
58850 // the amount that is being written when _write is called.
58851 this.writelen = 0;
58852
58853 this.bufferedRequest = null;
58854 this.lastBufferedRequest = null;
58855
58856 // number of pending user-supplied write callbacks
58857 // this must be 0 before 'finish' can be emitted
58858 this.pendingcb = 0;
58859
58860 // emit prefinish if the only thing we're waiting for is _write cbs
58861 // This is relevant for synchronous Transform streams
58862 this.prefinished = false;
58863
58864 // True if the error was already emitted and should not be thrown again
58865 this.errorEmitted = false;
58866
58867 // count buffered requests
58868 this.bufferedRequestCount = 0;
58869
58870 // allocate the first CorkedRequest, there is always
58871 // one allocated and free to use, and we maintain at most two
58872 this.corkedRequestsFree = new CorkedRequest(this);
58873}
58874
58875WritableState.prototype.getBuffer = function getBuffer() {
58876 var current = this.bufferedRequest;
58877 var out = [];
58878 while (current) {
58879 out.push(current);
58880 current = current.next;
58881 }
58882 return out;
58883};
58884
58885(function () {
58886 try {
58887 Object.defineProperty(WritableState.prototype, 'buffer', {
58888 get: internalUtil.deprecate(function () {
58889 return this.getBuffer();
58890 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
58891 });
58892 } catch (_) {}
58893})();
58894
58895// Test _writableState for inheritance to account for Duplex streams,
58896// whose prototype chain only points to Readable.
58897var realHasInstance;
58898if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
58899 realHasInstance = Function.prototype[Symbol.hasInstance];
58900 Object.defineProperty(Writable, Symbol.hasInstance, {
58901 value: function (object) {
58902 if (realHasInstance.call(this, object)) return true;
58903 if (this !== Writable) return false;
58904
58905 return object && object._writableState instanceof WritableState;
58906 }
58907 });
58908} else {
58909 realHasInstance = function (object) {
58910 return object instanceof this;
58911 };
58912}
58913
58914function Writable(options) {
58915 Duplex = Duplex || require('./_stream_duplex');
58916
58917 // Writable ctor is applied to Duplexes, too.
58918 // `realHasInstance` is necessary because using plain `instanceof`
58919 // would return false, as no `_writableState` property is attached.
58920
58921 // Trying to use the custom `instanceof` for Writable here will also break the
58922 // Node.js LazyTransform implementation, which has a non-trivial getter for
58923 // `_writableState` that would lead to infinite recursion.
58924 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
58925 return new Writable(options);
58926 }
58927
58928 this._writableState = new WritableState(options, this);
58929
58930 // legacy.
58931 this.writable = true;
58932
58933 if (options) {
58934 if (typeof options.write === 'function') this._write = options.write;
58935
58936 if (typeof options.writev === 'function') this._writev = options.writev;
58937
58938 if (typeof options.destroy === 'function') this._destroy = options.destroy;
58939
58940 if (typeof options.final === 'function') this._final = options.final;
58941 }
58942
58943 Stream.call(this);
58944}
58945
58946// Otherwise people can pipe Writable streams, which is just wrong.
58947Writable.prototype.pipe = function () {
58948 this.emit('error', new Error('Cannot pipe, not readable'));
58949};
58950
58951function writeAfterEnd(stream, cb) {
58952 var er = new Error('write after end');
58953 // TODO: defer error events consistently everywhere, not just the cb
58954 stream.emit('error', er);
58955 pna.nextTick(cb, er);
58956}
58957
58958// Checks that a user-supplied chunk is valid, especially for the particular
58959// mode the stream is in. Currently this means that `null` is never accepted
58960// and undefined/non-string values are only allowed in object mode.
58961function validChunk(stream, state, chunk, cb) {
58962 var valid = true;
58963 var er = false;
58964
58965 if (chunk === null) {
58966 er = new TypeError('May not write null values to stream');
58967 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
58968 er = new TypeError('Invalid non-string/buffer chunk');
58969 }
58970 if (er) {
58971 stream.emit('error', er);
58972 pna.nextTick(cb, er);
58973 valid = false;
58974 }
58975 return valid;
58976}
58977
58978Writable.prototype.write = function (chunk, encoding, cb) {
58979 var state = this._writableState;
58980 var ret = false;
58981 var isBuf = !state.objectMode && _isUint8Array(chunk);
58982
58983 if (isBuf && !Buffer.isBuffer(chunk)) {
58984 chunk = _uint8ArrayToBuffer(chunk);
58985 }
58986
58987 if (typeof encoding === 'function') {
58988 cb = encoding;
58989 encoding = null;
58990 }
58991
58992 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
58993
58994 if (typeof cb !== 'function') cb = nop;
58995
58996 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
58997 state.pendingcb++;
58998 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
58999 }
59000
59001 return ret;
59002};
59003
59004Writable.prototype.cork = function () {
59005 var state = this._writableState;
59006
59007 state.corked++;
59008};
59009
59010Writable.prototype.uncork = function () {
59011 var state = this._writableState;
59012
59013 if (state.corked) {
59014 state.corked--;
59015
59016 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
59017 }
59018};
59019
59020Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
59021 // node::ParseEncoding() requires lower case.
59022 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
59023 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);
59024 this._writableState.defaultEncoding = encoding;
59025 return this;
59026};
59027
59028function decodeChunk(state, chunk, encoding) {
59029 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
59030 chunk = Buffer.from(chunk, encoding);
59031 }
59032 return chunk;
59033}
59034
59035Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
59036 // making it explicit this property is not enumerable
59037 // because otherwise some prototype manipulation in
59038 // userland will fail
59039 enumerable: false,
59040 get: function () {
59041 return this._writableState.highWaterMark;
59042 }
59043});
59044
59045// if we're already writing something, then just put this
59046// in the queue, and wait our turn. Otherwise, call _write
59047// If we return false, then we need a drain event, so set that flag.
59048function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
59049 if (!isBuf) {
59050 var newChunk = decodeChunk(state, chunk, encoding);
59051 if (chunk !== newChunk) {
59052 isBuf = true;
59053 encoding = 'buffer';
59054 chunk = newChunk;
59055 }
59056 }
59057 var len = state.objectMode ? 1 : chunk.length;
59058
59059 state.length += len;
59060
59061 var ret = state.length < state.highWaterMark;
59062 // we must ensure that previous needDrain will not be reset to false.
59063 if (!ret) state.needDrain = true;
59064
59065 if (state.writing || state.corked) {
59066 var last = state.lastBufferedRequest;
59067 state.lastBufferedRequest = {
59068 chunk: chunk,
59069 encoding: encoding,
59070 isBuf: isBuf,
59071 callback: cb,
59072 next: null
59073 };
59074 if (last) {
59075 last.next = state.lastBufferedRequest;
59076 } else {
59077 state.bufferedRequest = state.lastBufferedRequest;
59078 }
59079 state.bufferedRequestCount += 1;
59080 } else {
59081 doWrite(stream, state, false, len, chunk, encoding, cb);
59082 }
59083
59084 return ret;
59085}
59086
59087function doWrite(stream, state, writev, len, chunk, encoding, cb) {
59088 state.writelen = len;
59089 state.writecb = cb;
59090 state.writing = true;
59091 state.sync = true;
59092 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
59093 state.sync = false;
59094}
59095
59096function onwriteError(stream, state, sync, er, cb) {
59097 --state.pendingcb;
59098
59099 if (sync) {
59100 // defer the callback if we are being called synchronously
59101 // to avoid piling up things on the stack
59102 pna.nextTick(cb, er);
59103 // this can emit finish, and it will always happen
59104 // after error
59105 pna.nextTick(finishMaybe, stream, state);
59106 stream._writableState.errorEmitted = true;
59107 stream.emit('error', er);
59108 } else {
59109 // the caller expect this to happen before if
59110 // it is async
59111 cb(er);
59112 stream._writableState.errorEmitted = true;
59113 stream.emit('error', er);
59114 // this can emit finish, but finish must
59115 // always follow error
59116 finishMaybe(stream, state);
59117 }
59118}
59119
59120function onwriteStateUpdate(state) {
59121 state.writing = false;
59122 state.writecb = null;
59123 state.length -= state.writelen;
59124 state.writelen = 0;
59125}
59126
59127function onwrite(stream, er) {
59128 var state = stream._writableState;
59129 var sync = state.sync;
59130 var cb = state.writecb;
59131
59132 onwriteStateUpdate(state);
59133
59134 if (er) onwriteError(stream, state, sync, er, cb);else {
59135 // Check if we're actually ready to finish, but don't emit yet
59136 var finished = needFinish(state);
59137
59138 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
59139 clearBuffer(stream, state);
59140 }
59141
59142 if (sync) {
59143 /*<replacement>*/
59144 asyncWrite(afterWrite, stream, state, finished, cb);
59145 /*</replacement>*/
59146 } else {
59147 afterWrite(stream, state, finished, cb);
59148 }
59149 }
59150}
59151
59152function afterWrite(stream, state, finished, cb) {
59153 if (!finished) onwriteDrain(stream, state);
59154 state.pendingcb--;
59155 cb();
59156 finishMaybe(stream, state);
59157}
59158
59159// Must force callback to be called on nextTick, so that we don't
59160// emit 'drain' before the write() consumer gets the 'false' return
59161// value, and has a chance to attach a 'drain' listener.
59162function onwriteDrain(stream, state) {
59163 if (state.length === 0 && state.needDrain) {
59164 state.needDrain = false;
59165 stream.emit('drain');
59166 }
59167}
59168
59169// if there's something in the buffer waiting, then process it
59170function clearBuffer(stream, state) {
59171 state.bufferProcessing = true;
59172 var entry = state.bufferedRequest;
59173
59174 if (stream._writev && entry && entry.next) {
59175 // Fast case, write everything using _writev()
59176 var l = state.bufferedRequestCount;
59177 var buffer = new Array(l);
59178 var holder = state.corkedRequestsFree;
59179 holder.entry = entry;
59180
59181 var count = 0;
59182 var allBuffers = true;
59183 while (entry) {
59184 buffer[count] = entry;
59185 if (!entry.isBuf) allBuffers = false;
59186 entry = entry.next;
59187 count += 1;
59188 }
59189 buffer.allBuffers = allBuffers;
59190
59191 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
59192
59193 // doWrite is almost always async, defer these to save a bit of time
59194 // as the hot path ends with doWrite
59195 state.pendingcb++;
59196 state.lastBufferedRequest = null;
59197 if (holder.next) {
59198 state.corkedRequestsFree = holder.next;
59199 holder.next = null;
59200 } else {
59201 state.corkedRequestsFree = new CorkedRequest(state);
59202 }
59203 state.bufferedRequestCount = 0;
59204 } else {
59205 // Slow case, write chunks one-by-one
59206 while (entry) {
59207 var chunk = entry.chunk;
59208 var encoding = entry.encoding;
59209 var cb = entry.callback;
59210 var len = state.objectMode ? 1 : chunk.length;
59211
59212 doWrite(stream, state, false, len, chunk, encoding, cb);
59213 entry = entry.next;
59214 state.bufferedRequestCount--;
59215 // if we didn't call the onwrite immediately, then
59216 // it means that we need to wait until it does.
59217 // also, that means that the chunk and cb are currently
59218 // being processed, so move the buffer counter past them.
59219 if (state.writing) {
59220 break;
59221 }
59222 }
59223
59224 if (entry === null) state.lastBufferedRequest = null;
59225 }
59226
59227 state.bufferedRequest = entry;
59228 state.bufferProcessing = false;
59229}
59230
59231Writable.prototype._write = function (chunk, encoding, cb) {
59232 cb(new Error('_write() is not implemented'));
59233};
59234
59235Writable.prototype._writev = null;
59236
59237Writable.prototype.end = function (chunk, encoding, cb) {
59238 var state = this._writableState;
59239
59240 if (typeof chunk === 'function') {
59241 cb = chunk;
59242 chunk = null;
59243 encoding = null;
59244 } else if (typeof encoding === 'function') {
59245 cb = encoding;
59246 encoding = null;
59247 }
59248
59249 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
59250
59251 // .end() fully uncorks
59252 if (state.corked) {
59253 state.corked = 1;
59254 this.uncork();
59255 }
59256
59257 // ignore unnecessary end() calls.
59258 if (!state.ending && !state.finished) endWritable(this, state, cb);
59259};
59260
59261function needFinish(state) {
59262 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
59263}
59264function callFinal(stream, state) {
59265 stream._final(function (err) {
59266 state.pendingcb--;
59267 if (err) {
59268 stream.emit('error', err);
59269 }
59270 state.prefinished = true;
59271 stream.emit('prefinish');
59272 finishMaybe(stream, state);
59273 });
59274}
59275function prefinish(stream, state) {
59276 if (!state.prefinished && !state.finalCalled) {
59277 if (typeof stream._final === 'function') {
59278 state.pendingcb++;
59279 state.finalCalled = true;
59280 pna.nextTick(callFinal, stream, state);
59281 } else {
59282 state.prefinished = true;
59283 stream.emit('prefinish');
59284 }
59285 }
59286}
59287
59288function finishMaybe(stream, state) {
59289 var need = needFinish(state);
59290 if (need) {
59291 prefinish(stream, state);
59292 if (state.pendingcb === 0) {
59293 state.finished = true;
59294 stream.emit('finish');
59295 }
59296 }
59297 return need;
59298}
59299
59300function endWritable(stream, state, cb) {
59301 state.ending = true;
59302 finishMaybe(stream, state);
59303 if (cb) {
59304 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
59305 }
59306 state.ended = true;
59307 stream.writable = false;
59308}
59309
59310function onCorkedFinish(corkReq, state, err) {
59311 var entry = corkReq.entry;
59312 corkReq.entry = null;
59313 while (entry) {
59314 var cb = entry.callback;
59315 state.pendingcb--;
59316 cb(err);
59317 entry = entry.next;
59318 }
59319 if (state.corkedRequestsFree) {
59320 state.corkedRequestsFree.next = corkReq;
59321 } else {
59322 state.corkedRequestsFree = corkReq;
59323 }
59324}
59325
59326Object.defineProperty(Writable.prototype, 'destroyed', {
59327 get: function () {
59328 if (this._writableState === undefined) {
59329 return false;
59330 }
59331 return this._writableState.destroyed;
59332 },
59333 set: function (value) {
59334 // we ignore the value if the stream
59335 // has not been initialized yet
59336 if (!this._writableState) {
59337 return;
59338 }
59339
59340 // backward compatibility, the user is explicitly
59341 // managing destroyed
59342 this._writableState.destroyed = value;
59343 }
59344});
59345
59346Writable.prototype.destroy = destroyImpl.destroy;
59347Writable.prototype._undestroy = destroyImpl.undestroy;
59348Writable.prototype._destroy = function (err, cb) {
59349 this.end();
59350 cb(err);
59351};
59352}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
59353},{"./_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){
59354'use strict';
59355
59356function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
59357
59358var Buffer = require('safe-buffer').Buffer;
59359var util = require('util');
59360
59361function copyBuffer(src, target, offset) {
59362 src.copy(target, offset);
59363}
59364
59365module.exports = function () {
59366 function BufferList() {
59367 _classCallCheck(this, BufferList);
59368
59369 this.head = null;
59370 this.tail = null;
59371 this.length = 0;
59372 }
59373
59374 BufferList.prototype.push = function push(v) {
59375 var entry = { data: v, next: null };
59376 if (this.length > 0) this.tail.next = entry;else this.head = entry;
59377 this.tail = entry;
59378 ++this.length;
59379 };
59380
59381 BufferList.prototype.unshift = function unshift(v) {
59382 var entry = { data: v, next: this.head };
59383 if (this.length === 0) this.tail = entry;
59384 this.head = entry;
59385 ++this.length;
59386 };
59387
59388 BufferList.prototype.shift = function shift() {
59389 if (this.length === 0) return;
59390 var ret = this.head.data;
59391 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
59392 --this.length;
59393 return ret;
59394 };
59395
59396 BufferList.prototype.clear = function clear() {
59397 this.head = this.tail = null;
59398 this.length = 0;
59399 };
59400
59401 BufferList.prototype.join = function join(s) {
59402 if (this.length === 0) return '';
59403 var p = this.head;
59404 var ret = '' + p.data;
59405 while (p = p.next) {
59406 ret += s + p.data;
59407 }return ret;
59408 };
59409
59410 BufferList.prototype.concat = function concat(n) {
59411 if (this.length === 0) return Buffer.alloc(0);
59412 if (this.length === 1) return this.head.data;
59413 var ret = Buffer.allocUnsafe(n >>> 0);
59414 var p = this.head;
59415 var i = 0;
59416 while (p) {
59417 copyBuffer(p.data, ret, i);
59418 i += p.data.length;
59419 p = p.next;
59420 }
59421 return ret;
59422 };
59423
59424 return BufferList;
59425}();
59426
59427if (util && util.inspect && util.inspect.custom) {
59428 module.exports.prototype[util.inspect.custom] = function () {
59429 var obj = util.inspect({ length: this.length });
59430 return this.constructor.name + ' ' + obj;
59431 };
59432}
59433},{"safe-buffer":325,"util":82}],287:[function(require,module,exports){
59434'use strict';
59435
59436/*<replacement>*/
59437
59438var pna = require('process-nextick-args');
59439/*</replacement>*/
59440
59441// undocumented cb() API, needed for core, not for public API
59442function destroy(err, cb) {
59443 var _this = this;
59444
59445 var readableDestroyed = this._readableState && this._readableState.destroyed;
59446 var writableDestroyed = this._writableState && this._writableState.destroyed;
59447
59448 if (readableDestroyed || writableDestroyed) {
59449 if (cb) {
59450 cb(err);
59451 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
59452 pna.nextTick(emitErrorNT, this, err);
59453 }
59454 return this;
59455 }
59456
59457 // we set destroyed to true before firing error callbacks in order
59458 // to make it re-entrance safe in case destroy() is called within callbacks
59459
59460 if (this._readableState) {
59461 this._readableState.destroyed = true;
59462 }
59463
59464 // if this is a duplex stream mark the writable part as destroyed as well
59465 if (this._writableState) {
59466 this._writableState.destroyed = true;
59467 }
59468
59469 this._destroy(err || null, function (err) {
59470 if (!cb && err) {
59471 pna.nextTick(emitErrorNT, _this, err);
59472 if (_this._writableState) {
59473 _this._writableState.errorEmitted = true;
59474 }
59475 } else if (cb) {
59476 cb(err);
59477 }
59478 });
59479
59480 return this;
59481}
59482
59483function undestroy() {
59484 if (this._readableState) {
59485 this._readableState.destroyed = false;
59486 this._readableState.reading = false;
59487 this._readableState.ended = false;
59488 this._readableState.endEmitted = false;
59489 }
59490
59491 if (this._writableState) {
59492 this._writableState.destroyed = false;
59493 this._writableState.ended = false;
59494 this._writableState.ending = false;
59495 this._writableState.finished = false;
59496 this._writableState.errorEmitted = false;
59497 }
59498}
59499
59500function emitErrorNT(self, err) {
59501 self.emit('error', err);
59502}
59503
59504module.exports = {
59505 destroy: destroy,
59506 undestroy: undestroy
59507};
59508},{"process-nextick-args":264}],288:[function(require,module,exports){
59509module.exports = require('events').EventEmitter;
59510
59511},{"events":159}],289:[function(require,module,exports){
59512// Copyright Joyent, Inc. and other Node contributors.
59513//
59514// Permission is hereby granted, free of charge, to any person obtaining a
59515// copy of this software and associated documentation files (the
59516// "Software"), to deal in the Software without restriction, including
59517// without limitation the rights to use, copy, modify, merge, publish,
59518// distribute, sublicense, and/or sell copies of the Software, and to permit
59519// persons to whom the Software is furnished to do so, subject to the
59520// following conditions:
59521//
59522// The above copyright notice and this permission notice shall be included
59523// in all copies or substantial portions of the Software.
59524//
59525// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
59526// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
59527// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
59528// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
59529// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
59530// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
59531// USE OR OTHER DEALINGS IN THE SOFTWARE.
59532
59533'use strict';
59534
59535/*<replacement>*/
59536
59537var Buffer = require('safe-buffer').Buffer;
59538/*</replacement>*/
59539
59540var isEncoding = Buffer.isEncoding || function (encoding) {
59541 encoding = '' + encoding;
59542 switch (encoding && encoding.toLowerCase()) {
59543 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':
59544 return true;
59545 default:
59546 return false;
59547 }
59548};
59549
59550function _normalizeEncoding(enc) {
59551 if (!enc) return 'utf8';
59552 var retried;
59553 while (true) {
59554 switch (enc) {
59555 case 'utf8':
59556 case 'utf-8':
59557 return 'utf8';
59558 case 'ucs2':
59559 case 'ucs-2':
59560 case 'utf16le':
59561 case 'utf-16le':
59562 return 'utf16le';
59563 case 'latin1':
59564 case 'binary':
59565 return 'latin1';
59566 case 'base64':
59567 case 'ascii':
59568 case 'hex':
59569 return enc;
59570 default:
59571 if (retried) return; // undefined
59572 enc = ('' + enc).toLowerCase();
59573 retried = true;
59574 }
59575 }
59576};
59577
59578// Do not cache `Buffer.isEncoding` when checking encoding names as some
59579// modules monkey-patch it to support additional encodings
59580function normalizeEncoding(enc) {
59581 var nenc = _normalizeEncoding(enc);
59582 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
59583 return nenc || enc;
59584}
59585
59586// StringDecoder provides an interface for efficiently splitting a series of
59587// buffers into a series of JS strings without breaking apart multi-byte
59588// characters.
59589exports.StringDecoder = StringDecoder;
59590function StringDecoder(encoding) {
59591 this.encoding = normalizeEncoding(encoding);
59592 var nb;
59593 switch (this.encoding) {
59594 case 'utf16le':
59595 this.text = utf16Text;
59596 this.end = utf16End;
59597 nb = 4;
59598 break;
59599 case 'utf8':
59600 this.fillLast = utf8FillLast;
59601 nb = 4;
59602 break;
59603 case 'base64':
59604 this.text = base64Text;
59605 this.end = base64End;
59606 nb = 3;
59607 break;
59608 default:
59609 this.write = simpleWrite;
59610 this.end = simpleEnd;
59611 return;
59612 }
59613 this.lastNeed = 0;
59614 this.lastTotal = 0;
59615 this.lastChar = Buffer.allocUnsafe(nb);
59616}
59617
59618StringDecoder.prototype.write = function (buf) {
59619 if (buf.length === 0) return '';
59620 var r;
59621 var i;
59622 if (this.lastNeed) {
59623 r = this.fillLast(buf);
59624 if (r === undefined) return '';
59625 i = this.lastNeed;
59626 this.lastNeed = 0;
59627 } else {
59628 i = 0;
59629 }
59630 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
59631 return r || '';
59632};
59633
59634StringDecoder.prototype.end = utf8End;
59635
59636// Returns only complete characters in a Buffer
59637StringDecoder.prototype.text = utf8Text;
59638
59639// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
59640StringDecoder.prototype.fillLast = function (buf) {
59641 if (this.lastNeed <= buf.length) {
59642 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
59643 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
59644 }
59645 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
59646 this.lastNeed -= buf.length;
59647};
59648
59649// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
59650// continuation byte. If an invalid byte is detected, -2 is returned.
59651function utf8CheckByte(byte) {
59652 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;
59653 return byte >> 6 === 0x02 ? -1 : -2;
59654}
59655
59656// Checks at most 3 bytes at the end of a Buffer in order to detect an
59657// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
59658// needed to complete the UTF-8 character (if applicable) are returned.
59659function utf8CheckIncomplete(self, buf, i) {
59660 var j = buf.length - 1;
59661 if (j < i) return 0;
59662 var nb = utf8CheckByte(buf[j]);
59663 if (nb >= 0) {
59664 if (nb > 0) self.lastNeed = nb - 1;
59665 return nb;
59666 }
59667 if (--j < i || nb === -2) return 0;
59668 nb = utf8CheckByte(buf[j]);
59669 if (nb >= 0) {
59670 if (nb > 0) self.lastNeed = nb - 2;
59671 return nb;
59672 }
59673 if (--j < i || nb === -2) return 0;
59674 nb = utf8CheckByte(buf[j]);
59675 if (nb >= 0) {
59676 if (nb > 0) {
59677 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
59678 }
59679 return nb;
59680 }
59681 return 0;
59682}
59683
59684// Validates as many continuation bytes for a multi-byte UTF-8 character as
59685// needed or are available. If we see a non-continuation byte where we expect
59686// one, we "replace" the validated continuation bytes we've seen so far with
59687// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
59688// behavior. The continuation byte check is included three times in the case
59689// where all of the continuation bytes for a character exist in the same buffer.
59690// It is also done this way as a slight performance increase instead of using a
59691// loop.
59692function utf8CheckExtraBytes(self, buf, p) {
59693 if ((buf[0] & 0xC0) !== 0x80) {
59694 self.lastNeed = 0;
59695 return '\ufffd';
59696 }
59697 if (self.lastNeed > 1 && buf.length > 1) {
59698 if ((buf[1] & 0xC0) !== 0x80) {
59699 self.lastNeed = 1;
59700 return '\ufffd';
59701 }
59702 if (self.lastNeed > 2 && buf.length > 2) {
59703 if ((buf[2] & 0xC0) !== 0x80) {
59704 self.lastNeed = 2;
59705 return '\ufffd';
59706 }
59707 }
59708 }
59709}
59710
59711// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
59712function utf8FillLast(buf) {
59713 var p = this.lastTotal - this.lastNeed;
59714 var r = utf8CheckExtraBytes(this, buf, p);
59715 if (r !== undefined) return r;
59716 if (this.lastNeed <= buf.length) {
59717 buf.copy(this.lastChar, p, 0, this.lastNeed);
59718 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
59719 }
59720 buf.copy(this.lastChar, p, 0, buf.length);
59721 this.lastNeed -= buf.length;
59722}
59723
59724// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
59725// partial character, the character's bytes are buffered until the required
59726// number of bytes are available.
59727function utf8Text(buf, i) {
59728 var total = utf8CheckIncomplete(this, buf, i);
59729 if (!this.lastNeed) return buf.toString('utf8', i);
59730 this.lastTotal = total;
59731 var end = buf.length - (total - this.lastNeed);
59732 buf.copy(this.lastChar, 0, end);
59733 return buf.toString('utf8', i, end);
59734}
59735
59736// For UTF-8, a replacement character is added when ending on a partial
59737// character.
59738function utf8End(buf) {
59739 var r = buf && buf.length ? this.write(buf) : '';
59740 if (this.lastNeed) return r + '\ufffd';
59741 return r;
59742}
59743
59744// UTF-16LE typically needs two bytes per character, but even if we have an even
59745// number of bytes available, we need to check if we end on a leading/high
59746// surrogate. In that case, we need to wait for the next two bytes in order to
59747// decode the last character properly.
59748function utf16Text(buf, i) {
59749 if ((buf.length - i) % 2 === 0) {
59750 var r = buf.toString('utf16le', i);
59751 if (r) {
59752 var c = r.charCodeAt(r.length - 1);
59753 if (c >= 0xD800 && c <= 0xDBFF) {
59754 this.lastNeed = 2;
59755 this.lastTotal = 4;
59756 this.lastChar[0] = buf[buf.length - 2];
59757 this.lastChar[1] = buf[buf.length - 1];
59758 return r.slice(0, -1);
59759 }
59760 }
59761 return r;
59762 }
59763 this.lastNeed = 1;
59764 this.lastTotal = 2;
59765 this.lastChar[0] = buf[buf.length - 1];
59766 return buf.toString('utf16le', i, buf.length - 1);
59767}
59768
59769// For UTF-16LE we do not explicitly append special replacement characters if we
59770// end on a partial character, we simply let v8 handle that.
59771function utf16End(buf) {
59772 var r = buf && buf.length ? this.write(buf) : '';
59773 if (this.lastNeed) {
59774 var end = this.lastTotal - this.lastNeed;
59775 return r + this.lastChar.toString('utf16le', 0, end);
59776 }
59777 return r;
59778}
59779
59780function base64Text(buf, i) {
59781 var n = (buf.length - i) % 3;
59782 if (n === 0) return buf.toString('base64', i);
59783 this.lastNeed = 3 - n;
59784 this.lastTotal = 3;
59785 if (n === 1) {
59786 this.lastChar[0] = buf[buf.length - 1];
59787 } else {
59788 this.lastChar[0] = buf[buf.length - 2];
59789 this.lastChar[1] = buf[buf.length - 1];
59790 }
59791 return buf.toString('base64', i, buf.length - n);
59792}
59793
59794function base64End(buf) {
59795 var r = buf && buf.length ? this.write(buf) : '';
59796 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
59797 return r;
59798}
59799
59800// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
59801function simpleWrite(buf) {
59802 return buf.toString(this.encoding);
59803}
59804
59805function simpleEnd(buf) {
59806 return buf && buf.length ? this.write(buf) : '';
59807}
59808},{"safe-buffer":325}],290:[function(require,module,exports){
59809module.exports = require('./readable').PassThrough
59810
59811},{"./readable":291}],291:[function(require,module,exports){
59812exports = module.exports = require('./lib/_stream_readable.js');
59813exports.Stream = exports;
59814exports.Readable = exports;
59815exports.Writable = require('./lib/_stream_writable.js');
59816exports.Duplex = require('./lib/_stream_duplex.js');
59817exports.Transform = require('./lib/_stream_transform.js');
59818exports.PassThrough = require('./lib/_stream_passthrough.js');
59819
59820},{"./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){
59821module.exports = require('./readable').Transform
59822
59823},{"./readable":291}],293:[function(require,module,exports){
59824module.exports = require('./lib/_stream_writable.js');
59825
59826},{"./lib/_stream_writable.js":285}],294:[function(require,module,exports){
59827/**
59828 * Copyright (c) 2014-present, Facebook, Inc.
59829 *
59830 * This source code is licensed under the MIT license found in the
59831 * LICENSE file in the root directory of this source tree.
59832 */
59833
59834var runtime = (function (exports) {
59835 "use strict";
59836
59837 var Op = Object.prototype;
59838 var hasOwn = Op.hasOwnProperty;
59839 var undefined; // More compressible than void 0.
59840 var $Symbol = typeof Symbol === "function" ? Symbol : {};
59841 var iteratorSymbol = $Symbol.iterator || "@@iterator";
59842 var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
59843 var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
59844
59845 function wrap(innerFn, outerFn, self, tryLocsList) {
59846 // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
59847 var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
59848 var generator = Object.create(protoGenerator.prototype);
59849 var context = new Context(tryLocsList || []);
59850
59851 // The ._invoke method unifies the implementations of the .next,
59852 // .throw, and .return methods.
59853 generator._invoke = makeInvokeMethod(innerFn, self, context);
59854
59855 return generator;
59856 }
59857 exports.wrap = wrap;
59858
59859 // Try/catch helper to minimize deoptimizations. Returns a completion
59860 // record like context.tryEntries[i].completion. This interface could
59861 // have been (and was previously) designed to take a closure to be
59862 // invoked without arguments, but in all the cases we care about we
59863 // already have an existing method we want to call, so there's no need
59864 // to create a new function object. We can even get away with assuming
59865 // the method takes exactly one argument, since that happens to be true
59866 // in every case, so we don't have to touch the arguments object. The
59867 // only additional allocation required is the completion record, which
59868 // has a stable shape and so hopefully should be cheap to allocate.
59869 function tryCatch(fn, obj, arg) {
59870 try {
59871 return { type: "normal", arg: fn.call(obj, arg) };
59872 } catch (err) {
59873 return { type: "throw", arg: err };
59874 }
59875 }
59876
59877 var GenStateSuspendedStart = "suspendedStart";
59878 var GenStateSuspendedYield = "suspendedYield";
59879 var GenStateExecuting = "executing";
59880 var GenStateCompleted = "completed";
59881
59882 // Returning this object from the innerFn has the same effect as
59883 // breaking out of the dispatch switch statement.
59884 var ContinueSentinel = {};
59885
59886 // Dummy constructor functions that we use as the .constructor and
59887 // .constructor.prototype properties for functions that return Generator
59888 // objects. For full spec compliance, you may wish to configure your
59889 // minifier not to mangle the names of these two functions.
59890 function Generator() {}
59891 function GeneratorFunction() {}
59892 function GeneratorFunctionPrototype() {}
59893
59894 // This is a polyfill for %IteratorPrototype% for environments that
59895 // don't natively support it.
59896 var IteratorPrototype = {};
59897 IteratorPrototype[iteratorSymbol] = function () {
59898 return this;
59899 };
59900
59901 var getProto = Object.getPrototypeOf;
59902 var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
59903 if (NativeIteratorPrototype &&
59904 NativeIteratorPrototype !== Op &&
59905 hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
59906 // This environment has a native %IteratorPrototype%; use it instead
59907 // of the polyfill.
59908 IteratorPrototype = NativeIteratorPrototype;
59909 }
59910
59911 var Gp = GeneratorFunctionPrototype.prototype =
59912 Generator.prototype = Object.create(IteratorPrototype);
59913 GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
59914 GeneratorFunctionPrototype.constructor = GeneratorFunction;
59915 GeneratorFunctionPrototype[toStringTagSymbol] =
59916 GeneratorFunction.displayName = "GeneratorFunction";
59917
59918 // Helper for defining the .next, .throw, and .return methods of the
59919 // Iterator interface in terms of a single ._invoke method.
59920 function defineIteratorMethods(prototype) {
59921 ["next", "throw", "return"].forEach(function(method) {
59922 prototype[method] = function(arg) {
59923 return this._invoke(method, arg);
59924 };
59925 });
59926 }
59927
59928 exports.isGeneratorFunction = function(genFun) {
59929 var ctor = typeof genFun === "function" && genFun.constructor;
59930 return ctor
59931 ? ctor === GeneratorFunction ||
59932 // For the native GeneratorFunction constructor, the best we can
59933 // do is to check its .name property.
59934 (ctor.displayName || ctor.name) === "GeneratorFunction"
59935 : false;
59936 };
59937
59938 exports.mark = function(genFun) {
59939 if (Object.setPrototypeOf) {
59940 Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
59941 } else {
59942 genFun.__proto__ = GeneratorFunctionPrototype;
59943 if (!(toStringTagSymbol in genFun)) {
59944 genFun[toStringTagSymbol] = "GeneratorFunction";
59945 }
59946 }
59947 genFun.prototype = Object.create(Gp);
59948 return genFun;
59949 };
59950
59951 // Within the body of any async function, `await x` is transformed to
59952 // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
59953 // `hasOwn.call(value, "__await")` to determine if the yielded value is
59954 // meant to be awaited.
59955 exports.awrap = function(arg) {
59956 return { __await: arg };
59957 };
59958
59959 function AsyncIterator(generator) {
59960 function invoke(method, arg, resolve, reject) {
59961 var record = tryCatch(generator[method], generator, arg);
59962 if (record.type === "throw") {
59963 reject(record.arg);
59964 } else {
59965 var result = record.arg;
59966 var value = result.value;
59967 if (value &&
59968 typeof value === "object" &&
59969 hasOwn.call(value, "__await")) {
59970 return Promise.resolve(value.__await).then(function(value) {
59971 invoke("next", value, resolve, reject);
59972 }, function(err) {
59973 invoke("throw", err, resolve, reject);
59974 });
59975 }
59976
59977 return Promise.resolve(value).then(function(unwrapped) {
59978 // When a yielded Promise is resolved, its final value becomes
59979 // the .value of the Promise<{value,done}> result for the
59980 // current iteration.
59981 result.value = unwrapped;
59982 resolve(result);
59983 }, function(error) {
59984 // If a rejected Promise was yielded, throw the rejection back
59985 // into the async generator function so it can be handled there.
59986 return invoke("throw", error, resolve, reject);
59987 });
59988 }
59989 }
59990
59991 var previousPromise;
59992
59993 function enqueue(method, arg) {
59994 function callInvokeWithMethodAndArg() {
59995 return new Promise(function(resolve, reject) {
59996 invoke(method, arg, resolve, reject);
59997 });
59998 }
59999
60000 return previousPromise =
60001 // If enqueue has been called before, then we want to wait until
60002 // all previous Promises have been resolved before calling invoke,
60003 // so that results are always delivered in the correct order. If
60004 // enqueue has not been called before, then it is important to
60005 // call invoke immediately, without waiting on a callback to fire,
60006 // so that the async generator function has the opportunity to do
60007 // any necessary setup in a predictable way. This predictability
60008 // is why the Promise constructor synchronously invokes its
60009 // executor callback, and why async functions synchronously
60010 // execute code before the first await. Since we implement simple
60011 // async functions in terms of async generators, it is especially
60012 // important to get this right, even though it requires care.
60013 previousPromise ? previousPromise.then(
60014 callInvokeWithMethodAndArg,
60015 // Avoid propagating failures to Promises returned by later
60016 // invocations of the iterator.
60017 callInvokeWithMethodAndArg
60018 ) : callInvokeWithMethodAndArg();
60019 }
60020
60021 // Define the unified helper method that is used to implement .next,
60022 // .throw, and .return (see defineIteratorMethods).
60023 this._invoke = enqueue;
60024 }
60025
60026 defineIteratorMethods(AsyncIterator.prototype);
60027 AsyncIterator.prototype[asyncIteratorSymbol] = function () {
60028 return this;
60029 };
60030 exports.AsyncIterator = AsyncIterator;
60031
60032 // Note that simple async functions are implemented on top of
60033 // AsyncIterator objects; they just return a Promise for the value of
60034 // the final result produced by the iterator.
60035 exports.async = function(innerFn, outerFn, self, tryLocsList) {
60036 var iter = new AsyncIterator(
60037 wrap(innerFn, outerFn, self, tryLocsList)
60038 );
60039
60040 return exports.isGeneratorFunction(outerFn)
60041 ? iter // If outerFn is a generator, return the full iterator.
60042 : iter.next().then(function(result) {
60043 return result.done ? result.value : iter.next();
60044 });
60045 };
60046
60047 function makeInvokeMethod(innerFn, self, context) {
60048 var state = GenStateSuspendedStart;
60049
60050 return function invoke(method, arg) {
60051 if (state === GenStateExecuting) {
60052 throw new Error("Generator is already running");
60053 }
60054
60055 if (state === GenStateCompleted) {
60056 if (method === "throw") {
60057 throw arg;
60058 }
60059
60060 // Be forgiving, per 25.3.3.3.3 of the spec:
60061 // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
60062 return doneResult();
60063 }
60064
60065 context.method = method;
60066 context.arg = arg;
60067
60068 while (true) {
60069 var delegate = context.delegate;
60070 if (delegate) {
60071 var delegateResult = maybeInvokeDelegate(delegate, context);
60072 if (delegateResult) {
60073 if (delegateResult === ContinueSentinel) continue;
60074 return delegateResult;
60075 }
60076 }
60077
60078 if (context.method === "next") {
60079 // Setting context._sent for legacy support of Babel's
60080 // function.sent implementation.
60081 context.sent = context._sent = context.arg;
60082
60083 } else if (context.method === "throw") {
60084 if (state === GenStateSuspendedStart) {
60085 state = GenStateCompleted;
60086 throw context.arg;
60087 }
60088
60089 context.dispatchException(context.arg);
60090
60091 } else if (context.method === "return") {
60092 context.abrupt("return", context.arg);
60093 }
60094
60095 state = GenStateExecuting;
60096
60097 var record = tryCatch(innerFn, self, context);
60098 if (record.type === "normal") {
60099 // If an exception is thrown from innerFn, we leave state ===
60100 // GenStateExecuting and loop back for another invocation.
60101 state = context.done
60102 ? GenStateCompleted
60103 : GenStateSuspendedYield;
60104
60105 if (record.arg === ContinueSentinel) {
60106 continue;
60107 }
60108
60109 return {
60110 value: record.arg,
60111 done: context.done
60112 };
60113
60114 } else if (record.type === "throw") {
60115 state = GenStateCompleted;
60116 // Dispatch the exception by looping back around to the
60117 // context.dispatchException(context.arg) call above.
60118 context.method = "throw";
60119 context.arg = record.arg;
60120 }
60121 }
60122 };
60123 }
60124
60125 // Call delegate.iterator[context.method](context.arg) and handle the
60126 // result, either by returning a { value, done } result from the
60127 // delegate iterator, or by modifying context.method and context.arg,
60128 // setting context.delegate to null, and returning the ContinueSentinel.
60129 function maybeInvokeDelegate(delegate, context) {
60130 var method = delegate.iterator[context.method];
60131 if (method === undefined) {
60132 // A .throw or .return when the delegate iterator has no .throw
60133 // method always terminates the yield* loop.
60134 context.delegate = null;
60135
60136 if (context.method === "throw") {
60137 // Note: ["return"] must be used for ES3 parsing compatibility.
60138 if (delegate.iterator["return"]) {
60139 // If the delegate iterator has a return method, give it a
60140 // chance to clean up.
60141 context.method = "return";
60142 context.arg = undefined;
60143 maybeInvokeDelegate(delegate, context);
60144
60145 if (context.method === "throw") {
60146 // If maybeInvokeDelegate(context) changed context.method from
60147 // "return" to "throw", let that override the TypeError below.
60148 return ContinueSentinel;
60149 }
60150 }
60151
60152 context.method = "throw";
60153 context.arg = new TypeError(
60154 "The iterator does not provide a 'throw' method");
60155 }
60156
60157 return ContinueSentinel;
60158 }
60159
60160 var record = tryCatch(method, delegate.iterator, context.arg);
60161
60162 if (record.type === "throw") {
60163 context.method = "throw";
60164 context.arg = record.arg;
60165 context.delegate = null;
60166 return ContinueSentinel;
60167 }
60168
60169 var info = record.arg;
60170
60171 if (! info) {
60172 context.method = "throw";
60173 context.arg = new TypeError("iterator result is not an object");
60174 context.delegate = null;
60175 return ContinueSentinel;
60176 }
60177
60178 if (info.done) {
60179 // Assign the result of the finished delegate to the temporary
60180 // variable specified by delegate.resultName (see delegateYield).
60181 context[delegate.resultName] = info.value;
60182
60183 // Resume execution at the desired location (see delegateYield).
60184 context.next = delegate.nextLoc;
60185
60186 // If context.method was "throw" but the delegate handled the
60187 // exception, let the outer generator proceed normally. If
60188 // context.method was "next", forget context.arg since it has been
60189 // "consumed" by the delegate iterator. If context.method was
60190 // "return", allow the original .return call to continue in the
60191 // outer generator.
60192 if (context.method !== "return") {
60193 context.method = "next";
60194 context.arg = undefined;
60195 }
60196
60197 } else {
60198 // Re-yield the result returned by the delegate method.
60199 return info;
60200 }
60201
60202 // The delegate iterator is finished, so forget it and continue with
60203 // the outer generator.
60204 context.delegate = null;
60205 return ContinueSentinel;
60206 }
60207
60208 // Define Generator.prototype.{next,throw,return} in terms of the
60209 // unified ._invoke helper method.
60210 defineIteratorMethods(Gp);
60211
60212 Gp[toStringTagSymbol] = "Generator";
60213
60214 // A Generator should always return itself as the iterator object when the
60215 // @@iterator function is called on it. Some browsers' implementations of the
60216 // iterator prototype chain incorrectly implement this, causing the Generator
60217 // object to not be returned from this call. This ensures that doesn't happen.
60218 // See https://github.com/facebook/regenerator/issues/274 for more details.
60219 Gp[iteratorSymbol] = function() {
60220 return this;
60221 };
60222
60223 Gp.toString = function() {
60224 return "[object Generator]";
60225 };
60226
60227 function pushTryEntry(locs) {
60228 var entry = { tryLoc: locs[0] };
60229
60230 if (1 in locs) {
60231 entry.catchLoc = locs[1];
60232 }
60233
60234 if (2 in locs) {
60235 entry.finallyLoc = locs[2];
60236 entry.afterLoc = locs[3];
60237 }
60238
60239 this.tryEntries.push(entry);
60240 }
60241
60242 function resetTryEntry(entry) {
60243 var record = entry.completion || {};
60244 record.type = "normal";
60245 delete record.arg;
60246 entry.completion = record;
60247 }
60248
60249 function Context(tryLocsList) {
60250 // The root entry object (effectively a try statement without a catch
60251 // or a finally block) gives us a place to store values thrown from
60252 // locations where there is no enclosing try statement.
60253 this.tryEntries = [{ tryLoc: "root" }];
60254 tryLocsList.forEach(pushTryEntry, this);
60255 this.reset(true);
60256 }
60257
60258 exports.keys = function(object) {
60259 var keys = [];
60260 for (var key in object) {
60261 keys.push(key);
60262 }
60263 keys.reverse();
60264
60265 // Rather than returning an object with a next method, we keep
60266 // things simple and return the next function itself.
60267 return function next() {
60268 while (keys.length) {
60269 var key = keys.pop();
60270 if (key in object) {
60271 next.value = key;
60272 next.done = false;
60273 return next;
60274 }
60275 }
60276
60277 // To avoid creating an additional object, we just hang the .value
60278 // and .done properties off the next function object itself. This
60279 // also ensures that the minifier will not anonymize the function.
60280 next.done = true;
60281 return next;
60282 };
60283 };
60284
60285 function values(iterable) {
60286 if (iterable) {
60287 var iteratorMethod = iterable[iteratorSymbol];
60288 if (iteratorMethod) {
60289 return iteratorMethod.call(iterable);
60290 }
60291
60292 if (typeof iterable.next === "function") {
60293 return iterable;
60294 }
60295
60296 if (!isNaN(iterable.length)) {
60297 var i = -1, next = function next() {
60298 while (++i < iterable.length) {
60299 if (hasOwn.call(iterable, i)) {
60300 next.value = iterable[i];
60301 next.done = false;
60302 return next;
60303 }
60304 }
60305
60306 next.value = undefined;
60307 next.done = true;
60308
60309 return next;
60310 };
60311
60312 return next.next = next;
60313 }
60314 }
60315
60316 // Return an iterator with no values.
60317 return { next: doneResult };
60318 }
60319 exports.values = values;
60320
60321 function doneResult() {
60322 return { value: undefined, done: true };
60323 }
60324
60325 Context.prototype = {
60326 constructor: Context,
60327
60328 reset: function(skipTempReset) {
60329 this.prev = 0;
60330 this.next = 0;
60331 // Resetting context._sent for legacy support of Babel's
60332 // function.sent implementation.
60333 this.sent = this._sent = undefined;
60334 this.done = false;
60335 this.delegate = null;
60336
60337 this.method = "next";
60338 this.arg = undefined;
60339
60340 this.tryEntries.forEach(resetTryEntry);
60341
60342 if (!skipTempReset) {
60343 for (var name in this) {
60344 // Not sure about the optimal order of these conditions:
60345 if (name.charAt(0) === "t" &&
60346 hasOwn.call(this, name) &&
60347 !isNaN(+name.slice(1))) {
60348 this[name] = undefined;
60349 }
60350 }
60351 }
60352 },
60353
60354 stop: function() {
60355 this.done = true;
60356
60357 var rootEntry = this.tryEntries[0];
60358 var rootRecord = rootEntry.completion;
60359 if (rootRecord.type === "throw") {
60360 throw rootRecord.arg;
60361 }
60362
60363 return this.rval;
60364 },
60365
60366 dispatchException: function(exception) {
60367 if (this.done) {
60368 throw exception;
60369 }
60370
60371 var context = this;
60372 function handle(loc, caught) {
60373 record.type = "throw";
60374 record.arg = exception;
60375 context.next = loc;
60376
60377 if (caught) {
60378 // If the dispatched exception was caught by a catch block,
60379 // then let that catch block handle the exception normally.
60380 context.method = "next";
60381 context.arg = undefined;
60382 }
60383
60384 return !! caught;
60385 }
60386
60387 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
60388 var entry = this.tryEntries[i];
60389 var record = entry.completion;
60390
60391 if (entry.tryLoc === "root") {
60392 // Exception thrown outside of any try block that could handle
60393 // it, so set the completion value of the entire function to
60394 // throw the exception.
60395 return handle("end");
60396 }
60397
60398 if (entry.tryLoc <= this.prev) {
60399 var hasCatch = hasOwn.call(entry, "catchLoc");
60400 var hasFinally = hasOwn.call(entry, "finallyLoc");
60401
60402 if (hasCatch && hasFinally) {
60403 if (this.prev < entry.catchLoc) {
60404 return handle(entry.catchLoc, true);
60405 } else if (this.prev < entry.finallyLoc) {
60406 return handle(entry.finallyLoc);
60407 }
60408
60409 } else if (hasCatch) {
60410 if (this.prev < entry.catchLoc) {
60411 return handle(entry.catchLoc, true);
60412 }
60413
60414 } else if (hasFinally) {
60415 if (this.prev < entry.finallyLoc) {
60416 return handle(entry.finallyLoc);
60417 }
60418
60419 } else {
60420 throw new Error("try statement without catch or finally");
60421 }
60422 }
60423 }
60424 },
60425
60426 abrupt: function(type, arg) {
60427 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
60428 var entry = this.tryEntries[i];
60429 if (entry.tryLoc <= this.prev &&
60430 hasOwn.call(entry, "finallyLoc") &&
60431 this.prev < entry.finallyLoc) {
60432 var finallyEntry = entry;
60433 break;
60434 }
60435 }
60436
60437 if (finallyEntry &&
60438 (type === "break" ||
60439 type === "continue") &&
60440 finallyEntry.tryLoc <= arg &&
60441 arg <= finallyEntry.finallyLoc) {
60442 // Ignore the finally entry if control is not jumping to a
60443 // location outside the try/catch block.
60444 finallyEntry = null;
60445 }
60446
60447 var record = finallyEntry ? finallyEntry.completion : {};
60448 record.type = type;
60449 record.arg = arg;
60450
60451 if (finallyEntry) {
60452 this.method = "next";
60453 this.next = finallyEntry.finallyLoc;
60454 return ContinueSentinel;
60455 }
60456
60457 return this.complete(record);
60458 },
60459
60460 complete: function(record, afterLoc) {
60461 if (record.type === "throw") {
60462 throw record.arg;
60463 }
60464
60465 if (record.type === "break" ||
60466 record.type === "continue") {
60467 this.next = record.arg;
60468 } else if (record.type === "return") {
60469 this.rval = this.arg = record.arg;
60470 this.method = "return";
60471 this.next = "end";
60472 } else if (record.type === "normal" && afterLoc) {
60473 this.next = afterLoc;
60474 }
60475
60476 return ContinueSentinel;
60477 },
60478
60479 finish: function(finallyLoc) {
60480 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
60481 var entry = this.tryEntries[i];
60482 if (entry.finallyLoc === finallyLoc) {
60483 this.complete(entry.completion, entry.afterLoc);
60484 resetTryEntry(entry);
60485 return ContinueSentinel;
60486 }
60487 }
60488 },
60489
60490 "catch": function(tryLoc) {
60491 for (var i = this.tryEntries.length - 1; i >= 0; --i) {
60492 var entry = this.tryEntries[i];
60493 if (entry.tryLoc === tryLoc) {
60494 var record = entry.completion;
60495 if (record.type === "throw") {
60496 var thrown = record.arg;
60497 resetTryEntry(entry);
60498 }
60499 return thrown;
60500 }
60501 }
60502
60503 // The context.catch method must only be called with a location
60504 // argument that corresponds to a known catch block.
60505 throw new Error("illegal catch attempt");
60506 },
60507
60508 delegateYield: function(iterable, resultName, nextLoc) {
60509 this.delegate = {
60510 iterator: values(iterable),
60511 resultName: resultName,
60512 nextLoc: nextLoc
60513 };
60514
60515 if (this.method === "next") {
60516 // Deliberately forget the last sent value so that we don't
60517 // accidentally pass it on to the delegate.
60518 this.arg = undefined;
60519 }
60520
60521 return ContinueSentinel;
60522 }
60523 };
60524
60525 // Regardless of whether this script is executing as a CommonJS module
60526 // or not, return the runtime object so that we can declare the variable
60527 // regeneratorRuntime in the outer scope, which allows this module to be
60528 // injected easily by `bin/regenerator --include-runtime script.js`.
60529 return exports;
60530
60531}(
60532 // If this script is executing as a CommonJS module, use module.exports
60533 // as the regeneratorRuntime namespace. Otherwise create a new empty
60534 // object. Either way, the resulting object will be used to initialize
60535 // the regeneratorRuntime variable at the top of this file.
60536 typeof module === "object" ? module.exports : {}
60537));
60538
60539try {
60540 regeneratorRuntime = runtime;
60541} catch (accidentalStrictMode) {
60542 // This module should not be running in strict mode, so the above
60543 // assignment should always work unless something is misconfigured. Just
60544 // in case runtime.js accidentally runs in strict mode, we can escape
60545 // strict mode using a global Function call. This could conceivably fail
60546 // if a Content Security Policy forbids using Function, but in that case
60547 // the proper solution is to fix the accidental strict mode problem. If
60548 // you've misconfigured your bundler to force strict mode and applied a
60549 // CSP to forbid Function, and you're not willing to fix either of those
60550 // problems, please detail your unique predicament in a GitHub issue.
60551 Function("r", "regeneratorRuntime = r")(runtime);
60552}
60553
60554},{}],295:[function(require,module,exports){
60555'use strict';
60556
60557var core = require('../'),
60558 isArray = require('lodash/isArray'),
60559 isFunction = require('lodash/isFunction'),
60560 isObjectLike = require('lodash/isObjectLike');
60561
60562
60563module.exports = function (options) {
60564
60565 var errorText = 'Please verify options'; // For better minification because this string is repeating
60566
60567 if (!isObjectLike(options)) {
60568 throw new TypeError(errorText);
60569 }
60570
60571 if (!isFunction(options.request)) {
60572 throw new TypeError(errorText + '.request');
60573 }
60574
60575 if (!isArray(options.expose) || options.expose.length === 0) {
60576 throw new TypeError(errorText + '.expose');
60577 }
60578
60579
60580 var plumbing = core({
60581 PromiseImpl: options.PromiseImpl,
60582 constructorMixin: options.constructorMixin
60583 });
60584
60585
60586 // Intercepting Request's init method
60587
60588 var originalInit = options.request.Request.prototype.init;
60589
60590 options.request.Request.prototype.init = function RP$initInterceptor(requestOptions) {
60591
60592 // Init may be called again - currently in case of redirects
60593 if (isObjectLike(requestOptions) && !this._callback && !this._rp_promise) {
60594
60595 plumbing.init.call(this, requestOptions);
60596
60597 }
60598
60599 return originalInit.apply(this, arguments);
60600
60601 };
60602
60603
60604 // Exposing the Promise capabilities
60605
60606 var thenExposed = false;
60607 for ( var i = 0; i < options.expose.length; i+=1 ) {
60608
60609 var method = options.expose[i];
60610
60611 plumbing[ method === 'promise' ? 'exposePromise' : 'exposePromiseMethod' ](
60612 options.request.Request.prototype,
60613 null,
60614 '_rp_promise',
60615 method
60616 );
60617
60618 if (method === 'then') {
60619 thenExposed = true;
60620 }
60621
60622 }
60623
60624 if (!thenExposed) {
60625 throw new Error('Please expose "then"');
60626 }
60627
60628};
60629
60630},{"../":297,"lodash/isArray":226,"lodash/isFunction":227,"lodash/isObjectLike":229}],296:[function(require,module,exports){
60631'use strict';
60632
60633
60634function RequestError(cause, options, response) {
60635
60636 this.name = 'RequestError';
60637 this.message = String(cause);
60638 this.cause = cause;
60639 this.error = cause; // legacy attribute
60640 this.options = options;
60641 this.response = response;
60642
60643 if (Error.captureStackTrace) { // required for non-V8 environments
60644 Error.captureStackTrace(this);
60645 }
60646
60647}
60648RequestError.prototype = Object.create(Error.prototype);
60649RequestError.prototype.constructor = RequestError;
60650
60651
60652function StatusCodeError(statusCode, body, options, response) {
60653
60654 this.name = 'StatusCodeError';
60655 this.statusCode = statusCode;
60656 this.message = statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body);
60657 this.error = body; // legacy attribute
60658 this.options = options;
60659 this.response = response;
60660
60661 if (Error.captureStackTrace) { // required for non-V8 environments
60662 Error.captureStackTrace(this);
60663 }
60664
60665}
60666StatusCodeError.prototype = Object.create(Error.prototype);
60667StatusCodeError.prototype.constructor = StatusCodeError;
60668
60669
60670function TransformError(cause, options, response) {
60671
60672 this.name = 'TransformError';
60673 this.message = String(cause);
60674 this.cause = cause;
60675 this.error = cause; // legacy attribute
60676 this.options = options;
60677 this.response = response;
60678
60679 if (Error.captureStackTrace) { // required for non-V8 environments
60680 Error.captureStackTrace(this);
60681 }
60682
60683}
60684TransformError.prototype = Object.create(Error.prototype);
60685TransformError.prototype.constructor = TransformError;
60686
60687
60688module.exports = {
60689 RequestError: RequestError,
60690 StatusCodeError: StatusCodeError,
60691 TransformError: TransformError
60692};
60693
60694},{}],297:[function(require,module,exports){
60695'use strict';
60696
60697var errors = require('./errors.js'),
60698 isFunction = require('lodash/isFunction'),
60699 isObjectLike = require('lodash/isObjectLike'),
60700 isString = require('lodash/isString'),
60701 isUndefined = require('lodash/isUndefined');
60702
60703
60704module.exports = function (options) {
60705
60706 var errorText = 'Please verify options'; // For better minification because this string is repeating
60707
60708 if (!isObjectLike(options)) {
60709 throw new TypeError(errorText);
60710 }
60711
60712 if (!isFunction(options.PromiseImpl)) {
60713 throw new TypeError(errorText + '.PromiseImpl');
60714 }
60715
60716 if (!isUndefined(options.constructorMixin) && !isFunction(options.constructorMixin)) {
60717 throw new TypeError(errorText + '.PromiseImpl');
60718 }
60719
60720 var PromiseImpl = options.PromiseImpl;
60721 var constructorMixin = options.constructorMixin;
60722
60723
60724 var plumbing = {};
60725
60726 plumbing.init = function (requestOptions) {
60727
60728 var self = this;
60729
60730 self._rp_promise = new PromiseImpl(function (resolve, reject) {
60731 self._rp_resolve = resolve;
60732 self._rp_reject = reject;
60733 if (constructorMixin) {
60734 constructorMixin.apply(self, arguments); // Using arguments since specific Promise libraries may pass additional parameters
60735 }
60736 });
60737
60738 self._rp_callbackOrig = requestOptions.callback;
60739 requestOptions.callback = self.callback = function RP$callback(err, response, body) {
60740 plumbing.callback.call(self, err, response, body);
60741 };
60742
60743 if (isString(requestOptions.method)) {
60744 requestOptions.method = requestOptions.method.toUpperCase();
60745 }
60746
60747 requestOptions.transform = requestOptions.transform || plumbing.defaultTransformations[requestOptions.method];
60748
60749 self._rp_options = requestOptions;
60750 self._rp_options.simple = requestOptions.simple !== false;
60751 self._rp_options.resolveWithFullResponse = requestOptions.resolveWithFullResponse === true;
60752 self._rp_options.transform2xxOnly = requestOptions.transform2xxOnly === true;
60753
60754 };
60755
60756 plumbing.defaultTransformations = {
60757 HEAD: function (body, response, resolveWithFullResponse) {
60758 return resolveWithFullResponse ? response : response.headers;
60759 }
60760 };
60761
60762 plumbing.callback = function (err, response, body) {
60763
60764 var self = this;
60765
60766 var origCallbackThrewException = false, thrownException = null;
60767
60768 if (isFunction(self._rp_callbackOrig)) {
60769 try {
60770 self._rp_callbackOrig.apply(self, arguments); // TODO: Apply to self mimics behavior of request@2. Is that also right for request@next?
60771 } catch (e) {
60772 origCallbackThrewException = true;
60773 thrownException = e;
60774 }
60775 }
60776
60777 var is2xx = !err && /^2/.test('' + response.statusCode);
60778
60779 if (err) {
60780
60781 self._rp_reject(new errors.RequestError(err, self._rp_options, response));
60782
60783 } else if (self._rp_options.simple && !is2xx) {
60784
60785 if (isFunction(self._rp_options.transform) && self._rp_options.transform2xxOnly === false) {
60786
60787 (new PromiseImpl(function (resolve) {
60788 resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
60789 }))
60790 .then(function (transformedResponse) {
60791 self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, transformedResponse));
60792 })
60793 .catch(function (transformErr) {
60794 self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
60795 });
60796
60797 } else {
60798 self._rp_reject(new errors.StatusCodeError(response.statusCode, body, self._rp_options, response));
60799 }
60800
60801 } else {
60802
60803 if (isFunction(self._rp_options.transform) && (is2xx || self._rp_options.transform2xxOnly === false)) {
60804
60805 (new PromiseImpl(function (resolve) {
60806 resolve(self._rp_options.transform(body, response, self._rp_options.resolveWithFullResponse)); // transform may return a Promise
60807 }))
60808 .then(function (transformedResponse) {
60809 self._rp_resolve(transformedResponse);
60810 })
60811 .catch(function (transformErr) {
60812 self._rp_reject(new errors.TransformError(transformErr, self._rp_options, response));
60813 });
60814
60815 } else if (self._rp_options.resolveWithFullResponse) {
60816 self._rp_resolve(response);
60817 } else {
60818 self._rp_resolve(body);
60819 }
60820
60821 }
60822
60823 if (origCallbackThrewException) {
60824 throw thrownException;
60825 }
60826
60827 };
60828
60829 plumbing.exposePromiseMethod = function (exposeTo, bindTo, promisePropertyKey, methodToExpose, exposeAs) {
60830
60831 exposeAs = exposeAs || methodToExpose;
60832
60833 if (exposeAs in exposeTo) {
60834 throw new Error('Unable to expose method "' + exposeAs + '"');
60835 }
60836
60837 exposeTo[exposeAs] = function RP$exposed() {
60838 var self = bindTo || this;
60839 return self[promisePropertyKey][methodToExpose].apply(self[promisePropertyKey], arguments);
60840 };
60841
60842 };
60843
60844 plumbing.exposePromise = function (exposeTo, bindTo, promisePropertyKey, exposeAs) {
60845
60846 exposeAs = exposeAs || 'promise';
60847
60848 if (exposeAs in exposeTo) {
60849 throw new Error('Unable to expose method "' + exposeAs + '"');
60850 }
60851
60852 exposeTo[exposeAs] = function RP$promise() {
60853 var self = bindTo || this;
60854 return self[promisePropertyKey];
60855 };
60856
60857 };
60858
60859 return plumbing;
60860
60861};
60862
60863},{"./errors.js":296,"lodash/isFunction":227,"lodash/isObjectLike":229,"lodash/isString":230,"lodash/isUndefined":231}],298:[function(require,module,exports){
60864'use strict';
60865
60866var Bluebird = require('bluebird').getNewLibraryCopy(),
60867 configure = require('request-promise-core/configure/request2'),
60868 stealthyRequire = require('stealthy-require');
60869
60870try {
60871
60872 // Load Request freshly - so that users can require an unaltered request instance!
60873 var request = stealthyRequire(require.cache, function () {
60874 return require('request');
60875 },
60876 function () {
60877 require('tough-cookie');
60878 }, module);
60879
60880} catch (err) {
60881 /* istanbul ignore next */
60882 var EOL = require('os').EOL;
60883 /* istanbul ignore next */
60884 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);
60885 /* istanbul ignore next */
60886 throw err;
60887}
60888
60889Bluebird.config({cancellation: true});
60890
60891configure({
60892 request: request,
60893 PromiseImpl: Bluebird,
60894 expose: [
60895 'then',
60896 'catch',
60897 'finally',
60898 'cancel',
60899 'promise'
60900 // Would you like to expose more Bluebird methods? Try e.g. `rp(...).promise().tap(...)` first. `.promise()` returns the full-fledged Bluebird promise.
60901 ],
60902 constructorMixin: function (resolve, reject, onCancel) {
60903 var self = this;
60904 onCancel(function () {
60905 self.abort();
60906 });
60907 }
60908});
60909
60910request.bindCLS = function RP$bindCLS() {
60911 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');
60912};
60913
60914
60915module.exports = request;
60916
60917},{"bluebird":79,"os":240,"request":299,"request-promise-core/configure/request2":295,"stealthy-require":360,"tough-cookie":383}],299:[function(require,module,exports){
60918// Copyright 2010-2012 Mikeal Rogers
60919//
60920// Licensed under the Apache License, Version 2.0 (the "License");
60921// you may not use this file except in compliance with the License.
60922// You may obtain a copy of the License at
60923//
60924// http://www.apache.org/licenses/LICENSE-2.0
60925//
60926// Unless required by applicable law or agreed to in writing, software
60927// distributed under the License is distributed on an "AS IS" BASIS,
60928// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
60929// See the License for the specific language governing permissions and
60930// limitations under the License.
60931
60932'use strict'
60933
60934var extend = require('extend')
60935var cookies = require('./lib/cookies')
60936var helpers = require('./lib/helpers')
60937
60938var paramsHaveRequestBody = helpers.paramsHaveRequestBody
60939
60940// organize params for patch, post, put, head, del
60941function initParams (uri, options, callback) {
60942 if (typeof options === 'function') {
60943 callback = options
60944 }
60945
60946 var params = {}
60947 if (typeof options === 'object') {
60948 extend(params, options, {uri: uri})
60949 } else if (typeof uri === 'string') {
60950 extend(params, {uri: uri})
60951 } else {
60952 extend(params, uri)
60953 }
60954
60955 params.callback = callback || params.callback
60956 return params
60957}
60958
60959function request (uri, options, callback) {
60960 if (typeof uri === 'undefined') {
60961 throw new Error('undefined is not a valid uri or options object.')
60962 }
60963
60964 var params = initParams(uri, options, callback)
60965
60966 if (params.method === 'HEAD' && paramsHaveRequestBody(params)) {
60967 throw new Error('HTTP HEAD requests MUST NOT include a request body.')
60968 }
60969
60970 return new request.Request(params)
60971}
60972
60973function verbFunc (verb) {
60974 var method = verb.toUpperCase()
60975 return function (uri, options, callback) {
60976 var params = initParams(uri, options, callback)
60977 params.method = method
60978 return request(params, params.callback)
60979 }
60980}
60981
60982// define like this to please codeintel/intellisense IDEs
60983request.get = verbFunc('get')
60984request.head = verbFunc('head')
60985request.options = verbFunc('options')
60986request.post = verbFunc('post')
60987request.put = verbFunc('put')
60988request.patch = verbFunc('patch')
60989request.del = verbFunc('delete')
60990request['delete'] = verbFunc('delete')
60991
60992request.jar = function (store) {
60993 return cookies.jar(store)
60994}
60995
60996request.cookie = function (str) {
60997 return cookies.parse(str)
60998}
60999
61000function wrapRequestMethod (method, options, requester, verb) {
61001 return function (uri, opts, callback) {
61002 var params = initParams(uri, opts, callback)
61003
61004 var target = {}
61005 extend(true, target, options, params)
61006
61007 target.pool = params.pool || options.pool
61008
61009 if (verb) {
61010 target.method = verb.toUpperCase()
61011 }
61012
61013 if (typeof requester === 'function') {
61014 method = requester
61015 }
61016
61017 return method(target, target.callback)
61018 }
61019}
61020
61021request.defaults = function (options, requester) {
61022 var self = this
61023
61024 options = options || {}
61025
61026 if (typeof options === 'function') {
61027 requester = options
61028 options = {}
61029 }
61030
61031 var defaults = wrapRequestMethod(self, options, requester)
61032
61033 var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete']
61034 verbs.forEach(function (verb) {
61035 defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb)
61036 })
61037
61038 defaults.cookie = wrapRequestMethod(self.cookie, options, requester)
61039 defaults.jar = self.jar
61040 defaults.defaults = self.defaults
61041 return defaults
61042}
61043
61044request.forever = function (agentOptions, optionsArg) {
61045 var options = {}
61046 if (optionsArg) {
61047 extend(options, optionsArg)
61048 }
61049 if (agentOptions) {
61050 options.agentOptions = agentOptions
61051 }
61052
61053 options.forever = true
61054 return request.defaults(options)
61055}
61056
61057// Exports
61058
61059module.exports = request
61060request.Request = require('./request')
61061request.initParams = initParams
61062
61063// Backwards compatibility for request.debug
61064Object.defineProperty(request, 'debug', {
61065 enumerable: true,
61066 get: function () {
61067 return request.Request.debug
61068 },
61069 set: function (debug) {
61070 request.Request.debug = debug
61071 }
61072})
61073
61074},{"./lib/cookies":301,"./lib/helpers":305,"./request":323,"extend":161}],300:[function(require,module,exports){
61075'use strict'
61076
61077var caseless = require('caseless')
61078var uuid = require('uuid/v4')
61079var helpers = require('./helpers')
61080
61081var md5 = helpers.md5
61082var toBase64 = helpers.toBase64
61083
61084function Auth (request) {
61085 // define all public properties here
61086 this.request = request
61087 this.hasAuth = false
61088 this.sentAuth = false
61089 this.bearerToken = null
61090 this.user = null
61091 this.pass = null
61092}
61093
61094Auth.prototype.basic = function (user, pass, sendImmediately) {
61095 var self = this
61096 if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
61097 self.request.emit('error', new Error('auth() received invalid user or password'))
61098 }
61099 self.user = user
61100 self.pass = pass
61101 self.hasAuth = true
61102 var header = user + ':' + (pass || '')
61103 if (sendImmediately || typeof sendImmediately === 'undefined') {
61104 var authHeader = 'Basic ' + toBase64(header)
61105 self.sentAuth = true
61106 return authHeader
61107 }
61108}
61109
61110Auth.prototype.bearer = function (bearer, sendImmediately) {
61111 var self = this
61112 self.bearerToken = bearer
61113 self.hasAuth = true
61114 if (sendImmediately || typeof sendImmediately === 'undefined') {
61115 if (typeof bearer === 'function') {
61116 bearer = bearer()
61117 }
61118 var authHeader = 'Bearer ' + (bearer || '')
61119 self.sentAuth = true
61120 return authHeader
61121 }
61122}
61123
61124Auth.prototype.digest = function (method, path, authHeader) {
61125 // TODO: More complete implementation of RFC 2617.
61126 // - handle challenge.domain
61127 // - support qop="auth-int" only
61128 // - handle Authentication-Info (not necessarily?)
61129 // - check challenge.stale (not necessarily?)
61130 // - increase nc (not necessarily?)
61131 // For reference:
61132 // http://tools.ietf.org/html/rfc2617#section-3
61133 // https://github.com/bagder/curl/blob/master/lib/http_digest.c
61134
61135 var self = this
61136
61137 var challenge = {}
61138 var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
61139 for (;;) {
61140 var match = re.exec(authHeader)
61141 if (!match) {
61142 break
61143 }
61144 challenge[match[1]] = match[2] || match[3]
61145 }
61146
61147 /**
61148 * RFC 2617: handle both MD5 and MD5-sess algorithms.
61149 *
61150 * If the algorithm directive's value is "MD5" or unspecified, then HA1 is
61151 * HA1=MD5(username:realm:password)
61152 * If the algorithm directive's value is "MD5-sess", then HA1 is
61153 * HA1=MD5(MD5(username:realm:password):nonce:cnonce)
61154 */
61155 var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) {
61156 var ha1 = md5(user + ':' + realm + ':' + pass)
61157 if (algorithm && algorithm.toLowerCase() === 'md5-sess') {
61158 return md5(ha1 + ':' + nonce + ':' + cnonce)
61159 } else {
61160 return ha1
61161 }
61162 }
61163
61164 var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
61165 var nc = qop && '00000001'
61166 var cnonce = qop && uuid().replace(/-/g, '')
61167 var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce)
61168 var ha2 = md5(method + ':' + path)
61169 var digestResponse = qop
61170 ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
61171 : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
61172 var authValues = {
61173 username: self.user,
61174 realm: challenge.realm,
61175 nonce: challenge.nonce,
61176 uri: path,
61177 qop: qop,
61178 response: digestResponse,
61179 nc: nc,
61180 cnonce: cnonce,
61181 algorithm: challenge.algorithm,
61182 opaque: challenge.opaque
61183 }
61184
61185 authHeader = []
61186 for (var k in authValues) {
61187 if (authValues[k]) {
61188 if (k === 'qop' || k === 'nc' || k === 'algorithm') {
61189 authHeader.push(k + '=' + authValues[k])
61190 } else {
61191 authHeader.push(k + '="' + authValues[k] + '"')
61192 }
61193 }
61194 }
61195 authHeader = 'Digest ' + authHeader.join(', ')
61196 self.sentAuth = true
61197 return authHeader
61198}
61199
61200Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) {
61201 var self = this
61202 var request = self.request
61203
61204 var authHeader
61205 if (bearer === undefined && user === undefined) {
61206 self.request.emit('error', new Error('no auth mechanism defined'))
61207 } else if (bearer !== undefined) {
61208 authHeader = self.bearer(bearer, sendImmediately)
61209 } else {
61210 authHeader = self.basic(user, pass, sendImmediately)
61211 }
61212 if (authHeader) {
61213 request.setHeader('authorization', authHeader)
61214 }
61215}
61216
61217Auth.prototype.onResponse = function (response) {
61218 var self = this
61219 var request = self.request
61220
61221 if (!self.hasAuth || self.sentAuth) { return null }
61222
61223 var c = caseless(response.headers)
61224
61225 var authHeader = c.get('www-authenticate')
61226 var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
61227 request.debug('reauth', authVerb)
61228
61229 switch (authVerb) {
61230 case 'basic':
61231 return self.basic(self.user, self.pass, true)
61232
61233 case 'bearer':
61234 return self.bearer(self.bearerToken, true)
61235
61236 case 'digest':
61237 return self.digest(request.method, request.path, authHeader)
61238 }
61239}
61240
61241exports.Auth = Auth
61242
61243},{"./helpers":305,"caseless":116,"uuid/v4":400}],301:[function(require,module,exports){
61244'use strict'
61245
61246var tough = require('tough-cookie')
61247
61248var Cookie = tough.Cookie
61249var CookieJar = tough.CookieJar
61250
61251exports.parse = function (str) {
61252 if (str && str.uri) {
61253 str = str.uri
61254 }
61255 if (typeof str !== 'string') {
61256 throw new Error('The cookie function only accepts STRING as param')
61257 }
61258 return Cookie.parse(str, {loose: true})
61259}
61260
61261// Adapt the sometimes-Async api of tough.CookieJar to our requirements
61262function RequestJar (store) {
61263 var self = this
61264 self._jar = new CookieJar(store, {looseMode: true})
61265}
61266RequestJar.prototype.setCookie = function (cookieOrStr, uri, options) {
61267 var self = this
61268 return self._jar.setCookieSync(cookieOrStr, uri, options || {})
61269}
61270RequestJar.prototype.getCookieString = function (uri) {
61271 var self = this
61272 return self._jar.getCookieStringSync(uri)
61273}
61274RequestJar.prototype.getCookies = function (uri) {
61275 var self = this
61276 return self._jar.getCookiesSync(uri)
61277}
61278
61279exports.jar = function (store) {
61280 return new RequestJar(store)
61281}
61282
61283},{"tough-cookie":316}],302:[function(require,module,exports){
61284(function (process){
61285'use strict'
61286
61287function formatHostname (hostname) {
61288 // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
61289 return hostname.replace(/^\.*/, '.').toLowerCase()
61290}
61291
61292function parseNoProxyZone (zone) {
61293 zone = zone.trim().toLowerCase()
61294
61295 var zoneParts = zone.split(':', 2)
61296 var zoneHost = formatHostname(zoneParts[0])
61297 var zonePort = zoneParts[1]
61298 var hasPort = zone.indexOf(':') > -1
61299
61300 return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
61301}
61302
61303function uriInNoProxy (uri, noProxy) {
61304 var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
61305 var hostname = formatHostname(uri.hostname)
61306 var noProxyList = noProxy.split(',')
61307
61308 // iterate through the noProxyList until it finds a match.
61309 return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) {
61310 var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
61311 var hostnameMatched = (
61312 isMatchedAt > -1 &&
61313 (isMatchedAt === hostname.length - noProxyZone.hostname.length)
61314 )
61315
61316 if (noProxyZone.hasPort) {
61317 return (port === noProxyZone.port) && hostnameMatched
61318 }
61319
61320 return hostnameMatched
61321 })
61322}
61323
61324function getProxyFromURI (uri) {
61325 // Decide the proper request proxy to use based on the request URI object and the
61326 // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
61327 // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
61328
61329 var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
61330
61331 // if the noProxy is a wildcard then return null
61332
61333 if (noProxy === '*') {
61334 return null
61335 }
61336
61337 // if the noProxy is not empty and the uri is found return null
61338
61339 if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
61340 return null
61341 }
61342
61343 // Check for HTTP or HTTPS Proxy in environment Else default to null
61344
61345 if (uri.protocol === 'http:') {
61346 return process.env.HTTP_PROXY ||
61347 process.env.http_proxy || null
61348 }
61349
61350 if (uri.protocol === 'https:') {
61351 return process.env.HTTPS_PROXY ||
61352 process.env.https_proxy ||
61353 process.env.HTTP_PROXY ||
61354 process.env.http_proxy || null
61355 }
61356
61357 // if none of that works, return null
61358 // (What uri protocol are you using then?)
61359
61360 return null
61361}
61362
61363module.exports = getProxyFromURI
61364
61365}).call(this,require('_process'))
61366},{"_process":265}],303:[function(require,module,exports){
61367'use strict'
61368
61369var fs = require('fs')
61370var qs = require('querystring')
61371var validate = require('har-validator')
61372var extend = require('extend')
61373
61374function Har (request) {
61375 this.request = request
61376}
61377
61378Har.prototype.reducer = function (obj, pair) {
61379 // new property ?
61380 if (obj[pair.name] === undefined) {
61381 obj[pair.name] = pair.value
61382 return obj
61383 }
61384
61385 // existing? convert to array
61386 var arr = [
61387 obj[pair.name],
61388 pair.value
61389 ]
61390
61391 obj[pair.name] = arr
61392
61393 return obj
61394}
61395
61396Har.prototype.prep = function (data) {
61397 // construct utility properties
61398 data.queryObj = {}
61399 data.headersObj = {}
61400 data.postData.jsonObj = false
61401 data.postData.paramsObj = false
61402
61403 // construct query objects
61404 if (data.queryString && data.queryString.length) {
61405 data.queryObj = data.queryString.reduce(this.reducer, {})
61406 }
61407
61408 // construct headers objects
61409 if (data.headers && data.headers.length) {
61410 // loweCase header keys
61411 data.headersObj = data.headers.reduceRight(function (headers, header) {
61412 headers[header.name] = header.value
61413 return headers
61414 }, {})
61415 }
61416
61417 // construct Cookie header
61418 if (data.cookies && data.cookies.length) {
61419 var cookies = data.cookies.map(function (cookie) {
61420 return cookie.name + '=' + cookie.value
61421 })
61422
61423 if (cookies.length) {
61424 data.headersObj.cookie = cookies.join('; ')
61425 }
61426 }
61427
61428 // prep body
61429 function some (arr) {
61430 return arr.some(function (type) {
61431 return data.postData.mimeType.indexOf(type) === 0
61432 })
61433 }
61434
61435 if (some([
61436 'multipart/mixed',
61437 'multipart/related',
61438 'multipart/form-data',
61439 'multipart/alternative'])) {
61440 // reset values
61441 data.postData.mimeType = 'multipart/form-data'
61442 } else if (some([
61443 'application/x-www-form-urlencoded'])) {
61444 if (!data.postData.params) {
61445 data.postData.text = ''
61446 } else {
61447 data.postData.paramsObj = data.postData.params.reduce(this.reducer, {})
61448
61449 // always overwrite
61450 data.postData.text = qs.stringify(data.postData.paramsObj)
61451 }
61452 } else if (some([
61453 'text/json',
61454 'text/x-json',
61455 'application/json',
61456 'application/x-json'])) {
61457 data.postData.mimeType = 'application/json'
61458
61459 if (data.postData.text) {
61460 try {
61461 data.postData.jsonObj = JSON.parse(data.postData.text)
61462 } catch (e) {
61463 this.request.debug(e)
61464
61465 // force back to text/plain
61466 data.postData.mimeType = 'text/plain'
61467 }
61468 }
61469 }
61470
61471 return data
61472}
61473
61474Har.prototype.options = function (options) {
61475 // skip if no har property defined
61476 if (!options.har) {
61477 return options
61478 }
61479
61480 var har = {}
61481 extend(har, options.har)
61482
61483 // only process the first entry
61484 if (har.log && har.log.entries) {
61485 har = har.log.entries[0]
61486 }
61487
61488 // add optional properties to make validation successful
61489 har.url = har.url || options.url || options.uri || options.baseUrl || '/'
61490 har.httpVersion = har.httpVersion || 'HTTP/1.1'
61491 har.queryString = har.queryString || []
61492 har.headers = har.headers || []
61493 har.cookies = har.cookies || []
61494 har.postData = har.postData || {}
61495 har.postData.mimeType = har.postData.mimeType || 'application/octet-stream'
61496
61497 har.bodySize = 0
61498 har.headersSize = 0
61499 har.postData.size = 0
61500
61501 if (!validate.request(har)) {
61502 return options
61503 }
61504
61505 // clean up and get some utility properties
61506 var req = this.prep(har)
61507
61508 // construct new options
61509 if (req.url) {
61510 options.url = req.url
61511 }
61512
61513 if (req.method) {
61514 options.method = req.method
61515 }
61516
61517 if (Object.keys(req.queryObj).length) {
61518 options.qs = req.queryObj
61519 }
61520
61521 if (Object.keys(req.headersObj).length) {
61522 options.headers = req.headersObj
61523 }
61524
61525 function test (type) {
61526 return req.postData.mimeType.indexOf(type) === 0
61527 }
61528 if (test('application/x-www-form-urlencoded')) {
61529 options.form = req.postData.paramsObj
61530 } else if (test('application/json')) {
61531 if (req.postData.jsonObj) {
61532 options.body = req.postData.jsonObj
61533 options.json = true
61534 }
61535 } else if (test('multipart/form-data')) {
61536 options.formData = {}
61537
61538 req.postData.params.forEach(function (param) {
61539 var attachment = {}
61540
61541 if (!param.fileName && !param.fileName && !param.contentType) {
61542 options.formData[param.name] = param.value
61543 return
61544 }
61545
61546 // attempt to read from disk!
61547 if (param.fileName && !param.value) {
61548 attachment.value = fs.createReadStream(param.fileName)
61549 } else if (param.value) {
61550 attachment.value = param.value
61551 }
61552
61553 if (param.fileName) {
61554 attachment.options = {
61555 filename: param.fileName,
61556 contentType: param.contentType ? param.contentType : null
61557 }
61558 }
61559
61560 options.formData[param.name] = attachment
61561 })
61562 } else {
61563 if (req.postData.text) {
61564 options.body = req.postData.text
61565 }
61566 }
61567
61568 return options
61569}
61570
61571exports.Har = Har
61572
61573},{"extend":161,"fs":112,"har-validator":188,"querystring":277}],304:[function(require,module,exports){
61574'use strict'
61575
61576var crypto = require('crypto')
61577
61578function randomString (size) {
61579 var bits = (size + 1) * 6
61580 var buffer = crypto.randomBytes(Math.ceil(bits / 8))
61581 var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '')
61582 return string.slice(0, size)
61583}
61584
61585function calculatePayloadHash (payload, algorithm, contentType) {
61586 var hash = crypto.createHash(algorithm)
61587 hash.update('hawk.1.payload\n')
61588 hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n')
61589 hash.update(payload || '')
61590 hash.update('\n')
61591 return hash.digest('base64')
61592}
61593
61594exports.calculateMac = function (credentials, opts) {
61595 var normalized = 'hawk.1.header\n' +
61596 opts.ts + '\n' +
61597 opts.nonce + '\n' +
61598 (opts.method || '').toUpperCase() + '\n' +
61599 opts.resource + '\n' +
61600 opts.host.toLowerCase() + '\n' +
61601 opts.port + '\n' +
61602 (opts.hash || '') + '\n'
61603
61604 if (opts.ext) {
61605 normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n')
61606 }
61607
61608 normalized = normalized + '\n'
61609
61610 if (opts.app) {
61611 normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n'
61612 }
61613
61614 var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized)
61615 var digest = hmac.digest('base64')
61616 return digest
61617}
61618
61619exports.header = function (uri, method, opts) {
61620 var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000)
61621 var credentials = opts.credentials
61622 if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) {
61623 return ''
61624 }
61625
61626 if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) {
61627 return ''
61628 }
61629
61630 var artifacts = {
61631 ts: timestamp,
61632 nonce: opts.nonce || randomString(6),
61633 method: method,
61634 resource: uri.pathname + (uri.search || ''),
61635 host: uri.hostname,
61636 port: uri.port || (uri.protocol === 'http:' ? 80 : 443),
61637 hash: opts.hash,
61638 ext: opts.ext,
61639 app: opts.app,
61640 dlg: opts.dlg
61641 }
61642
61643 if (!artifacts.hash && (opts.payload || opts.payload === '')) {
61644 artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType)
61645 }
61646
61647 var mac = exports.calculateMac(credentials, artifacts)
61648
61649 var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== ''
61650 var header = 'Hawk id="' + credentials.id +
61651 '", ts="' + artifacts.ts +
61652 '", nonce="' + artifacts.nonce +
61653 (artifacts.hash ? '", hash="' + artifacts.hash : '') +
61654 (hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') +
61655 '", mac="' + mac + '"'
61656
61657 if (artifacts.app) {
61658 header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"'
61659 }
61660
61661 return header
61662}
61663
61664},{"crypto":126}],305:[function(require,module,exports){
61665(function (process,setImmediate){
61666'use strict'
61667
61668var jsonSafeStringify = require('json-stringify-safe')
61669var crypto = require('crypto')
61670var Buffer = require('safe-buffer').Buffer
61671
61672var defer = typeof setImmediate === 'undefined'
61673 ? process.nextTick
61674 : setImmediate
61675
61676function paramsHaveRequestBody (params) {
61677 return (
61678 params.body ||
61679 params.requestBodyStream ||
61680 (params.json && typeof params.json !== 'boolean') ||
61681 params.multipart
61682 )
61683}
61684
61685function safeStringify (obj, replacer) {
61686 var ret
61687 try {
61688 ret = JSON.stringify(obj, replacer)
61689 } catch (e) {
61690 ret = jsonSafeStringify(obj, replacer)
61691 }
61692 return ret
61693}
61694
61695function md5 (str) {
61696 return crypto.createHash('md5').update(str).digest('hex')
61697}
61698
61699function isReadStream (rs) {
61700 return rs.readable && rs.path && rs.mode
61701}
61702
61703function toBase64 (str) {
61704 return Buffer.from(str || '', 'utf8').toString('base64')
61705}
61706
61707function copy (obj) {
61708 var o = {}
61709 Object.keys(obj).forEach(function (i) {
61710 o[i] = obj[i]
61711 })
61712 return o
61713}
61714
61715function version () {
61716 var numbers = process.version.replace('v', '').split('.')
61717 return {
61718 major: parseInt(numbers[0], 10),
61719 minor: parseInt(numbers[1], 10),
61720 patch: parseInt(numbers[2], 10)
61721 }
61722}
61723
61724exports.paramsHaveRequestBody = paramsHaveRequestBody
61725exports.safeStringify = safeStringify
61726exports.md5 = md5
61727exports.isReadStream = isReadStream
61728exports.toBase64 = toBase64
61729exports.copy = copy
61730exports.version = version
61731exports.defer = defer
61732
61733}).call(this,require('_process'),require("timers").setImmediate)
61734},{"_process":265,"crypto":126,"json-stringify-safe":218,"safe-buffer":325,"timers":382}],306:[function(require,module,exports){
61735'use strict'
61736
61737var uuid = require('uuid/v4')
61738var CombinedStream = require('combined-stream')
61739var isstream = require('isstream')
61740var Buffer = require('safe-buffer').Buffer
61741
61742function Multipart (request) {
61743 this.request = request
61744 this.boundary = uuid()
61745 this.chunked = false
61746 this.body = null
61747}
61748
61749Multipart.prototype.isChunked = function (options) {
61750 var self = this
61751 var chunked = false
61752 var parts = options.data || options
61753
61754 if (!parts.forEach) {
61755 self.request.emit('error', new Error('Argument error, options.multipart.'))
61756 }
61757
61758 if (options.chunked !== undefined) {
61759 chunked = options.chunked
61760 }
61761
61762 if (self.request.getHeader('transfer-encoding') === 'chunked') {
61763 chunked = true
61764 }
61765
61766 if (!chunked) {
61767 parts.forEach(function (part) {
61768 if (typeof part.body === 'undefined') {
61769 self.request.emit('error', new Error('Body attribute missing in multipart.'))
61770 }
61771 if (isstream(part.body)) {
61772 chunked = true
61773 }
61774 })
61775 }
61776
61777 return chunked
61778}
61779
61780Multipart.prototype.setHeaders = function (chunked) {
61781 var self = this
61782
61783 if (chunked && !self.request.hasHeader('transfer-encoding')) {
61784 self.request.setHeader('transfer-encoding', 'chunked')
61785 }
61786
61787 var header = self.request.getHeader('content-type')
61788
61789 if (!header || header.indexOf('multipart') === -1) {
61790 self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary)
61791 } else {
61792 if (header.indexOf('boundary') !== -1) {
61793 self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1')
61794 } else {
61795 self.request.setHeader('content-type', header + '; boundary=' + self.boundary)
61796 }
61797 }
61798}
61799
61800Multipart.prototype.build = function (parts, chunked) {
61801 var self = this
61802 var body = chunked ? new CombinedStream() : []
61803
61804 function add (part) {
61805 if (typeof part === 'number') {
61806 part = part.toString()
61807 }
61808 return chunked ? body.append(part) : body.push(Buffer.from(part))
61809 }
61810
61811 if (self.request.preambleCRLF) {
61812 add('\r\n')
61813 }
61814
61815 parts.forEach(function (part) {
61816 var preamble = '--' + self.boundary + '\r\n'
61817 Object.keys(part).forEach(function (key) {
61818 if (key === 'body') { return }
61819 preamble += key + ': ' + part[key] + '\r\n'
61820 })
61821 preamble += '\r\n'
61822 add(preamble)
61823 add(part.body)
61824 add('\r\n')
61825 })
61826 add('--' + self.boundary + '--')
61827
61828 if (self.request.postambleCRLF) {
61829 add('\r\n')
61830 }
61831
61832 return body
61833}
61834
61835Multipart.prototype.onRequest = function (options) {
61836 var self = this
61837
61838 var chunked = self.isChunked(options)
61839 var parts = options.data || options
61840
61841 self.setHeaders(chunked)
61842 self.chunked = chunked
61843 self.body = self.build(parts, chunked)
61844}
61845
61846exports.Multipart = Multipart
61847
61848},{"combined-stream":118,"isstream":214,"safe-buffer":325,"uuid/v4":400}],307:[function(require,module,exports){
61849'use strict'
61850
61851var url = require('url')
61852var qs = require('qs')
61853var caseless = require('caseless')
61854var uuid = require('uuid/v4')
61855var oauth = require('oauth-sign')
61856var crypto = require('crypto')
61857var Buffer = require('safe-buffer').Buffer
61858
61859function OAuth (request) {
61860 this.request = request
61861 this.params = null
61862}
61863
61864OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) {
61865 var oa = {}
61866 for (var i in _oauth) {
61867 oa['oauth_' + i] = _oauth[i]
61868 }
61869 if (!oa.oauth_version) {
61870 oa.oauth_version = '1.0'
61871 }
61872 if (!oa.oauth_timestamp) {
61873 oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString()
61874 }
61875 if (!oa.oauth_nonce) {
61876 oa.oauth_nonce = uuid().replace(/-/g, '')
61877 }
61878 if (!oa.oauth_signature_method) {
61879 oa.oauth_signature_method = 'HMAC-SHA1'
61880 }
61881
61882 var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase
61883 delete oa.oauth_consumer_secret
61884 delete oa.oauth_private_key
61885
61886 var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase
61887 delete oa.oauth_token_secret
61888
61889 var realm = oa.oauth_realm
61890 delete oa.oauth_realm
61891 delete oa.oauth_transport_method
61892
61893 var baseurl = uri.protocol + '//' + uri.host + uri.pathname
61894 var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'))
61895
61896 oa.oauth_signature = oauth.sign(
61897 oa.oauth_signature_method,
61898 method,
61899 baseurl,
61900 params,
61901 consumer_secret_or_private_key, // eslint-disable-line camelcase
61902 token_secret // eslint-disable-line camelcase
61903 )
61904
61905 if (realm) {
61906 oa.realm = realm
61907 }
61908
61909 return oa
61910}
61911
61912OAuth.prototype.buildBodyHash = function (_oauth, body) {
61913 if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) {
61914 this.request.emit('error', new Error('oauth: ' + _oauth.signature_method +
61915 ' signature_method not supported with body_hash signing.'))
61916 }
61917
61918 var shasum = crypto.createHash('sha1')
61919 shasum.update(body || '')
61920 var sha1 = shasum.digest('hex')
61921
61922 return Buffer.from(sha1, 'hex').toString('base64')
61923}
61924
61925OAuth.prototype.concatParams = function (oa, sep, wrap) {
61926 wrap = wrap || ''
61927
61928 var params = Object.keys(oa).filter(function (i) {
61929 return i !== 'realm' && i !== 'oauth_signature'
61930 }).sort()
61931
61932 if (oa.realm) {
61933 params.splice(0, 0, 'realm')
61934 }
61935 params.push('oauth_signature')
61936
61937 return params.map(function (i) {
61938 return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap
61939 }).join(sep)
61940}
61941
61942OAuth.prototype.onRequest = function (_oauth) {
61943 var self = this
61944 self.params = _oauth
61945
61946 var uri = self.request.uri || {}
61947 var method = self.request.method || ''
61948 var headers = caseless(self.request.headers)
61949 var body = self.request.body || ''
61950 var qsLib = self.request.qsLib || qs
61951
61952 var form
61953 var query
61954 var contentType = headers.get('content-type') || ''
61955 var formContentType = 'application/x-www-form-urlencoded'
61956 var transport = _oauth.transport_method || 'header'
61957
61958 if (contentType.slice(0, formContentType.length) === formContentType) {
61959 contentType = formContentType
61960 form = body
61961 }
61962 if (uri.query) {
61963 query = uri.query
61964 }
61965 if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
61966 self.request.emit('error', new Error('oauth: transport_method of body requires POST ' +
61967 'and content-type ' + formContentType))
61968 }
61969
61970 if (!form && typeof _oauth.body_hash === 'boolean') {
61971 _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString())
61972 }
61973
61974 var oa = self.buildParams(_oauth, uri, method, query, form, qsLib)
61975
61976 switch (transport) {
61977 case 'header':
61978 self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"'))
61979 break
61980
61981 case 'query':
61982 var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&')
61983 self.request.uri = url.parse(href)
61984 self.request.path = self.request.uri.path
61985 break
61986
61987 case 'body':
61988 self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&')
61989 break
61990
61991 default:
61992 self.request.emit('error', new Error('oauth: transport_method invalid'))
61993 }
61994}
61995
61996exports.OAuth = OAuth
61997
61998},{"caseless":116,"crypto":126,"oauth-sign":239,"qs":312,"safe-buffer":325,"url":393,"uuid/v4":400}],308:[function(require,module,exports){
61999'use strict'
62000
62001var qs = require('qs')
62002var querystring = require('querystring')
62003
62004function Querystring (request) {
62005 this.request = request
62006 this.lib = null
62007 this.useQuerystring = null
62008 this.parseOptions = null
62009 this.stringifyOptions = null
62010}
62011
62012Querystring.prototype.init = function (options) {
62013 if (this.lib) { return }
62014
62015 this.useQuerystring = options.useQuerystring
62016 this.lib = (this.useQuerystring ? querystring : qs)
62017
62018 this.parseOptions = options.qsParseOptions || {}
62019 this.stringifyOptions = options.qsStringifyOptions || {}
62020}
62021
62022Querystring.prototype.stringify = function (obj) {
62023 return (this.useQuerystring)
62024 ? this.rfc3986(this.lib.stringify(obj,
62025 this.stringifyOptions.sep || null,
62026 this.stringifyOptions.eq || null,
62027 this.stringifyOptions))
62028 : this.lib.stringify(obj, this.stringifyOptions)
62029}
62030
62031Querystring.prototype.parse = function (str) {
62032 return (this.useQuerystring)
62033 ? this.lib.parse(str,
62034 this.parseOptions.sep || null,
62035 this.parseOptions.eq || null,
62036 this.parseOptions)
62037 : this.lib.parse(str, this.parseOptions)
62038}
62039
62040Querystring.prototype.rfc3986 = function (str) {
62041 return str.replace(/[!'()*]/g, function (c) {
62042 return '%' + c.charCodeAt(0).toString(16).toUpperCase()
62043 })
62044}
62045
62046Querystring.prototype.unescape = querystring.unescape
62047
62048exports.Querystring = Querystring
62049
62050},{"qs":312,"querystring":277}],309:[function(require,module,exports){
62051'use strict'
62052
62053var url = require('url')
62054var isUrl = /^https?:/
62055
62056function Redirect (request) {
62057 this.request = request
62058 this.followRedirect = true
62059 this.followRedirects = true
62060 this.followAllRedirects = false
62061 this.followOriginalHttpMethod = false
62062 this.allowRedirect = function () { return true }
62063 this.maxRedirects = 10
62064 this.redirects = []
62065 this.redirectsFollowed = 0
62066 this.removeRefererHeader = false
62067}
62068
62069Redirect.prototype.onRequest = function (options) {
62070 var self = this
62071
62072 if (options.maxRedirects !== undefined) {
62073 self.maxRedirects = options.maxRedirects
62074 }
62075 if (typeof options.followRedirect === 'function') {
62076 self.allowRedirect = options.followRedirect
62077 }
62078 if (options.followRedirect !== undefined) {
62079 self.followRedirects = !!options.followRedirect
62080 }
62081 if (options.followAllRedirects !== undefined) {
62082 self.followAllRedirects = options.followAllRedirects
62083 }
62084 if (self.followRedirects || self.followAllRedirects) {
62085 self.redirects = self.redirects || []
62086 }
62087 if (options.removeRefererHeader !== undefined) {
62088 self.removeRefererHeader = options.removeRefererHeader
62089 }
62090 if (options.followOriginalHttpMethod !== undefined) {
62091 self.followOriginalHttpMethod = options.followOriginalHttpMethod
62092 }
62093}
62094
62095Redirect.prototype.redirectTo = function (response) {
62096 var self = this
62097 var request = self.request
62098
62099 var redirectTo = null
62100 if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) {
62101 var location = response.caseless.get('location')
62102 request.debug('redirect', location)
62103
62104 if (self.followAllRedirects) {
62105 redirectTo = location
62106 } else if (self.followRedirects) {
62107 switch (request.method) {
62108 case 'PATCH':
62109 case 'PUT':
62110 case 'POST':
62111 case 'DELETE':
62112 // Do not follow redirects
62113 break
62114 default:
62115 redirectTo = location
62116 break
62117 }
62118 }
62119 } else if (response.statusCode === 401) {
62120 var authHeader = request._auth.onResponse(response)
62121 if (authHeader) {
62122 request.setHeader('authorization', authHeader)
62123 redirectTo = request.uri
62124 }
62125 }
62126 return redirectTo
62127}
62128
62129Redirect.prototype.onResponse = function (response) {
62130 var self = this
62131 var request = self.request
62132
62133 var redirectTo = self.redirectTo(response)
62134 if (!redirectTo || !self.allowRedirect.call(request, response)) {
62135 return false
62136 }
62137
62138 request.debug('redirect to', redirectTo)
62139
62140 // ignore any potential response body. it cannot possibly be useful
62141 // to us at this point.
62142 // response.resume should be defined, but check anyway before calling. Workaround for browserify.
62143 if (response.resume) {
62144 response.resume()
62145 }
62146
62147 if (self.redirectsFollowed >= self.maxRedirects) {
62148 request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href))
62149 return false
62150 }
62151 self.redirectsFollowed += 1
62152
62153 if (!isUrl.test(redirectTo)) {
62154 redirectTo = url.resolve(request.uri.href, redirectTo)
62155 }
62156
62157 var uriPrev = request.uri
62158 request.uri = url.parse(redirectTo)
62159
62160 // handle the case where we change protocol from https to http or vice versa
62161 if (request.uri.protocol !== uriPrev.protocol) {
62162 delete request.agent
62163 }
62164
62165 self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo })
62166
62167 if (self.followAllRedirects && request.method !== 'HEAD' &&
62168 response.statusCode !== 401 && response.statusCode !== 307) {
62169 request.method = self.followOriginalHttpMethod ? request.method : 'GET'
62170 }
62171 // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215
62172 delete request.src
62173 delete request.req
62174 delete request._started
62175 if (response.statusCode !== 401 && response.statusCode !== 307) {
62176 // Remove parameters from the previous response, unless this is the second request
62177 // for a server that requires digest authentication.
62178 delete request.body
62179 delete request._form
62180 if (request.headers) {
62181 request.removeHeader('host')
62182 request.removeHeader('content-type')
62183 request.removeHeader('content-length')
62184 if (request.uri.hostname !== request.originalHost.split(':')[0]) {
62185 // Remove authorization if changing hostnames (but not if just
62186 // changing ports or protocols). This matches the behavior of curl:
62187 // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710
62188 request.removeHeader('authorization')
62189 }
62190 }
62191 }
62192
62193 if (!self.removeRefererHeader) {
62194 request.setHeader('referer', uriPrev.href)
62195 }
62196
62197 request.emit('redirect')
62198
62199 request.init()
62200
62201 return true
62202}
62203
62204exports.Redirect = Redirect
62205
62206},{"url":393}],310:[function(require,module,exports){
62207'use strict'
62208
62209var url = require('url')
62210var tunnel = require('tunnel-agent')
62211
62212var defaultProxyHeaderWhiteList = [
62213 'accept',
62214 'accept-charset',
62215 'accept-encoding',
62216 'accept-language',
62217 'accept-ranges',
62218 'cache-control',
62219 'content-encoding',
62220 'content-language',
62221 'content-location',
62222 'content-md5',
62223 'content-range',
62224 'content-type',
62225 'connection',
62226 'date',
62227 'expect',
62228 'max-forwards',
62229 'pragma',
62230 'referer',
62231 'te',
62232 'user-agent',
62233 'via'
62234]
62235
62236var defaultProxyHeaderExclusiveList = [
62237 'proxy-authorization'
62238]
62239
62240function constructProxyHost (uriObject) {
62241 var port = uriObject.port
62242 var protocol = uriObject.protocol
62243 var proxyHost = uriObject.hostname + ':'
62244
62245 if (port) {
62246 proxyHost += port
62247 } else if (protocol === 'https:') {
62248 proxyHost += '443'
62249 } else {
62250 proxyHost += '80'
62251 }
62252
62253 return proxyHost
62254}
62255
62256function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) {
62257 var whiteList = proxyHeaderWhiteList
62258 .reduce(function (set, header) {
62259 set[header.toLowerCase()] = true
62260 return set
62261 }, {})
62262
62263 return Object.keys(headers)
62264 .filter(function (header) {
62265 return whiteList[header.toLowerCase()]
62266 })
62267 .reduce(function (set, header) {
62268 set[header] = headers[header]
62269 return set
62270 }, {})
62271}
62272
62273function constructTunnelOptions (request, proxyHeaders) {
62274 var proxy = request.proxy
62275
62276 var tunnelOptions = {
62277 proxy: {
62278 host: proxy.hostname,
62279 port: +proxy.port,
62280 proxyAuth: proxy.auth,
62281 headers: proxyHeaders
62282 },
62283 headers: request.headers,
62284 ca: request.ca,
62285 cert: request.cert,
62286 key: request.key,
62287 passphrase: request.passphrase,
62288 pfx: request.pfx,
62289 ciphers: request.ciphers,
62290 rejectUnauthorized: request.rejectUnauthorized,
62291 secureOptions: request.secureOptions,
62292 secureProtocol: request.secureProtocol
62293 }
62294
62295 return tunnelOptions
62296}
62297
62298function constructTunnelFnName (uri, proxy) {
62299 var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http')
62300 var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http')
62301 return [uriProtocol, proxyProtocol].join('Over')
62302}
62303
62304function getTunnelFn (request) {
62305 var uri = request.uri
62306 var proxy = request.proxy
62307 var tunnelFnName = constructTunnelFnName(uri, proxy)
62308 return tunnel[tunnelFnName]
62309}
62310
62311function Tunnel (request) {
62312 this.request = request
62313 this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
62314 this.proxyHeaderExclusiveList = []
62315 if (typeof request.tunnel !== 'undefined') {
62316 this.tunnelOverride = request.tunnel
62317 }
62318}
62319
62320Tunnel.prototype.isEnabled = function () {
62321 var self = this
62322 var request = self.request
62323 // Tunnel HTTPS by default. Allow the user to override this setting.
62324
62325 // If self.tunnelOverride is set (the user specified a value), use it.
62326 if (typeof self.tunnelOverride !== 'undefined') {
62327 return self.tunnelOverride
62328 }
62329
62330 // If the destination is HTTPS, tunnel.
62331 if (request.uri.protocol === 'https:') {
62332 return true
62333 }
62334
62335 // Otherwise, do not use tunnel.
62336 return false
62337}
62338
62339Tunnel.prototype.setup = function (options) {
62340 var self = this
62341 var request = self.request
62342
62343 options = options || {}
62344
62345 if (typeof request.proxy === 'string') {
62346 request.proxy = url.parse(request.proxy)
62347 }
62348
62349 if (!request.proxy || !request.tunnel) {
62350 return false
62351 }
62352
62353 // Setup Proxy Header Exclusive List and White List
62354 if (options.proxyHeaderWhiteList) {
62355 self.proxyHeaderWhiteList = options.proxyHeaderWhiteList
62356 }
62357 if (options.proxyHeaderExclusiveList) {
62358 self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList
62359 }
62360
62361 var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
62362 var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
62363
62364 // Setup Proxy Headers and Proxy Headers Host
62365 // Only send the Proxy White Listed Header names
62366 var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList)
62367 proxyHeaders.host = constructProxyHost(request.uri)
62368
62369 proxyHeaderExclusiveList.forEach(request.removeHeader, request)
62370
62371 // Set Agent from Tunnel Data
62372 var tunnelFn = getTunnelFn(request)
62373 var tunnelOptions = constructTunnelOptions(request, proxyHeaders)
62374 request.agent = tunnelFn(tunnelOptions)
62375
62376 return true
62377}
62378
62379Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList
62380Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList
62381exports.Tunnel = Tunnel
62382
62383},{"tunnel-agent":390,"url":393}],311:[function(require,module,exports){
62384'use strict';
62385
62386var replace = String.prototype.replace;
62387var percentTwenties = /%20/g;
62388
62389module.exports = {
62390 'default': 'RFC3986',
62391 formatters: {
62392 RFC1738: function (value) {
62393 return replace.call(value, percentTwenties, '+');
62394 },
62395 RFC3986: function (value) {
62396 return value;
62397 }
62398 },
62399 RFC1738: 'RFC1738',
62400 RFC3986: 'RFC3986'
62401};
62402
62403},{}],312:[function(require,module,exports){
62404'use strict';
62405
62406var stringify = require('./stringify');
62407var parse = require('./parse');
62408var formats = require('./formats');
62409
62410module.exports = {
62411 formats: formats,
62412 parse: parse,
62413 stringify: stringify
62414};
62415
62416},{"./formats":311,"./parse":313,"./stringify":314}],313:[function(require,module,exports){
62417'use strict';
62418
62419var utils = require('./utils');
62420
62421var has = Object.prototype.hasOwnProperty;
62422
62423var defaults = {
62424 allowDots: false,
62425 allowPrototypes: false,
62426 arrayLimit: 20,
62427 decoder: utils.decode,
62428 delimiter: '&',
62429 depth: 5,
62430 parameterLimit: 1000,
62431 plainObjects: false,
62432 strictNullHandling: false
62433};
62434
62435var parseValues = function parseQueryStringValues(str, options) {
62436 var obj = {};
62437 var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str;
62438 var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit;
62439 var parts = cleanStr.split(options.delimiter, limit);
62440
62441 for (var i = 0; i < parts.length; ++i) {
62442 var part = parts[i];
62443
62444 var bracketEqualsPos = part.indexOf(']=');
62445 var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1;
62446
62447 var key, val;
62448 if (pos === -1) {
62449 key = options.decoder(part, defaults.decoder);
62450 val = options.strictNullHandling ? null : '';
62451 } else {
62452 key = options.decoder(part.slice(0, pos), defaults.decoder);
62453 val = options.decoder(part.slice(pos + 1), defaults.decoder);
62454 }
62455 if (has.call(obj, key)) {
62456 obj[key] = [].concat(obj[key]).concat(val);
62457 } else {
62458 obj[key] = val;
62459 }
62460 }
62461
62462 return obj;
62463};
62464
62465var parseObject = function (chain, val, options) {
62466 var leaf = val;
62467
62468 for (var i = chain.length - 1; i >= 0; --i) {
62469 var obj;
62470 var root = chain[i];
62471
62472 if (root === '[]') {
62473 obj = [];
62474 obj = obj.concat(leaf);
62475 } else {
62476 obj = options.plainObjects ? Object.create(null) : {};
62477 var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root;
62478 var index = parseInt(cleanRoot, 10);
62479 if (
62480 !isNaN(index)
62481 && root !== cleanRoot
62482 && String(index) === cleanRoot
62483 && index >= 0
62484 && (options.parseArrays && index <= options.arrayLimit)
62485 ) {
62486 obj = [];
62487 obj[index] = leaf;
62488 } else {
62489 obj[cleanRoot] = leaf;
62490 }
62491 }
62492
62493 leaf = obj;
62494 }
62495
62496 return leaf;
62497};
62498
62499var parseKeys = function parseQueryStringKeys(givenKey, val, options) {
62500 if (!givenKey) {
62501 return;
62502 }
62503
62504 // Transform dot notation to bracket notation
62505 var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey;
62506
62507 // The regex chunks
62508
62509 var brackets = /(\[[^[\]]*])/;
62510 var child = /(\[[^[\]]*])/g;
62511
62512 // Get the parent
62513
62514 var segment = brackets.exec(key);
62515 var parent = segment ? key.slice(0, segment.index) : key;
62516
62517 // Stash the parent if it exists
62518
62519 var keys = [];
62520 if (parent) {
62521 // If we aren't using plain objects, optionally prefix keys
62522 // that would overwrite object prototype properties
62523 if (!options.plainObjects && has.call(Object.prototype, parent)) {
62524 if (!options.allowPrototypes) {
62525 return;
62526 }
62527 }
62528
62529 keys.push(parent);
62530 }
62531
62532 // Loop through children appending to the array until we hit depth
62533
62534 var i = 0;
62535 while ((segment = child.exec(key)) !== null && i < options.depth) {
62536 i += 1;
62537 if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) {
62538 if (!options.allowPrototypes) {
62539 return;
62540 }
62541 }
62542 keys.push(segment[1]);
62543 }
62544
62545 // If there's a remainder, just add whatever is left
62546
62547 if (segment) {
62548 keys.push('[' + key.slice(segment.index) + ']');
62549 }
62550
62551 return parseObject(keys, val, options);
62552};
62553
62554module.exports = function (str, opts) {
62555 var options = opts ? utils.assign({}, opts) : {};
62556
62557 if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') {
62558 throw new TypeError('Decoder has to be a function.');
62559 }
62560
62561 options.ignoreQueryPrefix = options.ignoreQueryPrefix === true;
62562 options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter;
62563 options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth;
62564 options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit;
62565 options.parseArrays = options.parseArrays !== false;
62566 options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder;
62567 options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots;
62568 options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects;
62569 options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes;
62570 options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit;
62571 options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
62572
62573 if (str === '' || str === null || typeof str === 'undefined') {
62574 return options.plainObjects ? Object.create(null) : {};
62575 }
62576
62577 var tempObj = typeof str === 'string' ? parseValues(str, options) : str;
62578 var obj = options.plainObjects ? Object.create(null) : {};
62579
62580 // Iterate over the keys and setup the new object
62581
62582 var keys = Object.keys(tempObj);
62583 for (var i = 0; i < keys.length; ++i) {
62584 var key = keys[i];
62585 var newObj = parseKeys(key, tempObj[key], options);
62586 obj = utils.merge(obj, newObj, options);
62587 }
62588
62589 return utils.compact(obj);
62590};
62591
62592},{"./utils":315}],314:[function(require,module,exports){
62593'use strict';
62594
62595var utils = require('./utils');
62596var formats = require('./formats');
62597
62598var arrayPrefixGenerators = {
62599 brackets: function brackets(prefix) { // eslint-disable-line func-name-matching
62600 return prefix + '[]';
62601 },
62602 indices: function indices(prefix, key) { // eslint-disable-line func-name-matching
62603 return prefix + '[' + key + ']';
62604 },
62605 repeat: function repeat(prefix) { // eslint-disable-line func-name-matching
62606 return prefix;
62607 }
62608};
62609
62610var toISO = Date.prototype.toISOString;
62611
62612var defaults = {
62613 delimiter: '&',
62614 encode: true,
62615 encoder: utils.encode,
62616 encodeValuesOnly: false,
62617 serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching
62618 return toISO.call(date);
62619 },
62620 skipNulls: false,
62621 strictNullHandling: false
62622};
62623
62624var stringify = function stringify( // eslint-disable-line func-name-matching
62625 object,
62626 prefix,
62627 generateArrayPrefix,
62628 strictNullHandling,
62629 skipNulls,
62630 encoder,
62631 filter,
62632 sort,
62633 allowDots,
62634 serializeDate,
62635 formatter,
62636 encodeValuesOnly
62637) {
62638 var obj = object;
62639 if (typeof filter === 'function') {
62640 obj = filter(prefix, obj);
62641 } else if (obj instanceof Date) {
62642 obj = serializeDate(obj);
62643 } else if (obj === null) {
62644 if (strictNullHandling) {
62645 return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix;
62646 }
62647
62648 obj = '';
62649 }
62650
62651 if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) {
62652 if (encoder) {
62653 var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder);
62654 return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))];
62655 }
62656 return [formatter(prefix) + '=' + formatter(String(obj))];
62657 }
62658
62659 var values = [];
62660
62661 if (typeof obj === 'undefined') {
62662 return values;
62663 }
62664
62665 var objKeys;
62666 if (Array.isArray(filter)) {
62667 objKeys = filter;
62668 } else {
62669 var keys = Object.keys(obj);
62670 objKeys = sort ? keys.sort(sort) : keys;
62671 }
62672
62673 for (var i = 0; i < objKeys.length; ++i) {
62674 var key = objKeys[i];
62675
62676 if (skipNulls && obj[key] === null) {
62677 continue;
62678 }
62679
62680 if (Array.isArray(obj)) {
62681 values = values.concat(stringify(
62682 obj[key],
62683 generateArrayPrefix(prefix, key),
62684 generateArrayPrefix,
62685 strictNullHandling,
62686 skipNulls,
62687 encoder,
62688 filter,
62689 sort,
62690 allowDots,
62691 serializeDate,
62692 formatter,
62693 encodeValuesOnly
62694 ));
62695 } else {
62696 values = values.concat(stringify(
62697 obj[key],
62698 prefix + (allowDots ? '.' + key : '[' + key + ']'),
62699 generateArrayPrefix,
62700 strictNullHandling,
62701 skipNulls,
62702 encoder,
62703 filter,
62704 sort,
62705 allowDots,
62706 serializeDate,
62707 formatter,
62708 encodeValuesOnly
62709 ));
62710 }
62711 }
62712
62713 return values;
62714};
62715
62716module.exports = function (object, opts) {
62717 var obj = object;
62718 var options = opts ? utils.assign({}, opts) : {};
62719
62720 if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') {
62721 throw new TypeError('Encoder has to be a function.');
62722 }
62723
62724 var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter;
62725 var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling;
62726 var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls;
62727 var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode;
62728 var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder;
62729 var sort = typeof options.sort === 'function' ? options.sort : null;
62730 var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots;
62731 var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate;
62732 var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly;
62733 if (typeof options.format === 'undefined') {
62734 options.format = formats['default'];
62735 } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) {
62736 throw new TypeError('Unknown format option provided.');
62737 }
62738 var formatter = formats.formatters[options.format];
62739 var objKeys;
62740 var filter;
62741
62742 if (typeof options.filter === 'function') {
62743 filter = options.filter;
62744 obj = filter('', obj);
62745 } else if (Array.isArray(options.filter)) {
62746 filter = options.filter;
62747 objKeys = filter;
62748 }
62749
62750 var keys = [];
62751
62752 if (typeof obj !== 'object' || obj === null) {
62753 return '';
62754 }
62755
62756 var arrayFormat;
62757 if (options.arrayFormat in arrayPrefixGenerators) {
62758 arrayFormat = options.arrayFormat;
62759 } else if ('indices' in options) {
62760 arrayFormat = options.indices ? 'indices' : 'repeat';
62761 } else {
62762 arrayFormat = 'indices';
62763 }
62764
62765 var generateArrayPrefix = arrayPrefixGenerators[arrayFormat];
62766
62767 if (!objKeys) {
62768 objKeys = Object.keys(obj);
62769 }
62770
62771 if (sort) {
62772 objKeys.sort(sort);
62773 }
62774
62775 for (var i = 0; i < objKeys.length; ++i) {
62776 var key = objKeys[i];
62777
62778 if (skipNulls && obj[key] === null) {
62779 continue;
62780 }
62781
62782 keys = keys.concat(stringify(
62783 obj[key],
62784 key,
62785 generateArrayPrefix,
62786 strictNullHandling,
62787 skipNulls,
62788 encode ? encoder : null,
62789 filter,
62790 sort,
62791 allowDots,
62792 serializeDate,
62793 formatter,
62794 encodeValuesOnly
62795 ));
62796 }
62797
62798 var joined = keys.join(delimiter);
62799 var prefix = options.addQueryPrefix === true ? '?' : '';
62800
62801 return joined.length > 0 ? prefix + joined : '';
62802};
62803
62804},{"./formats":311,"./utils":315}],315:[function(require,module,exports){
62805'use strict';
62806
62807var has = Object.prototype.hasOwnProperty;
62808
62809var hexTable = (function () {
62810 var array = [];
62811 for (var i = 0; i < 256; ++i) {
62812 array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());
62813 }
62814
62815 return array;
62816}());
62817
62818var compactQueue = function compactQueue(queue) {
62819 var obj;
62820
62821 while (queue.length) {
62822 var item = queue.pop();
62823 obj = item.obj[item.prop];
62824
62825 if (Array.isArray(obj)) {
62826 var compacted = [];
62827
62828 for (var j = 0; j < obj.length; ++j) {
62829 if (typeof obj[j] !== 'undefined') {
62830 compacted.push(obj[j]);
62831 }
62832 }
62833
62834 item.obj[item.prop] = compacted;
62835 }
62836 }
62837
62838 return obj;
62839};
62840
62841var arrayToObject = function arrayToObject(source, options) {
62842 var obj = options && options.plainObjects ? Object.create(null) : {};
62843 for (var i = 0; i < source.length; ++i) {
62844 if (typeof source[i] !== 'undefined') {
62845 obj[i] = source[i];
62846 }
62847 }
62848
62849 return obj;
62850};
62851
62852var merge = function merge(target, source, options) {
62853 if (!source) {
62854 return target;
62855 }
62856
62857 if (typeof source !== 'object') {
62858 if (Array.isArray(target)) {
62859 target.push(source);
62860 } else if (typeof target === 'object') {
62861 if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) {
62862 target[source] = true;
62863 }
62864 } else {
62865 return [target, source];
62866 }
62867
62868 return target;
62869 }
62870
62871 if (typeof target !== 'object') {
62872 return [target].concat(source);
62873 }
62874
62875 var mergeTarget = target;
62876 if (Array.isArray(target) && !Array.isArray(source)) {
62877 mergeTarget = arrayToObject(target, options);
62878 }
62879
62880 if (Array.isArray(target) && Array.isArray(source)) {
62881 source.forEach(function (item, i) {
62882 if (has.call(target, i)) {
62883 if (target[i] && typeof target[i] === 'object') {
62884 target[i] = merge(target[i], item, options);
62885 } else {
62886 target.push(item);
62887 }
62888 } else {
62889 target[i] = item;
62890 }
62891 });
62892 return target;
62893 }
62894
62895 return Object.keys(source).reduce(function (acc, key) {
62896 var value = source[key];
62897
62898 if (has.call(acc, key)) {
62899 acc[key] = merge(acc[key], value, options);
62900 } else {
62901 acc[key] = value;
62902 }
62903 return acc;
62904 }, mergeTarget);
62905};
62906
62907var assign = function assignSingleSource(target, source) {
62908 return Object.keys(source).reduce(function (acc, key) {
62909 acc[key] = source[key];
62910 return acc;
62911 }, target);
62912};
62913
62914var decode = function (str) {
62915 try {
62916 return decodeURIComponent(str.replace(/\+/g, ' '));
62917 } catch (e) {
62918 return str;
62919 }
62920};
62921
62922var encode = function encode(str) {
62923 // This code was originally written by Brian White (mscdex) for the io.js core querystring library.
62924 // It has been adapted here for stricter adherence to RFC 3986
62925 if (str.length === 0) {
62926 return str;
62927 }
62928
62929 var string = typeof str === 'string' ? str : String(str);
62930
62931 var out = '';
62932 for (var i = 0; i < string.length; ++i) {
62933 var c = string.charCodeAt(i);
62934
62935 if (
62936 c === 0x2D // -
62937 || c === 0x2E // .
62938 || c === 0x5F // _
62939 || c === 0x7E // ~
62940 || (c >= 0x30 && c <= 0x39) // 0-9
62941 || (c >= 0x41 && c <= 0x5A) // a-z
62942 || (c >= 0x61 && c <= 0x7A) // A-Z
62943 ) {
62944 out += string.charAt(i);
62945 continue;
62946 }
62947
62948 if (c < 0x80) {
62949 out = out + hexTable[c];
62950 continue;
62951 }
62952
62953 if (c < 0x800) {
62954 out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]);
62955 continue;
62956 }
62957
62958 if (c < 0xD800 || c >= 0xE000) {
62959 out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]);
62960 continue;
62961 }
62962
62963 i += 1;
62964 c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF));
62965 out += hexTable[0xF0 | (c >> 18)]
62966 + hexTable[0x80 | ((c >> 12) & 0x3F)]
62967 + hexTable[0x80 | ((c >> 6) & 0x3F)]
62968 + hexTable[0x80 | (c & 0x3F)];
62969 }
62970
62971 return out;
62972};
62973
62974var compact = function compact(value) {
62975 var queue = [{ obj: { o: value }, prop: 'o' }];
62976 var refs = [];
62977
62978 for (var i = 0; i < queue.length; ++i) {
62979 var item = queue[i];
62980 var obj = item.obj[item.prop];
62981
62982 var keys = Object.keys(obj);
62983 for (var j = 0; j < keys.length; ++j) {
62984 var key = keys[j];
62985 var val = obj[key];
62986 if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {
62987 queue.push({ obj: obj, prop: key });
62988 refs.push(val);
62989 }
62990 }
62991 }
62992
62993 return compactQueue(queue);
62994};
62995
62996var isRegExp = function isRegExp(obj) {
62997 return Object.prototype.toString.call(obj) === '[object RegExp]';
62998};
62999
63000var isBuffer = function isBuffer(obj) {
63001 if (obj === null || typeof obj === 'undefined') {
63002 return false;
63003 }
63004
63005 return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));
63006};
63007
63008module.exports = {
63009 arrayToObject: arrayToObject,
63010 assign: assign,
63011 compact: compact,
63012 decode: decode,
63013 encode: encode,
63014 isBuffer: isBuffer,
63015 isRegExp: isRegExp,
63016 merge: merge
63017};
63018
63019},{}],316:[function(require,module,exports){
63020/*!
63021 * Copyright (c) 2015, Salesforce.com, Inc.
63022 * All rights reserved.
63023 *
63024 * Redistribution and use in source and binary forms, with or without
63025 * modification, are permitted provided that the following conditions are met:
63026 *
63027 * 1. Redistributions of source code must retain the above copyright notice,
63028 * this list of conditions and the following disclaimer.
63029 *
63030 * 2. Redistributions in binary form must reproduce the above copyright notice,
63031 * this list of conditions and the following disclaimer in the documentation
63032 * and/or other materials provided with the distribution.
63033 *
63034 * 3. Neither the name of Salesforce.com nor the names of its contributors may
63035 * be used to endorse or promote products derived from this software without
63036 * specific prior written permission.
63037 *
63038 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
63039 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
63040 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63041 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
63042 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
63043 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
63044 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63045 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
63046 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
63047 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
63048 * POSSIBILITY OF SUCH DAMAGE.
63049 */
63050'use strict';
63051var net = require('net');
63052var urlParse = require('url').parse;
63053var util = require('util');
63054var pubsuffix = require('./pubsuffix-psl');
63055var Store = require('./store').Store;
63056var MemoryCookieStore = require('./memstore').MemoryCookieStore;
63057var pathMatch = require('./pathMatch').pathMatch;
63058var VERSION = require('../package.json').version;
63059
63060var punycode;
63061try {
63062 punycode = require('punycode');
63063} catch(e) {
63064 console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization");
63065}
63066
63067// From RFC6265 S4.1.1
63068// note that it excludes \x3B ";"
63069var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
63070
63071var CONTROL_CHARS = /[\x00-\x1F]/;
63072
63073// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in
63074// the "relaxed" mode, see:
63075// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60
63076var TERMINATORS = ['\n', '\r', '\0'];
63077
63078// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
63079// Note ';' is \x3B
63080var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
63081
63082// date-time parsing constants (RFC6265 S5.1.1)
63083
63084var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
63085
63086var MONTH_TO_NUM = {
63087 jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
63088 jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
63089};
63090var NUM_TO_MONTH = [
63091 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
63092];
63093var NUM_TO_DAY = [
63094 'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
63095];
63096
63097var MAX_TIME = 2147483647000; // 31-bit max
63098var MIN_TIME = 0; // 31-bit min
63099
63100/*
63101 * Parses a Natural number (i.e., non-negative integer) with either the
63102 * <min>*<max>DIGIT ( non-digit *OCTET )
63103 * or
63104 * <min>*<max>DIGIT
63105 * grammar (RFC6265 S5.1.1).
63106 *
63107 * The "trailingOK" boolean controls if the grammar accepts a
63108 * "( non-digit *OCTET )" trailer.
63109 */
63110function parseDigits(token, minDigits, maxDigits, trailingOK) {
63111 var count = 0;
63112 while (count < token.length) {
63113 var c = token.charCodeAt(count);
63114 // "non-digit = %x00-2F / %x3A-FF"
63115 if (c <= 0x2F || c >= 0x3A) {
63116 break;
63117 }
63118 count++;
63119 }
63120
63121 // constrain to a minimum and maximum number of digits.
63122 if (count < minDigits || count > maxDigits) {
63123 return null;
63124 }
63125
63126 if (!trailingOK && count != token.length) {
63127 return null;
63128 }
63129
63130 return parseInt(token.substr(0,count), 10);
63131}
63132
63133function parseTime(token) {
63134 var parts = token.split(':');
63135 var result = [0,0,0];
63136
63137 /* RF6256 S5.1.1:
63138 * time = hms-time ( non-digit *OCTET )
63139 * hms-time = time-field ":" time-field ":" time-field
63140 * time-field = 1*2DIGIT
63141 */
63142
63143 if (parts.length !== 3) {
63144 return null;
63145 }
63146
63147 for (var i = 0; i < 3; i++) {
63148 // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be
63149 // followed by "( non-digit *OCTET )" so therefore the last time-field can
63150 // have a trailer
63151 var trailingOK = (i == 2);
63152 var num = parseDigits(parts[i], 1, 2, trailingOK);
63153 if (num === null) {
63154 return null;
63155 }
63156 result[i] = num;
63157 }
63158
63159 return result;
63160}
63161
63162function parseMonth(token) {
63163 token = String(token).substr(0,3).toLowerCase();
63164 var num = MONTH_TO_NUM[token];
63165 return num >= 0 ? num : null;
63166}
63167
63168/*
63169 * RFC6265 S5.1.1 date parser (see RFC for full grammar)
63170 */
63171function parseDate(str) {
63172 if (!str) {
63173 return;
63174 }
63175
63176 /* RFC6265 S5.1.1:
63177 * 2. Process each date-token sequentially in the order the date-tokens
63178 * appear in the cookie-date
63179 */
63180 var tokens = str.split(DATE_DELIM);
63181 if (!tokens) {
63182 return;
63183 }
63184
63185 var hour = null;
63186 var minute = null;
63187 var second = null;
63188 var dayOfMonth = null;
63189 var month = null;
63190 var year = null;
63191
63192 for (var i=0; i<tokens.length; i++) {
63193 var token = tokens[i].trim();
63194 if (!token.length) {
63195 continue;
63196 }
63197
63198 var result;
63199
63200 /* 2.1. If the found-time flag is not set and the token matches the time
63201 * production, set the found-time flag and set the hour- value,
63202 * minute-value, and second-value to the numbers denoted by the digits in
63203 * the date-token, respectively. Skip the remaining sub-steps and continue
63204 * to the next date-token.
63205 */
63206 if (second === null) {
63207 result = parseTime(token);
63208 if (result) {
63209 hour = result[0];
63210 minute = result[1];
63211 second = result[2];
63212 continue;
63213 }
63214 }
63215
63216 /* 2.2. If the found-day-of-month flag is not set and the date-token matches
63217 * the day-of-month production, set the found-day-of- month flag and set
63218 * the day-of-month-value to the number denoted by the date-token. Skip
63219 * the remaining sub-steps and continue to the next date-token.
63220 */
63221 if (dayOfMonth === null) {
63222 // "day-of-month = 1*2DIGIT ( non-digit *OCTET )"
63223 result = parseDigits(token, 1, 2, true);
63224 if (result !== null) {
63225 dayOfMonth = result;
63226 continue;
63227 }
63228 }
63229
63230 /* 2.3. If the found-month flag is not set and the date-token matches the
63231 * month production, set the found-month flag and set the month-value to
63232 * the month denoted by the date-token. Skip the remaining sub-steps and
63233 * continue to the next date-token.
63234 */
63235 if (month === null) {
63236 result = parseMonth(token);
63237 if (result !== null) {
63238 month = result;
63239 continue;
63240 }
63241 }
63242
63243 /* 2.4. If the found-year flag is not set and the date-token matches the
63244 * year production, set the found-year flag and set the year-value to the
63245 * number denoted by the date-token. Skip the remaining sub-steps and
63246 * continue to the next date-token.
63247 */
63248 if (year === null) {
63249 // "year = 2*4DIGIT ( non-digit *OCTET )"
63250 result = parseDigits(token, 2, 4, true);
63251 if (result !== null) {
63252 year = result;
63253 /* From S5.1.1:
63254 * 3. If the year-value is greater than or equal to 70 and less
63255 * than or equal to 99, increment the year-value by 1900.
63256 * 4. If the year-value is greater than or equal to 0 and less
63257 * than or equal to 69, increment the year-value by 2000.
63258 */
63259 if (year >= 70 && year <= 99) {
63260 year += 1900;
63261 } else if (year >= 0 && year <= 69) {
63262 year += 2000;
63263 }
63264 }
63265 }
63266 }
63267
63268 /* RFC 6265 S5.1.1
63269 * "5. Abort these steps and fail to parse the cookie-date if:
63270 * * at least one of the found-day-of-month, found-month, found-
63271 * year, or found-time flags is not set,
63272 * * the day-of-month-value is less than 1 or greater than 31,
63273 * * the year-value is less than 1601,
63274 * * the hour-value is greater than 23,
63275 * * the minute-value is greater than 59, or
63276 * * the second-value is greater than 59.
63277 * (Note that leap seconds cannot be represented in this syntax.)"
63278 *
63279 * So, in order as above:
63280 */
63281 if (
63282 dayOfMonth === null || month === null || year === null || second === null ||
63283 dayOfMonth < 1 || dayOfMonth > 31 ||
63284 year < 1601 ||
63285 hour > 23 ||
63286 minute > 59 ||
63287 second > 59
63288 ) {
63289 return;
63290 }
63291
63292 return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
63293}
63294
63295function formatDate(date) {
63296 var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
63297 var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
63298 var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
63299 var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
63300 return NUM_TO_DAY[date.getUTCDay()] + ', ' +
63301 d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
63302 h+':'+m+':'+s+' GMT';
63303}
63304
63305// S5.1.2 Canonicalized Host Names
63306function canonicalDomain(str) {
63307 if (str == null) {
63308 return null;
63309 }
63310 str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
63311
63312 // convert to IDN if any non-ASCII characters
63313 if (punycode && /[^\u0001-\u007f]/.test(str)) {
63314 str = punycode.toASCII(str);
63315 }
63316
63317 return str.toLowerCase();
63318}
63319
63320// S5.1.3 Domain Matching
63321function domainMatch(str, domStr, canonicalize) {
63322 if (str == null || domStr == null) {
63323 return null;
63324 }
63325 if (canonicalize !== false) {
63326 str = canonicalDomain(str);
63327 domStr = canonicalDomain(domStr);
63328 }
63329
63330 /*
63331 * "The domain string and the string are identical. (Note that both the
63332 * domain string and the string will have been canonicalized to lower case at
63333 * this point)"
63334 */
63335 if (str == domStr) {
63336 return true;
63337 }
63338
63339 /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
63340
63341 /* "* The string is a host name (i.e., not an IP address)." */
63342 if (net.isIP(str)) {
63343 return false;
63344 }
63345
63346 /* "* The domain string is a suffix of the string" */
63347 var idx = str.indexOf(domStr);
63348 if (idx <= 0) {
63349 return false; // it's a non-match (-1) or prefix (0)
63350 }
63351
63352 // e.g "a.b.c".indexOf("b.c") === 2
63353 // 5 === 3+2
63354 if (str.length !== domStr.length + idx) { // it's not a suffix
63355 return false;
63356 }
63357
63358 /* "* The last character of the string that is not included in the domain
63359 * string is a %x2E (".") character." */
63360 if (str.substr(idx-1,1) !== '.') {
63361 return false;
63362 }
63363
63364 return true;
63365}
63366
63367
63368// RFC6265 S5.1.4 Paths and Path-Match
63369
63370/*
63371 * "The user agent MUST use an algorithm equivalent to the following algorithm
63372 * to compute the default-path of a cookie:"
63373 *
63374 * Assumption: the path (and not query part or absolute uri) is passed in.
63375 */
63376function defaultPath(path) {
63377 // "2. If the uri-path is empty or if the first character of the uri-path is not
63378 // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
63379 if (!path || path.substr(0,1) !== "/") {
63380 return "/";
63381 }
63382
63383 // "3. If the uri-path contains no more than one %x2F ("/") character, output
63384 // %x2F ("/") and skip the remaining step."
63385 if (path === "/") {
63386 return path;
63387 }
63388
63389 var rightSlash = path.lastIndexOf("/");
63390 if (rightSlash === 0) {
63391 return "/";
63392 }
63393
63394 // "4. Output the characters of the uri-path from the first character up to,
63395 // but not including, the right-most %x2F ("/")."
63396 return path.slice(0, rightSlash);
63397}
63398
63399function trimTerminator(str) {
63400 for (var t = 0; t < TERMINATORS.length; t++) {
63401 var terminatorIdx = str.indexOf(TERMINATORS[t]);
63402 if (terminatorIdx !== -1) {
63403 str = str.substr(0,terminatorIdx);
63404 }
63405 }
63406
63407 return str;
63408}
63409
63410function parseCookiePair(cookiePair, looseMode) {
63411 cookiePair = trimTerminator(cookiePair);
63412
63413 var firstEq = cookiePair.indexOf('=');
63414 if (looseMode) {
63415 if (firstEq === 0) { // '=' is immediately at start
63416 cookiePair = cookiePair.substr(1);
63417 firstEq = cookiePair.indexOf('='); // might still need to split on '='
63418 }
63419 } else { // non-loose mode
63420 if (firstEq <= 0) { // no '=' or is at start
63421 return; // needs to have non-empty "cookie-name"
63422 }
63423 }
63424
63425 var cookieName, cookieValue;
63426 if (firstEq <= 0) {
63427 cookieName = "";
63428 cookieValue = cookiePair.trim();
63429 } else {
63430 cookieName = cookiePair.substr(0, firstEq).trim();
63431 cookieValue = cookiePair.substr(firstEq+1).trim();
63432 }
63433
63434 if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
63435 return;
63436 }
63437
63438 var c = new Cookie();
63439 c.key = cookieName;
63440 c.value = cookieValue;
63441 return c;
63442}
63443
63444function parse(str, options) {
63445 if (!options || typeof options !== 'object') {
63446 options = {};
63447 }
63448 str = str.trim();
63449
63450 // We use a regex to parse the "name-value-pair" part of S5.2
63451 var firstSemi = str.indexOf(';'); // S5.2 step 1
63452 var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi);
63453 var c = parseCookiePair(cookiePair, !!options.loose);
63454 if (!c) {
63455 return;
63456 }
63457
63458 if (firstSemi === -1) {
63459 return c;
63460 }
63461
63462 // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
63463 // (including the %x3B (";") in question)." plus later on in the same section
63464 // "discard the first ";" and trim".
63465 var unparsed = str.slice(firstSemi + 1).trim();
63466
63467 // "If the unparsed-attributes string is empty, skip the rest of these
63468 // steps."
63469 if (unparsed.length === 0) {
63470 return c;
63471 }
63472
63473 /*
63474 * S5.2 says that when looping over the items "[p]rocess the attribute-name
63475 * and attribute-value according to the requirements in the following
63476 * subsections" for every item. Plus, for many of the individual attributes
63477 * in S5.3 it says to use the "attribute-value of the last attribute in the
63478 * cookie-attribute-list". Therefore, in this implementation, we overwrite
63479 * the previous value.
63480 */
63481 var cookie_avs = unparsed.split(';');
63482 while (cookie_avs.length) {
63483 var av = cookie_avs.shift().trim();
63484 if (av.length === 0) { // happens if ";;" appears
63485 continue;
63486 }
63487 var av_sep = av.indexOf('=');
63488 var av_key, av_value;
63489
63490 if (av_sep === -1) {
63491 av_key = av;
63492 av_value = null;
63493 } else {
63494 av_key = av.substr(0,av_sep);
63495 av_value = av.substr(av_sep+1);
63496 }
63497
63498 av_key = av_key.trim().toLowerCase();
63499
63500 if (av_value) {
63501 av_value = av_value.trim();
63502 }
63503
63504 switch(av_key) {
63505 case 'expires': // S5.2.1
63506 if (av_value) {
63507 var exp = parseDate(av_value);
63508 // "If the attribute-value failed to parse as a cookie date, ignore the
63509 // cookie-av."
63510 if (exp) {
63511 // over and underflow not realistically a concern: V8's getTime() seems to
63512 // store something larger than a 32-bit time_t (even with 32-bit node)
63513 c.expires = exp;
63514 }
63515 }
63516 break;
63517
63518 case 'max-age': // S5.2.2
63519 if (av_value) {
63520 // "If the first character of the attribute-value is not a DIGIT or a "-"
63521 // character ...[or]... If the remainder of attribute-value contains a
63522 // non-DIGIT character, ignore the cookie-av."
63523 if (/^-?[0-9]+$/.test(av_value)) {
63524 var delta = parseInt(av_value, 10);
63525 // "If delta-seconds is less than or equal to zero (0), let expiry-time
63526 // be the earliest representable date and time."
63527 c.setMaxAge(delta);
63528 }
63529 }
63530 break;
63531
63532 case 'domain': // S5.2.3
63533 // "If the attribute-value is empty, the behavior is undefined. However,
63534 // the user agent SHOULD ignore the cookie-av entirely."
63535 if (av_value) {
63536 // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
63537 // (".") character."
63538 var domain = av_value.trim().replace(/^\./, '');
63539 if (domain) {
63540 // "Convert the cookie-domain to lower case."
63541 c.domain = domain.toLowerCase();
63542 }
63543 }
63544 break;
63545
63546 case 'path': // S5.2.4
63547 /*
63548 * "If the attribute-value is empty or if the first character of the
63549 * attribute-value is not %x2F ("/"):
63550 * Let cookie-path be the default-path.
63551 * Otherwise:
63552 * Let cookie-path be the attribute-value."
63553 *
63554 * We'll represent the default-path as null since it depends on the
63555 * context of the parsing.
63556 */
63557 c.path = av_value && av_value[0] === "/" ? av_value : null;
63558 break;
63559
63560 case 'secure': // S5.2.5
63561 /*
63562 * "If the attribute-name case-insensitively matches the string "Secure",
63563 * the user agent MUST append an attribute to the cookie-attribute-list
63564 * with an attribute-name of Secure and an empty attribute-value."
63565 */
63566 c.secure = true;
63567 break;
63568
63569 case 'httponly': // S5.2.6 -- effectively the same as 'secure'
63570 c.httpOnly = true;
63571 break;
63572
63573 default:
63574 c.extensions = c.extensions || [];
63575 c.extensions.push(av);
63576 break;
63577 }
63578 }
63579
63580 return c;
63581}
63582
63583// avoid the V8 deoptimization monster!
63584function jsonParse(str) {
63585 var obj;
63586 try {
63587 obj = JSON.parse(str);
63588 } catch (e) {
63589 return e;
63590 }
63591 return obj;
63592}
63593
63594function fromJSON(str) {
63595 if (!str) {
63596 return null;
63597 }
63598
63599 var obj;
63600 if (typeof str === 'string') {
63601 obj = jsonParse(str);
63602 if (obj instanceof Error) {
63603 return null;
63604 }
63605 } else {
63606 // assume it's an Object
63607 obj = str;
63608 }
63609
63610 var c = new Cookie();
63611 for (var i=0; i<Cookie.serializableProperties.length; i++) {
63612 var prop = Cookie.serializableProperties[i];
63613 if (obj[prop] === undefined ||
63614 obj[prop] === Cookie.prototype[prop])
63615 {
63616 continue; // leave as prototype default
63617 }
63618
63619 if (prop === 'expires' ||
63620 prop === 'creation' ||
63621 prop === 'lastAccessed')
63622 {
63623 if (obj[prop] === null) {
63624 c[prop] = null;
63625 } else {
63626 c[prop] = obj[prop] == "Infinity" ?
63627 "Infinity" : new Date(obj[prop]);
63628 }
63629 } else {
63630 c[prop] = obj[prop];
63631 }
63632 }
63633
63634 return c;
63635}
63636
63637/* Section 5.4 part 2:
63638 * "* Cookies with longer paths are listed before cookies with
63639 * shorter paths.
63640 *
63641 * * Among cookies that have equal-length path fields, cookies with
63642 * earlier creation-times are listed before cookies with later
63643 * creation-times."
63644 */
63645
63646function cookieCompare(a,b) {
63647 var cmp = 0;
63648
63649 // descending for length: b CMP a
63650 var aPathLen = a.path ? a.path.length : 0;
63651 var bPathLen = b.path ? b.path.length : 0;
63652 cmp = bPathLen - aPathLen;
63653 if (cmp !== 0) {
63654 return cmp;
63655 }
63656
63657 // ascending for time: a CMP b
63658 var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
63659 var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
63660 cmp = aTime - bTime;
63661 if (cmp !== 0) {
63662 return cmp;
63663 }
63664
63665 // break ties for the same millisecond (precision of JavaScript's clock)
63666 cmp = a.creationIndex - b.creationIndex;
63667
63668 return cmp;
63669}
63670
63671// Gives the permutation of all possible pathMatch()es of a given path. The
63672// array is in longest-to-shortest order. Handy for indexing.
63673function permutePath(path) {
63674 if (path === '/') {
63675 return ['/'];
63676 }
63677 if (path.lastIndexOf('/') === path.length-1) {
63678 path = path.substr(0,path.length-1);
63679 }
63680 var permutations = [path];
63681 while (path.length > 1) {
63682 var lindex = path.lastIndexOf('/');
63683 if (lindex === 0) {
63684 break;
63685 }
63686 path = path.substr(0,lindex);
63687 permutations.push(path);
63688 }
63689 permutations.push('/');
63690 return permutations;
63691}
63692
63693function getCookieContext(url) {
63694 if (url instanceof Object) {
63695 return url;
63696 }
63697 // NOTE: decodeURI will throw on malformed URIs (see GH-32).
63698 // Therefore, we will just skip decoding for such URIs.
63699 try {
63700 url = decodeURI(url);
63701 }
63702 catch(err) {
63703 // Silently swallow error
63704 }
63705
63706 return urlParse(url);
63707}
63708
63709function Cookie(options) {
63710 options = options || {};
63711
63712 Object.keys(options).forEach(function(prop) {
63713 if (Cookie.prototype.hasOwnProperty(prop) &&
63714 Cookie.prototype[prop] !== options[prop] &&
63715 prop.substr(0,1) !== '_')
63716 {
63717 this[prop] = options[prop];
63718 }
63719 }, this);
63720
63721 this.creation = this.creation || new Date();
63722
63723 // used to break creation ties in cookieCompare():
63724 Object.defineProperty(this, 'creationIndex', {
63725 configurable: false,
63726 enumerable: false, // important for assert.deepEqual checks
63727 writable: true,
63728 value: ++Cookie.cookiesCreated
63729 });
63730}
63731
63732Cookie.cookiesCreated = 0; // incremented each time a cookie is created
63733
63734Cookie.parse = parse;
63735Cookie.fromJSON = fromJSON;
63736
63737Cookie.prototype.key = "";
63738Cookie.prototype.value = "";
63739
63740// the order in which the RFC has them:
63741Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
63742Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
63743Cookie.prototype.domain = null;
63744Cookie.prototype.path = null;
63745Cookie.prototype.secure = false;
63746Cookie.prototype.httpOnly = false;
63747Cookie.prototype.extensions = null;
63748
63749// set by the CookieJar:
63750Cookie.prototype.hostOnly = null; // boolean when set
63751Cookie.prototype.pathIsDefault = null; // boolean when set
63752Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
63753Cookie.prototype.lastAccessed = null; // Date when set
63754Object.defineProperty(Cookie.prototype, 'creationIndex', {
63755 configurable: true,
63756 enumerable: false,
63757 writable: true,
63758 value: 0
63759});
63760
63761Cookie.serializableProperties = Object.keys(Cookie.prototype)
63762 .filter(function(prop) {
63763 return !(
63764 Cookie.prototype[prop] instanceof Function ||
63765 prop === 'creationIndex' ||
63766 prop.substr(0,1) === '_'
63767 );
63768 });
63769
63770Cookie.prototype.inspect = function inspect() {
63771 var now = Date.now();
63772 return 'Cookie="'+this.toString() +
63773 '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
63774 '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
63775 '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
63776 '"';
63777};
63778
63779// Use the new custom inspection symbol to add the custom inspect function if
63780// available.
63781if (util.inspect.custom) {
63782 Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect;
63783}
63784
63785Cookie.prototype.toJSON = function() {
63786 var obj = {};
63787
63788 var props = Cookie.serializableProperties;
63789 for (var i=0; i<props.length; i++) {
63790 var prop = props[i];
63791 if (this[prop] === Cookie.prototype[prop]) {
63792 continue; // leave as prototype default
63793 }
63794
63795 if (prop === 'expires' ||
63796 prop === 'creation' ||
63797 prop === 'lastAccessed')
63798 {
63799 if (this[prop] === null) {
63800 obj[prop] = null;
63801 } else {
63802 obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
63803 "Infinity" : this[prop].toISOString();
63804 }
63805 } else if (prop === 'maxAge') {
63806 if (this[prop] !== null) {
63807 // again, intentionally not ===
63808 obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
63809 this[prop].toString() : this[prop];
63810 }
63811 } else {
63812 if (this[prop] !== Cookie.prototype[prop]) {
63813 obj[prop] = this[prop];
63814 }
63815 }
63816 }
63817
63818 return obj;
63819};
63820
63821Cookie.prototype.clone = function() {
63822 return fromJSON(this.toJSON());
63823};
63824
63825Cookie.prototype.validate = function validate() {
63826 if (!COOKIE_OCTETS.test(this.value)) {
63827 return false;
63828 }
63829 if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
63830 return false;
63831 }
63832 if (this.maxAge != null && this.maxAge <= 0) {
63833 return false; // "Max-Age=" non-zero-digit *DIGIT
63834 }
63835 if (this.path != null && !PATH_VALUE.test(this.path)) {
63836 return false;
63837 }
63838
63839 var cdomain = this.cdomain();
63840 if (cdomain) {
63841 if (cdomain.match(/\.$/)) {
63842 return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
63843 }
63844 var suffix = pubsuffix.getPublicSuffix(cdomain);
63845 if (suffix == null) { // it's a public suffix
63846 return false;
63847 }
63848 }
63849 return true;
63850};
63851
63852Cookie.prototype.setExpires = function setExpires(exp) {
63853 if (exp instanceof Date) {
63854 this.expires = exp;
63855 } else {
63856 this.expires = parseDate(exp) || "Infinity";
63857 }
63858};
63859
63860Cookie.prototype.setMaxAge = function setMaxAge(age) {
63861 if (age === Infinity || age === -Infinity) {
63862 this.maxAge = age.toString(); // so JSON.stringify() works
63863 } else {
63864 this.maxAge = age;
63865 }
63866};
63867
63868// gives Cookie header format
63869Cookie.prototype.cookieString = function cookieString() {
63870 var val = this.value;
63871 if (val == null) {
63872 val = '';
63873 }
63874 if (this.key === '') {
63875 return val;
63876 }
63877 return this.key+'='+val;
63878};
63879
63880// gives Set-Cookie header format
63881Cookie.prototype.toString = function toString() {
63882 var str = this.cookieString();
63883
63884 if (this.expires != Infinity) {
63885 if (this.expires instanceof Date) {
63886 str += '; Expires='+formatDate(this.expires);
63887 } else {
63888 str += '; Expires='+this.expires;
63889 }
63890 }
63891
63892 if (this.maxAge != null && this.maxAge != Infinity) {
63893 str += '; Max-Age='+this.maxAge;
63894 }
63895
63896 if (this.domain && !this.hostOnly) {
63897 str += '; Domain='+this.domain;
63898 }
63899 if (this.path) {
63900 str += '; Path='+this.path;
63901 }
63902
63903 if (this.secure) {
63904 str += '; Secure';
63905 }
63906 if (this.httpOnly) {
63907 str += '; HttpOnly';
63908 }
63909 if (this.extensions) {
63910 this.extensions.forEach(function(ext) {
63911 str += '; '+ext;
63912 });
63913 }
63914
63915 return str;
63916};
63917
63918// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
63919// elsewhere)
63920// S5.3 says to give the "latest representable date" for which we use Infinity
63921// For "expired" we use 0
63922Cookie.prototype.TTL = function TTL(now) {
63923 /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
63924 * attribute, the Max-Age attribute has precedence and controls the
63925 * expiration date of the cookie.
63926 * (Concurs with S5.3 step 3)
63927 */
63928 if (this.maxAge != null) {
63929 return this.maxAge<=0 ? 0 : this.maxAge*1000;
63930 }
63931
63932 var expires = this.expires;
63933 if (expires != Infinity) {
63934 if (!(expires instanceof Date)) {
63935 expires = parseDate(expires) || Infinity;
63936 }
63937
63938 if (expires == Infinity) {
63939 return Infinity;
63940 }
63941
63942 return expires.getTime() - (now || Date.now());
63943 }
63944
63945 return Infinity;
63946};
63947
63948// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
63949// elsewhere)
63950Cookie.prototype.expiryTime = function expiryTime(now) {
63951 if (this.maxAge != null) {
63952 var relativeTo = now || this.creation || new Date();
63953 var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
63954 return relativeTo.getTime() + age;
63955 }
63956
63957 if (this.expires == Infinity) {
63958 return Infinity;
63959 }
63960 return this.expires.getTime();
63961};
63962
63963// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
63964// elsewhere), except it returns a Date
63965Cookie.prototype.expiryDate = function expiryDate(now) {
63966 var millisec = this.expiryTime(now);
63967 if (millisec == Infinity) {
63968 return new Date(MAX_TIME);
63969 } else if (millisec == -Infinity) {
63970 return new Date(MIN_TIME);
63971 } else {
63972 return new Date(millisec);
63973 }
63974};
63975
63976// This replaces the "persistent-flag" parts of S5.3 step 3
63977Cookie.prototype.isPersistent = function isPersistent() {
63978 return (this.maxAge != null || this.expires != Infinity);
63979};
63980
63981// Mostly S5.1.2 and S5.2.3:
63982Cookie.prototype.cdomain =
63983Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
63984 if (this.domain == null) {
63985 return null;
63986 }
63987 return canonicalDomain(this.domain);
63988};
63989
63990function CookieJar(store, options) {
63991 if (typeof options === "boolean") {
63992 options = {rejectPublicSuffixes: options};
63993 } else if (options == null) {
63994 options = {};
63995 }
63996 if (options.rejectPublicSuffixes != null) {
63997 this.rejectPublicSuffixes = options.rejectPublicSuffixes;
63998 }
63999 if (options.looseMode != null) {
64000 this.enableLooseMode = options.looseMode;
64001 }
64002
64003 if (!store) {
64004 store = new MemoryCookieStore();
64005 }
64006 this.store = store;
64007}
64008CookieJar.prototype.store = null;
64009CookieJar.prototype.rejectPublicSuffixes = true;
64010CookieJar.prototype.enableLooseMode = false;
64011var CAN_BE_SYNC = [];
64012
64013CAN_BE_SYNC.push('setCookie');
64014CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
64015 var err;
64016 var context = getCookieContext(url);
64017 if (options instanceof Function) {
64018 cb = options;
64019 options = {};
64020 }
64021
64022 var host = canonicalDomain(context.hostname);
64023 var loose = this.enableLooseMode;
64024 if (options.loose != null) {
64025 loose = options.loose;
64026 }
64027
64028 // S5.3 step 1
64029 if (!(cookie instanceof Cookie)) {
64030 cookie = Cookie.parse(cookie, { loose: loose });
64031 }
64032 if (!cookie) {
64033 err = new Error("Cookie failed to parse");
64034 return cb(options.ignoreError ? null : err);
64035 }
64036
64037 // S5.3 step 2
64038 var now = options.now || new Date(); // will assign later to save effort in the face of errors
64039
64040 // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
64041
64042 // S5.3 step 4: NOOP; domain is null by default
64043
64044 // S5.3 step 5: public suffixes
64045 if (this.rejectPublicSuffixes && cookie.domain) {
64046 var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
64047 if (suffix == null) { // e.g. "com"
64048 err = new Error("Cookie has domain set to a public suffix");
64049 return cb(options.ignoreError ? null : err);
64050 }
64051 }
64052
64053 // S5.3 step 6:
64054 if (cookie.domain) {
64055 if (!domainMatch(host, cookie.cdomain(), false)) {
64056 err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
64057 return cb(options.ignoreError ? null : err);
64058 }
64059
64060 if (cookie.hostOnly == null) { // don't reset if already set
64061 cookie.hostOnly = false;
64062 }
64063
64064 } else {
64065 cookie.hostOnly = true;
64066 cookie.domain = host;
64067 }
64068
64069 //S5.2.4 If the attribute-value is empty or if the first character of the
64070 //attribute-value is not %x2F ("/"):
64071 //Let cookie-path be the default-path.
64072 if (!cookie.path || cookie.path[0] !== '/') {
64073 cookie.path = defaultPath(context.pathname);
64074 cookie.pathIsDefault = true;
64075 }
64076
64077 // S5.3 step 8: NOOP; secure attribute
64078 // S5.3 step 9: NOOP; httpOnly attribute
64079
64080 // S5.3 step 10
64081 if (options.http === false && cookie.httpOnly) {
64082 err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
64083 return cb(options.ignoreError ? null : err);
64084 }
64085
64086 var store = this.store;
64087
64088 if (!store.updateCookie) {
64089 store.updateCookie = function(oldCookie, newCookie, cb) {
64090 this.putCookie(newCookie, cb);
64091 };
64092 }
64093
64094 function withCookie(err, oldCookie) {
64095 if (err) {
64096 return cb(err);
64097 }
64098
64099 var next = function(err) {
64100 if (err) {
64101 return cb(err);
64102 } else {
64103 cb(null, cookie);
64104 }
64105 };
64106
64107 if (oldCookie) {
64108 // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
64109 // domain, and path as the newly created cookie:"
64110 if (options.http === false && oldCookie.httpOnly) { // step 11.2
64111 err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
64112 return cb(options.ignoreError ? null : err);
64113 }
64114 cookie.creation = oldCookie.creation; // step 11.3
64115 cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
64116 cookie.lastAccessed = now;
64117 // Step 11.4 (delete cookie) is implied by just setting the new one:
64118 store.updateCookie(oldCookie, cookie, next); // step 12
64119
64120 } else {
64121 cookie.creation = cookie.lastAccessed = now;
64122 store.putCookie(cookie, next); // step 12
64123 }
64124 }
64125
64126 store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
64127};
64128
64129// RFC6365 S5.4
64130CAN_BE_SYNC.push('getCookies');
64131CookieJar.prototype.getCookies = function(url, options, cb) {
64132 var context = getCookieContext(url);
64133 if (options instanceof Function) {
64134 cb = options;
64135 options = {};
64136 }
64137
64138 var host = canonicalDomain(context.hostname);
64139 var path = context.pathname || '/';
64140
64141 var secure = options.secure;
64142 if (secure == null && context.protocol &&
64143 (context.protocol == 'https:' || context.protocol == 'wss:'))
64144 {
64145 secure = true;
64146 }
64147
64148 var http = options.http;
64149 if (http == null) {
64150 http = true;
64151 }
64152
64153 var now = options.now || Date.now();
64154 var expireCheck = options.expire !== false;
64155 var allPaths = !!options.allPaths;
64156 var store = this.store;
64157
64158 function matchingCookie(c) {
64159 // "Either:
64160 // The cookie's host-only-flag is true and the canonicalized
64161 // request-host is identical to the cookie's domain.
64162 // Or:
64163 // The cookie's host-only-flag is false and the canonicalized
64164 // request-host domain-matches the cookie's domain."
64165 if (c.hostOnly) {
64166 if (c.domain != host) {
64167 return false;
64168 }
64169 } else {
64170 if (!domainMatch(host, c.domain, false)) {
64171 return false;
64172 }
64173 }
64174
64175 // "The request-uri's path path-matches the cookie's path."
64176 if (!allPaths && !pathMatch(path, c.path)) {
64177 return false;
64178 }
64179
64180 // "If the cookie's secure-only-flag is true, then the request-uri's
64181 // scheme must denote a "secure" protocol"
64182 if (c.secure && !secure) {
64183 return false;
64184 }
64185
64186 // "If the cookie's http-only-flag is true, then exclude the cookie if the
64187 // cookie-string is being generated for a "non-HTTP" API"
64188 if (c.httpOnly && !http) {
64189 return false;
64190 }
64191
64192 // deferred from S5.3
64193 // non-RFC: allow retention of expired cookies by choice
64194 if (expireCheck && c.expiryTime() <= now) {
64195 store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
64196 return false;
64197 }
64198
64199 return true;
64200 }
64201
64202 store.findCookies(host, allPaths ? null : path, function(err,cookies) {
64203 if (err) {
64204 return cb(err);
64205 }
64206
64207 cookies = cookies.filter(matchingCookie);
64208
64209 // sorting of S5.4 part 2
64210 if (options.sort !== false) {
64211 cookies = cookies.sort(cookieCompare);
64212 }
64213
64214 // S5.4 part 3
64215 var now = new Date();
64216 cookies.forEach(function(c) {
64217 c.lastAccessed = now;
64218 });
64219 // TODO persist lastAccessed
64220
64221 cb(null,cookies);
64222 });
64223};
64224
64225CAN_BE_SYNC.push('getCookieString');
64226CookieJar.prototype.getCookieString = function(/*..., cb*/) {
64227 var args = Array.prototype.slice.call(arguments,0);
64228 var cb = args.pop();
64229 var next = function(err,cookies) {
64230 if (err) {
64231 cb(err);
64232 } else {
64233 cb(null, cookies
64234 .sort(cookieCompare)
64235 .map(function(c){
64236 return c.cookieString();
64237 })
64238 .join('; '));
64239 }
64240 };
64241 args.push(next);
64242 this.getCookies.apply(this,args);
64243};
64244
64245CAN_BE_SYNC.push('getSetCookieStrings');
64246CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
64247 var args = Array.prototype.slice.call(arguments,0);
64248 var cb = args.pop();
64249 var next = function(err,cookies) {
64250 if (err) {
64251 cb(err);
64252 } else {
64253 cb(null, cookies.map(function(c){
64254 return c.toString();
64255 }));
64256 }
64257 };
64258 args.push(next);
64259 this.getCookies.apply(this,args);
64260};
64261
64262CAN_BE_SYNC.push('serialize');
64263CookieJar.prototype.serialize = function(cb) {
64264 var type = this.store.constructor.name;
64265 if (type === 'Object') {
64266 type = null;
64267 }
64268
64269 // update README.md "Serialization Format" if you change this, please!
64270 var serialized = {
64271 // The version of tough-cookie that serialized this jar. Generally a good
64272 // practice since future versions can make data import decisions based on
64273 // known past behavior. When/if this matters, use `semver`.
64274 version: 'tough-cookie@'+VERSION,
64275
64276 // add the store type, to make humans happy:
64277 storeType: type,
64278
64279 // CookieJar configuration:
64280 rejectPublicSuffixes: !!this.rejectPublicSuffixes,
64281
64282 // this gets filled from getAllCookies:
64283 cookies: []
64284 };
64285
64286 if (!(this.store.getAllCookies &&
64287 typeof this.store.getAllCookies === 'function'))
64288 {
64289 return cb(new Error('store does not support getAllCookies and cannot be serialized'));
64290 }
64291
64292 this.store.getAllCookies(function(err,cookies) {
64293 if (err) {
64294 return cb(err);
64295 }
64296
64297 serialized.cookies = cookies.map(function(cookie) {
64298 // convert to serialized 'raw' cookies
64299 cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
64300
64301 // Remove the index so new ones get assigned during deserialization
64302 delete cookie.creationIndex;
64303
64304 return cookie;
64305 });
64306
64307 return cb(null, serialized);
64308 });
64309};
64310
64311// well-known name that JSON.stringify calls
64312CookieJar.prototype.toJSON = function() {
64313 return this.serializeSync();
64314};
64315
64316// use the class method CookieJar.deserialize instead of calling this directly
64317CAN_BE_SYNC.push('_importCookies');
64318CookieJar.prototype._importCookies = function(serialized, cb) {
64319 var jar = this;
64320 var cookies = serialized.cookies;
64321 if (!cookies || !Array.isArray(cookies)) {
64322 return cb(new Error('serialized jar has no cookies array'));
64323 }
64324 cookies = cookies.slice(); // do not modify the original
64325
64326 function putNext(err) {
64327 if (err) {
64328 return cb(err);
64329 }
64330
64331 if (!cookies.length) {
64332 return cb(err, jar);
64333 }
64334
64335 var cookie;
64336 try {
64337 cookie = fromJSON(cookies.shift());
64338 } catch (e) {
64339 return cb(e);
64340 }
64341
64342 if (cookie === null) {
64343 return putNext(null); // skip this cookie
64344 }
64345
64346 jar.store.putCookie(cookie, putNext);
64347 }
64348
64349 putNext();
64350};
64351
64352CookieJar.deserialize = function(strOrObj, store, cb) {
64353 if (arguments.length !== 3) {
64354 // store is optional
64355 cb = store;
64356 store = null;
64357 }
64358
64359 var serialized;
64360 if (typeof strOrObj === 'string') {
64361 serialized = jsonParse(strOrObj);
64362 if (serialized instanceof Error) {
64363 return cb(serialized);
64364 }
64365 } else {
64366 serialized = strOrObj;
64367 }
64368
64369 var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
64370 jar._importCookies(serialized, function(err) {
64371 if (err) {
64372 return cb(err);
64373 }
64374 cb(null, jar);
64375 });
64376};
64377
64378CookieJar.deserializeSync = function(strOrObj, store) {
64379 var serialized = typeof strOrObj === 'string' ?
64380 JSON.parse(strOrObj) : strOrObj;
64381 var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
64382
64383 // catch this mistake early:
64384 if (!jar.store.synchronous) {
64385 throw new Error('CookieJar store is not synchronous; use async API instead.');
64386 }
64387
64388 jar._importCookiesSync(serialized);
64389 return jar;
64390};
64391CookieJar.fromJSON = CookieJar.deserializeSync;
64392
64393CAN_BE_SYNC.push('clone');
64394CookieJar.prototype.clone = function(newStore, cb) {
64395 if (arguments.length === 1) {
64396 cb = newStore;
64397 newStore = null;
64398 }
64399
64400 this.serialize(function(err,serialized) {
64401 if (err) {
64402 return cb(err);
64403 }
64404 CookieJar.deserialize(newStore, serialized, cb);
64405 });
64406};
64407
64408// Use a closure to provide a true imperative API for synchronous stores.
64409function syncWrap(method) {
64410 return function() {
64411 if (!this.store.synchronous) {
64412 throw new Error('CookieJar store is not synchronous; use async API instead.');
64413 }
64414
64415 var args = Array.prototype.slice.call(arguments);
64416 var syncErr, syncResult;
64417 args.push(function syncCb(err, result) {
64418 syncErr = err;
64419 syncResult = result;
64420 });
64421 this[method].apply(this, args);
64422
64423 if (syncErr) {
64424 throw syncErr;
64425 }
64426 return syncResult;
64427 };
64428}
64429
64430// wrap all declared CAN_BE_SYNC methods in the sync wrapper
64431CAN_BE_SYNC.forEach(function(method) {
64432 CookieJar.prototype[method+'Sync'] = syncWrap(method);
64433});
64434
64435exports.CookieJar = CookieJar;
64436exports.Cookie = Cookie;
64437exports.Store = Store;
64438exports.MemoryCookieStore = MemoryCookieStore;
64439exports.parseDate = parseDate;
64440exports.formatDate = formatDate;
64441exports.parse = parse;
64442exports.fromJSON = fromJSON;
64443exports.domainMatch = domainMatch;
64444exports.defaultPath = defaultPath;
64445exports.pathMatch = pathMatch;
64446exports.getPublicSuffix = pubsuffix.getPublicSuffix;
64447exports.cookieCompare = cookieCompare;
64448exports.permuteDomain = require('./permuteDomain').permuteDomain;
64449exports.permutePath = permutePath;
64450exports.canonicalDomain = canonicalDomain;
64451
64452},{"../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){
64453/*!
64454 * Copyright (c) 2015, Salesforce.com, Inc.
64455 * All rights reserved.
64456 *
64457 * Redistribution and use in source and binary forms, with or without
64458 * modification, are permitted provided that the following conditions are met:
64459 *
64460 * 1. Redistributions of source code must retain the above copyright notice,
64461 * this list of conditions and the following disclaimer.
64462 *
64463 * 2. Redistributions in binary form must reproduce the above copyright notice,
64464 * this list of conditions and the following disclaimer in the documentation
64465 * and/or other materials provided with the distribution.
64466 *
64467 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64468 * be used to endorse or promote products derived from this software without
64469 * specific prior written permission.
64470 *
64471 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64472 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64473 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64474 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64475 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64476 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64477 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64478 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64479 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64480 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64481 * POSSIBILITY OF SUCH DAMAGE.
64482 */
64483'use strict';
64484var Store = require('./store').Store;
64485var permuteDomain = require('./permuteDomain').permuteDomain;
64486var pathMatch = require('./pathMatch').pathMatch;
64487var util = require('util');
64488
64489function MemoryCookieStore() {
64490 Store.call(this);
64491 this.idx = {};
64492}
64493util.inherits(MemoryCookieStore, Store);
64494exports.MemoryCookieStore = MemoryCookieStore;
64495MemoryCookieStore.prototype.idx = null;
64496
64497// Since it's just a struct in RAM, this Store is synchronous
64498MemoryCookieStore.prototype.synchronous = true;
64499
64500// force a default depth:
64501MemoryCookieStore.prototype.inspect = function() {
64502 return "{ idx: "+util.inspect(this.idx, false, 2)+' }';
64503};
64504
64505// Use the new custom inspection symbol to add the custom inspect function if
64506// available.
64507if (util.inspect.custom) {
64508 MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect;
64509}
64510
64511MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) {
64512 if (!this.idx[domain]) {
64513 return cb(null,undefined);
64514 }
64515 if (!this.idx[domain][path]) {
64516 return cb(null,undefined);
64517 }
64518 return cb(null,this.idx[domain][path][key]||null);
64519};
64520
64521MemoryCookieStore.prototype.findCookies = function(domain, path, cb) {
64522 var results = [];
64523 if (!domain) {
64524 return cb(null,[]);
64525 }
64526
64527 var pathMatcher;
64528 if (!path) {
64529 // null means "all paths"
64530 pathMatcher = function matchAll(domainIndex) {
64531 for (var curPath in domainIndex) {
64532 var pathIndex = domainIndex[curPath];
64533 for (var key in pathIndex) {
64534 results.push(pathIndex[key]);
64535 }
64536 }
64537 };
64538
64539 } else {
64540 pathMatcher = function matchRFC(domainIndex) {
64541 //NOTE: we should use path-match algorithm from S5.1.4 here
64542 //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
64543 Object.keys(domainIndex).forEach(function (cookiePath) {
64544 if (pathMatch(path, cookiePath)) {
64545 var pathIndex = domainIndex[cookiePath];
64546
64547 for (var key in pathIndex) {
64548 results.push(pathIndex[key]);
64549 }
64550 }
64551 });
64552 };
64553 }
64554
64555 var domains = permuteDomain(domain) || [domain];
64556 var idx = this.idx;
64557 domains.forEach(function(curDomain) {
64558 var domainIndex = idx[curDomain];
64559 if (!domainIndex) {
64560 return;
64561 }
64562 pathMatcher(domainIndex);
64563 });
64564
64565 cb(null,results);
64566};
64567
64568MemoryCookieStore.prototype.putCookie = function(cookie, cb) {
64569 if (!this.idx[cookie.domain]) {
64570 this.idx[cookie.domain] = {};
64571 }
64572 if (!this.idx[cookie.domain][cookie.path]) {
64573 this.idx[cookie.domain][cookie.path] = {};
64574 }
64575 this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
64576 cb(null);
64577};
64578
64579MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) {
64580 // updateCookie() may avoid updating cookies that are identical. For example,
64581 // lastAccessed may not be important to some stores and an equality
64582 // comparison could exclude that field.
64583 this.putCookie(newCookie,cb);
64584};
64585
64586MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) {
64587 if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) {
64588 delete this.idx[domain][path][key];
64589 }
64590 cb(null);
64591};
64592
64593MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) {
64594 if (this.idx[domain]) {
64595 if (path) {
64596 delete this.idx[domain][path];
64597 } else {
64598 delete this.idx[domain];
64599 }
64600 }
64601 return cb(null);
64602};
64603
64604MemoryCookieStore.prototype.getAllCookies = function(cb) {
64605 var cookies = [];
64606 var idx = this.idx;
64607
64608 var domains = Object.keys(idx);
64609 domains.forEach(function(domain) {
64610 var paths = Object.keys(idx[domain]);
64611 paths.forEach(function(path) {
64612 var keys = Object.keys(idx[domain][path]);
64613 keys.forEach(function(key) {
64614 if (key !== null) {
64615 cookies.push(idx[domain][path][key]);
64616 }
64617 });
64618 });
64619 });
64620
64621 // Sort by creationIndex so deserializing retains the creation order.
64622 // When implementing your own store, this SHOULD retain the order too
64623 cookies.sort(function(a,b) {
64624 return (a.creationIndex||0) - (b.creationIndex||0);
64625 });
64626
64627 cb(null, cookies);
64628};
64629
64630},{"./pathMatch":318,"./permuteDomain":319,"./store":321,"util":397}],318:[function(require,module,exports){
64631/*!
64632 * Copyright (c) 2015, Salesforce.com, Inc.
64633 * All rights reserved.
64634 *
64635 * Redistribution and use in source and binary forms, with or without
64636 * modification, are permitted provided that the following conditions are met:
64637 *
64638 * 1. Redistributions of source code must retain the above copyright notice,
64639 * this list of conditions and the following disclaimer.
64640 *
64641 * 2. Redistributions in binary form must reproduce the above copyright notice,
64642 * this list of conditions and the following disclaimer in the documentation
64643 * and/or other materials provided with the distribution.
64644 *
64645 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64646 * be used to endorse or promote products derived from this software without
64647 * specific prior written permission.
64648 *
64649 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64650 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64651 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64652 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64653 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64654 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64655 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64656 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64657 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64658 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64659 * POSSIBILITY OF SUCH DAMAGE.
64660 */
64661"use strict";
64662/*
64663 * "A request-path path-matches a given cookie-path if at least one of the
64664 * following conditions holds:"
64665 */
64666function pathMatch (reqPath, cookiePath) {
64667 // "o The cookie-path and the request-path are identical."
64668 if (cookiePath === reqPath) {
64669 return true;
64670 }
64671
64672 var idx = reqPath.indexOf(cookiePath);
64673 if (idx === 0) {
64674 // "o The cookie-path is a prefix of the request-path, and the last
64675 // character of the cookie-path is %x2F ("/")."
64676 if (cookiePath.substr(-1) === "/") {
64677 return true;
64678 }
64679
64680 // " o The cookie-path is a prefix of the request-path, and the first
64681 // character of the request-path that is not included in the cookie- path
64682 // is a %x2F ("/") character."
64683 if (reqPath.substr(cookiePath.length, 1) === "/") {
64684 return true;
64685 }
64686 }
64687
64688 return false;
64689}
64690
64691exports.pathMatch = pathMatch;
64692
64693},{}],319:[function(require,module,exports){
64694/*!
64695 * Copyright (c) 2015, Salesforce.com, Inc.
64696 * All rights reserved.
64697 *
64698 * Redistribution and use in source and binary forms, with or without
64699 * modification, are permitted provided that the following conditions are met:
64700 *
64701 * 1. Redistributions of source code must retain the above copyright notice,
64702 * this list of conditions and the following disclaimer.
64703 *
64704 * 2. Redistributions in binary form must reproduce the above copyright notice,
64705 * this list of conditions and the following disclaimer in the documentation
64706 * and/or other materials provided with the distribution.
64707 *
64708 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64709 * be used to endorse or promote products derived from this software without
64710 * specific prior written permission.
64711 *
64712 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64713 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64714 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64715 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64716 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64717 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64718 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64719 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64720 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64721 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64722 * POSSIBILITY OF SUCH DAMAGE.
64723 */
64724"use strict";
64725var pubsuffix = require('./pubsuffix-psl');
64726
64727// Gives the permutation of all possible domainMatch()es of a given domain. The
64728// array is in shortest-to-longest order. Handy for indexing.
64729function permuteDomain (domain) {
64730 var pubSuf = pubsuffix.getPublicSuffix(domain);
64731 if (!pubSuf) {
64732 return null;
64733 }
64734 if (pubSuf == domain) {
64735 return [domain];
64736 }
64737
64738 var prefix = domain.slice(0, -(pubSuf.length + 1)); // ".example.com"
64739 var parts = prefix.split('.').reverse();
64740 var cur = pubSuf;
64741 var permutations = [cur];
64742 while (parts.length) {
64743 cur = parts.shift() + '.' + cur;
64744 permutations.push(cur);
64745 }
64746 return permutations;
64747}
64748
64749exports.permuteDomain = permuteDomain;
64750
64751},{"./pubsuffix-psl":320}],320:[function(require,module,exports){
64752/*!
64753 * Copyright (c) 2018, Salesforce.com, Inc.
64754 * All rights reserved.
64755 *
64756 * Redistribution and use in source and binary forms, with or without
64757 * modification, are permitted provided that the following conditions are met:
64758 *
64759 * 1. Redistributions of source code must retain the above copyright notice,
64760 * this list of conditions and the following disclaimer.
64761 *
64762 * 2. Redistributions in binary form must reproduce the above copyright notice,
64763 * this list of conditions and the following disclaimer in the documentation
64764 * and/or other materials provided with the distribution.
64765 *
64766 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64767 * be used to endorse or promote products derived from this software without
64768 * specific prior written permission.
64769 *
64770 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64771 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64772 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64773 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64774 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64775 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64776 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64777 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64778 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64779 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64780 * POSSIBILITY OF SUCH DAMAGE.
64781 */
64782'use strict';
64783var psl = require('psl');
64784
64785function getPublicSuffix(domain) {
64786 return psl.get(domain);
64787}
64788
64789exports.getPublicSuffix = getPublicSuffix;
64790
64791},{"psl":267}],321:[function(require,module,exports){
64792/*!
64793 * Copyright (c) 2015, Salesforce.com, Inc.
64794 * All rights reserved.
64795 *
64796 * Redistribution and use in source and binary forms, with or without
64797 * modification, are permitted provided that the following conditions are met:
64798 *
64799 * 1. Redistributions of source code must retain the above copyright notice,
64800 * this list of conditions and the following disclaimer.
64801 *
64802 * 2. Redistributions in binary form must reproduce the above copyright notice,
64803 * this list of conditions and the following disclaimer in the documentation
64804 * and/or other materials provided with the distribution.
64805 *
64806 * 3. Neither the name of Salesforce.com nor the names of its contributors may
64807 * be used to endorse or promote products derived from this software without
64808 * specific prior written permission.
64809 *
64810 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
64811 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
64812 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
64813 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
64814 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
64815 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
64816 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
64817 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64818 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
64819 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
64820 * POSSIBILITY OF SUCH DAMAGE.
64821 */
64822'use strict';
64823/*jshint unused:false */
64824
64825function Store() {
64826}
64827exports.Store = Store;
64828
64829// Stores may be synchronous, but are still required to use a
64830// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync"
64831// API that converts from synchronous-callbacks to imperative style.
64832Store.prototype.synchronous = false;
64833
64834Store.prototype.findCookie = function(domain, path, key, cb) {
64835 throw new Error('findCookie is not implemented');
64836};
64837
64838Store.prototype.findCookies = function(domain, path, cb) {
64839 throw new Error('findCookies is not implemented');
64840};
64841
64842Store.prototype.putCookie = function(cookie, cb) {
64843 throw new Error('putCookie is not implemented');
64844};
64845
64846Store.prototype.updateCookie = function(oldCookie, newCookie, cb) {
64847 // recommended default implementation:
64848 // return this.putCookie(newCookie, cb);
64849 throw new Error('updateCookie is not implemented');
64850};
64851
64852Store.prototype.removeCookie = function(domain, path, key, cb) {
64853 throw new Error('removeCookie is not implemented');
64854};
64855
64856Store.prototype.removeCookies = function(domain, path, cb) {
64857 throw new Error('removeCookies is not implemented');
64858};
64859
64860Store.prototype.getAllCookies = function(cb) {
64861 throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)');
64862};
64863
64864},{}],322:[function(require,module,exports){
64865module.exports={
64866 "author": {
64867 "name": "Jeremy Stashewsky",
64868 "email": "jstash@gmail.com",
64869 "website": "https://github.com/stash"
64870 },
64871 "contributors": [
64872 {
64873 "name": "Alexander Savin",
64874 "website": "https://github.com/apsavin"
64875 },
64876 {
64877 "name": "Ian Livingstone",
64878 "website": "https://github.com/ianlivingstone"
64879 },
64880 {
64881 "name": "Ivan Nikulin",
64882 "website": "https://github.com/inikulin"
64883 },
64884 {
64885 "name": "Lalit Kapoor",
64886 "website": "https://github.com/lalitkapoor"
64887 },
64888 {
64889 "name": "Sam Thompson",
64890 "website": "https://github.com/sambthompson"
64891 },
64892 {
64893 "name": "Sebastian Mayr",
64894 "website": "https://github.com/Sebmaster"
64895 }
64896 ],
64897 "license": "BSD-3-Clause",
64898 "name": "tough-cookie",
64899 "description": "RFC6265 Cookies and Cookie Jar for node.js",
64900 "keywords": [
64901 "HTTP",
64902 "cookie",
64903 "cookies",
64904 "set-cookie",
64905 "cookiejar",
64906 "jar",
64907 "RFC6265",
64908 "RFC2965"
64909 ],
64910 "version": "2.4.3",
64911 "homepage": "https://github.com/salesforce/tough-cookie",
64912 "repository": {
64913 "type": "git",
64914 "url": "git://github.com/salesforce/tough-cookie.git"
64915 },
64916 "bugs": {
64917 "url": "https://github.com/salesforce/tough-cookie/issues"
64918 },
64919 "main": "./lib/cookie",
64920 "files": [
64921 "lib"
64922 ],
64923 "scripts": {
64924 "test": "vows test/*_test.js",
64925 "cover": "nyc --reporter=lcov --reporter=html vows test/*_test.js"
64926 },
64927 "engines": {
64928 "node": ">=0.8"
64929 },
64930 "devDependencies": {
64931 "async": "^1.4.2",
64932 "nyc": "^11.6.0",
64933 "string.prototype.repeat": "^0.2.0",
64934 "vows": "^0.8.1"
64935 },
64936 "dependencies": {
64937 "psl": "^1.1.24",
64938 "punycode": "^1.4.1"
64939 }
64940}
64941
64942},{}],323:[function(require,module,exports){
64943(function (process){
64944'use strict'
64945
64946var http = require('http')
64947var https = require('https')
64948var url = require('url')
64949var util = require('util')
64950var stream = require('stream')
64951var zlib = require('zlib')
64952var aws2 = require('aws-sign2')
64953var aws4 = require('aws4')
64954var httpSignature = require('http-signature')
64955var mime = require('mime-types')
64956var caseless = require('caseless')
64957var ForeverAgent = require('forever-agent')
64958var FormData = require('form-data')
64959var extend = require('extend')
64960var isstream = require('isstream')
64961var isTypedArray = require('is-typedarray').strict
64962var helpers = require('./lib/helpers')
64963var cookies = require('./lib/cookies')
64964var getProxyFromURI = require('./lib/getProxyFromURI')
64965var Querystring = require('./lib/querystring').Querystring
64966var Har = require('./lib/har').Har
64967var Auth = require('./lib/auth').Auth
64968var OAuth = require('./lib/oauth').OAuth
64969var hawk = require('./lib/hawk')
64970var Multipart = require('./lib/multipart').Multipart
64971var Redirect = require('./lib/redirect').Redirect
64972var Tunnel = require('./lib/tunnel').Tunnel
64973var now = require('performance-now')
64974var Buffer = require('safe-buffer').Buffer
64975
64976var safeStringify = helpers.safeStringify
64977var isReadStream = helpers.isReadStream
64978var toBase64 = helpers.toBase64
64979var defer = helpers.defer
64980var copy = helpers.copy
64981var version = helpers.version
64982var globalCookieJar = cookies.jar()
64983
64984var globalPool = {}
64985
64986function filterForNonReserved (reserved, options) {
64987 // Filter out properties that are not reserved.
64988 // Reserved values are passed in at call site.
64989
64990 var object = {}
64991 for (var i in options) {
64992 var notReserved = (reserved.indexOf(i) === -1)
64993 if (notReserved) {
64994 object[i] = options[i]
64995 }
64996 }
64997 return object
64998}
64999
65000function filterOutReservedFunctions (reserved, options) {
65001 // Filter out properties that are functions and are reserved.
65002 // Reserved values are passed in at call site.
65003
65004 var object = {}
65005 for (var i in options) {
65006 var isReserved = !(reserved.indexOf(i) === -1)
65007 var isFunction = (typeof options[i] === 'function')
65008 if (!(isReserved && isFunction)) {
65009 object[i] = options[i]
65010 }
65011 }
65012 return object
65013}
65014
65015// Return a simpler request object to allow serialization
65016function requestToJSON () {
65017 var self = this
65018 return {
65019 uri: self.uri,
65020 method: self.method,
65021 headers: self.headers
65022 }
65023}
65024
65025// Return a simpler response object to allow serialization
65026function responseToJSON () {
65027 var self = this
65028 return {
65029 statusCode: self.statusCode,
65030 body: self.body,
65031 headers: self.headers,
65032 request: requestToJSON.call(self.request)
65033 }
65034}
65035
65036function Request (options) {
65037 // if given the method property in options, set property explicitMethod to true
65038
65039 // extend the Request instance with any non-reserved properties
65040 // remove any reserved functions from the options object
65041 // set Request instance to be readable and writable
65042 // call init
65043
65044 var self = this
65045
65046 // start with HAR, then override with additional options
65047 if (options.har) {
65048 self._har = new Har(self)
65049 options = self._har.options(options)
65050 }
65051
65052 stream.Stream.call(self)
65053 var reserved = Object.keys(Request.prototype)
65054 var nonReserved = filterForNonReserved(reserved, options)
65055
65056 extend(self, nonReserved)
65057 options = filterOutReservedFunctions(reserved, options)
65058
65059 self.readable = true
65060 self.writable = true
65061 if (options.method) {
65062 self.explicitMethod = true
65063 }
65064 self._qs = new Querystring(self)
65065 self._auth = new Auth(self)
65066 self._oauth = new OAuth(self)
65067 self._multipart = new Multipart(self)
65068 self._redirect = new Redirect(self)
65069 self._tunnel = new Tunnel(self)
65070 self.init(options)
65071}
65072
65073util.inherits(Request, stream.Stream)
65074
65075// Debugging
65076Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
65077function debug () {
65078 if (Request.debug) {
65079 console.error('REQUEST %s', util.format.apply(util, arguments))
65080 }
65081}
65082Request.prototype.debug = debug
65083
65084Request.prototype.init = function (options) {
65085 // init() contains all the code to setup the request object.
65086 // the actual outgoing request is not started until start() is called
65087 // this function is called from both the constructor and on redirect.
65088 var self = this
65089 if (!options) {
65090 options = {}
65091 }
65092 self.headers = self.headers ? copy(self.headers) : {}
65093
65094 // Delete headers with value undefined since they break
65095 // ClientRequest.OutgoingMessage.setHeader in node 0.12
65096 for (var headerName in self.headers) {
65097 if (typeof self.headers[headerName] === 'undefined') {
65098 delete self.headers[headerName]
65099 }
65100 }
65101
65102 caseless.httpify(self, self.headers)
65103
65104 if (!self.method) {
65105 self.method = options.method || 'GET'
65106 }
65107 if (!self.localAddress) {
65108 self.localAddress = options.localAddress
65109 }
65110
65111 self._qs.init(options)
65112
65113 debug(options)
65114 if (!self.pool && self.pool !== false) {
65115 self.pool = globalPool
65116 }
65117 self.dests = self.dests || []
65118 self.__isRequestRequest = true
65119
65120 // Protect against double callback
65121 if (!self._callback && self.callback) {
65122 self._callback = self.callback
65123 self.callback = function () {
65124 if (self._callbackCalled) {
65125 return // Print a warning maybe?
65126 }
65127 self._callbackCalled = true
65128 self._callback.apply(self, arguments)
65129 }
65130 self.on('error', self.callback.bind())
65131 self.on('complete', self.callback.bind(self, null))
65132 }
65133
65134 // People use this property instead all the time, so support it
65135 if (!self.uri && self.url) {
65136 self.uri = self.url
65137 delete self.url
65138 }
65139
65140 // If there's a baseUrl, then use it as the base URL (i.e. uri must be
65141 // specified as a relative path and is appended to baseUrl).
65142 if (self.baseUrl) {
65143 if (typeof self.baseUrl !== 'string') {
65144 return self.emit('error', new Error('options.baseUrl must be a string'))
65145 }
65146
65147 if (typeof self.uri !== 'string') {
65148 return self.emit('error', new Error('options.uri must be a string when using options.baseUrl'))
65149 }
65150
65151 if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) {
65152 return self.emit('error', new Error('options.uri must be a path when using options.baseUrl'))
65153 }
65154
65155 // Handle all cases to make sure that there's only one slash between
65156 // baseUrl and uri.
65157 var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1
65158 var uriStartsWithSlash = self.uri.indexOf('/') === 0
65159
65160 if (baseUrlEndsWithSlash && uriStartsWithSlash) {
65161 self.uri = self.baseUrl + self.uri.slice(1)
65162 } else if (baseUrlEndsWithSlash || uriStartsWithSlash) {
65163 self.uri = self.baseUrl + self.uri
65164 } else if (self.uri === '') {
65165 self.uri = self.baseUrl
65166 } else {
65167 self.uri = self.baseUrl + '/' + self.uri
65168 }
65169 delete self.baseUrl
65170 }
65171
65172 // A URI is needed by this point, emit error if we haven't been able to get one
65173 if (!self.uri) {
65174 return self.emit('error', new Error('options.uri is a required argument'))
65175 }
65176
65177 // If a string URI/URL was given, parse it into a URL object
65178 if (typeof self.uri === 'string') {
65179 self.uri = url.parse(self.uri)
65180 }
65181
65182 // Some URL objects are not from a URL parsed string and need href added
65183 if (!self.uri.href) {
65184 self.uri.href = url.format(self.uri)
65185 }
65186
65187 // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme
65188 if (self.uri.protocol === 'unix:') {
65189 return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`'))
65190 }
65191
65192 // Support Unix Sockets
65193 if (self.uri.host === 'unix') {
65194 self.enableUnixSocket()
65195 }
65196
65197 if (self.strictSSL === false) {
65198 self.rejectUnauthorized = false
65199 }
65200
65201 if (!self.uri.pathname) { self.uri.pathname = '/' }
65202
65203 if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) {
65204 // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar
65205 // Detect and reject it as soon as possible
65206 var faultyUri = url.format(self.uri)
65207 var message = 'Invalid URI "' + faultyUri + '"'
65208 if (Object.keys(options).length === 0) {
65209 // No option ? This can be the sign of a redirect
65210 // As this is a case where the user cannot do anything (they didn't call request directly with this URL)
65211 // they should be warned that it can be caused by a redirection (can save some hair)
65212 message += '. This can be caused by a crappy redirection.'
65213 }
65214 // This error was fatal
65215 self.abort()
65216 return self.emit('error', new Error(message))
65217 }
65218
65219 if (!self.hasOwnProperty('proxy')) {
65220 self.proxy = getProxyFromURI(self.uri)
65221 }
65222
65223 self.tunnel = self._tunnel.isEnabled()
65224 if (self.proxy) {
65225 self._tunnel.setup(options)
65226 }
65227
65228 self._redirect.onRequest(options)
65229
65230 self.setHost = false
65231 if (!self.hasHeader('host')) {
65232 var hostHeaderName = self.originalHostHeaderName || 'host'
65233 self.setHeader(hostHeaderName, self.uri.host)
65234 // Drop :port suffix from Host header if known protocol.
65235 if (self.uri.port) {
65236 if ((self.uri.port === '80' && self.uri.protocol === 'http:') ||
65237 (self.uri.port === '443' && self.uri.protocol === 'https:')) {
65238 self.setHeader(hostHeaderName, self.uri.hostname)
65239 }
65240 }
65241 self.setHost = true
65242 }
65243
65244 self.jar(self._jar || options.jar)
65245
65246 if (!self.uri.port) {
65247 if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 }
65248 }
65249
65250 if (self.proxy && !self.tunnel) {
65251 self.port = self.proxy.port
65252 self.host = self.proxy.hostname
65253 } else {
65254 self.port = self.uri.port
65255 self.host = self.uri.hostname
65256 }
65257
65258 if (options.form) {
65259 self.form(options.form)
65260 }
65261
65262 if (options.formData) {
65263 var formData = options.formData
65264 var requestForm = self.form()
65265 var appendFormValue = function (key, value) {
65266 if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) {
65267 requestForm.append(key, value.value, value.options)
65268 } else {
65269 requestForm.append(key, value)
65270 }
65271 }
65272 for (var formKey in formData) {
65273 if (formData.hasOwnProperty(formKey)) {
65274 var formValue = formData[formKey]
65275 if (formValue instanceof Array) {
65276 for (var j = 0; j < formValue.length; j++) {
65277 appendFormValue(formKey, formValue[j])
65278 }
65279 } else {
65280 appendFormValue(formKey, formValue)
65281 }
65282 }
65283 }
65284 }
65285
65286 if (options.qs) {
65287 self.qs(options.qs)
65288 }
65289
65290 if (self.uri.path) {
65291 self.path = self.uri.path
65292 } else {
65293 self.path = self.uri.pathname + (self.uri.search || '')
65294 }
65295
65296 if (self.path.length === 0) {
65297 self.path = '/'
65298 }
65299
65300 // Auth must happen last in case signing is dependent on other headers
65301 if (options.aws) {
65302 self.aws(options.aws)
65303 }
65304
65305 if (options.hawk) {
65306 self.hawk(options.hawk)
65307 }
65308
65309 if (options.httpSignature) {
65310 self.httpSignature(options.httpSignature)
65311 }
65312
65313 if (options.auth) {
65314 if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) {
65315 options.auth.user = options.auth.username
65316 }
65317 if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) {
65318 options.auth.pass = options.auth.password
65319 }
65320
65321 self.auth(
65322 options.auth.user,
65323 options.auth.pass,
65324 options.auth.sendImmediately,
65325 options.auth.bearer
65326 )
65327 }
65328
65329 if (self.gzip && !self.hasHeader('accept-encoding')) {
65330 self.setHeader('accept-encoding', 'gzip, deflate')
65331 }
65332
65333 if (self.uri.auth && !self.hasHeader('authorization')) {
65334 var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) })
65335 self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true)
65336 }
65337
65338 if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) {
65339 var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) })
65340 var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':'))
65341 self.setHeader('proxy-authorization', authHeader)
65342 }
65343
65344 if (self.proxy && !self.tunnel) {
65345 self.path = (self.uri.protocol + '//' + self.uri.host + self.path)
65346 }
65347
65348 if (options.json) {
65349 self.json(options.json)
65350 }
65351 if (options.multipart) {
65352 self.multipart(options.multipart)
65353 }
65354
65355 if (options.time) {
65356 self.timing = true
65357
65358 // NOTE: elapsedTime is deprecated in favor of .timings
65359 self.elapsedTime = self.elapsedTime || 0
65360 }
65361
65362 function setContentLength () {
65363 if (isTypedArray(self.body)) {
65364 self.body = Buffer.from(self.body)
65365 }
65366
65367 if (!self.hasHeader('content-length')) {
65368 var length
65369 if (typeof self.body === 'string') {
65370 length = Buffer.byteLength(self.body)
65371 } else if (Array.isArray(self.body)) {
65372 length = self.body.reduce(function (a, b) { return a + b.length }, 0)
65373 } else {
65374 length = self.body.length
65375 }
65376
65377 if (length) {
65378 self.setHeader('content-length', length)
65379 } else {
65380 self.emit('error', new Error('Argument error, options.body.'))
65381 }
65382 }
65383 }
65384 if (self.body && !isstream(self.body)) {
65385 setContentLength()
65386 }
65387
65388 if (options.oauth) {
65389 self.oauth(options.oauth)
65390 } else if (self._oauth.params && self.hasHeader('authorization')) {
65391 self.oauth(self._oauth.params)
65392 }
65393
65394 var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol
65395 var defaultModules = {'http:': http, 'https:': https}
65396 var httpModules = self.httpModules || {}
65397
65398 self.httpModule = httpModules[protocol] || defaultModules[protocol]
65399
65400 if (!self.httpModule) {
65401 return self.emit('error', new Error('Invalid protocol: ' + protocol))
65402 }
65403
65404 if (options.ca) {
65405 self.ca = options.ca
65406 }
65407
65408 if (!self.agent) {
65409 if (options.agentOptions) {
65410 self.agentOptions = options.agentOptions
65411 }
65412
65413 if (options.agentClass) {
65414 self.agentClass = options.agentClass
65415 } else if (options.forever) {
65416 var v = version()
65417 // use ForeverAgent in node 0.10- only
65418 if (v.major === 0 && v.minor <= 10) {
65419 self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL
65420 } else {
65421 self.agentClass = self.httpModule.Agent
65422 self.agentOptions = self.agentOptions || {}
65423 self.agentOptions.keepAlive = true
65424 }
65425 } else {
65426 self.agentClass = self.httpModule.Agent
65427 }
65428 }
65429
65430 if (self.pool === false) {
65431 self.agent = false
65432 } else {
65433 self.agent = self.agent || self.getNewAgent()
65434 }
65435
65436 self.on('pipe', function (src) {
65437 if (self.ntick && self._started) {
65438 self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.'))
65439 }
65440 self.src = src
65441 if (isReadStream(src)) {
65442 if (!self.hasHeader('content-type')) {
65443 self.setHeader('content-type', mime.lookup(src.path))
65444 }
65445 } else {
65446 if (src.headers) {
65447 for (var i in src.headers) {
65448 if (!self.hasHeader(i)) {
65449 self.setHeader(i, src.headers[i])
65450 }
65451 }
65452 }
65453 if (self._json && !self.hasHeader('content-type')) {
65454 self.setHeader('content-type', 'application/json')
65455 }
65456 if (src.method && !self.explicitMethod) {
65457 self.method = src.method
65458 }
65459 }
65460
65461 // self.on('pipe', function () {
65462 // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.')
65463 // })
65464 })
65465
65466 defer(function () {
65467 if (self._aborted) {
65468 return
65469 }
65470
65471 var end = function () {
65472 if (self._form) {
65473 if (!self._auth.hasAuth) {
65474 self._form.pipe(self)
65475 } else if (self._auth.hasAuth && self._auth.sentAuth) {
65476 self._form.pipe(self)
65477 }
65478 }
65479 if (self._multipart && self._multipart.chunked) {
65480 self._multipart.body.pipe(self)
65481 }
65482 if (self.body) {
65483 if (isstream(self.body)) {
65484 self.body.pipe(self)
65485 } else {
65486 setContentLength()
65487 if (Array.isArray(self.body)) {
65488 self.body.forEach(function (part) {
65489 self.write(part)
65490 })
65491 } else {
65492 self.write(self.body)
65493 }
65494 self.end()
65495 }
65496 } else if (self.requestBodyStream) {
65497 console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.')
65498 self.requestBodyStream.pipe(self)
65499 } else if (!self.src) {
65500 if (self._auth.hasAuth && !self._auth.sentAuth) {
65501 self.end()
65502 return
65503 }
65504 if (self.method !== 'GET' && typeof self.method !== 'undefined') {
65505 self.setHeader('content-length', 0)
65506 }
65507 self.end()
65508 }
65509 }
65510
65511 if (self._form && !self.hasHeader('content-length')) {
65512 // Before ending the request, we had to compute the length of the whole form, asyncly
65513 self.setHeader(self._form.getHeaders(), true)
65514 self._form.getLength(function (err, length) {
65515 if (!err && !isNaN(length)) {
65516 self.setHeader('content-length', length)
65517 }
65518 end()
65519 })
65520 } else {
65521 end()
65522 }
65523
65524 self.ntick = true
65525 })
65526}
65527
65528Request.prototype.getNewAgent = function () {
65529 var self = this
65530 var Agent = self.agentClass
65531 var options = {}
65532 if (self.agentOptions) {
65533 for (var i in self.agentOptions) {
65534 options[i] = self.agentOptions[i]
65535 }
65536 }
65537 if (self.ca) {
65538 options.ca = self.ca
65539 }
65540 if (self.ciphers) {
65541 options.ciphers = self.ciphers
65542 }
65543 if (self.secureProtocol) {
65544 options.secureProtocol = self.secureProtocol
65545 }
65546 if (self.secureOptions) {
65547 options.secureOptions = self.secureOptions
65548 }
65549 if (typeof self.rejectUnauthorized !== 'undefined') {
65550 options.rejectUnauthorized = self.rejectUnauthorized
65551 }
65552
65553 if (self.cert && self.key) {
65554 options.key = self.key
65555 options.cert = self.cert
65556 }
65557
65558 if (self.pfx) {
65559 options.pfx = self.pfx
65560 }
65561
65562 if (self.passphrase) {
65563 options.passphrase = self.passphrase
65564 }
65565
65566 var poolKey = ''
65567
65568 // different types of agents are in different pools
65569 if (Agent !== self.httpModule.Agent) {
65570 poolKey += Agent.name
65571 }
65572
65573 // ca option is only relevant if proxy or destination are https
65574 var proxy = self.proxy
65575 if (typeof proxy === 'string') {
65576 proxy = url.parse(proxy)
65577 }
65578 var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:'
65579
65580 if (isHttps) {
65581 if (options.ca) {
65582 if (poolKey) {
65583 poolKey += ':'
65584 }
65585 poolKey += options.ca
65586 }
65587
65588 if (typeof options.rejectUnauthorized !== 'undefined') {
65589 if (poolKey) {
65590 poolKey += ':'
65591 }
65592 poolKey += options.rejectUnauthorized
65593 }
65594
65595 if (options.cert) {
65596 if (poolKey) {
65597 poolKey += ':'
65598 }
65599 poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
65600 }
65601
65602 if (options.pfx) {
65603 if (poolKey) {
65604 poolKey += ':'
65605 }
65606 poolKey += options.pfx.toString('ascii')
65607 }
65608
65609 if (options.ciphers) {
65610 if (poolKey) {
65611 poolKey += ':'
65612 }
65613 poolKey += options.ciphers
65614 }
65615
65616 if (options.secureProtocol) {
65617 if (poolKey) {
65618 poolKey += ':'
65619 }
65620 poolKey += options.secureProtocol
65621 }
65622
65623 if (options.secureOptions) {
65624 if (poolKey) {
65625 poolKey += ':'
65626 }
65627 poolKey += options.secureOptions
65628 }
65629 }
65630
65631 if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) {
65632 // not doing anything special. Use the globalAgent
65633 return self.httpModule.globalAgent
65634 }
65635
65636 // we're using a stored agent. Make sure it's protocol-specific
65637 poolKey = self.uri.protocol + poolKey
65638
65639 // generate a new agent for this setting if none yet exists
65640 if (!self.pool[poolKey]) {
65641 self.pool[poolKey] = new Agent(options)
65642 // properly set maxSockets on new agents
65643 if (self.pool.maxSockets) {
65644 self.pool[poolKey].maxSockets = self.pool.maxSockets
65645 }
65646 }
65647
65648 return self.pool[poolKey]
65649}
65650
65651Request.prototype.start = function () {
65652 // start() is called once we are ready to send the outgoing HTTP request.
65653 // this is usually called on the first write(), end() or on nextTick()
65654 var self = this
65655
65656 if (self.timing) {
65657 // All timings will be relative to this request's startTime. In order to do this,
65658 // we need to capture the wall-clock start time (via Date), immediately followed
65659 // by the high-resolution timer (via now()). While these two won't be set
65660 // at the _exact_ same time, they should be close enough to be able to calculate
65661 // high-resolution, monotonically non-decreasing timestamps relative to startTime.
65662 var startTime = new Date().getTime()
65663 var startTimeNow = now()
65664 }
65665
65666 if (self._aborted) {
65667 return
65668 }
65669
65670 self._started = true
65671 self.method = self.method || 'GET'
65672 self.href = self.uri.href
65673
65674 if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) {
65675 self.setHeader('content-length', self.src.stat.size)
65676 }
65677 if (self._aws) {
65678 self.aws(self._aws, true)
65679 }
65680
65681 // We have a method named auth, which is completely different from the http.request
65682 // auth option. If we don't remove it, we're gonna have a bad time.
65683 var reqOptions = copy(self)
65684 delete reqOptions.auth
65685
65686 debug('make request', self.uri.href)
65687
65688 // node v6.8.0 now supports a `timeout` value in `http.request()`, but we
65689 // should delete it for now since we handle timeouts manually for better
65690 // consistency with node versions before v6.8.0
65691 delete reqOptions.timeout
65692
65693 try {
65694 self.req = self.httpModule.request(reqOptions)
65695 } catch (err) {
65696 self.emit('error', err)
65697 return
65698 }
65699
65700 if (self.timing) {
65701 self.startTime = startTime
65702 self.startTimeNow = startTimeNow
65703
65704 // Timing values will all be relative to startTime (by comparing to startTimeNow
65705 // so we have an accurate clock)
65706 self.timings = {}
65707 }
65708
65709 var timeout
65710 if (self.timeout && !self.timeoutTimer) {
65711 if (self.timeout < 0) {
65712 timeout = 0
65713 } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) {
65714 timeout = self.timeout
65715 }
65716 }
65717
65718 self.req.on('response', self.onRequestResponse.bind(self))
65719 self.req.on('error', self.onRequestError.bind(self))
65720 self.req.on('drain', function () {
65721 self.emit('drain')
65722 })
65723
65724 self.req.on('socket', function (socket) {
65725 // `._connecting` was the old property which was made public in node v6.1.0
65726 var isConnecting = socket._connecting || socket.connecting
65727 if (self.timing) {
65728 self.timings.socket = now() - self.startTimeNow
65729
65730 if (isConnecting) {
65731 var onLookupTiming = function () {
65732 self.timings.lookup = now() - self.startTimeNow
65733 }
65734
65735 var onConnectTiming = function () {
65736 self.timings.connect = now() - self.startTimeNow
65737 }
65738
65739 socket.once('lookup', onLookupTiming)
65740 socket.once('connect', onConnectTiming)
65741
65742 // clean up timing event listeners if needed on error
65743 self.req.once('error', function () {
65744 socket.removeListener('lookup', onLookupTiming)
65745 socket.removeListener('connect', onConnectTiming)
65746 })
65747 }
65748 }
65749
65750 var setReqTimeout = function () {
65751 // This timeout sets the amount of time to wait *between* bytes sent
65752 // from the server once connected.
65753 //
65754 // In particular, it's useful for erroring if the server fails to send
65755 // data halfway through streaming a response.
65756 self.req.setTimeout(timeout, function () {
65757 if (self.req) {
65758 self.abort()
65759 var e = new Error('ESOCKETTIMEDOUT')
65760 e.code = 'ESOCKETTIMEDOUT'
65761 e.connect = false
65762 self.emit('error', e)
65763 }
65764 })
65765 }
65766 if (timeout !== undefined) {
65767 // Only start the connection timer if we're actually connecting a new
65768 // socket, otherwise if we're already connected (because this is a
65769 // keep-alive connection) do not bother. This is important since we won't
65770 // get a 'connect' event for an already connected socket.
65771 if (isConnecting) {
65772 var onReqSockConnect = function () {
65773 socket.removeListener('connect', onReqSockConnect)
65774 clearTimeout(self.timeoutTimer)
65775 self.timeoutTimer = null
65776 setReqTimeout()
65777 }
65778
65779 socket.on('connect', onReqSockConnect)
65780
65781 self.req.on('error', function (err) { // eslint-disable-line handle-callback-err
65782 socket.removeListener('connect', onReqSockConnect)
65783 })
65784
65785 // Set a timeout in memory - this block will throw if the server takes more
65786 // than `timeout` to write the HTTP status and headers (corresponding to
65787 // the on('response') event on the client). NB: this measures wall-clock
65788 // time, not the time between bytes sent by the server.
65789 self.timeoutTimer = setTimeout(function () {
65790 socket.removeListener('connect', onReqSockConnect)
65791 self.abort()
65792 var e = new Error('ETIMEDOUT')
65793 e.code = 'ETIMEDOUT'
65794 e.connect = true
65795 self.emit('error', e)
65796 }, timeout)
65797 } else {
65798 // We're already connected
65799 setReqTimeout()
65800 }
65801 }
65802 self.emit('socket', socket)
65803 })
65804
65805 self.emit('request', self.req)
65806}
65807
65808Request.prototype.onRequestError = function (error) {
65809 var self = this
65810 if (self._aborted) {
65811 return
65812 }
65813 if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' &&
65814 self.agent.addRequestNoreuse) {
65815 self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) }
65816 self.start()
65817 self.req.end()
65818 return
65819 }
65820 if (self.timeout && self.timeoutTimer) {
65821 clearTimeout(self.timeoutTimer)
65822 self.timeoutTimer = null
65823 }
65824 self.emit('error', error)
65825}
65826
65827Request.prototype.onRequestResponse = function (response) {
65828 var self = this
65829
65830 if (self.timing) {
65831 self.timings.response = now() - self.startTimeNow
65832 }
65833
65834 debug('onRequestResponse', self.uri.href, response.statusCode, response.headers)
65835 response.on('end', function () {
65836 if (self.timing) {
65837 self.timings.end = now() - self.startTimeNow
65838 response.timingStart = self.startTime
65839
65840 // fill in the blanks for any periods that didn't trigger, such as
65841 // no lookup or connect due to keep alive
65842 if (!self.timings.socket) {
65843 self.timings.socket = 0
65844 }
65845 if (!self.timings.lookup) {
65846 self.timings.lookup = self.timings.socket
65847 }
65848 if (!self.timings.connect) {
65849 self.timings.connect = self.timings.lookup
65850 }
65851 if (!self.timings.response) {
65852 self.timings.response = self.timings.connect
65853 }
65854
65855 debug('elapsed time', self.timings.end)
65856
65857 // elapsedTime includes all redirects
65858 self.elapsedTime += Math.round(self.timings.end)
65859
65860 // NOTE: elapsedTime is deprecated in favor of .timings
65861 response.elapsedTime = self.elapsedTime
65862
65863 // timings is just for the final fetch
65864 response.timings = self.timings
65865
65866 // pre-calculate phase timings as well
65867 response.timingPhases = {
65868 wait: self.timings.socket,
65869 dns: self.timings.lookup - self.timings.socket,
65870 tcp: self.timings.connect - self.timings.lookup,
65871 firstByte: self.timings.response - self.timings.connect,
65872 download: self.timings.end - self.timings.response,
65873 total: self.timings.end
65874 }
65875 }
65876 debug('response end', self.uri.href, response.statusCode, response.headers)
65877 })
65878
65879 if (self._aborted) {
65880 debug('aborted', self.uri.href)
65881 response.resume()
65882 return
65883 }
65884
65885 self.response = response
65886 response.request = self
65887 response.toJSON = responseToJSON
65888
65889 // XXX This is different on 0.10, because SSL is strict by default
65890 if (self.httpModule === https &&
65891 self.strictSSL && (!response.hasOwnProperty('socket') ||
65892 !response.socket.authorized)) {
65893 debug('strict ssl error', self.uri.href)
65894 var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL'
65895 self.emit('error', new Error('SSL Error: ' + sslErr))
65896 return
65897 }
65898
65899 // Save the original host before any redirect (if it changes, we need to
65900 // remove any authorization headers). Also remember the case of the header
65901 // name because lots of broken servers expect Host instead of host and we
65902 // want the caller to be able to specify this.
65903 self.originalHost = self.getHeader('host')
65904 if (!self.originalHostHeaderName) {
65905 self.originalHostHeaderName = self.hasHeader('host')
65906 }
65907 if (self.setHost) {
65908 self.removeHeader('host')
65909 }
65910 if (self.timeout && self.timeoutTimer) {
65911 clearTimeout(self.timeoutTimer)
65912 self.timeoutTimer = null
65913 }
65914
65915 var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar
65916 var addCookie = function (cookie) {
65917 // set the cookie if it's domain in the href's domain.
65918 try {
65919 targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true})
65920 } catch (e) {
65921 self.emit('error', e)
65922 }
65923 }
65924
65925 response.caseless = caseless(response.headers)
65926
65927 if (response.caseless.has('set-cookie') && (!self._disableCookies)) {
65928 var headerName = response.caseless.has('set-cookie')
65929 if (Array.isArray(response.headers[headerName])) {
65930 response.headers[headerName].forEach(addCookie)
65931 } else {
65932 addCookie(response.headers[headerName])
65933 }
65934 }
65935
65936 if (self._redirect.onResponse(response)) {
65937 return // Ignore the rest of the response
65938 } else {
65939 // Be a good stream and emit end when the response is finished.
65940 // Hack to emit end on close because of a core bug that never fires end
65941 response.on('close', function () {
65942 if (!self._ended) {
65943 self.response.emit('end')
65944 }
65945 })
65946
65947 response.once('end', function () {
65948 self._ended = true
65949 })
65950
65951 var noBody = function (code) {
65952 return (
65953 self.method === 'HEAD' ||
65954 // Informational
65955 (code >= 100 && code < 200) ||
65956 // No Content
65957 code === 204 ||
65958 // Not Modified
65959 code === 304
65960 )
65961 }
65962
65963 var responseContent
65964 if (self.gzip && !noBody(response.statusCode)) {
65965 var contentEncoding = response.headers['content-encoding'] || 'identity'
65966 contentEncoding = contentEncoding.trim().toLowerCase()
65967
65968 // Be more lenient with decoding compressed responses, since (very rarely)
65969 // servers send slightly invalid gzip responses that are still accepted
65970 // by common browsers.
65971 // Always using Z_SYNC_FLUSH is what cURL does.
65972 var zlibOptions = {
65973 flush: zlib.Z_SYNC_FLUSH,
65974 finishFlush: zlib.Z_SYNC_FLUSH
65975 }
65976
65977 if (contentEncoding === 'gzip') {
65978 responseContent = zlib.createGunzip(zlibOptions)
65979 response.pipe(responseContent)
65980 } else if (contentEncoding === 'deflate') {
65981 responseContent = zlib.createInflate(zlibOptions)
65982 response.pipe(responseContent)
65983 } else {
65984 // Since previous versions didn't check for Content-Encoding header,
65985 // ignore any invalid values to preserve backwards-compatibility
65986 if (contentEncoding !== 'identity') {
65987 debug('ignoring unrecognized Content-Encoding ' + contentEncoding)
65988 }
65989 responseContent = response
65990 }
65991 } else {
65992 responseContent = response
65993 }
65994
65995 if (self.encoding) {
65996 if (self.dests.length !== 0) {
65997 console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.')
65998 } else {
65999 responseContent.setEncoding(self.encoding)
66000 }
66001 }
66002
66003 if (self._paused) {
66004 responseContent.pause()
66005 }
66006
66007 self.responseContent = responseContent
66008
66009 self.emit('response', response)
66010
66011 self.dests.forEach(function (dest) {
66012 self.pipeDest(dest)
66013 })
66014
66015 responseContent.on('data', function (chunk) {
66016 if (self.timing && !self.responseStarted) {
66017 self.responseStartTime = (new Date()).getTime()
66018
66019 // NOTE: responseStartTime is deprecated in favor of .timings
66020 response.responseStartTime = self.responseStartTime
66021 }
66022 self._destdata = true
66023 self.emit('data', chunk)
66024 })
66025 responseContent.once('end', function (chunk) {
66026 self.emit('end', chunk)
66027 })
66028 responseContent.on('error', function (error) {
66029 self.emit('error', error)
66030 })
66031 responseContent.on('close', function () { self.emit('close') })
66032
66033 if (self.callback) {
66034 self.readResponseBody(response)
66035 } else { // if no callback
66036 self.on('end', function () {
66037 if (self._aborted) {
66038 debug('aborted', self.uri.href)
66039 return
66040 }
66041 self.emit('complete', response)
66042 })
66043 }
66044 }
66045 debug('finish init function', self.uri.href)
66046}
66047
66048Request.prototype.readResponseBody = function (response) {
66049 var self = this
66050 debug("reading response's body")
66051 var buffers = []
66052 var bufferLength = 0
66053 var strings = []
66054
66055 self.on('data', function (chunk) {
66056 if (!Buffer.isBuffer(chunk)) {
66057 strings.push(chunk)
66058 } else if (chunk.length) {
66059 bufferLength += chunk.length
66060 buffers.push(chunk)
66061 }
66062 })
66063 self.on('end', function () {
66064 debug('end event', self.uri.href)
66065 if (self._aborted) {
66066 debug('aborted', self.uri.href)
66067 // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request.
66068 // This can lead to leaky behavior if the user retains a reference to the request object.
66069 buffers = []
66070 bufferLength = 0
66071 return
66072 }
66073
66074 if (bufferLength) {
66075 debug('has body', self.uri.href, bufferLength)
66076 response.body = Buffer.concat(buffers, bufferLength)
66077 if (self.encoding !== null) {
66078 response.body = response.body.toString(self.encoding)
66079 }
66080 // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request.
66081 // This can lead to leaky behavior if the user retains a reference to the request object.
66082 buffers = []
66083 bufferLength = 0
66084 } else if (strings.length) {
66085 // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation.
66086 // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse().
66087 if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') {
66088 strings[0] = strings[0].substring(1)
66089 }
66090 response.body = strings.join('')
66091 }
66092
66093 if (self._json) {
66094 try {
66095 response.body = JSON.parse(response.body, self._jsonReviver)
66096 } catch (e) {
66097 debug('invalid JSON received', self.uri.href)
66098 }
66099 }
66100 debug('emitting complete', self.uri.href)
66101 if (typeof response.body === 'undefined' && !self._json) {
66102 response.body = self.encoding === null ? Buffer.alloc(0) : ''
66103 }
66104 self.emit('complete', response, response.body)
66105 })
66106}
66107
66108Request.prototype.abort = function () {
66109 var self = this
66110 self._aborted = true
66111
66112 if (self.req) {
66113 self.req.abort()
66114 } else if (self.response) {
66115 self.response.destroy()
66116 }
66117
66118 self.emit('abort')
66119}
66120
66121Request.prototype.pipeDest = function (dest) {
66122 var self = this
66123 var response = self.response
66124 // Called after the response is received
66125 if (dest.headers && !dest.headersSent) {
66126 if (response.caseless.has('content-type')) {
66127 var ctname = response.caseless.has('content-type')
66128 if (dest.setHeader) {
66129 dest.setHeader(ctname, response.headers[ctname])
66130 } else {
66131 dest.headers[ctname] = response.headers[ctname]
66132 }
66133 }
66134
66135 if (response.caseless.has('content-length')) {
66136 var clname = response.caseless.has('content-length')
66137 if (dest.setHeader) {
66138 dest.setHeader(clname, response.headers[clname])
66139 } else {
66140 dest.headers[clname] = response.headers[clname]
66141 }
66142 }
66143 }
66144 if (dest.setHeader && !dest.headersSent) {
66145 for (var i in response.headers) {
66146 // If the response content is being decoded, the Content-Encoding header
66147 // of the response doesn't represent the piped content, so don't pass it.
66148 if (!self.gzip || i !== 'content-encoding') {
66149 dest.setHeader(i, response.headers[i])
66150 }
66151 }
66152 dest.statusCode = response.statusCode
66153 }
66154 if (self.pipefilter) {
66155 self.pipefilter(response, dest)
66156 }
66157}
66158
66159Request.prototype.qs = function (q, clobber) {
66160 var self = this
66161 var base
66162 if (!clobber && self.uri.query) {
66163 base = self._qs.parse(self.uri.query)
66164 } else {
66165 base = {}
66166 }
66167
66168 for (var i in q) {
66169 base[i] = q[i]
66170 }
66171
66172 var qs = self._qs.stringify(base)
66173
66174 if (qs === '') {
66175 return self
66176 }
66177
66178 self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs)
66179 self.url = self.uri
66180 self.path = self.uri.path
66181
66182 if (self.uri.host === 'unix') {
66183 self.enableUnixSocket()
66184 }
66185
66186 return self
66187}
66188Request.prototype.form = function (form) {
66189 var self = this
66190 if (form) {
66191 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
66192 self.setHeader('content-type', 'application/x-www-form-urlencoded')
66193 }
66194 self.body = (typeof form === 'string')
66195 ? self._qs.rfc3986(form.toString('utf8'))
66196 : self._qs.stringify(form).toString('utf8')
66197 return self
66198 }
66199 // create form-data object
66200 self._form = new FormData()
66201 self._form.on('error', function (err) {
66202 err.message = 'form-data: ' + err.message
66203 self.emit('error', err)
66204 self.abort()
66205 })
66206 return self._form
66207}
66208Request.prototype.multipart = function (multipart) {
66209 var self = this
66210
66211 self._multipart.onRequest(multipart)
66212
66213 if (!self._multipart.chunked) {
66214 self.body = self._multipart.body
66215 }
66216
66217 return self
66218}
66219Request.prototype.json = function (val) {
66220 var self = this
66221
66222 if (!self.hasHeader('accept')) {
66223 self.setHeader('accept', 'application/json')
66224 }
66225
66226 if (typeof self.jsonReplacer === 'function') {
66227 self._jsonReplacer = self.jsonReplacer
66228 }
66229
66230 self._json = true
66231 if (typeof val === 'boolean') {
66232 if (self.body !== undefined) {
66233 if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
66234 self.body = safeStringify(self.body, self._jsonReplacer)
66235 } else {
66236 self.body = self._qs.rfc3986(self.body)
66237 }
66238 if (!self.hasHeader('content-type')) {
66239 self.setHeader('content-type', 'application/json')
66240 }
66241 }
66242 } else {
66243 self.body = safeStringify(val, self._jsonReplacer)
66244 if (!self.hasHeader('content-type')) {
66245 self.setHeader('content-type', 'application/json')
66246 }
66247 }
66248
66249 if (typeof self.jsonReviver === 'function') {
66250 self._jsonReviver = self.jsonReviver
66251 }
66252
66253 return self
66254}
66255Request.prototype.getHeader = function (name, headers) {
66256 var self = this
66257 var result, re, match
66258 if (!headers) {
66259 headers = self.headers
66260 }
66261 Object.keys(headers).forEach(function (key) {
66262 if (key.length !== name.length) {
66263 return
66264 }
66265 re = new RegExp(name, 'i')
66266 match = key.match(re)
66267 if (match) {
66268 result = headers[key]
66269 }
66270 })
66271 return result
66272}
66273Request.prototype.enableUnixSocket = function () {
66274 // Get the socket & request paths from the URL
66275 var unixParts = this.uri.path.split(':')
66276 var host = unixParts[0]
66277 var path = unixParts[1]
66278 // Apply unix properties to request
66279 this.socketPath = host
66280 this.uri.pathname = path
66281 this.uri.path = path
66282 this.uri.host = host
66283 this.uri.hostname = host
66284 this.uri.isUnix = true
66285}
66286
66287Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
66288 var self = this
66289
66290 self._auth.onRequest(user, pass, sendImmediately, bearer)
66291
66292 return self
66293}
66294Request.prototype.aws = function (opts, now) {
66295 var self = this
66296
66297 if (!now) {
66298 self._aws = opts
66299 return self
66300 }
66301
66302 if (opts.sign_version === 4 || opts.sign_version === '4') {
66303 // use aws4
66304 var options = {
66305 host: self.uri.host,
66306 path: self.uri.path,
66307 method: self.method,
66308 headers: self.headers,
66309 body: self.body
66310 }
66311 if (opts.service) {
66312 options.service = opts.service
66313 }
66314 var signRes = aws4.sign(options, {
66315 accessKeyId: opts.key,
66316 secretAccessKey: opts.secret,
66317 sessionToken: opts.session
66318 })
66319 self.setHeader('authorization', signRes.headers.Authorization)
66320 self.setHeader('x-amz-date', signRes.headers['X-Amz-Date'])
66321 if (signRes.headers['X-Amz-Security-Token']) {
66322 self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token'])
66323 }
66324 } else {
66325 // default: use aws-sign2
66326 var date = new Date()
66327 self.setHeader('date', date.toUTCString())
66328 var auth = {
66329 key: opts.key,
66330 secret: opts.secret,
66331 verb: self.method.toUpperCase(),
66332 date: date,
66333 contentType: self.getHeader('content-type') || '',
66334 md5: self.getHeader('content-md5') || '',
66335 amazonHeaders: aws2.canonicalizeHeaders(self.headers)
66336 }
66337 var path = self.uri.path
66338 if (opts.bucket && path) {
66339 auth.resource = '/' + opts.bucket + path
66340 } else if (opts.bucket && !path) {
66341 auth.resource = '/' + opts.bucket
66342 } else if (!opts.bucket && path) {
66343 auth.resource = path
66344 } else if (!opts.bucket && !path) {
66345 auth.resource = '/'
66346 }
66347 auth.resource = aws2.canonicalizeResource(auth.resource)
66348 self.setHeader('authorization', aws2.authorization(auth))
66349 }
66350
66351 return self
66352}
66353Request.prototype.httpSignature = function (opts) {
66354 var self = this
66355 httpSignature.signRequest({
66356 getHeader: function (header) {
66357 return self.getHeader(header, self.headers)
66358 },
66359 setHeader: function (header, value) {
66360 self.setHeader(header, value)
66361 },
66362 method: self.method,
66363 path: self.path
66364 }, opts)
66365 debug('httpSignature authorization', self.getHeader('authorization'))
66366
66367 return self
66368}
66369Request.prototype.hawk = function (opts) {
66370 var self = this
66371 self.setHeader('Authorization', hawk.header(self.uri, self.method, opts))
66372}
66373Request.prototype.oauth = function (_oauth) {
66374 var self = this
66375
66376 self._oauth.onRequest(_oauth)
66377
66378 return self
66379}
66380
66381Request.prototype.jar = function (jar) {
66382 var self = this
66383 var cookies
66384
66385 if (self._redirect.redirectsFollowed === 0) {
66386 self.originalCookieHeader = self.getHeader('cookie')
66387 }
66388
66389 if (!jar) {
66390 // disable cookies
66391 cookies = false
66392 self._disableCookies = true
66393 } else {
66394 var targetCookieJar = (jar && jar.getCookieString) ? jar : globalCookieJar
66395 var urihref = self.uri.href
66396 // fetch cookie in the Specified host
66397 if (targetCookieJar) {
66398 cookies = targetCookieJar.getCookieString(urihref)
66399 }
66400 }
66401
66402 // if need cookie and cookie is not empty
66403 if (cookies && cookies.length) {
66404 if (self.originalCookieHeader) {
66405 // Don't overwrite existing Cookie header
66406 self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies)
66407 } else {
66408 self.setHeader('cookie', cookies)
66409 }
66410 }
66411 self._jar = jar
66412 return self
66413}
66414
66415// Stream API
66416Request.prototype.pipe = function (dest, opts) {
66417 var self = this
66418
66419 if (self.response) {
66420 if (self._destdata) {
66421 self.emit('error', new Error('You cannot pipe after data has been emitted from the response.'))
66422 } else if (self._ended) {
66423 self.emit('error', new Error('You cannot pipe after the response has been ended.'))
66424 } else {
66425 stream.Stream.prototype.pipe.call(self, dest, opts)
66426 self.pipeDest(dest)
66427 return dest
66428 }
66429 } else {
66430 self.dests.push(dest)
66431 stream.Stream.prototype.pipe.call(self, dest, opts)
66432 return dest
66433 }
66434}
66435Request.prototype.write = function () {
66436 var self = this
66437 if (self._aborted) { return }
66438
66439 if (!self._started) {
66440 self.start()
66441 }
66442 if (self.req) {
66443 return self.req.write.apply(self.req, arguments)
66444 }
66445}
66446Request.prototype.end = function (chunk) {
66447 var self = this
66448 if (self._aborted) { return }
66449
66450 if (chunk) {
66451 self.write(chunk)
66452 }
66453 if (!self._started) {
66454 self.start()
66455 }
66456 if (self.req) {
66457 self.req.end()
66458 }
66459}
66460Request.prototype.pause = function () {
66461 var self = this
66462 if (!self.responseContent) {
66463 self._paused = true
66464 } else {
66465 self.responseContent.pause.apply(self.responseContent, arguments)
66466 }
66467}
66468Request.prototype.resume = function () {
66469 var self = this
66470 if (!self.responseContent) {
66471 self._paused = false
66472 } else {
66473 self.responseContent.resume.apply(self.responseContent, arguments)
66474 }
66475}
66476Request.prototype.destroy = function () {
66477 var self = this
66478 if (!self._ended) {
66479 self.end()
66480 } else if (self.response) {
66481 self.response.destroy()
66482 }
66483}
66484
66485Request.defaultProxyHeaderWhiteList =
66486 Tunnel.defaultProxyHeaderWhiteList.slice()
66487
66488Request.defaultProxyHeaderExclusiveList =
66489 Tunnel.defaultProxyHeaderExclusiveList.slice()
66490
66491// Exports
66492
66493Request.prototype.toJSON = requestToJSON
66494module.exports = Request
66495
66496}).call(this,require('_process'))
66497},{"./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){
66498'use strict'
66499var Buffer = require('buffer').Buffer
66500var inherits = require('inherits')
66501var HashBase = require('hash-base')
66502
66503var ARRAY16 = new Array(16)
66504
66505var zl = [
66506 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
66507 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
66508 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
66509 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
66510 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
66511]
66512
66513var zr = [
66514 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
66515 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
66516 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
66517 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
66518 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
66519]
66520
66521var sl = [
66522 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
66523 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
66524 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
66525 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
66526 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
66527]
66528
66529var sr = [
66530 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
66531 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
66532 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
66533 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
66534 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
66535]
66536
66537var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
66538var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]
66539
66540function RIPEMD160 () {
66541 HashBase.call(this, 64)
66542
66543 // state
66544 this._a = 0x67452301
66545 this._b = 0xefcdab89
66546 this._c = 0x98badcfe
66547 this._d = 0x10325476
66548 this._e = 0xc3d2e1f0
66549}
66550
66551inherits(RIPEMD160, HashBase)
66552
66553RIPEMD160.prototype._update = function () {
66554 var words = ARRAY16
66555 for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)
66556
66557 var al = this._a | 0
66558 var bl = this._b | 0
66559 var cl = this._c | 0
66560 var dl = this._d | 0
66561 var el = this._e | 0
66562
66563 var ar = this._a | 0
66564 var br = this._b | 0
66565 var cr = this._c | 0
66566 var dr = this._d | 0
66567 var er = this._e | 0
66568
66569 // computation
66570 for (var i = 0; i < 80; i += 1) {
66571 var tl
66572 var tr
66573 if (i < 16) {
66574 tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])
66575 tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])
66576 } else if (i < 32) {
66577 tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])
66578 tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])
66579 } else if (i < 48) {
66580 tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])
66581 tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])
66582 } else if (i < 64) {
66583 tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])
66584 tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])
66585 } else { // if (i<80) {
66586 tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])
66587 tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])
66588 }
66589
66590 al = el
66591 el = dl
66592 dl = rotl(cl, 10)
66593 cl = bl
66594 bl = tl
66595
66596 ar = er
66597 er = dr
66598 dr = rotl(cr, 10)
66599 cr = br
66600 br = tr
66601 }
66602
66603 // update state
66604 var t = (this._b + cl + dr) | 0
66605 this._b = (this._c + dl + er) | 0
66606 this._c = (this._d + el + ar) | 0
66607 this._d = (this._e + al + br) | 0
66608 this._e = (this._a + bl + cr) | 0
66609 this._a = t
66610}
66611
66612RIPEMD160.prototype._digest = function () {
66613 // create padding and handle blocks
66614 this._block[this._blockOffset++] = 0x80
66615 if (this._blockOffset > 56) {
66616 this._block.fill(0, this._blockOffset, 64)
66617 this._update()
66618 this._blockOffset = 0
66619 }
66620
66621 this._block.fill(0, this._blockOffset, 56)
66622 this._block.writeUInt32LE(this._length[0], 56)
66623 this._block.writeUInt32LE(this._length[1], 60)
66624 this._update()
66625
66626 // produce result
66627 var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)
66628 buffer.writeInt32LE(this._a, 0)
66629 buffer.writeInt32LE(this._b, 4)
66630 buffer.writeInt32LE(this._c, 8)
66631 buffer.writeInt32LE(this._d, 12)
66632 buffer.writeInt32LE(this._e, 16)
66633 return buffer
66634}
66635
66636function rotl (x, n) {
66637 return (x << n) | (x >>> (32 - n))
66638}
66639
66640function fn1 (a, b, c, d, e, m, k, s) {
66641 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
66642}
66643
66644function fn2 (a, b, c, d, e, m, k, s) {
66645 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
66646}
66647
66648function fn3 (a, b, c, d, e, m, k, s) {
66649 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
66650}
66651
66652function fn4 (a, b, c, d, e, m, k, s) {
66653 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
66654}
66655
66656function fn5 (a, b, c, d, e, m, k, s) {
66657 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
66658}
66659
66660module.exports = RIPEMD160
66661
66662},{"buffer":114,"hash-base":189,"inherits":210}],325:[function(require,module,exports){
66663/* eslint-disable node/no-deprecated-api */
66664var buffer = require('buffer')
66665var Buffer = buffer.Buffer
66666
66667// alternative to using Object.keys for old browsers
66668function copyProps (src, dst) {
66669 for (var key in src) {
66670 dst[key] = src[key]
66671 }
66672}
66673if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
66674 module.exports = buffer
66675} else {
66676 // Copy properties from require('buffer')
66677 copyProps(buffer, exports)
66678 exports.Buffer = SafeBuffer
66679}
66680
66681function SafeBuffer (arg, encodingOrOffset, length) {
66682 return Buffer(arg, encodingOrOffset, length)
66683}
66684
66685// Copy static methods from Buffer
66686copyProps(Buffer, SafeBuffer)
66687
66688SafeBuffer.from = function (arg, encodingOrOffset, length) {
66689 if (typeof arg === 'number') {
66690 throw new TypeError('Argument must not be a number')
66691 }
66692 return Buffer(arg, encodingOrOffset, length)
66693}
66694
66695SafeBuffer.alloc = function (size, fill, encoding) {
66696 if (typeof size !== 'number') {
66697 throw new TypeError('Argument must be a number')
66698 }
66699 var buf = Buffer(size)
66700 if (fill !== undefined) {
66701 if (typeof encoding === 'string') {
66702 buf.fill(fill, encoding)
66703 } else {
66704 buf.fill(fill)
66705 }
66706 } else {
66707 buf.fill(0)
66708 }
66709 return buf
66710}
66711
66712SafeBuffer.allocUnsafe = function (size) {
66713 if (typeof size !== 'number') {
66714 throw new TypeError('Argument must be a number')
66715 }
66716 return Buffer(size)
66717}
66718
66719SafeBuffer.allocUnsafeSlow = function (size) {
66720 if (typeof size !== 'number') {
66721 throw new TypeError('Argument must be a number')
66722 }
66723 return buffer.SlowBuffer(size)
66724}
66725
66726},{"buffer":114}],326:[function(require,module,exports){
66727(function (process){
66728/* eslint-disable node/no-deprecated-api */
66729
66730'use strict'
66731
66732var buffer = require('buffer')
66733var Buffer = buffer.Buffer
66734
66735var safer = {}
66736
66737var key
66738
66739for (key in buffer) {
66740 if (!buffer.hasOwnProperty(key)) continue
66741 if (key === 'SlowBuffer' || key === 'Buffer') continue
66742 safer[key] = buffer[key]
66743}
66744
66745var Safer = safer.Buffer = {}
66746for (key in Buffer) {
66747 if (!Buffer.hasOwnProperty(key)) continue
66748 if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
66749 Safer[key] = Buffer[key]
66750}
66751
66752safer.Buffer.prototype = Buffer.prototype
66753
66754if (!Safer.from || Safer.from === Uint8Array.from) {
66755 Safer.from = function (value, encodingOrOffset, length) {
66756 if (typeof value === 'number') {
66757 throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
66758 }
66759 if (value && typeof value.length === 'undefined') {
66760 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
66761 }
66762 return Buffer(value, encodingOrOffset, length)
66763 }
66764}
66765
66766if (!Safer.alloc) {
66767 Safer.alloc = function (size, fill, encoding) {
66768 if (typeof size !== 'number') {
66769 throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
66770 }
66771 if (size < 0 || size >= 2 * (1 << 30)) {
66772 throw new RangeError('The value "' + size + '" is invalid for option "size"')
66773 }
66774 var buf = Buffer(size)
66775 if (!fill || fill.length === 0) {
66776 buf.fill(0)
66777 } else if (typeof encoding === 'string') {
66778 buf.fill(fill, encoding)
66779 } else {
66780 buf.fill(fill)
66781 }
66782 return buf
66783 }
66784}
66785
66786if (!safer.kStringMaxLength) {
66787 try {
66788 safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
66789 } catch (e) {
66790 // we can't determine kStringMaxLength in environments where process.binding
66791 // is unsupported, so let's not set it
66792 }
66793}
66794
66795if (!safer.constants) {
66796 safer.constants = {
66797 MAX_LENGTH: safer.kMaxLength
66798 }
66799 if (safer.kStringMaxLength) {
66800 safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
66801 }
66802}
66803
66804module.exports = safer
66805
66806}).call(this,require('_process'))
66807},{"_process":265,"buffer":114}],327:[function(require,module,exports){
66808var Buffer = require('safe-buffer').Buffer
66809
66810// prototype class for hash functions
66811function Hash (blockSize, finalSize) {
66812 this._block = Buffer.alloc(blockSize)
66813 this._finalSize = finalSize
66814 this._blockSize = blockSize
66815 this._len = 0
66816}
66817
66818Hash.prototype.update = function (data, enc) {
66819 if (typeof data === 'string') {
66820 enc = enc || 'utf8'
66821 data = Buffer.from(data, enc)
66822 }
66823
66824 var block = this._block
66825 var blockSize = this._blockSize
66826 var length = data.length
66827 var accum = this._len
66828
66829 for (var offset = 0; offset < length;) {
66830 var assigned = accum % blockSize
66831 var remainder = Math.min(length - offset, blockSize - assigned)
66832
66833 for (var i = 0; i < remainder; i++) {
66834 block[assigned + i] = data[offset + i]
66835 }
66836
66837 accum += remainder
66838 offset += remainder
66839
66840 if ((accum % blockSize) === 0) {
66841 this._update(block)
66842 }
66843 }
66844
66845 this._len += length
66846 return this
66847}
66848
66849Hash.prototype.digest = function (enc) {
66850 var rem = this._len % this._blockSize
66851
66852 this._block[rem] = 0x80
66853
66854 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
66855 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
66856 this._block.fill(0, rem + 1)
66857
66858 if (rem >= this._finalSize) {
66859 this._update(this._block)
66860 this._block.fill(0)
66861 }
66862
66863 var bits = this._len * 8
66864
66865 // uint32
66866 if (bits <= 0xffffffff) {
66867 this._block.writeUInt32BE(bits, this._blockSize - 4)
66868
66869 // uint64
66870 } else {
66871 var lowBits = (bits & 0xffffffff) >>> 0
66872 var highBits = (bits - lowBits) / 0x100000000
66873
66874 this._block.writeUInt32BE(highBits, this._blockSize - 8)
66875 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
66876 }
66877
66878 this._update(this._block)
66879 var hash = this._hash()
66880
66881 return enc ? hash.toString(enc) : hash
66882}
66883
66884Hash.prototype._update = function () {
66885 throw new Error('_update must be implemented by subclass')
66886}
66887
66888module.exports = Hash
66889
66890},{"safe-buffer":325}],328:[function(require,module,exports){
66891var exports = module.exports = function SHA (algorithm) {
66892 algorithm = algorithm.toLowerCase()
66893
66894 var Algorithm = exports[algorithm]
66895 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
66896
66897 return new Algorithm()
66898}
66899
66900exports.sha = require('./sha')
66901exports.sha1 = require('./sha1')
66902exports.sha224 = require('./sha224')
66903exports.sha256 = require('./sha256')
66904exports.sha384 = require('./sha384')
66905exports.sha512 = require('./sha512')
66906
66907},{"./sha":329,"./sha1":330,"./sha224":331,"./sha256":332,"./sha384":333,"./sha512":334}],329:[function(require,module,exports){
66908/*
66909 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
66910 * in FIPS PUB 180-1
66911 * This source code is derived from sha1.js of the same repository.
66912 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
66913 * operation was added.
66914 */
66915
66916var inherits = require('inherits')
66917var Hash = require('./hash')
66918var Buffer = require('safe-buffer').Buffer
66919
66920var K = [
66921 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
66922]
66923
66924var W = new Array(80)
66925
66926function Sha () {
66927 this.init()
66928 this._w = W
66929
66930 Hash.call(this, 64, 56)
66931}
66932
66933inherits(Sha, Hash)
66934
66935Sha.prototype.init = function () {
66936 this._a = 0x67452301
66937 this._b = 0xefcdab89
66938 this._c = 0x98badcfe
66939 this._d = 0x10325476
66940 this._e = 0xc3d2e1f0
66941
66942 return this
66943}
66944
66945function rotl5 (num) {
66946 return (num << 5) | (num >>> 27)
66947}
66948
66949function rotl30 (num) {
66950 return (num << 30) | (num >>> 2)
66951}
66952
66953function ft (s, b, c, d) {
66954 if (s === 0) return (b & c) | ((~b) & d)
66955 if (s === 2) return (b & c) | (b & d) | (c & d)
66956 return b ^ c ^ d
66957}
66958
66959Sha.prototype._update = function (M) {
66960 var W = this._w
66961
66962 var a = this._a | 0
66963 var b = this._b | 0
66964 var c = this._c | 0
66965 var d = this._d | 0
66966 var e = this._e | 0
66967
66968 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
66969 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
66970
66971 for (var j = 0; j < 80; ++j) {
66972 var s = ~~(j / 20)
66973 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
66974
66975 e = d
66976 d = c
66977 c = rotl30(b)
66978 b = a
66979 a = t
66980 }
66981
66982 this._a = (a + this._a) | 0
66983 this._b = (b + this._b) | 0
66984 this._c = (c + this._c) | 0
66985 this._d = (d + this._d) | 0
66986 this._e = (e + this._e) | 0
66987}
66988
66989Sha.prototype._hash = function () {
66990 var H = Buffer.allocUnsafe(20)
66991
66992 H.writeInt32BE(this._a | 0, 0)
66993 H.writeInt32BE(this._b | 0, 4)
66994 H.writeInt32BE(this._c | 0, 8)
66995 H.writeInt32BE(this._d | 0, 12)
66996 H.writeInt32BE(this._e | 0, 16)
66997
66998 return H
66999}
67000
67001module.exports = Sha
67002
67003},{"./hash":327,"inherits":210,"safe-buffer":325}],330:[function(require,module,exports){
67004/*
67005 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
67006 * in FIPS PUB 180-1
67007 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
67008 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
67009 * Distributed under the BSD License
67010 * See http://pajhome.org.uk/crypt/md5 for details.
67011 */
67012
67013var inherits = require('inherits')
67014var Hash = require('./hash')
67015var Buffer = require('safe-buffer').Buffer
67016
67017var K = [
67018 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
67019]
67020
67021var W = new Array(80)
67022
67023function Sha1 () {
67024 this.init()
67025 this._w = W
67026
67027 Hash.call(this, 64, 56)
67028}
67029
67030inherits(Sha1, Hash)
67031
67032Sha1.prototype.init = function () {
67033 this._a = 0x67452301
67034 this._b = 0xefcdab89
67035 this._c = 0x98badcfe
67036 this._d = 0x10325476
67037 this._e = 0xc3d2e1f0
67038
67039 return this
67040}
67041
67042function rotl1 (num) {
67043 return (num << 1) | (num >>> 31)
67044}
67045
67046function rotl5 (num) {
67047 return (num << 5) | (num >>> 27)
67048}
67049
67050function rotl30 (num) {
67051 return (num << 30) | (num >>> 2)
67052}
67053
67054function ft (s, b, c, d) {
67055 if (s === 0) return (b & c) | ((~b) & d)
67056 if (s === 2) return (b & c) | (b & d) | (c & d)
67057 return b ^ c ^ d
67058}
67059
67060Sha1.prototype._update = function (M) {
67061 var W = this._w
67062
67063 var a = this._a | 0
67064 var b = this._b | 0
67065 var c = this._c | 0
67066 var d = this._d | 0
67067 var e = this._e | 0
67068
67069 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
67070 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
67071
67072 for (var j = 0; j < 80; ++j) {
67073 var s = ~~(j / 20)
67074 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
67075
67076 e = d
67077 d = c
67078 c = rotl30(b)
67079 b = a
67080 a = t
67081 }
67082
67083 this._a = (a + this._a) | 0
67084 this._b = (b + this._b) | 0
67085 this._c = (c + this._c) | 0
67086 this._d = (d + this._d) | 0
67087 this._e = (e + this._e) | 0
67088}
67089
67090Sha1.prototype._hash = function () {
67091 var H = Buffer.allocUnsafe(20)
67092
67093 H.writeInt32BE(this._a | 0, 0)
67094 H.writeInt32BE(this._b | 0, 4)
67095 H.writeInt32BE(this._c | 0, 8)
67096 H.writeInt32BE(this._d | 0, 12)
67097 H.writeInt32BE(this._e | 0, 16)
67098
67099 return H
67100}
67101
67102module.exports = Sha1
67103
67104},{"./hash":327,"inherits":210,"safe-buffer":325}],331:[function(require,module,exports){
67105/**
67106 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
67107 * in FIPS 180-2
67108 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
67109 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
67110 *
67111 */
67112
67113var inherits = require('inherits')
67114var Sha256 = require('./sha256')
67115var Hash = require('./hash')
67116var Buffer = require('safe-buffer').Buffer
67117
67118var W = new Array(64)
67119
67120function Sha224 () {
67121 this.init()
67122
67123 this._w = W // new Array(64)
67124
67125 Hash.call(this, 64, 56)
67126}
67127
67128inherits(Sha224, Sha256)
67129
67130Sha224.prototype.init = function () {
67131 this._a = 0xc1059ed8
67132 this._b = 0x367cd507
67133 this._c = 0x3070dd17
67134 this._d = 0xf70e5939
67135 this._e = 0xffc00b31
67136 this._f = 0x68581511
67137 this._g = 0x64f98fa7
67138 this._h = 0xbefa4fa4
67139
67140 return this
67141}
67142
67143Sha224.prototype._hash = function () {
67144 var H = Buffer.allocUnsafe(28)
67145
67146 H.writeInt32BE(this._a, 0)
67147 H.writeInt32BE(this._b, 4)
67148 H.writeInt32BE(this._c, 8)
67149 H.writeInt32BE(this._d, 12)
67150 H.writeInt32BE(this._e, 16)
67151 H.writeInt32BE(this._f, 20)
67152 H.writeInt32BE(this._g, 24)
67153
67154 return H
67155}
67156
67157module.exports = Sha224
67158
67159},{"./hash":327,"./sha256":332,"inherits":210,"safe-buffer":325}],332:[function(require,module,exports){
67160/**
67161 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
67162 * in FIPS 180-2
67163 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
67164 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
67165 *
67166 */
67167
67168var inherits = require('inherits')
67169var Hash = require('./hash')
67170var Buffer = require('safe-buffer').Buffer
67171
67172var K = [
67173 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
67174 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
67175 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
67176 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
67177 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
67178 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
67179 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
67180 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
67181 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
67182 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
67183 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
67184 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
67185 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
67186 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
67187 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
67188 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
67189]
67190
67191var W = new Array(64)
67192
67193function Sha256 () {
67194 this.init()
67195
67196 this._w = W // new Array(64)
67197
67198 Hash.call(this, 64, 56)
67199}
67200
67201inherits(Sha256, Hash)
67202
67203Sha256.prototype.init = function () {
67204 this._a = 0x6a09e667
67205 this._b = 0xbb67ae85
67206 this._c = 0x3c6ef372
67207 this._d = 0xa54ff53a
67208 this._e = 0x510e527f
67209 this._f = 0x9b05688c
67210 this._g = 0x1f83d9ab
67211 this._h = 0x5be0cd19
67212
67213 return this
67214}
67215
67216function ch (x, y, z) {
67217 return z ^ (x & (y ^ z))
67218}
67219
67220function maj (x, y, z) {
67221 return (x & y) | (z & (x | y))
67222}
67223
67224function sigma0 (x) {
67225 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
67226}
67227
67228function sigma1 (x) {
67229 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
67230}
67231
67232function gamma0 (x) {
67233 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
67234}
67235
67236function gamma1 (x) {
67237 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
67238}
67239
67240Sha256.prototype._update = function (M) {
67241 var W = this._w
67242
67243 var a = this._a | 0
67244 var b = this._b | 0
67245 var c = this._c | 0
67246 var d = this._d | 0
67247 var e = this._e | 0
67248 var f = this._f | 0
67249 var g = this._g | 0
67250 var h = this._h | 0
67251
67252 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
67253 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
67254
67255 for (var j = 0; j < 64; ++j) {
67256 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
67257 var T2 = (sigma0(a) + maj(a, b, c)) | 0
67258
67259 h = g
67260 g = f
67261 f = e
67262 e = (d + T1) | 0
67263 d = c
67264 c = b
67265 b = a
67266 a = (T1 + T2) | 0
67267 }
67268
67269 this._a = (a + this._a) | 0
67270 this._b = (b + this._b) | 0
67271 this._c = (c + this._c) | 0
67272 this._d = (d + this._d) | 0
67273 this._e = (e + this._e) | 0
67274 this._f = (f + this._f) | 0
67275 this._g = (g + this._g) | 0
67276 this._h = (h + this._h) | 0
67277}
67278
67279Sha256.prototype._hash = function () {
67280 var H = Buffer.allocUnsafe(32)
67281
67282 H.writeInt32BE(this._a, 0)
67283 H.writeInt32BE(this._b, 4)
67284 H.writeInt32BE(this._c, 8)
67285 H.writeInt32BE(this._d, 12)
67286 H.writeInt32BE(this._e, 16)
67287 H.writeInt32BE(this._f, 20)
67288 H.writeInt32BE(this._g, 24)
67289 H.writeInt32BE(this._h, 28)
67290
67291 return H
67292}
67293
67294module.exports = Sha256
67295
67296},{"./hash":327,"inherits":210,"safe-buffer":325}],333:[function(require,module,exports){
67297var inherits = require('inherits')
67298var SHA512 = require('./sha512')
67299var Hash = require('./hash')
67300var Buffer = require('safe-buffer').Buffer
67301
67302var W = new Array(160)
67303
67304function Sha384 () {
67305 this.init()
67306 this._w = W
67307
67308 Hash.call(this, 128, 112)
67309}
67310
67311inherits(Sha384, SHA512)
67312
67313Sha384.prototype.init = function () {
67314 this._ah = 0xcbbb9d5d
67315 this._bh = 0x629a292a
67316 this._ch = 0x9159015a
67317 this._dh = 0x152fecd8
67318 this._eh = 0x67332667
67319 this._fh = 0x8eb44a87
67320 this._gh = 0xdb0c2e0d
67321 this._hh = 0x47b5481d
67322
67323 this._al = 0xc1059ed8
67324 this._bl = 0x367cd507
67325 this._cl = 0x3070dd17
67326 this._dl = 0xf70e5939
67327 this._el = 0xffc00b31
67328 this._fl = 0x68581511
67329 this._gl = 0x64f98fa7
67330 this._hl = 0xbefa4fa4
67331
67332 return this
67333}
67334
67335Sha384.prototype._hash = function () {
67336 var H = Buffer.allocUnsafe(48)
67337
67338 function writeInt64BE (h, l, offset) {
67339 H.writeInt32BE(h, offset)
67340 H.writeInt32BE(l, offset + 4)
67341 }
67342
67343 writeInt64BE(this._ah, this._al, 0)
67344 writeInt64BE(this._bh, this._bl, 8)
67345 writeInt64BE(this._ch, this._cl, 16)
67346 writeInt64BE(this._dh, this._dl, 24)
67347 writeInt64BE(this._eh, this._el, 32)
67348 writeInt64BE(this._fh, this._fl, 40)
67349
67350 return H
67351}
67352
67353module.exports = Sha384
67354
67355},{"./hash":327,"./sha512":334,"inherits":210,"safe-buffer":325}],334:[function(require,module,exports){
67356var inherits = require('inherits')
67357var Hash = require('./hash')
67358var Buffer = require('safe-buffer').Buffer
67359
67360var K = [
67361 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
67362 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
67363 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
67364 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
67365 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
67366 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
67367 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
67368 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
67369 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
67370 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
67371 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
67372 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
67373 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
67374 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
67375 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
67376 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
67377 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
67378 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
67379 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
67380 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
67381 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
67382 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
67383 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
67384 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
67385 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
67386 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
67387 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
67388 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
67389 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
67390 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
67391 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
67392 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
67393 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
67394 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
67395 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
67396 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
67397 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
67398 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
67399 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
67400 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
67401]
67402
67403var W = new Array(160)
67404
67405function Sha512 () {
67406 this.init()
67407 this._w = W
67408
67409 Hash.call(this, 128, 112)
67410}
67411
67412inherits(Sha512, Hash)
67413
67414Sha512.prototype.init = function () {
67415 this._ah = 0x6a09e667
67416 this._bh = 0xbb67ae85
67417 this._ch = 0x3c6ef372
67418 this._dh = 0xa54ff53a
67419 this._eh = 0x510e527f
67420 this._fh = 0x9b05688c
67421 this._gh = 0x1f83d9ab
67422 this._hh = 0x5be0cd19
67423
67424 this._al = 0xf3bcc908
67425 this._bl = 0x84caa73b
67426 this._cl = 0xfe94f82b
67427 this._dl = 0x5f1d36f1
67428 this._el = 0xade682d1
67429 this._fl = 0x2b3e6c1f
67430 this._gl = 0xfb41bd6b
67431 this._hl = 0x137e2179
67432
67433 return this
67434}
67435
67436function Ch (x, y, z) {
67437 return z ^ (x & (y ^ z))
67438}
67439
67440function maj (x, y, z) {
67441 return (x & y) | (z & (x | y))
67442}
67443
67444function sigma0 (x, xl) {
67445 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
67446}
67447
67448function sigma1 (x, xl) {
67449 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
67450}
67451
67452function Gamma0 (x, xl) {
67453 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
67454}
67455
67456function Gamma0l (x, xl) {
67457 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
67458}
67459
67460function Gamma1 (x, xl) {
67461 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
67462}
67463
67464function Gamma1l (x, xl) {
67465 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
67466}
67467
67468function getCarry (a, b) {
67469 return (a >>> 0) < (b >>> 0) ? 1 : 0
67470}
67471
67472Sha512.prototype._update = function (M) {
67473 var W = this._w
67474
67475 var ah = this._ah | 0
67476 var bh = this._bh | 0
67477 var ch = this._ch | 0
67478 var dh = this._dh | 0
67479 var eh = this._eh | 0
67480 var fh = this._fh | 0
67481 var gh = this._gh | 0
67482 var hh = this._hh | 0
67483
67484 var al = this._al | 0
67485 var bl = this._bl | 0
67486 var cl = this._cl | 0
67487 var dl = this._dl | 0
67488 var el = this._el | 0
67489 var fl = this._fl | 0
67490 var gl = this._gl | 0
67491 var hl = this._hl | 0
67492
67493 for (var i = 0; i < 32; i += 2) {
67494 W[i] = M.readInt32BE(i * 4)
67495 W[i + 1] = M.readInt32BE(i * 4 + 4)
67496 }
67497 for (; i < 160; i += 2) {
67498 var xh = W[i - 15 * 2]
67499 var xl = W[i - 15 * 2 + 1]
67500 var gamma0 = Gamma0(xh, xl)
67501 var gamma0l = Gamma0l(xl, xh)
67502
67503 xh = W[i - 2 * 2]
67504 xl = W[i - 2 * 2 + 1]
67505 var gamma1 = Gamma1(xh, xl)
67506 var gamma1l = Gamma1l(xl, xh)
67507
67508 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
67509 var Wi7h = W[i - 7 * 2]
67510 var Wi7l = W[i - 7 * 2 + 1]
67511
67512 var Wi16h = W[i - 16 * 2]
67513 var Wi16l = W[i - 16 * 2 + 1]
67514
67515 var Wil = (gamma0l + Wi7l) | 0
67516 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
67517 Wil = (Wil + gamma1l) | 0
67518 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
67519 Wil = (Wil + Wi16l) | 0
67520 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
67521
67522 W[i] = Wih
67523 W[i + 1] = Wil
67524 }
67525
67526 for (var j = 0; j < 160; j += 2) {
67527 Wih = W[j]
67528 Wil = W[j + 1]
67529
67530 var majh = maj(ah, bh, ch)
67531 var majl = maj(al, bl, cl)
67532
67533 var sigma0h = sigma0(ah, al)
67534 var sigma0l = sigma0(al, ah)
67535 var sigma1h = sigma1(eh, el)
67536 var sigma1l = sigma1(el, eh)
67537
67538 // t1 = h + sigma1 + ch + K[j] + W[j]
67539 var Kih = K[j]
67540 var Kil = K[j + 1]
67541
67542 var chh = Ch(eh, fh, gh)
67543 var chl = Ch(el, fl, gl)
67544
67545 var t1l = (hl + sigma1l) | 0
67546 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
67547 t1l = (t1l + chl) | 0
67548 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
67549 t1l = (t1l + Kil) | 0
67550 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
67551 t1l = (t1l + Wil) | 0
67552 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
67553
67554 // t2 = sigma0 + maj
67555 var t2l = (sigma0l + majl) | 0
67556 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
67557
67558 hh = gh
67559 hl = gl
67560 gh = fh
67561 gl = fl
67562 fh = eh
67563 fl = el
67564 el = (dl + t1l) | 0
67565 eh = (dh + t1h + getCarry(el, dl)) | 0
67566 dh = ch
67567 dl = cl
67568 ch = bh
67569 cl = bl
67570 bh = ah
67571 bl = al
67572 al = (t1l + t2l) | 0
67573 ah = (t1h + t2h + getCarry(al, t1l)) | 0
67574 }
67575
67576 this._al = (this._al + al) | 0
67577 this._bl = (this._bl + bl) | 0
67578 this._cl = (this._cl + cl) | 0
67579 this._dl = (this._dl + dl) | 0
67580 this._el = (this._el + el) | 0
67581 this._fl = (this._fl + fl) | 0
67582 this._gl = (this._gl + gl) | 0
67583 this._hl = (this._hl + hl) | 0
67584
67585 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
67586 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
67587 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
67588 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
67589 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
67590 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
67591 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
67592 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
67593}
67594
67595Sha512.prototype._hash = function () {
67596 var H = Buffer.allocUnsafe(64)
67597
67598 function writeInt64BE (h, l, offset) {
67599 H.writeInt32BE(h, offset)
67600 H.writeInt32BE(l, offset + 4)
67601 }
67602
67603 writeInt64BE(this._ah, this._al, 0)
67604 writeInt64BE(this._bh, this._bl, 8)
67605 writeInt64BE(this._ch, this._cl, 16)
67606 writeInt64BE(this._dh, this._dl, 24)
67607 writeInt64BE(this._eh, this._el, 32)
67608 writeInt64BE(this._fh, this._fl, 40)
67609 writeInt64BE(this._gh, this._gl, 48)
67610 writeInt64BE(this._hh, this._hl, 56)
67611
67612 return H
67613}
67614
67615module.exports = Sha512
67616
67617},{"./hash":327,"inherits":210,"safe-buffer":325}],335:[function(require,module,exports){
67618// Copyright 2015 Joyent, Inc.
67619
67620var Buffer = require('safer-buffer').Buffer;
67621
67622var algInfo = {
67623 'dsa': {
67624 parts: ['p', 'q', 'g', 'y'],
67625 sizePart: 'p'
67626 },
67627 'rsa': {
67628 parts: ['e', 'n'],
67629 sizePart: 'n'
67630 },
67631 'ecdsa': {
67632 parts: ['curve', 'Q'],
67633 sizePart: 'Q'
67634 },
67635 'ed25519': {
67636 parts: ['A'],
67637 sizePart: 'A'
67638 }
67639};
67640algInfo['curve25519'] = algInfo['ed25519'];
67641
67642var algPrivInfo = {
67643 'dsa': {
67644 parts: ['p', 'q', 'g', 'y', 'x']
67645 },
67646 'rsa': {
67647 parts: ['n', 'e', 'd', 'iqmp', 'p', 'q']
67648 },
67649 'ecdsa': {
67650 parts: ['curve', 'Q', 'd']
67651 },
67652 'ed25519': {
67653 parts: ['A', 'k']
67654 }
67655};
67656algPrivInfo['curve25519'] = algPrivInfo['ed25519'];
67657
67658var hashAlgs = {
67659 'md5': true,
67660 'sha1': true,
67661 'sha256': true,
67662 'sha384': true,
67663 'sha512': true
67664};
67665
67666/*
67667 * Taken from
67668 * http://csrc.nist.gov/groups/ST/toolkit/documents/dss/NISTReCur.pdf
67669 */
67670var curves = {
67671 'nistp256': {
67672 size: 256,
67673 pkcs8oid: '1.2.840.10045.3.1.7',
67674 p: Buffer.from(('00' +
67675 'ffffffff 00000001 00000000 00000000' +
67676 '00000000 ffffffff ffffffff ffffffff').
67677 replace(/ /g, ''), 'hex'),
67678 a: Buffer.from(('00' +
67679 'FFFFFFFF 00000001 00000000 00000000' +
67680 '00000000 FFFFFFFF FFFFFFFF FFFFFFFC').
67681 replace(/ /g, ''), 'hex'),
67682 b: Buffer.from((
67683 '5ac635d8 aa3a93e7 b3ebbd55 769886bc' +
67684 '651d06b0 cc53b0f6 3bce3c3e 27d2604b').
67685 replace(/ /g, ''), 'hex'),
67686 s: Buffer.from(('00' +
67687 'c49d3608 86e70493 6a6678e1 139d26b7' +
67688 '819f7e90').
67689 replace(/ /g, ''), 'hex'),
67690 n: Buffer.from(('00' +
67691 'ffffffff 00000000 ffffffff ffffffff' +
67692 'bce6faad a7179e84 f3b9cac2 fc632551').
67693 replace(/ /g, ''), 'hex'),
67694 G: Buffer.from(('04' +
67695 '6b17d1f2 e12c4247 f8bce6e5 63a440f2' +
67696 '77037d81 2deb33a0 f4a13945 d898c296' +
67697 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16' +
67698 '2bce3357 6b315ece cbb64068 37bf51f5').
67699 replace(/ /g, ''), 'hex')
67700 },
67701 'nistp384': {
67702 size: 384,
67703 pkcs8oid: '1.3.132.0.34',
67704 p: Buffer.from(('00' +
67705 'ffffffff ffffffff ffffffff ffffffff' +
67706 'ffffffff ffffffff ffffffff fffffffe' +
67707 'ffffffff 00000000 00000000 ffffffff').
67708 replace(/ /g, ''), 'hex'),
67709 a: Buffer.from(('00' +
67710 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
67711 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE' +
67712 'FFFFFFFF 00000000 00000000 FFFFFFFC').
67713 replace(/ /g, ''), 'hex'),
67714 b: Buffer.from((
67715 'b3312fa7 e23ee7e4 988e056b e3f82d19' +
67716 '181d9c6e fe814112 0314088f 5013875a' +
67717 'c656398d 8a2ed19d 2a85c8ed d3ec2aef').
67718 replace(/ /g, ''), 'hex'),
67719 s: Buffer.from(('00' +
67720 'a335926a a319a27a 1d00896a 6773a482' +
67721 '7acdac73').
67722 replace(/ /g, ''), 'hex'),
67723 n: Buffer.from(('00' +
67724 'ffffffff ffffffff ffffffff ffffffff' +
67725 'ffffffff ffffffff c7634d81 f4372ddf' +
67726 '581a0db2 48b0a77a ecec196a ccc52973').
67727 replace(/ /g, ''), 'hex'),
67728 G: Buffer.from(('04' +
67729 'aa87ca22 be8b0537 8eb1c71e f320ad74' +
67730 '6e1d3b62 8ba79b98 59f741e0 82542a38' +
67731 '5502f25d bf55296c 3a545e38 72760ab7' +
67732 '3617de4a 96262c6f 5d9e98bf 9292dc29' +
67733 'f8f41dbd 289a147c e9da3113 b5f0b8c0' +
67734 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f').
67735 replace(/ /g, ''), 'hex')
67736 },
67737 'nistp521': {
67738 size: 521,
67739 pkcs8oid: '1.3.132.0.35',
67740 p: Buffer.from((
67741 '01ffffff ffffffff ffffffff ffffffff' +
67742 'ffffffff ffffffff ffffffff ffffffff' +
67743 'ffffffff ffffffff ffffffff ffffffff' +
67744 'ffffffff ffffffff ffffffff ffffffff' +
67745 'ffff').replace(/ /g, ''), 'hex'),
67746 a: Buffer.from(('01FF' +
67747 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
67748 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
67749 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFF' +
67750 'FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFC').
67751 replace(/ /g, ''), 'hex'),
67752 b: Buffer.from(('51' +
67753 '953eb961 8e1c9a1f 929a21a0 b68540ee' +
67754 'a2da725b 99b315f3 b8b48991 8ef109e1' +
67755 '56193951 ec7e937b 1652c0bd 3bb1bf07' +
67756 '3573df88 3d2c34f1 ef451fd4 6b503f00').
67757 replace(/ /g, ''), 'hex'),
67758 s: Buffer.from(('00' +
67759 'd09e8800 291cb853 96cc6717 393284aa' +
67760 'a0da64ba').replace(/ /g, ''), 'hex'),
67761 n: Buffer.from(('01ff' +
67762 'ffffffff ffffffff ffffffff ffffffff' +
67763 'ffffffff ffffffff ffffffff fffffffa' +
67764 '51868783 bf2f966b 7fcc0148 f709a5d0' +
67765 '3bb5c9b8 899c47ae bb6fb71e 91386409').
67766 replace(/ /g, ''), 'hex'),
67767 G: Buffer.from(('04' +
67768 '00c6 858e06b7 0404e9cd 9e3ecb66 2395b442' +
67769 '9c648139 053fb521 f828af60 6b4d3dba' +
67770 'a14b5e77 efe75928 fe1dc127 a2ffa8de' +
67771 '3348b3c1 856a429b f97e7e31 c2e5bd66' +
67772 '0118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9' +
67773 '98f54449 579b4468 17afbd17 273e662c' +
67774 '97ee7299 5ef42640 c550b901 3fad0761' +
67775 '353c7086 a272c240 88be9476 9fd16650').
67776 replace(/ /g, ''), 'hex')
67777 }
67778};
67779
67780module.exports = {
67781 info: algInfo,
67782 privInfo: algPrivInfo,
67783 hashAlgs: hashAlgs,
67784 curves: curves
67785};
67786
67787},{"safer-buffer":326}],336:[function(require,module,exports){
67788// Copyright 2016 Joyent, Inc.
67789
67790module.exports = Certificate;
67791
67792var assert = require('assert-plus');
67793var Buffer = require('safer-buffer').Buffer;
67794var algs = require('./algs');
67795var crypto = require('crypto');
67796var Fingerprint = require('./fingerprint');
67797var Signature = require('./signature');
67798var errs = require('./errors');
67799var util = require('util');
67800var utils = require('./utils');
67801var Key = require('./key');
67802var PrivateKey = require('./private-key');
67803var Identity = require('./identity');
67804
67805var formats = {};
67806formats['openssh'] = require('./formats/openssh-cert');
67807formats['x509'] = require('./formats/x509');
67808formats['pem'] = require('./formats/x509-pem');
67809
67810var CertificateParseError = errs.CertificateParseError;
67811var InvalidAlgorithmError = errs.InvalidAlgorithmError;
67812
67813function Certificate(opts) {
67814 assert.object(opts, 'options');
67815 assert.arrayOfObject(opts.subjects, 'options.subjects');
67816 utils.assertCompatible(opts.subjects[0], Identity, [1, 0],
67817 'options.subjects');
67818 utils.assertCompatible(opts.subjectKey, Key, [1, 0],
67819 'options.subjectKey');
67820 utils.assertCompatible(opts.issuer, Identity, [1, 0], 'options.issuer');
67821 if (opts.issuerKey !== undefined) {
67822 utils.assertCompatible(opts.issuerKey, Key, [1, 0],
67823 'options.issuerKey');
67824 }
67825 assert.object(opts.signatures, 'options.signatures');
67826 assert.buffer(opts.serial, 'options.serial');
67827 assert.date(opts.validFrom, 'options.validFrom');
67828 assert.date(opts.validUntil, 'optons.validUntil');
67829
67830 assert.optionalArrayOfString(opts.purposes, 'options.purposes');
67831
67832 this._hashCache = {};
67833
67834 this.subjects = opts.subjects;
67835 this.issuer = opts.issuer;
67836 this.subjectKey = opts.subjectKey;
67837 this.issuerKey = opts.issuerKey;
67838 this.signatures = opts.signatures;
67839 this.serial = opts.serial;
67840 this.validFrom = opts.validFrom;
67841 this.validUntil = opts.validUntil;
67842 this.purposes = opts.purposes;
67843}
67844
67845Certificate.formats = formats;
67846
67847Certificate.prototype.toBuffer = function (format, options) {
67848 if (format === undefined)
67849 format = 'x509';
67850 assert.string(format, 'format');
67851 assert.object(formats[format], 'formats[format]');
67852 assert.optionalObject(options, 'options');
67853
67854 return (formats[format].write(this, options));
67855};
67856
67857Certificate.prototype.toString = function (format, options) {
67858 if (format === undefined)
67859 format = 'pem';
67860 return (this.toBuffer(format, options).toString());
67861};
67862
67863Certificate.prototype.fingerprint = function (algo) {
67864 if (algo === undefined)
67865 algo = 'sha256';
67866 assert.string(algo, 'algorithm');
67867 var opts = {
67868 type: 'certificate',
67869 hash: this.hash(algo),
67870 algorithm: algo
67871 };
67872 return (new Fingerprint(opts));
67873};
67874
67875Certificate.prototype.hash = function (algo) {
67876 assert.string(algo, 'algorithm');
67877 algo = algo.toLowerCase();
67878 if (algs.hashAlgs[algo] === undefined)
67879 throw (new InvalidAlgorithmError(algo));
67880
67881 if (this._hashCache[algo])
67882 return (this._hashCache[algo]);
67883
67884 var hash = crypto.createHash(algo).
67885 update(this.toBuffer('x509')).digest();
67886 this._hashCache[algo] = hash;
67887 return (hash);
67888};
67889
67890Certificate.prototype.isExpired = function (when) {
67891 if (when === undefined)
67892 when = new Date();
67893 return (!((when.getTime() >= this.validFrom.getTime()) &&
67894 (when.getTime() < this.validUntil.getTime())));
67895};
67896
67897Certificate.prototype.isSignedBy = function (issuerCert) {
67898 utils.assertCompatible(issuerCert, Certificate, [1, 0], 'issuer');
67899
67900 if (!this.issuer.equals(issuerCert.subjects[0]))
67901 return (false);
67902 if (this.issuer.purposes && this.issuer.purposes.length > 0 &&
67903 this.issuer.purposes.indexOf('ca') === -1) {
67904 return (false);
67905 }
67906
67907 return (this.isSignedByKey(issuerCert.subjectKey));
67908};
67909
67910Certificate.prototype.getExtension = function (keyOrOid) {
67911 assert.string(keyOrOid, 'keyOrOid');
67912 var ext = this.getExtensions().filter(function (maybeExt) {
67913 if (maybeExt.format === 'x509')
67914 return (maybeExt.oid === keyOrOid);
67915 if (maybeExt.format === 'openssh')
67916 return (maybeExt.name === keyOrOid);
67917 return (false);
67918 })[0];
67919 return (ext);
67920};
67921
67922Certificate.prototype.getExtensions = function () {
67923 var exts = [];
67924 var x509 = this.signatures.x509;
67925 if (x509 && x509.extras && x509.extras.exts) {
67926 x509.extras.exts.forEach(function (ext) {
67927 ext.format = 'x509';
67928 exts.push(ext);
67929 });
67930 }
67931 var openssh = this.signatures.openssh;
67932 if (openssh && openssh.exts) {
67933 openssh.exts.forEach(function (ext) {
67934 ext.format = 'openssh';
67935 exts.push(ext);
67936 });
67937 }
67938 return (exts);
67939};
67940
67941Certificate.prototype.isSignedByKey = function (issuerKey) {
67942 utils.assertCompatible(issuerKey, Key, [1, 2], 'issuerKey');
67943
67944 if (this.issuerKey !== undefined) {
67945 return (this.issuerKey.
67946 fingerprint('sha512').matches(issuerKey));
67947 }
67948
67949 var fmt = Object.keys(this.signatures)[0];
67950 var valid = formats[fmt].verify(this, issuerKey);
67951 if (valid)
67952 this.issuerKey = issuerKey;
67953 return (valid);
67954};
67955
67956Certificate.prototype.signWith = function (key) {
67957 utils.assertCompatible(key, PrivateKey, [1, 2], 'key');
67958 var fmts = Object.keys(formats);
67959 var didOne = false;
67960 for (var i = 0; i < fmts.length; ++i) {
67961 if (fmts[i] !== 'pem') {
67962 var ret = formats[fmts[i]].sign(this, key);
67963 if (ret === true)
67964 didOne = true;
67965 }
67966 }
67967 if (!didOne) {
67968 throw (new Error('Failed to sign the certificate for any ' +
67969 'available certificate formats'));
67970 }
67971};
67972
67973Certificate.createSelfSigned = function (subjectOrSubjects, key, options) {
67974 var subjects;
67975 if (Array.isArray(subjectOrSubjects))
67976 subjects = subjectOrSubjects;
67977 else
67978 subjects = [subjectOrSubjects];
67979
67980 assert.arrayOfObject(subjects);
67981 subjects.forEach(function (subject) {
67982 utils.assertCompatible(subject, Identity, [1, 0], 'subject');
67983 });
67984
67985 utils.assertCompatible(key, PrivateKey, [1, 2], 'private key');
67986
67987 assert.optionalObject(options, 'options');
67988 if (options === undefined)
67989 options = {};
67990 assert.optionalObject(options.validFrom, 'options.validFrom');
67991 assert.optionalObject(options.validUntil, 'options.validUntil');
67992 var validFrom = options.validFrom;
67993 var validUntil = options.validUntil;
67994 if (validFrom === undefined)
67995 validFrom = new Date();
67996 if (validUntil === undefined) {
67997 assert.optionalNumber(options.lifetime, 'options.lifetime');
67998 var lifetime = options.lifetime;
67999 if (lifetime === undefined)
68000 lifetime = 10*365*24*3600;
68001 validUntil = new Date();
68002 validUntil.setTime(validUntil.getTime() + lifetime*1000);
68003 }
68004 assert.optionalBuffer(options.serial, 'options.serial');
68005 var serial = options.serial;
68006 if (serial === undefined)
68007 serial = Buffer.from('0000000000000001', 'hex');
68008
68009 var purposes = options.purposes;
68010 if (purposes === undefined)
68011 purposes = [];
68012
68013 if (purposes.indexOf('signature') === -1)
68014 purposes.push('signature');
68015
68016 /* Self-signed certs are always CAs. */
68017 if (purposes.indexOf('ca') === -1)
68018 purposes.push('ca');
68019 if (purposes.indexOf('crl') === -1)
68020 purposes.push('crl');
68021
68022 /*
68023 * If we weren't explicitly given any other purposes, do the sensible
68024 * thing and add some basic ones depending on the subject type.
68025 */
68026 if (purposes.length <= 3) {
68027 var hostSubjects = subjects.filter(function (subject) {
68028 return (subject.type === 'host');
68029 });
68030 var userSubjects = subjects.filter(function (subject) {
68031 return (subject.type === 'user');
68032 });
68033 if (hostSubjects.length > 0) {
68034 if (purposes.indexOf('serverAuth') === -1)
68035 purposes.push('serverAuth');
68036 }
68037 if (userSubjects.length > 0) {
68038 if (purposes.indexOf('clientAuth') === -1)
68039 purposes.push('clientAuth');
68040 }
68041 if (userSubjects.length > 0 || hostSubjects.length > 0) {
68042 if (purposes.indexOf('keyAgreement') === -1)
68043 purposes.push('keyAgreement');
68044 if (key.type === 'rsa' &&
68045 purposes.indexOf('encryption') === -1)
68046 purposes.push('encryption');
68047 }
68048 }
68049
68050 var cert = new Certificate({
68051 subjects: subjects,
68052 issuer: subjects[0],
68053 subjectKey: key.toPublic(),
68054 issuerKey: key.toPublic(),
68055 signatures: {},
68056 serial: serial,
68057 validFrom: validFrom,
68058 validUntil: validUntil,
68059 purposes: purposes
68060 });
68061 cert.signWith(key);
68062
68063 return (cert);
68064};
68065
68066Certificate.create =
68067 function (subjectOrSubjects, key, issuer, issuerKey, options) {
68068 var subjects;
68069 if (Array.isArray(subjectOrSubjects))
68070 subjects = subjectOrSubjects;
68071 else
68072 subjects = [subjectOrSubjects];
68073
68074 assert.arrayOfObject(subjects);
68075 subjects.forEach(function (subject) {
68076 utils.assertCompatible(subject, Identity, [1, 0], 'subject');
68077 });
68078
68079 utils.assertCompatible(key, Key, [1, 0], 'key');
68080 if (PrivateKey.isPrivateKey(key))
68081 key = key.toPublic();
68082 utils.assertCompatible(issuer, Identity, [1, 0], 'issuer');
68083 utils.assertCompatible(issuerKey, PrivateKey, [1, 2], 'issuer key');
68084
68085 assert.optionalObject(options, 'options');
68086 if (options === undefined)
68087 options = {};
68088 assert.optionalObject(options.validFrom, 'options.validFrom');
68089 assert.optionalObject(options.validUntil, 'options.validUntil');
68090 var validFrom = options.validFrom;
68091 var validUntil = options.validUntil;
68092 if (validFrom === undefined)
68093 validFrom = new Date();
68094 if (validUntil === undefined) {
68095 assert.optionalNumber(options.lifetime, 'options.lifetime');
68096 var lifetime = options.lifetime;
68097 if (lifetime === undefined)
68098 lifetime = 10*365*24*3600;
68099 validUntil = new Date();
68100 validUntil.setTime(validUntil.getTime() + lifetime*1000);
68101 }
68102 assert.optionalBuffer(options.serial, 'options.serial');
68103 var serial = options.serial;
68104 if (serial === undefined)
68105 serial = Buffer.from('0000000000000001', 'hex');
68106
68107 var purposes = options.purposes;
68108 if (purposes === undefined)
68109 purposes = [];
68110
68111 if (purposes.indexOf('signature') === -1)
68112 purposes.push('signature');
68113
68114 if (options.ca === true) {
68115 if (purposes.indexOf('ca') === -1)
68116 purposes.push('ca');
68117 if (purposes.indexOf('crl') === -1)
68118 purposes.push('crl');
68119 }
68120
68121 var hostSubjects = subjects.filter(function (subject) {
68122 return (subject.type === 'host');
68123 });
68124 var userSubjects = subjects.filter(function (subject) {
68125 return (subject.type === 'user');
68126 });
68127 if (hostSubjects.length > 0) {
68128 if (purposes.indexOf('serverAuth') === -1)
68129 purposes.push('serverAuth');
68130 }
68131 if (userSubjects.length > 0) {
68132 if (purposes.indexOf('clientAuth') === -1)
68133 purposes.push('clientAuth');
68134 }
68135 if (userSubjects.length > 0 || hostSubjects.length > 0) {
68136 if (purposes.indexOf('keyAgreement') === -1)
68137 purposes.push('keyAgreement');
68138 if (key.type === 'rsa' &&
68139 purposes.indexOf('encryption') === -1)
68140 purposes.push('encryption');
68141 }
68142
68143 var cert = new Certificate({
68144 subjects: subjects,
68145 issuer: issuer,
68146 subjectKey: key,
68147 issuerKey: issuerKey.toPublic(),
68148 signatures: {},
68149 serial: serial,
68150 validFrom: validFrom,
68151 validUntil: validUntil,
68152 purposes: purposes
68153 });
68154 cert.signWith(issuerKey);
68155
68156 return (cert);
68157};
68158
68159Certificate.parse = function (data, format, options) {
68160 if (typeof (data) !== 'string')
68161 assert.buffer(data, 'data');
68162 if (format === undefined)
68163 format = 'auto';
68164 assert.string(format, 'format');
68165 if (typeof (options) === 'string')
68166 options = { filename: options };
68167 assert.optionalObject(options, 'options');
68168 if (options === undefined)
68169 options = {};
68170 assert.optionalString(options.filename, 'options.filename');
68171 if (options.filename === undefined)
68172 options.filename = '(unnamed)';
68173
68174 assert.object(formats[format], 'formats[format]');
68175
68176 try {
68177 var k = formats[format].read(data, options);
68178 return (k);
68179 } catch (e) {
68180 throw (new CertificateParseError(options.filename, format, e));
68181 }
68182};
68183
68184Certificate.isCertificate = function (obj, ver) {
68185 return (utils.isCompatible(obj, Certificate, ver));
68186};
68187
68188/*
68189 * API versions for Certificate:
68190 * [1,0] -- initial ver
68191 * [1,1] -- openssh format now unpacks extensions
68192 */
68193Certificate.prototype._sshpkApiVersion = [1, 1];
68194
68195Certificate._oldVersionDetect = function (obj) {
68196 return ([1, 0]);
68197};
68198
68199},{"./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){
68200// Copyright 2017 Joyent, Inc.
68201
68202module.exports = {
68203 DiffieHellman: DiffieHellman,
68204 generateECDSA: generateECDSA,
68205 generateED25519: generateED25519
68206};
68207
68208var assert = require('assert-plus');
68209var crypto = require('crypto');
68210var Buffer = require('safer-buffer').Buffer;
68211var algs = require('./algs');
68212var utils = require('./utils');
68213var nacl = require('tweetnacl');
68214
68215var Key = require('./key');
68216var PrivateKey = require('./private-key');
68217
68218var CRYPTO_HAVE_ECDH = (crypto.createECDH !== undefined);
68219
68220var ecdh = require('ecc-jsbn');
68221var ec = require('ecc-jsbn/lib/ec');
68222var jsbn = require('jsbn').BigInteger;
68223
68224function DiffieHellman(key) {
68225 utils.assertCompatible(key, Key, [1, 4], 'key');
68226 this._isPriv = PrivateKey.isPrivateKey(key, [1, 3]);
68227 this._algo = key.type;
68228 this._curve = key.curve;
68229 this._key = key;
68230 if (key.type === 'dsa') {
68231 if (!CRYPTO_HAVE_ECDH) {
68232 throw (new Error('Due to bugs in the node 0.10 ' +
68233 'crypto API, node 0.12.x or later is required ' +
68234 'to use DH'));
68235 }
68236 this._dh = crypto.createDiffieHellman(
68237 key.part.p.data, undefined,
68238 key.part.g.data, undefined);
68239 this._p = key.part.p;
68240 this._g = key.part.g;
68241 if (this._isPriv)
68242 this._dh.setPrivateKey(key.part.x.data);
68243 this._dh.setPublicKey(key.part.y.data);
68244
68245 } else if (key.type === 'ecdsa') {
68246 if (!CRYPTO_HAVE_ECDH) {
68247 this._ecParams = new X9ECParameters(this._curve);
68248
68249 if (this._isPriv) {
68250 this._priv = new ECPrivate(
68251 this._ecParams, key.part.d.data);
68252 }
68253 return;
68254 }
68255
68256 var curve = {
68257 'nistp256': 'prime256v1',
68258 'nistp384': 'secp384r1',
68259 'nistp521': 'secp521r1'
68260 }[key.curve];
68261 this._dh = crypto.createECDH(curve);
68262 if (typeof (this._dh) !== 'object' ||
68263 typeof (this._dh.setPrivateKey) !== 'function') {
68264 CRYPTO_HAVE_ECDH = false;
68265 DiffieHellman.call(this, key);
68266 return;
68267 }
68268 if (this._isPriv)
68269 this._dh.setPrivateKey(key.part.d.data);
68270 this._dh.setPublicKey(key.part.Q.data);
68271
68272 } else if (key.type === 'curve25519') {
68273 if (this._isPriv) {
68274 utils.assertCompatible(key, PrivateKey, [1, 5], 'key');
68275 this._priv = key.part.k.data;
68276 }
68277
68278 } else {
68279 throw (new Error('DH not supported for ' + key.type + ' keys'));
68280 }
68281}
68282
68283DiffieHellman.prototype.getPublicKey = function () {
68284 if (this._isPriv)
68285 return (this._key.toPublic());
68286 return (this._key);
68287};
68288
68289DiffieHellman.prototype.getPrivateKey = function () {
68290 if (this._isPriv)
68291 return (this._key);
68292 else
68293 return (undefined);
68294};
68295DiffieHellman.prototype.getKey = DiffieHellman.prototype.getPrivateKey;
68296
68297DiffieHellman.prototype._keyCheck = function (pk, isPub) {
68298 assert.object(pk, 'key');
68299 if (!isPub)
68300 utils.assertCompatible(pk, PrivateKey, [1, 3], 'key');
68301 utils.assertCompatible(pk, Key, [1, 4], 'key');
68302
68303 if (pk.type !== this._algo) {
68304 throw (new Error('A ' + pk.type + ' key cannot be used in ' +
68305 this._algo + ' Diffie-Hellman'));
68306 }
68307
68308 if (pk.curve !== this._curve) {
68309 throw (new Error('A key from the ' + pk.curve + ' curve ' +
68310 'cannot be used with a ' + this._curve +
68311 ' Diffie-Hellman'));
68312 }
68313
68314 if (pk.type === 'dsa') {
68315 assert.deepEqual(pk.part.p, this._p,
68316 'DSA key prime does not match');
68317 assert.deepEqual(pk.part.g, this._g,
68318 'DSA key generator does not match');
68319 }
68320};
68321
68322DiffieHellman.prototype.setKey = function (pk) {
68323 this._keyCheck(pk);
68324
68325 if (pk.type === 'dsa') {
68326 this._dh.setPrivateKey(pk.part.x.data);
68327 this._dh.setPublicKey(pk.part.y.data);
68328
68329 } else if (pk.type === 'ecdsa') {
68330 if (CRYPTO_HAVE_ECDH) {
68331 this._dh.setPrivateKey(pk.part.d.data);
68332 this._dh.setPublicKey(pk.part.Q.data);
68333 } else {
68334 this._priv = new ECPrivate(
68335 this._ecParams, pk.part.d.data);
68336 }
68337
68338 } else if (pk.type === 'curve25519') {
68339 var k = pk.part.k;
68340 if (!pk.part.k)
68341 k = pk.part.r;
68342 this._priv = k.data;
68343 if (this._priv[0] === 0x00)
68344 this._priv = this._priv.slice(1);
68345 this._priv = this._priv.slice(0, 32);
68346 }
68347 this._key = pk;
68348 this._isPriv = true;
68349};
68350DiffieHellman.prototype.setPrivateKey = DiffieHellman.prototype.setKey;
68351
68352DiffieHellman.prototype.computeSecret = function (otherpk) {
68353 this._keyCheck(otherpk, true);
68354 if (!this._isPriv)
68355 throw (new Error('DH exchange has not been initialized with ' +
68356 'a private key yet'));
68357
68358 var pub;
68359 if (this._algo === 'dsa') {
68360 return (this._dh.computeSecret(
68361 otherpk.part.y.data));
68362
68363 } else if (this._algo === 'ecdsa') {
68364 if (CRYPTO_HAVE_ECDH) {
68365 return (this._dh.computeSecret(
68366 otherpk.part.Q.data));
68367 } else {
68368 pub = new ECPublic(
68369 this._ecParams, otherpk.part.Q.data);
68370 return (this._priv.deriveSharedSecret(pub));
68371 }
68372
68373 } else if (this._algo === 'curve25519') {
68374 pub = otherpk.part.A.data;
68375 while (pub[0] === 0x00 && pub.length > 32)
68376 pub = pub.slice(1);
68377 var priv = this._priv;
68378 assert.strictEqual(pub.length, 32);
68379 assert.strictEqual(priv.length, 32);
68380
68381 var secret = nacl.box.before(new Uint8Array(pub),
68382 new Uint8Array(priv));
68383
68384 return (Buffer.from(secret));
68385 }
68386
68387 throw (new Error('Invalid algorithm: ' + this._algo));
68388};
68389
68390DiffieHellman.prototype.generateKey = function () {
68391 var parts = [];
68392 var priv, pub;
68393 if (this._algo === 'dsa') {
68394 this._dh.generateKeys();
68395
68396 parts.push({name: 'p', data: this._p.data});
68397 parts.push({name: 'q', data: this._key.part.q.data});
68398 parts.push({name: 'g', data: this._g.data});
68399 parts.push({name: 'y', data: this._dh.getPublicKey()});
68400 parts.push({name: 'x', data: this._dh.getPrivateKey()});
68401 this._key = new PrivateKey({
68402 type: 'dsa',
68403 parts: parts
68404 });
68405 this._isPriv = true;
68406 return (this._key);
68407
68408 } else if (this._algo === 'ecdsa') {
68409 if (CRYPTO_HAVE_ECDH) {
68410 this._dh.generateKeys();
68411
68412 parts.push({name: 'curve',
68413 data: Buffer.from(this._curve)});
68414 parts.push({name: 'Q', data: this._dh.getPublicKey()});
68415 parts.push({name: 'd', data: this._dh.getPrivateKey()});
68416 this._key = new PrivateKey({
68417 type: 'ecdsa',
68418 curve: this._curve,
68419 parts: parts
68420 });
68421 this._isPriv = true;
68422 return (this._key);
68423
68424 } else {
68425 var n = this._ecParams.getN();
68426 var r = new jsbn(crypto.randomBytes(n.bitLength()));
68427 var n1 = n.subtract(jsbn.ONE);
68428 priv = r.mod(n1).add(jsbn.ONE);
68429 pub = this._ecParams.getG().multiply(priv);
68430
68431 priv = Buffer.from(priv.toByteArray());
68432 pub = Buffer.from(this._ecParams.getCurve().
68433 encodePointHex(pub), 'hex');
68434
68435 this._priv = new ECPrivate(this._ecParams, priv);
68436
68437 parts.push({name: 'curve',
68438 data: Buffer.from(this._curve)});
68439 parts.push({name: 'Q', data: pub});
68440 parts.push({name: 'd', data: priv});
68441
68442 this._key = new PrivateKey({
68443 type: 'ecdsa',
68444 curve: this._curve,
68445 parts: parts
68446 });
68447 this._isPriv = true;
68448 return (this._key);
68449 }
68450
68451 } else if (this._algo === 'curve25519') {
68452 var pair = nacl.box.keyPair();
68453 priv = Buffer.from(pair.secretKey);
68454 pub = Buffer.from(pair.publicKey);
68455 priv = Buffer.concat([priv, pub]);
68456 assert.strictEqual(priv.length, 64);
68457 assert.strictEqual(pub.length, 32);
68458
68459 parts.push({name: 'A', data: pub});
68460 parts.push({name: 'k', data: priv});
68461 this._key = new PrivateKey({
68462 type: 'curve25519',
68463 parts: parts
68464 });
68465 this._isPriv = true;
68466 return (this._key);
68467 }
68468
68469 throw (new Error('Invalid algorithm: ' + this._algo));
68470};
68471DiffieHellman.prototype.generateKeys = DiffieHellman.prototype.generateKey;
68472
68473/* These are helpers for using ecc-jsbn (for node 0.10 compatibility). */
68474
68475function X9ECParameters(name) {
68476 var params = algs.curves[name];
68477 assert.object(params);
68478
68479 var p = new jsbn(params.p);
68480 var a = new jsbn(params.a);
68481 var b = new jsbn(params.b);
68482 var n = new jsbn(params.n);
68483 var h = jsbn.ONE;
68484 var curve = new ec.ECCurveFp(p, a, b);
68485 var G = curve.decodePointHex(params.G.toString('hex'));
68486
68487 this.curve = curve;
68488 this.g = G;
68489 this.n = n;
68490 this.h = h;
68491}
68492X9ECParameters.prototype.getCurve = function () { return (this.curve); };
68493X9ECParameters.prototype.getG = function () { return (this.g); };
68494X9ECParameters.prototype.getN = function () { return (this.n); };
68495X9ECParameters.prototype.getH = function () { return (this.h); };
68496
68497function ECPublic(params, buffer) {
68498 this._params = params;
68499 if (buffer[0] === 0x00)
68500 buffer = buffer.slice(1);
68501 this._pub = params.getCurve().decodePointHex(buffer.toString('hex'));
68502}
68503
68504function ECPrivate(params, buffer) {
68505 this._params = params;
68506 this._priv = new jsbn(utils.mpNormalize(buffer));
68507}
68508ECPrivate.prototype.deriveSharedSecret = function (pubKey) {
68509 assert.ok(pubKey instanceof ECPublic);
68510 var S = pubKey._pub.multiply(this._priv);
68511 return (Buffer.from(S.getX().toBigInteger().toByteArray()));
68512};
68513
68514function generateED25519() {
68515 var pair = nacl.sign.keyPair();
68516 var priv = Buffer.from(pair.secretKey);
68517 var pub = Buffer.from(pair.publicKey);
68518 assert.strictEqual(priv.length, 64);
68519 assert.strictEqual(pub.length, 32);
68520
68521 var parts = [];
68522 parts.push({name: 'A', data: pub});
68523 parts.push({name: 'k', data: priv.slice(0, 32)});
68524 var key = new PrivateKey({
68525 type: 'ed25519',
68526 parts: parts
68527 });
68528 return (key);
68529}
68530
68531/* Generates a new ECDSA private key on a given curve. */
68532function generateECDSA(curve) {
68533 var parts = [];
68534 var key;
68535
68536 if (CRYPTO_HAVE_ECDH) {
68537 /*
68538 * Node crypto doesn't expose key generation directly, but the
68539 * ECDH instances can generate keys. It turns out this just
68540 * calls into the OpenSSL generic key generator, and we can
68541 * read its output happily without doing an actual DH. So we
68542 * use that here.
68543 */
68544 var osCurve = {
68545 'nistp256': 'prime256v1',
68546 'nistp384': 'secp384r1',
68547 'nistp521': 'secp521r1'
68548 }[curve];
68549
68550 var dh = crypto.createECDH(osCurve);
68551 dh.generateKeys();
68552
68553 parts.push({name: 'curve',
68554 data: Buffer.from(curve)});
68555 parts.push({name: 'Q', data: dh.getPublicKey()});
68556 parts.push({name: 'd', data: dh.getPrivateKey()});
68557
68558 key = new PrivateKey({
68559 type: 'ecdsa',
68560 curve: curve,
68561 parts: parts
68562 });
68563 return (key);
68564 } else {
68565
68566 var ecParams = new X9ECParameters(curve);
68567
68568 /* This algorithm taken from FIPS PUB 186-4 (section B.4.1) */
68569 var n = ecParams.getN();
68570 /*
68571 * The crypto.randomBytes() function can only give us whole
68572 * bytes, so taking a nod from X9.62, we round up.
68573 */
68574 var cByteLen = Math.ceil((n.bitLength() + 64) / 8);
68575 var c = new jsbn(crypto.randomBytes(cByteLen));
68576
68577 var n1 = n.subtract(jsbn.ONE);
68578 var priv = c.mod(n1).add(jsbn.ONE);
68579 var pub = ecParams.getG().multiply(priv);
68580
68581 priv = Buffer.from(priv.toByteArray());
68582 pub = Buffer.from(ecParams.getCurve().
68583 encodePointHex(pub), 'hex');
68584
68585 parts.push({name: 'curve', data: Buffer.from(curve)});
68586 parts.push({name: 'Q', data: pub});
68587 parts.push({name: 'd', data: priv});
68588
68589 key = new PrivateKey({
68590 type: 'ecdsa',
68591 curve: curve,
68592 parts: parts
68593 });
68594 return (key);
68595 }
68596}
68597
68598},{"./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){
68599// Copyright 2015 Joyent, Inc.
68600
68601module.exports = {
68602 Verifier: Verifier,
68603 Signer: Signer
68604};
68605
68606var nacl = require('tweetnacl');
68607var stream = require('stream');
68608var util = require('util');
68609var assert = require('assert-plus');
68610var Buffer = require('safer-buffer').Buffer;
68611var Signature = require('./signature');
68612
68613function Verifier(key, hashAlgo) {
68614 if (hashAlgo.toLowerCase() !== 'sha512')
68615 throw (new Error('ED25519 only supports the use of ' +
68616 'SHA-512 hashes'));
68617
68618 this.key = key;
68619 this.chunks = [];
68620
68621 stream.Writable.call(this, {});
68622}
68623util.inherits(Verifier, stream.Writable);
68624
68625Verifier.prototype._write = function (chunk, enc, cb) {
68626 this.chunks.push(chunk);
68627 cb();
68628};
68629
68630Verifier.prototype.update = function (chunk) {
68631 if (typeof (chunk) === 'string')
68632 chunk = Buffer.from(chunk, 'binary');
68633 this.chunks.push(chunk);
68634};
68635
68636Verifier.prototype.verify = function (signature, fmt) {
68637 var sig;
68638 if (Signature.isSignature(signature, [2, 0])) {
68639 if (signature.type !== 'ed25519')
68640 return (false);
68641 sig = signature.toBuffer('raw');
68642
68643 } else if (typeof (signature) === 'string') {
68644 sig = Buffer.from(signature, 'base64');
68645
68646 } else if (Signature.isSignature(signature, [1, 0])) {
68647 throw (new Error('signature was created by too old ' +
68648 'a version of sshpk and cannot be verified'));
68649 }
68650
68651 assert.buffer(sig);
68652 return (nacl.sign.detached.verify(
68653 new Uint8Array(Buffer.concat(this.chunks)),
68654 new Uint8Array(sig),
68655 new Uint8Array(this.key.part.A.data)));
68656};
68657
68658function Signer(key, hashAlgo) {
68659 if (hashAlgo.toLowerCase() !== 'sha512')
68660 throw (new Error('ED25519 only supports the use of ' +
68661 'SHA-512 hashes'));
68662
68663 this.key = key;
68664 this.chunks = [];
68665
68666 stream.Writable.call(this, {});
68667}
68668util.inherits(Signer, stream.Writable);
68669
68670Signer.prototype._write = function (chunk, enc, cb) {
68671 this.chunks.push(chunk);
68672 cb();
68673};
68674
68675Signer.prototype.update = function (chunk) {
68676 if (typeof (chunk) === 'string')
68677 chunk = Buffer.from(chunk, 'binary');
68678 this.chunks.push(chunk);
68679};
68680
68681Signer.prototype.sign = function () {
68682 var sig = nacl.sign.detached(
68683 new Uint8Array(Buffer.concat(this.chunks)),
68684 new Uint8Array(Buffer.concat([
68685 this.key.part.k.data, this.key.part.A.data])));
68686 var sigBuf = Buffer.from(sig);
68687 var sigObj = Signature.parse(sigBuf, 'ed25519', 'raw');
68688 sigObj.hashAlgorithm = 'sha512';
68689 return (sigObj);
68690};
68691
68692},{"./signature":357,"assert-plus":67,"safer-buffer":326,"stream":361,"tweetnacl":391,"util":397}],339:[function(require,module,exports){
68693// Copyright 2015 Joyent, Inc.
68694
68695var assert = require('assert-plus');
68696var util = require('util');
68697
68698function FingerprintFormatError(fp, format) {
68699 if (Error.captureStackTrace)
68700 Error.captureStackTrace(this, FingerprintFormatError);
68701 this.name = 'FingerprintFormatError';
68702 this.fingerprint = fp;
68703 this.format = format;
68704 this.message = 'Fingerprint format is not supported, or is invalid: ';
68705 if (fp !== undefined)
68706 this.message += ' fingerprint = ' + fp;
68707 if (format !== undefined)
68708 this.message += ' format = ' + format;
68709}
68710util.inherits(FingerprintFormatError, Error);
68711
68712function InvalidAlgorithmError(alg) {
68713 if (Error.captureStackTrace)
68714 Error.captureStackTrace(this, InvalidAlgorithmError);
68715 this.name = 'InvalidAlgorithmError';
68716 this.algorithm = alg;
68717 this.message = 'Algorithm "' + alg + '" is not supported';
68718}
68719util.inherits(InvalidAlgorithmError, Error);
68720
68721function KeyParseError(name, format, innerErr) {
68722 if (Error.captureStackTrace)
68723 Error.captureStackTrace(this, KeyParseError);
68724 this.name = 'KeyParseError';
68725 this.format = format;
68726 this.keyName = name;
68727 this.innerErr = innerErr;
68728 this.message = 'Failed to parse ' + name + ' as a valid ' + format +
68729 ' format key: ' + innerErr.message;
68730}
68731util.inherits(KeyParseError, Error);
68732
68733function SignatureParseError(type, format, innerErr) {
68734 if (Error.captureStackTrace)
68735 Error.captureStackTrace(this, SignatureParseError);
68736 this.name = 'SignatureParseError';
68737 this.type = type;
68738 this.format = format;
68739 this.innerErr = innerErr;
68740 this.message = 'Failed to parse the given data as a ' + type +
68741 ' signature in ' + format + ' format: ' + innerErr.message;
68742}
68743util.inherits(SignatureParseError, Error);
68744
68745function CertificateParseError(name, format, innerErr) {
68746 if (Error.captureStackTrace)
68747 Error.captureStackTrace(this, CertificateParseError);
68748 this.name = 'CertificateParseError';
68749 this.format = format;
68750 this.certName = name;
68751 this.innerErr = innerErr;
68752 this.message = 'Failed to parse ' + name + ' as a valid ' + format +
68753 ' format certificate: ' + innerErr.message;
68754}
68755util.inherits(CertificateParseError, Error);
68756
68757function KeyEncryptedError(name, format) {
68758 if (Error.captureStackTrace)
68759 Error.captureStackTrace(this, KeyEncryptedError);
68760 this.name = 'KeyEncryptedError';
68761 this.format = format;
68762 this.keyName = name;
68763 this.message = 'The ' + format + ' format key ' + name + ' is ' +
68764 'encrypted (password-protected), and no passphrase was ' +
68765 'provided in `options`';
68766}
68767util.inherits(KeyEncryptedError, Error);
68768
68769module.exports = {
68770 FingerprintFormatError: FingerprintFormatError,
68771 InvalidAlgorithmError: InvalidAlgorithmError,
68772 KeyParseError: KeyParseError,
68773 SignatureParseError: SignatureParseError,
68774 KeyEncryptedError: KeyEncryptedError,
68775 CertificateParseError: CertificateParseError
68776};
68777
68778},{"assert-plus":67,"util":397}],340:[function(require,module,exports){
68779// Copyright 2018 Joyent, Inc.
68780
68781module.exports = Fingerprint;
68782
68783var assert = require('assert-plus');
68784var Buffer = require('safer-buffer').Buffer;
68785var algs = require('./algs');
68786var crypto = require('crypto');
68787var errs = require('./errors');
68788var Key = require('./key');
68789var PrivateKey = require('./private-key');
68790var Certificate = require('./certificate');
68791var utils = require('./utils');
68792
68793var FingerprintFormatError = errs.FingerprintFormatError;
68794var InvalidAlgorithmError = errs.InvalidAlgorithmError;
68795
68796function Fingerprint(opts) {
68797 assert.object(opts, 'options');
68798 assert.string(opts.type, 'options.type');
68799 assert.buffer(opts.hash, 'options.hash');
68800 assert.string(opts.algorithm, 'options.algorithm');
68801
68802 this.algorithm = opts.algorithm.toLowerCase();
68803 if (algs.hashAlgs[this.algorithm] !== true)
68804 throw (new InvalidAlgorithmError(this.algorithm));
68805
68806 this.hash = opts.hash;
68807 this.type = opts.type;
68808 this.hashType = opts.hashType;
68809}
68810
68811Fingerprint.prototype.toString = function (format) {
68812 if (format === undefined) {
68813 if (this.algorithm === 'md5' || this.hashType === 'spki')
68814 format = 'hex';
68815 else
68816 format = 'base64';
68817 }
68818 assert.string(format);
68819
68820 switch (format) {
68821 case 'hex':
68822 if (this.hashType === 'spki')
68823 return (this.hash.toString('hex'));
68824 return (addColons(this.hash.toString('hex')));
68825 case 'base64':
68826 if (this.hashType === 'spki')
68827 return (this.hash.toString('base64'));
68828 return (sshBase64Format(this.algorithm,
68829 this.hash.toString('base64')));
68830 default:
68831 throw (new FingerprintFormatError(undefined, format));
68832 }
68833};
68834
68835Fingerprint.prototype.matches = function (other) {
68836 assert.object(other, 'key or certificate');
68837 if (this.type === 'key' && this.hashType !== 'ssh') {
68838 utils.assertCompatible(other, Key, [1, 7], 'key with spki');
68839 if (PrivateKey.isPrivateKey(other)) {
68840 utils.assertCompatible(other, PrivateKey, [1, 6],
68841 'privatekey with spki support');
68842 }
68843 } else if (this.type === 'key') {
68844 utils.assertCompatible(other, Key, [1, 0], 'key');
68845 } else {
68846 utils.assertCompatible(other, Certificate, [1, 0],
68847 'certificate');
68848 }
68849
68850 var theirHash = other.hash(this.algorithm, this.hashType);
68851 var theirHash2 = crypto.createHash(this.algorithm).
68852 update(theirHash).digest('base64');
68853
68854 if (this.hash2 === undefined)
68855 this.hash2 = crypto.createHash(this.algorithm).
68856 update(this.hash).digest('base64');
68857
68858 return (this.hash2 === theirHash2);
68859};
68860
68861/*JSSTYLED*/
68862var base64RE = /^[A-Za-z0-9+\/=]+$/;
68863/*JSSTYLED*/
68864var hexRE = /^[a-fA-F0-9]+$/;
68865
68866Fingerprint.parse = function (fp, options) {
68867 assert.string(fp, 'fingerprint');
68868
68869 var alg, hash, enAlgs;
68870 if (Array.isArray(options)) {
68871 enAlgs = options;
68872 options = {};
68873 }
68874 assert.optionalObject(options, 'options');
68875 if (options === undefined)
68876 options = {};
68877 if (options.enAlgs !== undefined)
68878 enAlgs = options.enAlgs;
68879 if (options.algorithms !== undefined)
68880 enAlgs = options.algorithms;
68881 assert.optionalArrayOfString(enAlgs, 'algorithms');
68882
68883 var hashType = 'ssh';
68884 if (options.hashType !== undefined)
68885 hashType = options.hashType;
68886 assert.string(hashType, 'options.hashType');
68887
68888 var parts = fp.split(':');
68889 if (parts.length == 2) {
68890 alg = parts[0].toLowerCase();
68891 if (!base64RE.test(parts[1]))
68892 throw (new FingerprintFormatError(fp));
68893 try {
68894 hash = Buffer.from(parts[1], 'base64');
68895 } catch (e) {
68896 throw (new FingerprintFormatError(fp));
68897 }
68898 } else if (parts.length > 2) {
68899 alg = 'md5';
68900 if (parts[0].toLowerCase() === 'md5')
68901 parts = parts.slice(1);
68902 parts = parts.map(function (p) {
68903 while (p.length < 2)
68904 p = '0' + p;
68905 if (p.length > 2)
68906 throw (new FingerprintFormatError(fp));
68907 return (p);
68908 });
68909 parts = parts.join('');
68910 if (!hexRE.test(parts) || parts.length % 2 !== 0)
68911 throw (new FingerprintFormatError(fp));
68912 try {
68913 hash = Buffer.from(parts, 'hex');
68914 } catch (e) {
68915 throw (new FingerprintFormatError(fp));
68916 }
68917 } else {
68918 if (hexRE.test(fp)) {
68919 hash = Buffer.from(fp, 'hex');
68920 } else if (base64RE.test(fp)) {
68921 hash = Buffer.from(fp, 'base64');
68922 } else {
68923 throw (new FingerprintFormatError(fp));
68924 }
68925
68926 switch (hash.length) {
68927 case 32:
68928 alg = 'sha256';
68929 break;
68930 case 16:
68931 alg = 'md5';
68932 break;
68933 case 20:
68934 alg = 'sha1';
68935 break;
68936 case 64:
68937 alg = 'sha512';
68938 break;
68939 default:
68940 throw (new FingerprintFormatError(fp));
68941 }
68942
68943 /* Plain hex/base64: guess it's probably SPKI unless told. */
68944 if (options.hashType === undefined)
68945 hashType = 'spki';
68946 }
68947
68948 if (alg === undefined)
68949 throw (new FingerprintFormatError(fp));
68950
68951 if (algs.hashAlgs[alg] === undefined)
68952 throw (new InvalidAlgorithmError(alg));
68953
68954 if (enAlgs !== undefined) {
68955 enAlgs = enAlgs.map(function (a) { return a.toLowerCase(); });
68956 if (enAlgs.indexOf(alg) === -1)
68957 throw (new InvalidAlgorithmError(alg));
68958 }
68959
68960 return (new Fingerprint({
68961 algorithm: alg,
68962 hash: hash,
68963 type: options.type || 'key',
68964 hashType: hashType
68965 }));
68966};
68967
68968function addColons(s) {
68969 /*JSSTYLED*/
68970 return (s.replace(/(.{2})(?=.)/g, '$1:'));
68971}
68972
68973function base64Strip(s) {
68974 /*JSSTYLED*/
68975 return (s.replace(/=*$/, ''));
68976}
68977
68978function sshBase64Format(alg, h) {
68979 return (alg.toUpperCase() + ':' + base64Strip(h));
68980}
68981
68982Fingerprint.isFingerprint = function (obj, ver) {
68983 return (utils.isCompatible(obj, Fingerprint, ver));
68984};
68985
68986/*
68987 * API versions for Fingerprint:
68988 * [1,0] -- initial ver
68989 * [1,1] -- first tagged ver
68990 * [1,2] -- hashType and spki support
68991 */
68992Fingerprint.prototype._sshpkApiVersion = [1, 2];
68993
68994Fingerprint._oldVersionDetect = function (obj) {
68995 assert.func(obj.toString);
68996 assert.func(obj.matches);
68997 return ([1, 0]);
68998};
68999
69000},{"./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){
69001// Copyright 2018 Joyent, Inc.
69002
69003module.exports = {
69004 read: read,
69005 write: write
69006};
69007
69008var assert = require('assert-plus');
69009var Buffer = require('safer-buffer').Buffer;
69010var utils = require('../utils');
69011var Key = require('../key');
69012var PrivateKey = require('../private-key');
69013
69014var pem = require('./pem');
69015var ssh = require('./ssh');
69016var rfc4253 = require('./rfc4253');
69017var dnssec = require('./dnssec');
69018var putty = require('./putty');
69019
69020var DNSSEC_PRIVKEY_HEADER_PREFIX = 'Private-key-format: v1';
69021
69022function read(buf, options) {
69023 if (typeof (buf) === 'string') {
69024 if (buf.trim().match(/^[-]+[ ]*BEGIN/))
69025 return (pem.read(buf, options));
69026 if (buf.match(/^\s*ssh-[a-z]/))
69027 return (ssh.read(buf, options));
69028 if (buf.match(/^\s*ecdsa-/))
69029 return (ssh.read(buf, options));
69030 if (buf.match(/^putty-user-key-file-2:/i))
69031 return (putty.read(buf, options));
69032 if (findDNSSECHeader(buf))
69033 return (dnssec.read(buf, options));
69034 buf = Buffer.from(buf, 'binary');
69035 } else {
69036 assert.buffer(buf);
69037 if (findPEMHeader(buf))
69038 return (pem.read(buf, options));
69039 if (findSSHHeader(buf))
69040 return (ssh.read(buf, options));
69041 if (findPuTTYHeader(buf))
69042 return (putty.read(buf, options));
69043 if (findDNSSECHeader(buf))
69044 return (dnssec.read(buf, options));
69045 }
69046 if (buf.readUInt32BE(0) < buf.length)
69047 return (rfc4253.read(buf, options));
69048 throw (new Error('Failed to auto-detect format of key'));
69049}
69050
69051function findPuTTYHeader(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 + 22 <= buf.length &&
69057 buf.slice(offset, offset + 22).toString('ascii').toLowerCase() ===
69058 'putty-user-key-file-2:')
69059 return (true);
69060 return (false);
69061}
69062
69063function findSSHHeader(buf) {
69064 var offset = 0;
69065 while (offset < buf.length &&
69066 (buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
69067 ++offset;
69068 if (offset + 4 <= buf.length &&
69069 buf.slice(offset, offset + 4).toString('ascii') === 'ssh-')
69070 return (true);
69071 if (offset + 6 <= buf.length &&
69072 buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-')
69073 return (true);
69074 return (false);
69075}
69076
69077function findPEMHeader(buf) {
69078 var offset = 0;
69079 while (offset < buf.length &&
69080 (buf[offset] === 32 || buf[offset] === 10))
69081 ++offset;
69082 if (buf[offset] !== 45)
69083 return (false);
69084 while (offset < buf.length &&
69085 (buf[offset] === 45))
69086 ++offset;
69087 while (offset < buf.length &&
69088 (buf[offset] === 32))
69089 ++offset;
69090 if (offset + 5 > buf.length ||
69091 buf.slice(offset, offset + 5).toString('ascii') !== 'BEGIN')
69092 return (false);
69093 return (true);
69094}
69095
69096function findDNSSECHeader(buf) {
69097 // private case first
69098 if (buf.length <= DNSSEC_PRIVKEY_HEADER_PREFIX.length)
69099 return (false);
69100 var headerCheck = buf.slice(0, DNSSEC_PRIVKEY_HEADER_PREFIX.length);
69101 if (headerCheck.toString('ascii') === DNSSEC_PRIVKEY_HEADER_PREFIX)
69102 return (true);
69103
69104 // public-key RFC3110 ?
69105 // 'domain.com. IN KEY ...' or 'domain.com. IN DNSKEY ...'
69106 // skip any comment-lines
69107 if (typeof (buf) !== 'string') {
69108 buf = buf.toString('ascii');
69109 }
69110 var lines = buf.split('\n');
69111 var line = 0;
69112 /* JSSTYLED */
69113 while (lines[line].match(/^\;/))
69114 line++;
69115 if (lines[line].toString('ascii').match(/\. IN KEY /))
69116 return (true);
69117 if (lines[line].toString('ascii').match(/\. IN DNSKEY /))
69118 return (true);
69119 return (false);
69120}
69121
69122function write(key, options) {
69123 throw (new Error('"auto" format cannot be used for writing'));
69124}
69125
69126},{"../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){
69127// Copyright 2017 Joyent, Inc.
69128
69129module.exports = {
69130 read: read,
69131 write: write
69132};
69133
69134var assert = require('assert-plus');
69135var Buffer = require('safer-buffer').Buffer;
69136var Key = require('../key');
69137var PrivateKey = require('../private-key');
69138var utils = require('../utils');
69139var SSHBuffer = require('../ssh-buffer');
69140var Dhe = require('../dhe');
69141
69142var supportedAlgos = {
69143 'rsa-sha1' : 5,
69144 'rsa-sha256' : 8,
69145 'rsa-sha512' : 10,
69146 'ecdsa-p256-sha256' : 13,
69147 'ecdsa-p384-sha384' : 14
69148 /*
69149 * ed25519 is hypothetically supported with id 15
69150 * but the common tools available don't appear to be
69151 * capable of generating/using ed25519 keys
69152 */
69153};
69154
69155var supportedAlgosById = {};
69156Object.keys(supportedAlgos).forEach(function (k) {
69157 supportedAlgosById[supportedAlgos[k]] = k.toUpperCase();
69158});
69159
69160function read(buf, options) {
69161 if (typeof (buf) !== 'string') {
69162 assert.buffer(buf, 'buf');
69163 buf = buf.toString('ascii');
69164 }
69165 var lines = buf.split('\n');
69166 if (lines[0].match(/^Private-key-format\: v1/)) {
69167 var algElems = lines[1].split(' ');
69168 var algoNum = parseInt(algElems[1], 10);
69169 var algoName = algElems[2];
69170 if (!supportedAlgosById[algoNum])
69171 throw (new Error('Unsupported algorithm: ' + algoName));
69172 return (readDNSSECPrivateKey(algoNum, lines.slice(2)));
69173 }
69174
69175 // skip any comment-lines
69176 var line = 0;
69177 /* JSSTYLED */
69178 while (lines[line].match(/^\;/))
69179 line++;
69180 // we should now have *one single* line left with our KEY on it.
69181 if ((lines[line].match(/\. IN KEY /) ||
69182 lines[line].match(/\. IN DNSKEY /)) && lines[line+1].length === 0) {
69183 return (readRFC3110(lines[line]));
69184 }
69185 throw (new Error('Cannot parse dnssec key'));
69186}
69187
69188function readRFC3110(keyString) {
69189 var elems = keyString.split(' ');
69190 //unused var flags = parseInt(elems[3], 10);
69191 //unused var protocol = parseInt(elems[4], 10);
69192 var algorithm = parseInt(elems[5], 10);
69193 if (!supportedAlgosById[algorithm])
69194 throw (new Error('Unsupported algorithm: ' + algorithm));
69195 var base64key = elems.slice(6, elems.length).join();
69196 var keyBuffer = Buffer.from(base64key, 'base64');
69197 if (supportedAlgosById[algorithm].match(/^RSA-/)) {
69198 // join the rest of the body into a single base64-blob
69199 var publicExponentLen = keyBuffer.readUInt8(0);
69200 if (publicExponentLen != 3 && publicExponentLen != 1)
69201 throw (new Error('Cannot parse dnssec key: ' +
69202 'unsupported exponent length'));
69203
69204 var publicExponent = keyBuffer.slice(1, publicExponentLen+1);
69205 publicExponent = utils.mpNormalize(publicExponent);
69206 var modulus = keyBuffer.slice(1+publicExponentLen);
69207 modulus = utils.mpNormalize(modulus);
69208 // now, make the key
69209 var rsaKey = {
69210 type: 'rsa',
69211 parts: []
69212 };
69213 rsaKey.parts.push({ name: 'e', data: publicExponent});
69214 rsaKey.parts.push({ name: 'n', data: modulus});
69215 return (new Key(rsaKey));
69216 }
69217 if (supportedAlgosById[algorithm] === 'ECDSA-P384-SHA384' ||
69218 supportedAlgosById[algorithm] === 'ECDSA-P256-SHA256') {
69219 var curve = 'nistp384';
69220 var size = 384;
69221 if (supportedAlgosById[algorithm].match(/^ECDSA-P256-SHA256/)) {
69222 curve = 'nistp256';
69223 size = 256;
69224 }
69225
69226 var ecdsaKey = {
69227 type: 'ecdsa',
69228 curve: curve,
69229 size: size,
69230 parts: [
69231 {name: 'curve', data: Buffer.from(curve) },
69232 {name: 'Q', data: utils.ecNormalize(keyBuffer) }
69233 ]
69234 };
69235 return (new Key(ecdsaKey));
69236 }
69237 throw (new Error('Unsupported algorithm: ' +
69238 supportedAlgosById[algorithm]));
69239}
69240
69241function elementToBuf(e) {
69242 return (Buffer.from(e.split(' ')[1], 'base64'));
69243}
69244
69245function readDNSSECRSAPrivateKey(elements) {
69246 var rsaParams = {};
69247 elements.forEach(function (element) {
69248 if (element.split(' ')[0] === 'Modulus:')
69249 rsaParams['n'] = elementToBuf(element);
69250 else if (element.split(' ')[0] === 'PublicExponent:')
69251 rsaParams['e'] = elementToBuf(element);
69252 else if (element.split(' ')[0] === 'PrivateExponent:')
69253 rsaParams['d'] = elementToBuf(element);
69254 else if (element.split(' ')[0] === 'Prime1:')
69255 rsaParams['p'] = elementToBuf(element);
69256 else if (element.split(' ')[0] === 'Prime2:')
69257 rsaParams['q'] = elementToBuf(element);
69258 else if (element.split(' ')[0] === 'Exponent1:')
69259 rsaParams['dmodp'] = elementToBuf(element);
69260 else if (element.split(' ')[0] === 'Exponent2:')
69261 rsaParams['dmodq'] = elementToBuf(element);
69262 else if (element.split(' ')[0] === 'Coefficient:')
69263 rsaParams['iqmp'] = elementToBuf(element);
69264 });
69265 // now, make the key
69266 var key = {
69267 type: 'rsa',
69268 parts: [
69269 { name: 'e', data: utils.mpNormalize(rsaParams['e'])},
69270 { name: 'n', data: utils.mpNormalize(rsaParams['n'])},
69271 { name: 'd', data: utils.mpNormalize(rsaParams['d'])},
69272 { name: 'p', data: utils.mpNormalize(rsaParams['p'])},
69273 { name: 'q', data: utils.mpNormalize(rsaParams['q'])},
69274 { name: 'dmodp',
69275 data: utils.mpNormalize(rsaParams['dmodp'])},
69276 { name: 'dmodq',
69277 data: utils.mpNormalize(rsaParams['dmodq'])},
69278 { name: 'iqmp',
69279 data: utils.mpNormalize(rsaParams['iqmp'])}
69280 ]
69281 };
69282 return (new PrivateKey(key));
69283}
69284
69285function readDNSSECPrivateKey(alg, elements) {
69286 if (supportedAlgosById[alg].match(/^RSA-/)) {
69287 return (readDNSSECRSAPrivateKey(elements));
69288 }
69289 if (supportedAlgosById[alg] === 'ECDSA-P384-SHA384' ||
69290 supportedAlgosById[alg] === 'ECDSA-P256-SHA256') {
69291 var d = Buffer.from(elements[0].split(' ')[1], 'base64');
69292 var curve = 'nistp384';
69293 var size = 384;
69294 if (supportedAlgosById[alg] === 'ECDSA-P256-SHA256') {
69295 curve = 'nistp256';
69296 size = 256;
69297 }
69298 // DNSSEC generates the public-key on the fly (go calculate it)
69299 var publicKey = utils.publicFromPrivateECDSA(curve, d);
69300 var Q = publicKey.part['Q'].data;
69301 var ecdsaKey = {
69302 type: 'ecdsa',
69303 curve: curve,
69304 size: size,
69305 parts: [
69306 {name: 'curve', data: Buffer.from(curve) },
69307 {name: 'd', data: d },
69308 {name: 'Q', data: Q }
69309 ]
69310 };
69311 return (new PrivateKey(ecdsaKey));
69312 }
69313 throw (new Error('Unsupported algorithm: ' + supportedAlgosById[alg]));
69314}
69315
69316function dnssecTimestamp(date) {
69317 var year = date.getFullYear() + ''; //stringify
69318 var month = (date.getMonth() + 1);
69319 var timestampStr = year + month + date.getUTCDate();
69320 timestampStr += '' + date.getUTCHours() + date.getUTCMinutes();
69321 timestampStr += date.getUTCSeconds();
69322 return (timestampStr);
69323}
69324
69325function rsaAlgFromOptions(opts) {
69326 if (!opts || !opts.hashAlgo || opts.hashAlgo === 'sha1')
69327 return ('5 (RSASHA1)');
69328 else if (opts.hashAlgo === 'sha256')
69329 return ('8 (RSASHA256)');
69330 else if (opts.hashAlgo === 'sha512')
69331 return ('10 (RSASHA512)');
69332 else
69333 throw (new Error('Unknown or unsupported hash: ' +
69334 opts.hashAlgo));
69335}
69336
69337function writeRSA(key, options) {
69338 // if we're missing parts, add them.
69339 if (!key.part.dmodp || !key.part.dmodq) {
69340 utils.addRSAMissing(key);
69341 }
69342
69343 var out = '';
69344 out += 'Private-key-format: v1.3\n';
69345 out += 'Algorithm: ' + rsaAlgFromOptions(options) + '\n';
69346 var n = utils.mpDenormalize(key.part['n'].data);
69347 out += 'Modulus: ' + n.toString('base64') + '\n';
69348 var e = utils.mpDenormalize(key.part['e'].data);
69349 out += 'PublicExponent: ' + e.toString('base64') + '\n';
69350 var d = utils.mpDenormalize(key.part['d'].data);
69351 out += 'PrivateExponent: ' + d.toString('base64') + '\n';
69352 var p = utils.mpDenormalize(key.part['p'].data);
69353 out += 'Prime1: ' + p.toString('base64') + '\n';
69354 var q = utils.mpDenormalize(key.part['q'].data);
69355 out += 'Prime2: ' + q.toString('base64') + '\n';
69356 var dmodp = utils.mpDenormalize(key.part['dmodp'].data);
69357 out += 'Exponent1: ' + dmodp.toString('base64') + '\n';
69358 var dmodq = utils.mpDenormalize(key.part['dmodq'].data);
69359 out += 'Exponent2: ' + dmodq.toString('base64') + '\n';
69360 var iqmp = utils.mpDenormalize(key.part['iqmp'].data);
69361 out += 'Coefficient: ' + iqmp.toString('base64') + '\n';
69362 // Assume that we're valid as-of now
69363 var timestamp = new Date();
69364 out += 'Created: ' + dnssecTimestamp(timestamp) + '\n';
69365 out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n';
69366 out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n';
69367 return (Buffer.from(out, 'ascii'));
69368}
69369
69370function writeECDSA(key, options) {
69371 var out = '';
69372 out += 'Private-key-format: v1.3\n';
69373
69374 if (key.curve === 'nistp256') {
69375 out += 'Algorithm: 13 (ECDSAP256SHA256)\n';
69376 } else if (key.curve === 'nistp384') {
69377 out += 'Algorithm: 14 (ECDSAP384SHA384)\n';
69378 } else {
69379 throw (new Error('Unsupported curve'));
69380 }
69381 var base64Key = key.part['d'].data.toString('base64');
69382 out += 'PrivateKey: ' + base64Key + '\n';
69383
69384 // Assume that we're valid as-of now
69385 var timestamp = new Date();
69386 out += 'Created: ' + dnssecTimestamp(timestamp) + '\n';
69387 out += 'Publish: ' + dnssecTimestamp(timestamp) + '\n';
69388 out += 'Activate: ' + dnssecTimestamp(timestamp) + '\n';
69389
69390 return (Buffer.from(out, 'ascii'));
69391}
69392
69393function write(key, options) {
69394 if (PrivateKey.isPrivateKey(key)) {
69395 if (key.type === 'rsa') {
69396 return (writeRSA(key, options));
69397 } else if (key.type === 'ecdsa') {
69398 return (writeECDSA(key, options));
69399 } else {
69400 throw (new Error('Unsupported algorithm: ' + key.type));
69401 }
69402 } else if (Key.isKey(key)) {
69403 /*
69404 * RFC3110 requires a keyname, and a keytype, which we
69405 * don't really have a mechanism for specifying such
69406 * additional metadata.
69407 */
69408 throw (new Error('Format "dnssec" only supports ' +
69409 'writing private keys'));
69410 } else {
69411 throw (new Error('key is not a Key or PrivateKey'));
69412 }
69413}
69414
69415},{"../dhe":337,"../key":355,"../private-key":356,"../ssh-buffer":358,"../utils":359,"assert-plus":67,"safer-buffer":326}],343:[function(require,module,exports){
69416// Copyright 2017 Joyent, Inc.
69417
69418module.exports = {
69419 read: read,
69420 verify: verify,
69421 sign: sign,
69422 signAsync: signAsync,
69423 write: write,
69424
69425 /* Internal private API */
69426 fromBuffer: fromBuffer,
69427 toBuffer: toBuffer
69428};
69429
69430var assert = require('assert-plus');
69431var SSHBuffer = require('../ssh-buffer');
69432var crypto = require('crypto');
69433var Buffer = require('safer-buffer').Buffer;
69434var algs = require('../algs');
69435var Key = require('../key');
69436var PrivateKey = require('../private-key');
69437var Identity = require('../identity');
69438var rfc4253 = require('./rfc4253');
69439var Signature = require('../signature');
69440var utils = require('../utils');
69441var Certificate = require('../certificate');
69442
69443function verify(cert, key) {
69444 /*
69445 * We always give an issuerKey, so if our verify() is being called then
69446 * there was no signature. Return false.
69447 */
69448 return (false);
69449}
69450
69451var TYPES = {
69452 'user': 1,
69453 'host': 2
69454};
69455Object.keys(TYPES).forEach(function (k) { TYPES[TYPES[k]] = k; });
69456
69457var ECDSA_ALGO = /^ecdsa-sha2-([^@-]+)-cert-v01@openssh.com$/;
69458
69459function read(buf, options) {
69460 if (Buffer.isBuffer(buf))
69461 buf = buf.toString('ascii');
69462 var parts = buf.trim().split(/[ \t\n]+/g);
69463 if (parts.length < 2 || parts.length > 3)
69464 throw (new Error('Not a valid SSH certificate line'));
69465
69466 var algo = parts[0];
69467 var data = parts[1];
69468
69469 data = Buffer.from(data, 'base64');
69470 return (fromBuffer(data, algo));
69471}
69472
69473function fromBuffer(data, algo, partial) {
69474 var sshbuf = new SSHBuffer({ buffer: data });
69475 var innerAlgo = sshbuf.readString();
69476 if (algo !== undefined && innerAlgo !== algo)
69477 throw (new Error('SSH certificate algorithm mismatch'));
69478 if (algo === undefined)
69479 algo = innerAlgo;
69480
69481 var cert = {};
69482 cert.signatures = {};
69483 cert.signatures.openssh = {};
69484
69485 cert.signatures.openssh.nonce = sshbuf.readBuffer();
69486
69487 var key = {};
69488 var parts = (key.parts = []);
69489 key.type = getAlg(algo);
69490
69491 var partCount = algs.info[key.type].parts.length;
69492 while (parts.length < partCount)
69493 parts.push(sshbuf.readPart());
69494 assert.ok(parts.length >= 1, 'key must have at least one part');
69495
69496 var algInfo = algs.info[key.type];
69497 if (key.type === 'ecdsa') {
69498 var res = ECDSA_ALGO.exec(algo);
69499 assert.ok(res !== null);
69500 assert.strictEqual(res[1], parts[0].data.toString());
69501 }
69502
69503 for (var i = 0; i < algInfo.parts.length; ++i) {
69504 parts[i].name = algInfo.parts[i];
69505 if (parts[i].name !== 'curve' &&
69506 algInfo.normalize !== false) {
69507 var p = parts[i];
69508 p.data = utils.mpNormalize(p.data);
69509 }
69510 }
69511
69512 cert.subjectKey = new Key(key);
69513
69514 cert.serial = sshbuf.readInt64();
69515
69516 var type = TYPES[sshbuf.readInt()];
69517 assert.string(type, 'valid cert type');
69518
69519 cert.signatures.openssh.keyId = sshbuf.readString();
69520
69521 var principals = [];
69522 var pbuf = sshbuf.readBuffer();
69523 var psshbuf = new SSHBuffer({ buffer: pbuf });
69524 while (!psshbuf.atEnd())
69525 principals.push(psshbuf.readString());
69526 if (principals.length === 0)
69527 principals = ['*'];
69528
69529 cert.subjects = principals.map(function (pr) {
69530 if (type === 'user')
69531 return (Identity.forUser(pr));
69532 else if (type === 'host')
69533 return (Identity.forHost(pr));
69534 throw (new Error('Unknown identity type ' + type));
69535 });
69536
69537 cert.validFrom = int64ToDate(sshbuf.readInt64());
69538 cert.validUntil = int64ToDate(sshbuf.readInt64());
69539
69540 var exts = [];
69541 var extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() });
69542 var ext;
69543 while (!extbuf.atEnd()) {
69544 ext = { critical: true };
69545 ext.name = extbuf.readString();
69546 ext.data = extbuf.readBuffer();
69547 exts.push(ext);
69548 }
69549 extbuf = new SSHBuffer({ buffer: sshbuf.readBuffer() });
69550 while (!extbuf.atEnd()) {
69551 ext = { critical: false };
69552 ext.name = extbuf.readString();
69553 ext.data = extbuf.readBuffer();
69554 exts.push(ext);
69555 }
69556 cert.signatures.openssh.exts = exts;
69557
69558 /* reserved */
69559 sshbuf.readBuffer();
69560
69561 var signingKeyBuf = sshbuf.readBuffer();
69562 cert.issuerKey = rfc4253.read(signingKeyBuf);
69563
69564 /*
69565 * OpenSSH certs don't give the identity of the issuer, just their
69566 * public key. So, we use an Identity that matches anything. The
69567 * isSignedBy() function will later tell you if the key matches.
69568 */
69569 cert.issuer = Identity.forHost('**');
69570
69571 var sigBuf = sshbuf.readBuffer();
69572 cert.signatures.openssh.signature =
69573 Signature.parse(sigBuf, cert.issuerKey.type, 'ssh');
69574
69575 if (partial !== undefined) {
69576 partial.remainder = sshbuf.remainder();
69577 partial.consumed = sshbuf._offset;
69578 }
69579
69580 return (new Certificate(cert));
69581}
69582
69583function int64ToDate(buf) {
69584 var i = buf.readUInt32BE(0) * 4294967296;
69585 i += buf.readUInt32BE(4);
69586 var d = new Date();
69587 d.setTime(i * 1000);
69588 d.sourceInt64 = buf;
69589 return (d);
69590}
69591
69592function dateToInt64(date) {
69593 if (date.sourceInt64 !== undefined)
69594 return (date.sourceInt64);
69595 var i = Math.round(date.getTime() / 1000);
69596 var upper = Math.floor(i / 4294967296);
69597 var lower = Math.floor(i % 4294967296);
69598 var buf = Buffer.alloc(8);
69599 buf.writeUInt32BE(upper, 0);
69600 buf.writeUInt32BE(lower, 4);
69601 return (buf);
69602}
69603
69604function sign(cert, key) {
69605 if (cert.signatures.openssh === undefined)
69606 cert.signatures.openssh = {};
69607 try {
69608 var blob = toBuffer(cert, true);
69609 } catch (e) {
69610 delete (cert.signatures.openssh);
69611 return (false);
69612 }
69613 var sig = cert.signatures.openssh;
69614 var hashAlgo = undefined;
69615 if (key.type === 'rsa' || key.type === 'dsa')
69616 hashAlgo = 'sha1';
69617 var signer = key.createSign(hashAlgo);
69618 signer.write(blob);
69619 sig.signature = signer.sign();
69620 return (true);
69621}
69622
69623function signAsync(cert, signer, done) {
69624 if (cert.signatures.openssh === undefined)
69625 cert.signatures.openssh = {};
69626 try {
69627 var blob = toBuffer(cert, true);
69628 } catch (e) {
69629 delete (cert.signatures.openssh);
69630 done(e);
69631 return;
69632 }
69633 var sig = cert.signatures.openssh;
69634
69635 signer(blob, function (err, signature) {
69636 if (err) {
69637 done(err);
69638 return;
69639 }
69640 try {
69641 /*
69642 * This will throw if the signature isn't of a
69643 * type/algo that can be used for SSH.
69644 */
69645 signature.toBuffer('ssh');
69646 } catch (e) {
69647 done(e);
69648 return;
69649 }
69650 sig.signature = signature;
69651 done();
69652 });
69653}
69654
69655function write(cert, options) {
69656 if (options === undefined)
69657 options = {};
69658
69659 var blob = toBuffer(cert);
69660 var out = getCertType(cert.subjectKey) + ' ' + blob.toString('base64');
69661 if (options.comment)
69662 out = out + ' ' + options.comment;
69663 return (out);
69664}
69665
69666
69667function toBuffer(cert, noSig) {
69668 assert.object(cert.signatures.openssh, 'signature for openssh format');
69669 var sig = cert.signatures.openssh;
69670
69671 if (sig.nonce === undefined)
69672 sig.nonce = crypto.randomBytes(16);
69673 var buf = new SSHBuffer({});
69674 buf.writeString(getCertType(cert.subjectKey));
69675 buf.writeBuffer(sig.nonce);
69676
69677 var key = cert.subjectKey;
69678 var algInfo = algs.info[key.type];
69679 algInfo.parts.forEach(function (part) {
69680 buf.writePart(key.part[part]);
69681 });
69682
69683 buf.writeInt64(cert.serial);
69684
69685 var type = cert.subjects[0].type;
69686 assert.notStrictEqual(type, 'unknown');
69687 cert.subjects.forEach(function (id) {
69688 assert.strictEqual(id.type, type);
69689 });
69690 type = TYPES[type];
69691 buf.writeInt(type);
69692
69693 if (sig.keyId === undefined) {
69694 sig.keyId = cert.subjects[0].type + '_' +
69695 (cert.subjects[0].uid || cert.subjects[0].hostname);
69696 }
69697 buf.writeString(sig.keyId);
69698
69699 var sub = new SSHBuffer({});
69700 cert.subjects.forEach(function (id) {
69701 if (type === TYPES.host)
69702 sub.writeString(id.hostname);
69703 else if (type === TYPES.user)
69704 sub.writeString(id.uid);
69705 });
69706 buf.writeBuffer(sub.toBuffer());
69707
69708 buf.writeInt64(dateToInt64(cert.validFrom));
69709 buf.writeInt64(dateToInt64(cert.validUntil));
69710
69711 var exts = sig.exts;
69712 if (exts === undefined)
69713 exts = [];
69714
69715 var extbuf = new SSHBuffer({});
69716 exts.forEach(function (ext) {
69717 if (ext.critical !== true)
69718 return;
69719 extbuf.writeString(ext.name);
69720 extbuf.writeBuffer(ext.data);
69721 });
69722 buf.writeBuffer(extbuf.toBuffer());
69723
69724 extbuf = new SSHBuffer({});
69725 exts.forEach(function (ext) {
69726 if (ext.critical === true)
69727 return;
69728 extbuf.writeString(ext.name);
69729 extbuf.writeBuffer(ext.data);
69730 });
69731 buf.writeBuffer(extbuf.toBuffer());
69732
69733 /* reserved */
69734 buf.writeBuffer(Buffer.alloc(0));
69735
69736 sub = rfc4253.write(cert.issuerKey);
69737 buf.writeBuffer(sub);
69738
69739 if (!noSig)
69740 buf.writeBuffer(sig.signature.toBuffer('ssh'));
69741
69742 return (buf.toBuffer());
69743}
69744
69745function getAlg(certType) {
69746 if (certType === 'ssh-rsa-cert-v01@openssh.com')
69747 return ('rsa');
69748 if (certType === 'ssh-dss-cert-v01@openssh.com')
69749 return ('dsa');
69750 if (certType.match(ECDSA_ALGO))
69751 return ('ecdsa');
69752 if (certType === 'ssh-ed25519-cert-v01@openssh.com')
69753 return ('ed25519');
69754 throw (new Error('Unsupported cert type ' + certType));
69755}
69756
69757function getCertType(key) {
69758 if (key.type === 'rsa')
69759 return ('ssh-rsa-cert-v01@openssh.com');
69760 if (key.type === 'dsa')
69761 return ('ssh-dss-cert-v01@openssh.com');
69762 if (key.type === 'ecdsa')
69763 return ('ecdsa-sha2-' + key.curve + '-cert-v01@openssh.com');
69764 if (key.type === 'ed25519')
69765 return ('ssh-ed25519-cert-v01@openssh.com');
69766 throw (new Error('Unsupported key type ' + key.type));
69767}
69768
69769},{"../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){
69770// Copyright 2018 Joyent, Inc.
69771
69772module.exports = {
69773 read: read,
69774 write: write
69775};
69776
69777var assert = require('assert-plus');
69778var asn1 = require('asn1');
69779var crypto = require('crypto');
69780var Buffer = require('safer-buffer').Buffer;
69781var algs = require('../algs');
69782var utils = require('../utils');
69783var Key = require('../key');
69784var PrivateKey = require('../private-key');
69785
69786var pkcs1 = require('./pkcs1');
69787var pkcs8 = require('./pkcs8');
69788var sshpriv = require('./ssh-private');
69789var rfc4253 = require('./rfc4253');
69790
69791var errors = require('../errors');
69792
69793var OID_PBES2 = '1.2.840.113549.1.5.13';
69794var OID_PBKDF2 = '1.2.840.113549.1.5.12';
69795
69796var OID_TO_CIPHER = {
69797 '1.2.840.113549.3.7': '3des-cbc',
69798 '2.16.840.1.101.3.4.1.2': 'aes128-cbc',
69799 '2.16.840.1.101.3.4.1.42': 'aes256-cbc'
69800};
69801var CIPHER_TO_OID = {};
69802Object.keys(OID_TO_CIPHER).forEach(function (k) {
69803 CIPHER_TO_OID[OID_TO_CIPHER[k]] = k;
69804});
69805
69806var OID_TO_HASH = {
69807 '1.2.840.113549.2.7': 'sha1',
69808 '1.2.840.113549.2.9': 'sha256',
69809 '1.2.840.113549.2.11': 'sha512'
69810};
69811var HASH_TO_OID = {};
69812Object.keys(OID_TO_HASH).forEach(function (k) {
69813 HASH_TO_OID[OID_TO_HASH[k]] = k;
69814});
69815
69816/*
69817 * For reading we support both PKCS#1 and PKCS#8. If we find a private key,
69818 * we just take the public component of it and use that.
69819 */
69820function read(buf, options, forceType) {
69821 var input = buf;
69822 if (typeof (buf) !== 'string') {
69823 assert.buffer(buf, 'buf');
69824 buf = buf.toString('ascii');
69825 }
69826
69827 var lines = buf.trim().split(/[\r\n]+/g);
69828
69829 var m;
69830 var si = -1;
69831 while (!m && si < lines.length) {
69832 m = lines[++si].match(/*JSSTYLED*/
69833 /[-]+[ ]*BEGIN ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
69834 }
69835 assert.ok(m, 'invalid PEM header');
69836
69837 var m2;
69838 var ei = lines.length;
69839 while (!m2 && ei > 0) {
69840 m2 = lines[--ei].match(/*JSSTYLED*/
69841 /[-]+[ ]*END ([A-Z0-9][A-Za-z0-9]+ )?(PUBLIC|PRIVATE) KEY[ ]*[-]+/);
69842 }
69843 assert.ok(m2, 'invalid PEM footer');
69844
69845 /* Begin and end banners must match key type */
69846 assert.equal(m[2], m2[2]);
69847 var type = m[2].toLowerCase();
69848
69849 var alg;
69850 if (m[1]) {
69851 /* They also must match algorithms, if given */
69852 assert.equal(m[1], m2[1], 'PEM header and footer mismatch');
69853 alg = m[1].trim();
69854 }
69855
69856 lines = lines.slice(si, ei + 1);
69857
69858 var headers = {};
69859 while (true) {
69860 lines = lines.slice(1);
69861 m = lines[0].match(/*JSSTYLED*/
69862 /^([A-Za-z0-9-]+): (.+)$/);
69863 if (!m)
69864 break;
69865 headers[m[1].toLowerCase()] = m[2];
69866 }
69867
69868 /* Chop off the first and last lines */
69869 lines = lines.slice(0, -1).join('');
69870 buf = Buffer.from(lines, 'base64');
69871
69872 var cipher, key, iv;
69873 if (headers['proc-type']) {
69874 var parts = headers['proc-type'].split(',');
69875 if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
69876 if (typeof (options.passphrase) === 'string') {
69877 options.passphrase = Buffer.from(
69878 options.passphrase, 'utf-8');
69879 }
69880 if (!Buffer.isBuffer(options.passphrase)) {
69881 throw (new errors.KeyEncryptedError(
69882 options.filename, 'PEM'));
69883 } else {
69884 parts = headers['dek-info'].split(',');
69885 assert.ok(parts.length === 2);
69886 cipher = parts[0].toLowerCase();
69887 iv = Buffer.from(parts[1], 'hex');
69888 key = utils.opensslKeyDeriv(cipher, iv,
69889 options.passphrase, 1).key;
69890 }
69891 }
69892 }
69893
69894 if (alg && alg.toLowerCase() === 'encrypted') {
69895 var eder = new asn1.BerReader(buf);
69896 var pbesEnd;
69897 eder.readSequence();
69898
69899 eder.readSequence();
69900 pbesEnd = eder.offset + eder.length;
69901
69902 var method = eder.readOID();
69903 if (method !== OID_PBES2) {
69904 throw (new Error('Unsupported PEM/PKCS8 encryption ' +
69905 'scheme: ' + method));
69906 }
69907
69908 eder.readSequence(); /* PBES2-params */
69909
69910 eder.readSequence(); /* keyDerivationFunc */
69911 var kdfEnd = eder.offset + eder.length;
69912 var kdfOid = eder.readOID();
69913 if (kdfOid !== OID_PBKDF2)
69914 throw (new Error('Unsupported PBES2 KDF: ' + kdfOid));
69915 eder.readSequence();
69916 var salt = eder.readString(asn1.Ber.OctetString, true);
69917 var iterations = eder.readInt();
69918 var hashAlg = 'sha1';
69919 if (eder.offset < kdfEnd) {
69920 eder.readSequence();
69921 var hashAlgOid = eder.readOID();
69922 hashAlg = OID_TO_HASH[hashAlgOid];
69923 if (hashAlg === undefined) {
69924 throw (new Error('Unsupported PBKDF2 hash: ' +
69925 hashAlgOid));
69926 }
69927 }
69928 eder._offset = kdfEnd;
69929
69930 eder.readSequence(); /* encryptionScheme */
69931 var cipherOid = eder.readOID();
69932 cipher = OID_TO_CIPHER[cipherOid];
69933 if (cipher === undefined) {
69934 throw (new Error('Unsupported PBES2 cipher: ' +
69935 cipherOid));
69936 }
69937 iv = eder.readString(asn1.Ber.OctetString, true);
69938
69939 eder._offset = pbesEnd;
69940 buf = eder.readString(asn1.Ber.OctetString, true);
69941
69942 if (typeof (options.passphrase) === 'string') {
69943 options.passphrase = Buffer.from(
69944 options.passphrase, 'utf-8');
69945 }
69946 if (!Buffer.isBuffer(options.passphrase)) {
69947 throw (new errors.KeyEncryptedError(
69948 options.filename, 'PEM'));
69949 }
69950
69951 var cinfo = utils.opensshCipherInfo(cipher);
69952
69953 cipher = cinfo.opensslName;
69954 key = utils.pbkdf2(hashAlg, salt, iterations, cinfo.keySize,
69955 options.passphrase);
69956 alg = undefined;
69957 }
69958
69959 if (cipher && key && iv) {
69960 var cipherStream = crypto.createDecipheriv(cipher, key, iv);
69961 var chunk, chunks = [];
69962 cipherStream.once('error', function (e) {
69963 if (e.toString().indexOf('bad decrypt') !== -1) {
69964 throw (new Error('Incorrect passphrase ' +
69965 'supplied, could not decrypt key'));
69966 }
69967 throw (e);
69968 });
69969 cipherStream.write(buf);
69970 cipherStream.end();
69971 while ((chunk = cipherStream.read()) !== null)
69972 chunks.push(chunk);
69973 buf = Buffer.concat(chunks);
69974 }
69975
69976 /* The new OpenSSH internal format abuses PEM headers */
69977 if (alg && alg.toLowerCase() === 'openssh')
69978 return (sshpriv.readSSHPrivate(type, buf, options));
69979 if (alg && alg.toLowerCase() === 'ssh2')
69980 return (rfc4253.readType(type, buf, options));
69981
69982 var der = new asn1.BerReader(buf);
69983 der.originalInput = input;
69984
69985 /*
69986 * All of the PEM file types start with a sequence tag, so chop it
69987 * off here
69988 */
69989 der.readSequence();
69990
69991 /* PKCS#1 type keys name an algorithm in the banner explicitly */
69992 if (alg) {
69993 if (forceType)
69994 assert.strictEqual(forceType, 'pkcs1');
69995 return (pkcs1.readPkcs1(alg, type, der));
69996 } else {
69997 if (forceType)
69998 assert.strictEqual(forceType, 'pkcs8');
69999 return (pkcs8.readPkcs8(alg, type, der));
70000 }
70001}
70002
70003function write(key, options, type) {
70004 assert.object(key);
70005
70006 var alg = {
70007 'ecdsa': 'EC',
70008 'rsa': 'RSA',
70009 'dsa': 'DSA',
70010 'ed25519': 'EdDSA'
70011 }[key.type];
70012 var header;
70013
70014 var der = new asn1.BerWriter();
70015
70016 if (PrivateKey.isPrivateKey(key)) {
70017 if (type && type === 'pkcs8') {
70018 header = 'PRIVATE KEY';
70019 pkcs8.writePkcs8(der, key);
70020 } else {
70021 if (type)
70022 assert.strictEqual(type, 'pkcs1');
70023 header = alg + ' PRIVATE KEY';
70024 pkcs1.writePkcs1(der, key);
70025 }
70026
70027 } else if (Key.isKey(key)) {
70028 if (type && type === 'pkcs1') {
70029 header = alg + ' PUBLIC KEY';
70030 pkcs1.writePkcs1(der, key);
70031 } else {
70032 if (type)
70033 assert.strictEqual(type, 'pkcs8');
70034 header = 'PUBLIC KEY';
70035 pkcs8.writePkcs8(der, key);
70036 }
70037
70038 } else {
70039 throw (new Error('key is not a Key or PrivateKey'));
70040 }
70041
70042 var tmp = der.buffer.toString('base64');
70043 var len = tmp.length + (tmp.length / 64) +
70044 18 + 16 + header.length*2 + 10;
70045 var buf = Buffer.alloc(len);
70046 var o = 0;
70047 o += buf.write('-----BEGIN ' + header + '-----\n', o);
70048 for (var i = 0; i < tmp.length; ) {
70049 var limit = i + 64;
70050 if (limit > tmp.length)
70051 limit = tmp.length;
70052 o += buf.write(tmp.slice(i, limit), o);
70053 buf[o++] = 10;
70054 i = limit;
70055 }
70056 o += buf.write('-----END ' + header + '-----\n', o);
70057
70058 return (buf.slice(0, o));
70059}
70060
70061},{"../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){
70062// Copyright 2015 Joyent, Inc.
70063
70064module.exports = {
70065 read: read,
70066 readPkcs1: readPkcs1,
70067 write: write,
70068 writePkcs1: writePkcs1
70069};
70070
70071var assert = require('assert-plus');
70072var asn1 = require('asn1');
70073var Buffer = require('safer-buffer').Buffer;
70074var algs = require('../algs');
70075var utils = require('../utils');
70076
70077var Key = require('../key');
70078var PrivateKey = require('../private-key');
70079var pem = require('./pem');
70080
70081var pkcs8 = require('./pkcs8');
70082var readECDSACurve = pkcs8.readECDSACurve;
70083
70084function read(buf, options) {
70085 return (pem.read(buf, options, 'pkcs1'));
70086}
70087
70088function write(key, options) {
70089 return (pem.write(key, options, 'pkcs1'));
70090}
70091
70092/* Helper to read in a single mpint */
70093function readMPInt(der, nm) {
70094 assert.strictEqual(der.peek(), asn1.Ber.Integer,
70095 nm + ' is not an Integer');
70096 return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
70097}
70098
70099function readPkcs1(alg, type, der) {
70100 switch (alg) {
70101 case 'RSA':
70102 if (type === 'public')
70103 return (readPkcs1RSAPublic(der));
70104 else if (type === 'private')
70105 return (readPkcs1RSAPrivate(der));
70106 throw (new Error('Unknown key type: ' + type));
70107 case 'DSA':
70108 if (type === 'public')
70109 return (readPkcs1DSAPublic(der));
70110 else if (type === 'private')
70111 return (readPkcs1DSAPrivate(der));
70112 throw (new Error('Unknown key type: ' + type));
70113 case 'EC':
70114 case 'ECDSA':
70115 if (type === 'private')
70116 return (readPkcs1ECDSAPrivate(der));
70117 else if (type === 'public')
70118 return (readPkcs1ECDSAPublic(der));
70119 throw (new Error('Unknown key type: ' + type));
70120 case 'EDDSA':
70121 case 'EdDSA':
70122 if (type === 'private')
70123 return (readPkcs1EdDSAPrivate(der));
70124 throw (new Error(type + ' keys not supported with EdDSA'));
70125 default:
70126 throw (new Error('Unknown key algo: ' + alg));
70127 }
70128}
70129
70130function readPkcs1RSAPublic(der) {
70131 // modulus and exponent
70132 var n = readMPInt(der, 'modulus');
70133 var e = readMPInt(der, 'exponent');
70134
70135 // now, make the key
70136 var key = {
70137 type: 'rsa',
70138 parts: [
70139 { name: 'e', data: e },
70140 { name: 'n', data: n }
70141 ]
70142 };
70143
70144 return (new Key(key));
70145}
70146
70147function readPkcs1RSAPrivate(der) {
70148 var version = readMPInt(der, 'version');
70149 assert.strictEqual(version[0], 0);
70150
70151 // modulus then public exponent
70152 var n = readMPInt(der, 'modulus');
70153 var e = readMPInt(der, 'public exponent');
70154 var d = readMPInt(der, 'private exponent');
70155 var p = readMPInt(der, 'prime1');
70156 var q = readMPInt(der, 'prime2');
70157 var dmodp = readMPInt(der, 'exponent1');
70158 var dmodq = readMPInt(der, 'exponent2');
70159 var iqmp = readMPInt(der, 'iqmp');
70160
70161 // now, make the key
70162 var key = {
70163 type: 'rsa',
70164 parts: [
70165 { name: 'n', data: n },
70166 { name: 'e', data: e },
70167 { name: 'd', data: d },
70168 { name: 'iqmp', data: iqmp },
70169 { name: 'p', data: p },
70170 { name: 'q', data: q },
70171 { name: 'dmodp', data: dmodp },
70172 { name: 'dmodq', data: dmodq }
70173 ]
70174 };
70175
70176 return (new PrivateKey(key));
70177}
70178
70179function readPkcs1DSAPrivate(der) {
70180 var version = readMPInt(der, 'version');
70181 assert.strictEqual(version.readUInt8(0), 0);
70182
70183 var p = readMPInt(der, 'p');
70184 var q = readMPInt(der, 'q');
70185 var g = readMPInt(der, 'g');
70186 var y = readMPInt(der, 'y');
70187 var x = readMPInt(der, 'x');
70188
70189 // now, make the key
70190 var key = {
70191 type: 'dsa',
70192 parts: [
70193 { name: 'p', data: p },
70194 { name: 'q', data: q },
70195 { name: 'g', data: g },
70196 { name: 'y', data: y },
70197 { name: 'x', data: x }
70198 ]
70199 };
70200
70201 return (new PrivateKey(key));
70202}
70203
70204function readPkcs1EdDSAPrivate(der) {
70205 var version = readMPInt(der, 'version');
70206 assert.strictEqual(version.readUInt8(0), 1);
70207
70208 // private key
70209 var k = der.readString(asn1.Ber.OctetString, true);
70210
70211 der.readSequence(0xa0);
70212 var oid = der.readOID();
70213 assert.strictEqual(oid, '1.3.101.112', 'the ed25519 curve identifier');
70214
70215 der.readSequence(0xa1);
70216 var A = utils.readBitString(der);
70217
70218 var key = {
70219 type: 'ed25519',
70220 parts: [
70221 { name: 'A', data: utils.zeroPadToLength(A, 32) },
70222 { name: 'k', data: k }
70223 ]
70224 };
70225
70226 return (new PrivateKey(key));
70227}
70228
70229function readPkcs1DSAPublic(der) {
70230 var y = readMPInt(der, 'y');
70231 var p = readMPInt(der, 'p');
70232 var q = readMPInt(der, 'q');
70233 var g = readMPInt(der, 'g');
70234
70235 var key = {
70236 type: 'dsa',
70237 parts: [
70238 { name: 'y', data: y },
70239 { name: 'p', data: p },
70240 { name: 'q', data: q },
70241 { name: 'g', data: g }
70242 ]
70243 };
70244
70245 return (new Key(key));
70246}
70247
70248function readPkcs1ECDSAPublic(der) {
70249 der.readSequence();
70250
70251 var oid = der.readOID();
70252 assert.strictEqual(oid, '1.2.840.10045.2.1', 'must be ecPublicKey');
70253
70254 var curveOid = der.readOID();
70255
70256 var curve;
70257 var curves = Object.keys(algs.curves);
70258 for (var j = 0; j < curves.length; ++j) {
70259 var c = curves[j];
70260 var cd = algs.curves[c];
70261 if (cd.pkcs8oid === curveOid) {
70262 curve = c;
70263 break;
70264 }
70265 }
70266 assert.string(curve, 'a known ECDSA named curve');
70267
70268 var Q = der.readString(asn1.Ber.BitString, true);
70269 Q = utils.ecNormalize(Q);
70270
70271 var key = {
70272 type: 'ecdsa',
70273 parts: [
70274 { name: 'curve', data: Buffer.from(curve) },
70275 { name: 'Q', data: Q }
70276 ]
70277 };
70278
70279 return (new Key(key));
70280}
70281
70282function readPkcs1ECDSAPrivate(der) {
70283 var version = readMPInt(der, 'version');
70284 assert.strictEqual(version.readUInt8(0), 1);
70285
70286 // private key
70287 var d = der.readString(asn1.Ber.OctetString, true);
70288
70289 der.readSequence(0xa0);
70290 var curve = readECDSACurve(der);
70291 assert.string(curve, 'a known elliptic curve');
70292
70293 der.readSequence(0xa1);
70294 var Q = der.readString(asn1.Ber.BitString, true);
70295 Q = utils.ecNormalize(Q);
70296
70297 var key = {
70298 type: 'ecdsa',
70299 parts: [
70300 { name: 'curve', data: Buffer.from(curve) },
70301 { name: 'Q', data: Q },
70302 { name: 'd', data: d }
70303 ]
70304 };
70305
70306 return (new PrivateKey(key));
70307}
70308
70309function writePkcs1(der, key) {
70310 der.startSequence();
70311
70312 switch (key.type) {
70313 case 'rsa':
70314 if (PrivateKey.isPrivateKey(key))
70315 writePkcs1RSAPrivate(der, key);
70316 else
70317 writePkcs1RSAPublic(der, key);
70318 break;
70319 case 'dsa':
70320 if (PrivateKey.isPrivateKey(key))
70321 writePkcs1DSAPrivate(der, key);
70322 else
70323 writePkcs1DSAPublic(der, key);
70324 break;
70325 case 'ecdsa':
70326 if (PrivateKey.isPrivateKey(key))
70327 writePkcs1ECDSAPrivate(der, key);
70328 else
70329 writePkcs1ECDSAPublic(der, key);
70330 break;
70331 case 'ed25519':
70332 if (PrivateKey.isPrivateKey(key))
70333 writePkcs1EdDSAPrivate(der, key);
70334 else
70335 writePkcs1EdDSAPublic(der, key);
70336 break;
70337 default:
70338 throw (new Error('Unknown key algo: ' + key.type));
70339 }
70340
70341 der.endSequence();
70342}
70343
70344function writePkcs1RSAPublic(der, key) {
70345 der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
70346 der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
70347}
70348
70349function writePkcs1RSAPrivate(der, key) {
70350 var ver = Buffer.from([0]);
70351 der.writeBuffer(ver, asn1.Ber.Integer);
70352
70353 der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
70354 der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
70355 der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
70356 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70357 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70358 if (!key.part.dmodp || !key.part.dmodq)
70359 utils.addRSAMissing(key);
70360 der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
70361 der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
70362 der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
70363}
70364
70365function writePkcs1DSAPrivate(der, key) {
70366 var ver = Buffer.from([0]);
70367 der.writeBuffer(ver, asn1.Ber.Integer);
70368
70369 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70370 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70371 der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
70372 der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
70373 der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
70374}
70375
70376function writePkcs1DSAPublic(der, key) {
70377 der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
70378 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70379 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70380 der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
70381}
70382
70383function writePkcs1ECDSAPublic(der, key) {
70384 der.startSequence();
70385
70386 der.writeOID('1.2.840.10045.2.1'); /* ecPublicKey */
70387 var curve = key.part.curve.data.toString();
70388 var curveOid = algs.curves[curve].pkcs8oid;
70389 assert.string(curveOid, 'a known ECDSA named curve');
70390 der.writeOID(curveOid);
70391
70392 der.endSequence();
70393
70394 var Q = utils.ecNormalize(key.part.Q.data, true);
70395 der.writeBuffer(Q, asn1.Ber.BitString);
70396}
70397
70398function writePkcs1ECDSAPrivate(der, key) {
70399 var ver = Buffer.from([1]);
70400 der.writeBuffer(ver, asn1.Ber.Integer);
70401
70402 der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
70403
70404 der.startSequence(0xa0);
70405 var curve = key.part.curve.data.toString();
70406 var curveOid = algs.curves[curve].pkcs8oid;
70407 assert.string(curveOid, 'a known ECDSA named curve');
70408 der.writeOID(curveOid);
70409 der.endSequence();
70410
70411 der.startSequence(0xa1);
70412 var Q = utils.ecNormalize(key.part.Q.data, true);
70413 der.writeBuffer(Q, asn1.Ber.BitString);
70414 der.endSequence();
70415}
70416
70417function writePkcs1EdDSAPrivate(der, key) {
70418 var ver = Buffer.from([1]);
70419 der.writeBuffer(ver, asn1.Ber.Integer);
70420
70421 der.writeBuffer(key.part.k.data, asn1.Ber.OctetString);
70422
70423 der.startSequence(0xa0);
70424 der.writeOID('1.3.101.112');
70425 der.endSequence();
70426
70427 der.startSequence(0xa1);
70428 utils.writeBitString(der, key.part.A.data);
70429 der.endSequence();
70430}
70431
70432function writePkcs1EdDSAPublic(der, key) {
70433 throw (new Error('Public keys are not supported for EdDSA PKCS#1'));
70434}
70435
70436},{"../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){
70437// Copyright 2018 Joyent, Inc.
70438
70439module.exports = {
70440 read: read,
70441 readPkcs8: readPkcs8,
70442 write: write,
70443 writePkcs8: writePkcs8,
70444 pkcs8ToBuffer: pkcs8ToBuffer,
70445
70446 readECDSACurve: readECDSACurve,
70447 writeECDSACurve: writeECDSACurve
70448};
70449
70450var assert = require('assert-plus');
70451var asn1 = require('asn1');
70452var Buffer = require('safer-buffer').Buffer;
70453var algs = require('../algs');
70454var utils = require('../utils');
70455var Key = require('../key');
70456var PrivateKey = require('../private-key');
70457var pem = require('./pem');
70458
70459function read(buf, options) {
70460 return (pem.read(buf, options, 'pkcs8'));
70461}
70462
70463function write(key, options) {
70464 return (pem.write(key, options, 'pkcs8'));
70465}
70466
70467/* Helper to read in a single mpint */
70468function readMPInt(der, nm) {
70469 assert.strictEqual(der.peek(), asn1.Ber.Integer,
70470 nm + ' is not an Integer');
70471 return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
70472}
70473
70474function readPkcs8(alg, type, der) {
70475 /* Private keys in pkcs#8 format have a weird extra int */
70476 if (der.peek() === asn1.Ber.Integer) {
70477 assert.strictEqual(type, 'private',
70478 'unexpected Integer at start of public key');
70479 der.readString(asn1.Ber.Integer, true);
70480 }
70481
70482 der.readSequence();
70483 var next = der.offset + der.length;
70484
70485 var oid = der.readOID();
70486 switch (oid) {
70487 case '1.2.840.113549.1.1.1':
70488 der._offset = next;
70489 if (type === 'public')
70490 return (readPkcs8RSAPublic(der));
70491 else
70492 return (readPkcs8RSAPrivate(der));
70493 case '1.2.840.10040.4.1':
70494 if (type === 'public')
70495 return (readPkcs8DSAPublic(der));
70496 else
70497 return (readPkcs8DSAPrivate(der));
70498 case '1.2.840.10045.2.1':
70499 if (type === 'public')
70500 return (readPkcs8ECDSAPublic(der));
70501 else
70502 return (readPkcs8ECDSAPrivate(der));
70503 case '1.3.101.112':
70504 if (type === 'public') {
70505 return (readPkcs8EdDSAPublic(der));
70506 } else {
70507 return (readPkcs8EdDSAPrivate(der));
70508 }
70509 case '1.3.101.110':
70510 if (type === 'public') {
70511 return (readPkcs8X25519Public(der));
70512 } else {
70513 return (readPkcs8X25519Private(der));
70514 }
70515 default:
70516 throw (new Error('Unknown key type OID ' + oid));
70517 }
70518}
70519
70520function readPkcs8RSAPublic(der) {
70521 // bit string sequence
70522 der.readSequence(asn1.Ber.BitString);
70523 der.readByte();
70524 der.readSequence();
70525
70526 // modulus
70527 var n = readMPInt(der, 'modulus');
70528 var e = readMPInt(der, 'exponent');
70529
70530 // now, make the key
70531 var key = {
70532 type: 'rsa',
70533 source: der.originalInput,
70534 parts: [
70535 { name: 'e', data: e },
70536 { name: 'n', data: n }
70537 ]
70538 };
70539
70540 return (new Key(key));
70541}
70542
70543function readPkcs8RSAPrivate(der) {
70544 der.readSequence(asn1.Ber.OctetString);
70545 der.readSequence();
70546
70547 var ver = readMPInt(der, 'version');
70548 assert.equal(ver[0], 0x0, 'unknown RSA private key version');
70549
70550 // modulus then public exponent
70551 var n = readMPInt(der, 'modulus');
70552 var e = readMPInt(der, 'public exponent');
70553 var d = readMPInt(der, 'private exponent');
70554 var p = readMPInt(der, 'prime1');
70555 var q = readMPInt(der, 'prime2');
70556 var dmodp = readMPInt(der, 'exponent1');
70557 var dmodq = readMPInt(der, 'exponent2');
70558 var iqmp = readMPInt(der, 'iqmp');
70559
70560 // now, make the key
70561 var key = {
70562 type: 'rsa',
70563 parts: [
70564 { name: 'n', data: n },
70565 { name: 'e', data: e },
70566 { name: 'd', data: d },
70567 { name: 'iqmp', data: iqmp },
70568 { name: 'p', data: p },
70569 { name: 'q', data: q },
70570 { name: 'dmodp', data: dmodp },
70571 { name: 'dmodq', data: dmodq }
70572 ]
70573 };
70574
70575 return (new PrivateKey(key));
70576}
70577
70578function readPkcs8DSAPublic(der) {
70579 der.readSequence();
70580
70581 var p = readMPInt(der, 'p');
70582 var q = readMPInt(der, 'q');
70583 var g = readMPInt(der, 'g');
70584
70585 // bit string sequence
70586 der.readSequence(asn1.Ber.BitString);
70587 der.readByte();
70588
70589 var y = readMPInt(der, 'y');
70590
70591 // now, make the key
70592 var key = {
70593 type: 'dsa',
70594 parts: [
70595 { name: 'p', data: p },
70596 { name: 'q', data: q },
70597 { name: 'g', data: g },
70598 { name: 'y', data: y }
70599 ]
70600 };
70601
70602 return (new Key(key));
70603}
70604
70605function readPkcs8DSAPrivate(der) {
70606 der.readSequence();
70607
70608 var p = readMPInt(der, 'p');
70609 var q = readMPInt(der, 'q');
70610 var g = readMPInt(der, 'g');
70611
70612 der.readSequence(asn1.Ber.OctetString);
70613 var x = readMPInt(der, 'x');
70614
70615 /* The pkcs#8 format does not include the public key */
70616 var y = utils.calculateDSAPublic(g, p, x);
70617
70618 var key = {
70619 type: 'dsa',
70620 parts: [
70621 { name: 'p', data: p },
70622 { name: 'q', data: q },
70623 { name: 'g', data: g },
70624 { name: 'y', data: y },
70625 { name: 'x', data: x }
70626 ]
70627 };
70628
70629 return (new PrivateKey(key));
70630}
70631
70632function readECDSACurve(der) {
70633 var curveName, curveNames;
70634 var j, c, cd;
70635
70636 if (der.peek() === asn1.Ber.OID) {
70637 var oid = der.readOID();
70638
70639 curveNames = Object.keys(algs.curves);
70640 for (j = 0; j < curveNames.length; ++j) {
70641 c = curveNames[j];
70642 cd = algs.curves[c];
70643 if (cd.pkcs8oid === oid) {
70644 curveName = c;
70645 break;
70646 }
70647 }
70648
70649 } else {
70650 // ECParameters sequence
70651 der.readSequence();
70652 var version = der.readString(asn1.Ber.Integer, true);
70653 assert.strictEqual(version[0], 1, 'ECDSA key not version 1');
70654
70655 var curve = {};
70656
70657 // FieldID sequence
70658 der.readSequence();
70659 var fieldTypeOid = der.readOID();
70660 assert.strictEqual(fieldTypeOid, '1.2.840.10045.1.1',
70661 'ECDSA key is not from a prime-field');
70662 var p = curve.p = utils.mpNormalize(
70663 der.readString(asn1.Ber.Integer, true));
70664 /*
70665 * p always starts with a 1 bit, so count the zeros to get its
70666 * real size.
70667 */
70668 curve.size = p.length * 8 - utils.countZeros(p);
70669
70670 // Curve sequence
70671 der.readSequence();
70672 curve.a = utils.mpNormalize(
70673 der.readString(asn1.Ber.OctetString, true));
70674 curve.b = utils.mpNormalize(
70675 der.readString(asn1.Ber.OctetString, true));
70676 if (der.peek() === asn1.Ber.BitString)
70677 curve.s = der.readString(asn1.Ber.BitString, true);
70678
70679 // Combined Gx and Gy
70680 curve.G = der.readString(asn1.Ber.OctetString, true);
70681 assert.strictEqual(curve.G[0], 0x4,
70682 'uncompressed G is required');
70683
70684 curve.n = utils.mpNormalize(
70685 der.readString(asn1.Ber.Integer, true));
70686 curve.h = utils.mpNormalize(
70687 der.readString(asn1.Ber.Integer, true));
70688 assert.strictEqual(curve.h[0], 0x1, 'a cofactor=1 curve is ' +
70689 'required');
70690
70691 curveNames = Object.keys(algs.curves);
70692 var ks = Object.keys(curve);
70693 for (j = 0; j < curveNames.length; ++j) {
70694 c = curveNames[j];
70695 cd = algs.curves[c];
70696 var equal = true;
70697 for (var i = 0; i < ks.length; ++i) {
70698 var k = ks[i];
70699 if (cd[k] === undefined)
70700 continue;
70701 if (typeof (cd[k]) === 'object' &&
70702 cd[k].equals !== undefined) {
70703 if (!cd[k].equals(curve[k])) {
70704 equal = false;
70705 break;
70706 }
70707 } else if (Buffer.isBuffer(cd[k])) {
70708 if (cd[k].toString('binary')
70709 !== curve[k].toString('binary')) {
70710 equal = false;
70711 break;
70712 }
70713 } else {
70714 if (cd[k] !== curve[k]) {
70715 equal = false;
70716 break;
70717 }
70718 }
70719 }
70720 if (equal) {
70721 curveName = c;
70722 break;
70723 }
70724 }
70725 }
70726 return (curveName);
70727}
70728
70729function readPkcs8ECDSAPrivate(der) {
70730 var curveName = readECDSACurve(der);
70731 assert.string(curveName, 'a known elliptic curve');
70732
70733 der.readSequence(asn1.Ber.OctetString);
70734 der.readSequence();
70735
70736 var version = readMPInt(der, 'version');
70737 assert.equal(version[0], 1, 'unknown version of ECDSA key');
70738
70739 var d = der.readString(asn1.Ber.OctetString, true);
70740 var Q;
70741
70742 if (der.peek() == 0xa0) {
70743 der.readSequence(0xa0);
70744 der._offset += der.length;
70745 }
70746 if (der.peek() == 0xa1) {
70747 der.readSequence(0xa1);
70748 Q = der.readString(asn1.Ber.BitString, true);
70749 Q = utils.ecNormalize(Q);
70750 }
70751
70752 if (Q === undefined) {
70753 var pub = utils.publicFromPrivateECDSA(curveName, d);
70754 Q = pub.part.Q.data;
70755 }
70756
70757 var key = {
70758 type: 'ecdsa',
70759 parts: [
70760 { name: 'curve', data: Buffer.from(curveName) },
70761 { name: 'Q', data: Q },
70762 { name: 'd', data: d }
70763 ]
70764 };
70765
70766 return (new PrivateKey(key));
70767}
70768
70769function readPkcs8ECDSAPublic(der) {
70770 var curveName = readECDSACurve(der);
70771 assert.string(curveName, 'a known elliptic curve');
70772
70773 var Q = der.readString(asn1.Ber.BitString, true);
70774 Q = utils.ecNormalize(Q);
70775
70776 var key = {
70777 type: 'ecdsa',
70778 parts: [
70779 { name: 'curve', data: Buffer.from(curveName) },
70780 { name: 'Q', data: Q }
70781 ]
70782 };
70783
70784 return (new Key(key));
70785}
70786
70787function readPkcs8EdDSAPublic(der) {
70788 if (der.peek() === 0x00)
70789 der.readByte();
70790
70791 var A = utils.readBitString(der);
70792
70793 var key = {
70794 type: 'ed25519',
70795 parts: [
70796 { name: 'A', data: utils.zeroPadToLength(A, 32) }
70797 ]
70798 };
70799
70800 return (new Key(key));
70801}
70802
70803function readPkcs8X25519Public(der) {
70804 var A = utils.readBitString(der);
70805
70806 var key = {
70807 type: 'curve25519',
70808 parts: [
70809 { name: 'A', data: utils.zeroPadToLength(A, 32) }
70810 ]
70811 };
70812
70813 return (new Key(key));
70814}
70815
70816function readPkcs8EdDSAPrivate(der) {
70817 if (der.peek() === 0x00)
70818 der.readByte();
70819
70820 der.readSequence(asn1.Ber.OctetString);
70821 var k = der.readString(asn1.Ber.OctetString, true);
70822 k = utils.zeroPadToLength(k, 32);
70823
70824 var A;
70825 if (der.peek() === asn1.Ber.BitString) {
70826 A = utils.readBitString(der);
70827 A = utils.zeroPadToLength(A, 32);
70828 } else {
70829 A = utils.calculateED25519Public(k);
70830 }
70831
70832 var key = {
70833 type: 'ed25519',
70834 parts: [
70835 { name: 'A', data: utils.zeroPadToLength(A, 32) },
70836 { name: 'k', data: utils.zeroPadToLength(k, 32) }
70837 ]
70838 };
70839
70840 return (new PrivateKey(key));
70841}
70842
70843function readPkcs8X25519Private(der) {
70844 if (der.peek() === 0x00)
70845 der.readByte();
70846
70847 der.readSequence(asn1.Ber.OctetString);
70848 var k = der.readString(asn1.Ber.OctetString, true);
70849 k = utils.zeroPadToLength(k, 32);
70850
70851 var A = utils.calculateX25519Public(k);
70852
70853 var key = {
70854 type: 'curve25519',
70855 parts: [
70856 { name: 'A', data: utils.zeroPadToLength(A, 32) },
70857 { name: 'k', data: utils.zeroPadToLength(k, 32) }
70858 ]
70859 };
70860
70861 return (new PrivateKey(key));
70862}
70863
70864function pkcs8ToBuffer(key) {
70865 var der = new asn1.BerWriter();
70866 writePkcs8(der, key);
70867 return (der.buffer);
70868}
70869
70870function writePkcs8(der, key) {
70871 der.startSequence();
70872
70873 if (PrivateKey.isPrivateKey(key)) {
70874 var sillyInt = Buffer.from([0]);
70875 der.writeBuffer(sillyInt, asn1.Ber.Integer);
70876 }
70877
70878 der.startSequence();
70879 switch (key.type) {
70880 case 'rsa':
70881 der.writeOID('1.2.840.113549.1.1.1');
70882 if (PrivateKey.isPrivateKey(key))
70883 writePkcs8RSAPrivate(key, der);
70884 else
70885 writePkcs8RSAPublic(key, der);
70886 break;
70887 case 'dsa':
70888 der.writeOID('1.2.840.10040.4.1');
70889 if (PrivateKey.isPrivateKey(key))
70890 writePkcs8DSAPrivate(key, der);
70891 else
70892 writePkcs8DSAPublic(key, der);
70893 break;
70894 case 'ecdsa':
70895 der.writeOID('1.2.840.10045.2.1');
70896 if (PrivateKey.isPrivateKey(key))
70897 writePkcs8ECDSAPrivate(key, der);
70898 else
70899 writePkcs8ECDSAPublic(key, der);
70900 break;
70901 case 'ed25519':
70902 der.writeOID('1.3.101.112');
70903 if (PrivateKey.isPrivateKey(key))
70904 throw (new Error('Ed25519 private keys in pkcs8 ' +
70905 'format are not supported'));
70906 writePkcs8EdDSAPublic(key, der);
70907 break;
70908 default:
70909 throw (new Error('Unsupported key type: ' + key.type));
70910 }
70911
70912 der.endSequence();
70913}
70914
70915function writePkcs8RSAPrivate(key, der) {
70916 der.writeNull();
70917 der.endSequence();
70918
70919 der.startSequence(asn1.Ber.OctetString);
70920 der.startSequence();
70921
70922 var version = Buffer.from([0]);
70923 der.writeBuffer(version, asn1.Ber.Integer);
70924
70925 der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
70926 der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
70927 der.writeBuffer(key.part.d.data, asn1.Ber.Integer);
70928 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70929 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70930 if (!key.part.dmodp || !key.part.dmodq)
70931 utils.addRSAMissing(key);
70932 der.writeBuffer(key.part.dmodp.data, asn1.Ber.Integer);
70933 der.writeBuffer(key.part.dmodq.data, asn1.Ber.Integer);
70934 der.writeBuffer(key.part.iqmp.data, asn1.Ber.Integer);
70935
70936 der.endSequence();
70937 der.endSequence();
70938}
70939
70940function writePkcs8RSAPublic(key, der) {
70941 der.writeNull();
70942 der.endSequence();
70943
70944 der.startSequence(asn1.Ber.BitString);
70945 der.writeByte(0x00);
70946
70947 der.startSequence();
70948 der.writeBuffer(key.part.n.data, asn1.Ber.Integer);
70949 der.writeBuffer(key.part.e.data, asn1.Ber.Integer);
70950 der.endSequence();
70951
70952 der.endSequence();
70953}
70954
70955function writePkcs8DSAPrivate(key, der) {
70956 der.startSequence();
70957 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70958 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70959 der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
70960 der.endSequence();
70961
70962 der.endSequence();
70963
70964 der.startSequence(asn1.Ber.OctetString);
70965 der.writeBuffer(key.part.x.data, asn1.Ber.Integer);
70966 der.endSequence();
70967}
70968
70969function writePkcs8DSAPublic(key, der) {
70970 der.startSequence();
70971 der.writeBuffer(key.part.p.data, asn1.Ber.Integer);
70972 der.writeBuffer(key.part.q.data, asn1.Ber.Integer);
70973 der.writeBuffer(key.part.g.data, asn1.Ber.Integer);
70974 der.endSequence();
70975 der.endSequence();
70976
70977 der.startSequence(asn1.Ber.BitString);
70978 der.writeByte(0x00);
70979 der.writeBuffer(key.part.y.data, asn1.Ber.Integer);
70980 der.endSequence();
70981}
70982
70983function writeECDSACurve(key, der) {
70984 var curve = algs.curves[key.curve];
70985 if (curve.pkcs8oid) {
70986 /* This one has a name in pkcs#8, so just write the oid */
70987 der.writeOID(curve.pkcs8oid);
70988
70989 } else {
70990 // ECParameters sequence
70991 der.startSequence();
70992
70993 var version = Buffer.from([1]);
70994 der.writeBuffer(version, asn1.Ber.Integer);
70995
70996 // FieldID sequence
70997 der.startSequence();
70998 der.writeOID('1.2.840.10045.1.1'); // prime-field
70999 der.writeBuffer(curve.p, asn1.Ber.Integer);
71000 der.endSequence();
71001
71002 // Curve sequence
71003 der.startSequence();
71004 var a = curve.p;
71005 if (a[0] === 0x0)
71006 a = a.slice(1);
71007 der.writeBuffer(a, asn1.Ber.OctetString);
71008 der.writeBuffer(curve.b, asn1.Ber.OctetString);
71009 der.writeBuffer(curve.s, asn1.Ber.BitString);
71010 der.endSequence();
71011
71012 der.writeBuffer(curve.G, asn1.Ber.OctetString);
71013 der.writeBuffer(curve.n, asn1.Ber.Integer);
71014 var h = curve.h;
71015 if (!h) {
71016 h = Buffer.from([1]);
71017 }
71018 der.writeBuffer(h, asn1.Ber.Integer);
71019
71020 // ECParameters
71021 der.endSequence();
71022 }
71023}
71024
71025function writePkcs8ECDSAPublic(key, der) {
71026 writeECDSACurve(key, der);
71027 der.endSequence();
71028
71029 var Q = utils.ecNormalize(key.part.Q.data, true);
71030 der.writeBuffer(Q, asn1.Ber.BitString);
71031}
71032
71033function writePkcs8ECDSAPrivate(key, der) {
71034 writeECDSACurve(key, der);
71035 der.endSequence();
71036
71037 der.startSequence(asn1.Ber.OctetString);
71038 der.startSequence();
71039
71040 var version = Buffer.from([1]);
71041 der.writeBuffer(version, asn1.Ber.Integer);
71042
71043 der.writeBuffer(key.part.d.data, asn1.Ber.OctetString);
71044
71045 der.startSequence(0xa1);
71046 var Q = utils.ecNormalize(key.part.Q.data, true);
71047 der.writeBuffer(Q, asn1.Ber.BitString);
71048 der.endSequence();
71049
71050 der.endSequence();
71051 der.endSequence();
71052}
71053
71054function writePkcs8EdDSAPublic(key, der) {
71055 der.endSequence();
71056
71057 utils.writeBitString(der, key.part.A.data);
71058}
71059
71060function writePkcs8EdDSAPrivate(key, der) {
71061 der.endSequence();
71062
71063 var k = utils.mpNormalize(key.part.k.data, true);
71064 der.startSequence(asn1.Ber.OctetString);
71065 der.writeBuffer(k, asn1.Ber.OctetString);
71066 der.endSequence();
71067}
71068
71069},{"../algs":335,"../key":355,"../private-key":356,"../utils":359,"./pem":344,"asn1":66,"assert-plus":67,"safer-buffer":326}],347:[function(require,module,exports){
71070// Copyright 2018 Joyent, Inc.
71071
71072module.exports = {
71073 read: read,
71074 write: write
71075};
71076
71077var assert = require('assert-plus');
71078var Buffer = require('safer-buffer').Buffer;
71079var rfc4253 = require('./rfc4253');
71080var Key = require('../key');
71081
71082var errors = require('../errors');
71083
71084function read(buf, options) {
71085 var lines = buf.toString('ascii').split(/[\r\n]+/);
71086 var found = false;
71087 var parts;
71088 var si = 0;
71089 while (si < lines.length) {
71090 parts = splitHeader(lines[si++]);
71091 if (parts &&
71092 parts[0].toLowerCase() === 'putty-user-key-file-2') {
71093 found = true;
71094 break;
71095 }
71096 }
71097 if (!found) {
71098 throw (new Error('No PuTTY format first line found'));
71099 }
71100 var alg = parts[1];
71101
71102 parts = splitHeader(lines[si++]);
71103 assert.equal(parts[0].toLowerCase(), 'encryption');
71104
71105 parts = splitHeader(lines[si++]);
71106 assert.equal(parts[0].toLowerCase(), 'comment');
71107 var comment = parts[1];
71108
71109 parts = splitHeader(lines[si++]);
71110 assert.equal(parts[0].toLowerCase(), 'public-lines');
71111 var publicLines = parseInt(parts[1], 10);
71112 if (!isFinite(publicLines) || publicLines < 0 ||
71113 publicLines > lines.length) {
71114 throw (new Error('Invalid public-lines count'));
71115 }
71116
71117 var publicBuf = Buffer.from(
71118 lines.slice(si, si + publicLines).join(''), 'base64');
71119 var keyType = rfc4253.algToKeyType(alg);
71120 var key = rfc4253.read(publicBuf);
71121 if (key.type !== keyType) {
71122 throw (new Error('Outer key algorithm mismatch'));
71123 }
71124 key.comment = comment;
71125 return (key);
71126}
71127
71128function splitHeader(line) {
71129 var idx = line.indexOf(':');
71130 if (idx === -1)
71131 return (null);
71132 var header = line.slice(0, idx);
71133 ++idx;
71134 while (line[idx] === ' ')
71135 ++idx;
71136 var rest = line.slice(idx);
71137 return ([header, rest]);
71138}
71139
71140function write(key, options) {
71141 assert.object(key);
71142 if (!Key.isKey(key))
71143 throw (new Error('Must be a public key'));
71144
71145 var alg = rfc4253.keyTypeToAlg(key);
71146 var buf = rfc4253.write(key);
71147 var comment = key.comment || '';
71148
71149 var b64 = buf.toString('base64');
71150 var lines = wrap(b64, 64);
71151
71152 lines.unshift('Public-Lines: ' + lines.length);
71153 lines.unshift('Comment: ' + comment);
71154 lines.unshift('Encryption: none');
71155 lines.unshift('PuTTY-User-Key-File-2: ' + alg);
71156
71157 return (Buffer.from(lines.join('\n') + '\n'));
71158}
71159
71160function wrap(txt, len) {
71161 var lines = [];
71162 var pos = 0;
71163 while (pos < txt.length) {
71164 lines.push(txt.slice(pos, pos + 64));
71165 pos += 64;
71166 }
71167 return (lines);
71168}
71169
71170},{"../errors":339,"../key":355,"./rfc4253":348,"assert-plus":67,"safer-buffer":326}],348:[function(require,module,exports){
71171// Copyright 2015 Joyent, Inc.
71172
71173module.exports = {
71174 read: read.bind(undefined, false, undefined),
71175 readType: read.bind(undefined, false),
71176 write: write,
71177 /* semi-private api, used by sshpk-agent */
71178 readPartial: read.bind(undefined, true),
71179
71180 /* shared with ssh format */
71181 readInternal: read,
71182 keyTypeToAlg: keyTypeToAlg,
71183 algToKeyType: algToKeyType
71184};
71185
71186var assert = require('assert-plus');
71187var Buffer = require('safer-buffer').Buffer;
71188var algs = require('../algs');
71189var utils = require('../utils');
71190var Key = require('../key');
71191var PrivateKey = require('../private-key');
71192var SSHBuffer = require('../ssh-buffer');
71193
71194function algToKeyType(alg) {
71195 assert.string(alg);
71196 if (alg === 'ssh-dss')
71197 return ('dsa');
71198 else if (alg === 'ssh-rsa')
71199 return ('rsa');
71200 else if (alg === 'ssh-ed25519')
71201 return ('ed25519');
71202 else if (alg === 'ssh-curve25519')
71203 return ('curve25519');
71204 else if (alg.match(/^ecdsa-sha2-/))
71205 return ('ecdsa');
71206 else
71207 throw (new Error('Unknown algorithm ' + alg));
71208}
71209
71210function keyTypeToAlg(key) {
71211 assert.object(key);
71212 if (key.type === 'dsa')
71213 return ('ssh-dss');
71214 else if (key.type === 'rsa')
71215 return ('ssh-rsa');
71216 else if (key.type === 'ed25519')
71217 return ('ssh-ed25519');
71218 else if (key.type === 'curve25519')
71219 return ('ssh-curve25519');
71220 else if (key.type === 'ecdsa')
71221 return ('ecdsa-sha2-' + key.part.curve.data.toString());
71222 else
71223 throw (new Error('Unknown key type ' + key.type));
71224}
71225
71226function read(partial, type, buf, options) {
71227 if (typeof (buf) === 'string')
71228 buf = Buffer.from(buf);
71229 assert.buffer(buf, 'buf');
71230
71231 var key = {};
71232
71233 var parts = key.parts = [];
71234 var sshbuf = new SSHBuffer({buffer: buf});
71235
71236 var alg = sshbuf.readString();
71237 assert.ok(!sshbuf.atEnd(), 'key must have at least one part');
71238
71239 key.type = algToKeyType(alg);
71240
71241 var partCount = algs.info[key.type].parts.length;
71242 if (type && type === 'private')
71243 partCount = algs.privInfo[key.type].parts.length;
71244
71245 while (!sshbuf.atEnd() && parts.length < partCount)
71246 parts.push(sshbuf.readPart());
71247 while (!partial && !sshbuf.atEnd())
71248 parts.push(sshbuf.readPart());
71249
71250 assert.ok(parts.length >= 1,
71251 'key must have at least one part');
71252 assert.ok(partial || sshbuf.atEnd(),
71253 'leftover bytes at end of key');
71254
71255 var Constructor = Key;
71256 var algInfo = algs.info[key.type];
71257 if (type === 'private' || algInfo.parts.length !== parts.length) {
71258 algInfo = algs.privInfo[key.type];
71259 Constructor = PrivateKey;
71260 }
71261 assert.strictEqual(algInfo.parts.length, parts.length);
71262
71263 if (key.type === 'ecdsa') {
71264 var res = /^ecdsa-sha2-(.+)$/.exec(alg);
71265 assert.ok(res !== null);
71266 assert.strictEqual(res[1], parts[0].data.toString());
71267 }
71268
71269 var normalized = true;
71270 for (var i = 0; i < algInfo.parts.length; ++i) {
71271 var p = parts[i];
71272 p.name = algInfo.parts[i];
71273 /*
71274 * OpenSSH stores ed25519 "private" keys as seed + public key
71275 * concat'd together (k followed by A). We want to keep them
71276 * separate for other formats that don't do this.
71277 */
71278 if (key.type === 'ed25519' && p.name === 'k')
71279 p.data = p.data.slice(0, 32);
71280
71281 if (p.name !== 'curve' && algInfo.normalize !== false) {
71282 var nd;
71283 if (key.type === 'ed25519') {
71284 nd = utils.zeroPadToLength(p.data, 32);
71285 } else {
71286 nd = utils.mpNormalize(p.data);
71287 }
71288 if (nd.toString('binary') !==
71289 p.data.toString('binary')) {
71290 p.data = nd;
71291 normalized = false;
71292 }
71293 }
71294 }
71295
71296 if (normalized)
71297 key._rfc4253Cache = sshbuf.toBuffer();
71298
71299 if (partial && typeof (partial) === 'object') {
71300 partial.remainder = sshbuf.remainder();
71301 partial.consumed = sshbuf._offset;
71302 }
71303
71304 return (new Constructor(key));
71305}
71306
71307function write(key, options) {
71308 assert.object(key);
71309
71310 var alg = keyTypeToAlg(key);
71311 var i;
71312
71313 var algInfo = algs.info[key.type];
71314 if (PrivateKey.isPrivateKey(key))
71315 algInfo = algs.privInfo[key.type];
71316 var parts = algInfo.parts;
71317
71318 var buf = new SSHBuffer({});
71319
71320 buf.writeString(alg);
71321
71322 for (i = 0; i < parts.length; ++i) {
71323 var data = key.part[parts[i]].data;
71324 if (algInfo.normalize !== false) {
71325 if (key.type === 'ed25519')
71326 data = utils.zeroPadToLength(data, 32);
71327 else
71328 data = utils.mpNormalize(data);
71329 }
71330 if (key.type === 'ed25519' && parts[i] === 'k')
71331 data = Buffer.concat([data, key.part.A.data]);
71332 buf.writeBuffer(data);
71333 }
71334
71335 return (buf.toBuffer());
71336}
71337
71338},{"../algs":335,"../key":355,"../private-key":356,"../ssh-buffer":358,"../utils":359,"assert-plus":67,"safer-buffer":326}],349:[function(require,module,exports){
71339// Copyright 2015 Joyent, Inc.
71340
71341module.exports = {
71342 read: read,
71343 readSSHPrivate: readSSHPrivate,
71344 write: write
71345};
71346
71347var assert = require('assert-plus');
71348var asn1 = require('asn1');
71349var Buffer = require('safer-buffer').Buffer;
71350var algs = require('../algs');
71351var utils = require('../utils');
71352var crypto = require('crypto');
71353
71354var Key = require('../key');
71355var PrivateKey = require('../private-key');
71356var pem = require('./pem');
71357var rfc4253 = require('./rfc4253');
71358var SSHBuffer = require('../ssh-buffer');
71359var errors = require('../errors');
71360
71361var bcrypt;
71362
71363function read(buf, options) {
71364 return (pem.read(buf, options));
71365}
71366
71367var MAGIC = 'openssh-key-v1';
71368
71369function readSSHPrivate(type, buf, options) {
71370 buf = new SSHBuffer({buffer: buf});
71371
71372 var magic = buf.readCString();
71373 assert.strictEqual(magic, MAGIC, 'bad magic string');
71374
71375 var cipher = buf.readString();
71376 var kdf = buf.readString();
71377 var kdfOpts = buf.readBuffer();
71378
71379 var nkeys = buf.readInt();
71380 if (nkeys !== 1) {
71381 throw (new Error('OpenSSH-format key file contains ' +
71382 'multiple keys: this is unsupported.'));
71383 }
71384
71385 var pubKey = buf.readBuffer();
71386
71387 if (type === 'public') {
71388 assert.ok(buf.atEnd(), 'excess bytes left after key');
71389 return (rfc4253.read(pubKey));
71390 }
71391
71392 var privKeyBlob = buf.readBuffer();
71393 assert.ok(buf.atEnd(), 'excess bytes left after key');
71394
71395 var kdfOptsBuf = new SSHBuffer({ buffer: kdfOpts });
71396 switch (kdf) {
71397 case 'none':
71398 if (cipher !== 'none') {
71399 throw (new Error('OpenSSH-format key uses KDF "none" ' +
71400 'but specifies a cipher other than "none"'));
71401 }
71402 break;
71403 case 'bcrypt':
71404 var salt = kdfOptsBuf.readBuffer();
71405 var rounds = kdfOptsBuf.readInt();
71406 var cinf = utils.opensshCipherInfo(cipher);
71407 if (bcrypt === undefined) {
71408 bcrypt = require('bcrypt-pbkdf');
71409 }
71410
71411 if (typeof (options.passphrase) === 'string') {
71412 options.passphrase = Buffer.from(options.passphrase,
71413 'utf-8');
71414 }
71415 if (!Buffer.isBuffer(options.passphrase)) {
71416 throw (new errors.KeyEncryptedError(
71417 options.filename, 'OpenSSH'));
71418 }
71419
71420 var pass = new Uint8Array(options.passphrase);
71421 var salti = new Uint8Array(salt);
71422 /* Use the pbkdf to derive both the key and the IV. */
71423 var out = new Uint8Array(cinf.keySize + cinf.blockSize);
71424 var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length,
71425 out, out.length, rounds);
71426 if (res !== 0) {
71427 throw (new Error('bcrypt_pbkdf function returned ' +
71428 'failure, parameters invalid'));
71429 }
71430 out = Buffer.from(out);
71431 var ckey = out.slice(0, cinf.keySize);
71432 var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
71433 var cipherStream = crypto.createDecipheriv(cinf.opensslName,
71434 ckey, iv);
71435 cipherStream.setAutoPadding(false);
71436 var chunk, chunks = [];
71437 cipherStream.once('error', function (e) {
71438 if (e.toString().indexOf('bad decrypt') !== -1) {
71439 throw (new Error('Incorrect passphrase ' +
71440 'supplied, could not decrypt key'));
71441 }
71442 throw (e);
71443 });
71444 cipherStream.write(privKeyBlob);
71445 cipherStream.end();
71446 while ((chunk = cipherStream.read()) !== null)
71447 chunks.push(chunk);
71448 privKeyBlob = Buffer.concat(chunks);
71449 break;
71450 default:
71451 throw (new Error(
71452 'OpenSSH-format key uses unknown KDF "' + kdf + '"'));
71453 }
71454
71455 buf = new SSHBuffer({buffer: privKeyBlob});
71456
71457 var checkInt1 = buf.readInt();
71458 var checkInt2 = buf.readInt();
71459 if (checkInt1 !== checkInt2) {
71460 throw (new Error('Incorrect passphrase supplied, could not ' +
71461 'decrypt key'));
71462 }
71463
71464 var ret = {};
71465 var key = rfc4253.readInternal(ret, 'private', buf.remainder());
71466
71467 buf.skip(ret.consumed);
71468
71469 var comment = buf.readString();
71470 key.comment = comment;
71471
71472 return (key);
71473}
71474
71475function write(key, options) {
71476 var pubKey;
71477 if (PrivateKey.isPrivateKey(key))
71478 pubKey = key.toPublic();
71479 else
71480 pubKey = key;
71481
71482 var cipher = 'none';
71483 var kdf = 'none';
71484 var kdfopts = Buffer.alloc(0);
71485 var cinf = { blockSize: 8 };
71486 var passphrase;
71487 if (options !== undefined) {
71488 passphrase = options.passphrase;
71489 if (typeof (passphrase) === 'string')
71490 passphrase = Buffer.from(passphrase, 'utf-8');
71491 if (passphrase !== undefined) {
71492 assert.buffer(passphrase, 'options.passphrase');
71493 assert.optionalString(options.cipher, 'options.cipher');
71494 cipher = options.cipher;
71495 if (cipher === undefined)
71496 cipher = 'aes128-ctr';
71497 cinf = utils.opensshCipherInfo(cipher);
71498 kdf = 'bcrypt';
71499 }
71500 }
71501
71502 var privBuf;
71503 if (PrivateKey.isPrivateKey(key)) {
71504 privBuf = new SSHBuffer({});
71505 var checkInt = crypto.randomBytes(4).readUInt32BE(0);
71506 privBuf.writeInt(checkInt);
71507 privBuf.writeInt(checkInt);
71508 privBuf.write(key.toBuffer('rfc4253'));
71509 privBuf.writeString(key.comment || '');
71510
71511 var n = 1;
71512 while (privBuf._offset % cinf.blockSize !== 0)
71513 privBuf.writeChar(n++);
71514 privBuf = privBuf.toBuffer();
71515 }
71516
71517 switch (kdf) {
71518 case 'none':
71519 break;
71520 case 'bcrypt':
71521 var salt = crypto.randomBytes(16);
71522 var rounds = 16;
71523 var kdfssh = new SSHBuffer({});
71524 kdfssh.writeBuffer(salt);
71525 kdfssh.writeInt(rounds);
71526 kdfopts = kdfssh.toBuffer();
71527
71528 if (bcrypt === undefined) {
71529 bcrypt = require('bcrypt-pbkdf');
71530 }
71531 var pass = new Uint8Array(passphrase);
71532 var salti = new Uint8Array(salt);
71533 /* Use the pbkdf to derive both the key and the IV. */
71534 var out = new Uint8Array(cinf.keySize + cinf.blockSize);
71535 var res = bcrypt.pbkdf(pass, pass.length, salti, salti.length,
71536 out, out.length, rounds);
71537 if (res !== 0) {
71538 throw (new Error('bcrypt_pbkdf function returned ' +
71539 'failure, parameters invalid'));
71540 }
71541 out = Buffer.from(out);
71542 var ckey = out.slice(0, cinf.keySize);
71543 var iv = out.slice(cinf.keySize, cinf.keySize + cinf.blockSize);
71544
71545 var cipherStream = crypto.createCipheriv(cinf.opensslName,
71546 ckey, iv);
71547 cipherStream.setAutoPadding(false);
71548 var chunk, chunks = [];
71549 cipherStream.once('error', function (e) {
71550 throw (e);
71551 });
71552 cipherStream.write(privBuf);
71553 cipherStream.end();
71554 while ((chunk = cipherStream.read()) !== null)
71555 chunks.push(chunk);
71556 privBuf = Buffer.concat(chunks);
71557 break;
71558 default:
71559 throw (new Error('Unsupported kdf ' + kdf));
71560 }
71561
71562 var buf = new SSHBuffer({});
71563
71564 buf.writeCString(MAGIC);
71565 buf.writeString(cipher); /* cipher */
71566 buf.writeString(kdf); /* kdf */
71567 buf.writeBuffer(kdfopts); /* kdfoptions */
71568
71569 buf.writeInt(1); /* nkeys */
71570 buf.writeBuffer(pubKey.toBuffer('rfc4253'));
71571
71572 if (privBuf)
71573 buf.writeBuffer(privBuf);
71574
71575 buf = buf.toBuffer();
71576
71577 var header;
71578 if (PrivateKey.isPrivateKey(key))
71579 header = 'OPENSSH PRIVATE KEY';
71580 else
71581 header = 'OPENSSH PUBLIC KEY';
71582
71583 var tmp = buf.toString('base64');
71584 var len = tmp.length + (tmp.length / 70) +
71585 18 + 16 + header.length*2 + 10;
71586 buf = Buffer.alloc(len);
71587 var o = 0;
71588 o += buf.write('-----BEGIN ' + header + '-----\n', o);
71589 for (var i = 0; i < tmp.length; ) {
71590 var limit = i + 70;
71591 if (limit > tmp.length)
71592 limit = tmp.length;
71593 o += buf.write(tmp.slice(i, limit), o);
71594 buf[o++] = 10;
71595 i = limit;
71596 }
71597 o += buf.write('-----END ' + header + '-----\n', o);
71598
71599 return (buf.slice(0, o));
71600}
71601
71602},{"../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){
71603// Copyright 2015 Joyent, Inc.
71604
71605module.exports = {
71606 read: read,
71607 write: write
71608};
71609
71610var assert = require('assert-plus');
71611var Buffer = require('safer-buffer').Buffer;
71612var rfc4253 = require('./rfc4253');
71613var utils = require('../utils');
71614var Key = require('../key');
71615var PrivateKey = require('../private-key');
71616
71617var sshpriv = require('./ssh-private');
71618
71619/*JSSTYLED*/
71620var SSHKEY_RE = /^([a-z0-9-]+)[ \t]+([a-zA-Z0-9+\/]+[=]*)([ \t]+([^ \t][^\n]*[\n]*)?)?$/;
71621/*JSSTYLED*/
71622var SSHKEY_RE2 = /^([a-z0-9-]+)[ \t\n]+([a-zA-Z0-9+\/][a-zA-Z0-9+\/ \t\n=]*)([^a-zA-Z0-9+\/ \t\n=].*)?$/;
71623
71624function read(buf, options) {
71625 if (typeof (buf) !== 'string') {
71626 assert.buffer(buf, 'buf');
71627 buf = buf.toString('ascii');
71628 }
71629
71630 var trimmed = buf.trim().replace(/[\\\r]/g, '');
71631 var m = trimmed.match(SSHKEY_RE);
71632 if (!m)
71633 m = trimmed.match(SSHKEY_RE2);
71634 assert.ok(m, 'key must match regex');
71635
71636 var type = rfc4253.algToKeyType(m[1]);
71637 var kbuf = Buffer.from(m[2], 'base64');
71638
71639 /*
71640 * This is a bit tricky. If we managed to parse the key and locate the
71641 * key comment with the regex, then do a non-partial read and assert
71642 * that we have consumed all bytes. If we couldn't locate the key
71643 * comment, though, there may be whitespace shenanigans going on that
71644 * have conjoined the comment to the rest of the key. We do a partial
71645 * read in this case to try to make the best out of a sorry situation.
71646 */
71647 var key;
71648 var ret = {};
71649 if (m[4]) {
71650 try {
71651 key = rfc4253.read(kbuf);
71652
71653 } catch (e) {
71654 m = trimmed.match(SSHKEY_RE2);
71655 assert.ok(m, 'key must match regex');
71656 kbuf = Buffer.from(m[2], 'base64');
71657 key = rfc4253.readInternal(ret, 'public', kbuf);
71658 }
71659 } else {
71660 key = rfc4253.readInternal(ret, 'public', kbuf);
71661 }
71662
71663 assert.strictEqual(type, key.type);
71664
71665 if (m[4] && m[4].length > 0) {
71666 key.comment = m[4];
71667
71668 } else if (ret.consumed) {
71669 /*
71670 * Now the magic: trying to recover the key comment when it's
71671 * gotten conjoined to the key or otherwise shenanigan'd.
71672 *
71673 * Work out how much base64 we used, then drop all non-base64
71674 * chars from the beginning up to this point in the the string.
71675 * Then offset in this and try to make up for missing = chars.
71676 */
71677 var data = m[2] + (m[3] ? m[3] : '');
71678 var realOffset = Math.ceil(ret.consumed / 3) * 4;
71679 data = data.slice(0, realOffset - 2). /*JSSTYLED*/
71680 replace(/[^a-zA-Z0-9+\/=]/g, '') +
71681 data.slice(realOffset - 2);
71682
71683 var padding = ret.consumed % 3;
71684 if (padding > 0 &&
71685 data.slice(realOffset - 1, realOffset) !== '=')
71686 realOffset--;
71687 while (data.slice(realOffset, realOffset + 1) === '=')
71688 realOffset++;
71689
71690 /* Finally, grab what we think is the comment & clean it up. */
71691 var trailer = data.slice(realOffset);
71692 trailer = trailer.replace(/[\r\n]/g, ' ').
71693 replace(/^\s+/, '');
71694 if (trailer.match(/^[a-zA-Z0-9]/))
71695 key.comment = trailer;
71696 }
71697
71698 return (key);
71699}
71700
71701function write(key, options) {
71702 assert.object(key);
71703 if (!Key.isKey(key))
71704 throw (new Error('Must be a public key'));
71705
71706 var parts = [];
71707 var alg = rfc4253.keyTypeToAlg(key);
71708 parts.push(alg);
71709
71710 var buf = rfc4253.write(key);
71711 parts.push(buf.toString('base64'));
71712
71713 if (key.comment)
71714 parts.push(key.comment);
71715
71716 return (Buffer.from(parts.join(' ')));
71717}
71718
71719},{"../key":355,"../private-key":356,"../utils":359,"./rfc4253":348,"./ssh-private":349,"assert-plus":67,"safer-buffer":326}],351:[function(require,module,exports){
71720// Copyright 2016 Joyent, Inc.
71721
71722var x509 = require('./x509');
71723
71724module.exports = {
71725 read: read,
71726 verify: x509.verify,
71727 sign: x509.sign,
71728 write: write
71729};
71730
71731var assert = require('assert-plus');
71732var asn1 = require('asn1');
71733var Buffer = require('safer-buffer').Buffer;
71734var algs = require('../algs');
71735var utils = require('../utils');
71736var Key = require('../key');
71737var PrivateKey = require('../private-key');
71738var pem = require('./pem');
71739var Identity = require('../identity');
71740var Signature = require('../signature');
71741var Certificate = require('../certificate');
71742
71743function read(buf, options) {
71744 if (typeof (buf) !== 'string') {
71745 assert.buffer(buf, 'buf');
71746 buf = buf.toString('ascii');
71747 }
71748
71749 var lines = buf.trim().split(/[\r\n]+/g);
71750
71751 var m;
71752 var si = -1;
71753 while (!m && si < lines.length) {
71754 m = lines[++si].match(/*JSSTYLED*/
71755 /[-]+[ ]*BEGIN CERTIFICATE[ ]*[-]+/);
71756 }
71757 assert.ok(m, 'invalid PEM header');
71758
71759 var m2;
71760 var ei = lines.length;
71761 while (!m2 && ei > 0) {
71762 m2 = lines[--ei].match(/*JSSTYLED*/
71763 /[-]+[ ]*END CERTIFICATE[ ]*[-]+/);
71764 }
71765 assert.ok(m2, 'invalid PEM footer');
71766
71767 lines = lines.slice(si, ei + 1);
71768
71769 var headers = {};
71770 while (true) {
71771 lines = lines.slice(1);
71772 m = lines[0].match(/*JSSTYLED*/
71773 /^([A-Za-z0-9-]+): (.+)$/);
71774 if (!m)
71775 break;
71776 headers[m[1].toLowerCase()] = m[2];
71777 }
71778
71779 /* Chop off the first and last lines */
71780 lines = lines.slice(0, -1).join('');
71781 buf = Buffer.from(lines, 'base64');
71782
71783 return (x509.read(buf, options));
71784}
71785
71786function write(cert, options) {
71787 var dbuf = x509.write(cert, options);
71788
71789 var header = 'CERTIFICATE';
71790 var tmp = dbuf.toString('base64');
71791 var len = tmp.length + (tmp.length / 64) +
71792 18 + 16 + header.length*2 + 10;
71793 var buf = Buffer.alloc(len);
71794 var o = 0;
71795 o += buf.write('-----BEGIN ' + header + '-----\n', o);
71796 for (var i = 0; i < tmp.length; ) {
71797 var limit = i + 64;
71798 if (limit > tmp.length)
71799 limit = tmp.length;
71800 o += buf.write(tmp.slice(i, limit), o);
71801 buf[o++] = 10;
71802 i = limit;
71803 }
71804 o += buf.write('-----END ' + header + '-----\n', o);
71805
71806 return (buf.slice(0, o));
71807}
71808
71809},{"../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){
71810// Copyright 2017 Joyent, Inc.
71811
71812module.exports = {
71813 read: read,
71814 verify: verify,
71815 sign: sign,
71816 signAsync: signAsync,
71817 write: write
71818};
71819
71820var assert = require('assert-plus');
71821var asn1 = require('asn1');
71822var Buffer = require('safer-buffer').Buffer;
71823var algs = require('../algs');
71824var utils = require('../utils');
71825var Key = require('../key');
71826var PrivateKey = require('../private-key');
71827var pem = require('./pem');
71828var Identity = require('../identity');
71829var Signature = require('../signature');
71830var Certificate = require('../certificate');
71831var pkcs8 = require('./pkcs8');
71832
71833/*
71834 * This file is based on RFC5280 (X.509).
71835 */
71836
71837/* Helper to read in a single mpint */
71838function readMPInt(der, nm) {
71839 assert.strictEqual(der.peek(), asn1.Ber.Integer,
71840 nm + ' is not an Integer');
71841 return (utils.mpNormalize(der.readString(asn1.Ber.Integer, true)));
71842}
71843
71844function verify(cert, key) {
71845 var sig = cert.signatures.x509;
71846 assert.object(sig, 'x509 signature');
71847
71848 var algParts = sig.algo.split('-');
71849 if (algParts[0] !== key.type)
71850 return (false);
71851
71852 var blob = sig.cache;
71853 if (blob === undefined) {
71854 var der = new asn1.BerWriter();
71855 writeTBSCert(cert, der);
71856 blob = der.buffer;
71857 }
71858
71859 var verifier = key.createVerify(algParts[1]);
71860 verifier.write(blob);
71861 return (verifier.verify(sig.signature));
71862}
71863
71864function Local(i) {
71865 return (asn1.Ber.Context | asn1.Ber.Constructor | i);
71866}
71867
71868function Context(i) {
71869 return (asn1.Ber.Context | i);
71870}
71871
71872var SIGN_ALGS = {
71873 'rsa-md5': '1.2.840.113549.1.1.4',
71874 'rsa-sha1': '1.2.840.113549.1.1.5',
71875 'rsa-sha256': '1.2.840.113549.1.1.11',
71876 'rsa-sha384': '1.2.840.113549.1.1.12',
71877 'rsa-sha512': '1.2.840.113549.1.1.13',
71878 'dsa-sha1': '1.2.840.10040.4.3',
71879 'dsa-sha256': '2.16.840.1.101.3.4.3.2',
71880 'ecdsa-sha1': '1.2.840.10045.4.1',
71881 'ecdsa-sha256': '1.2.840.10045.4.3.2',
71882 'ecdsa-sha384': '1.2.840.10045.4.3.3',
71883 'ecdsa-sha512': '1.2.840.10045.4.3.4',
71884 'ed25519-sha512': '1.3.101.112'
71885};
71886Object.keys(SIGN_ALGS).forEach(function (k) {
71887 SIGN_ALGS[SIGN_ALGS[k]] = k;
71888});
71889SIGN_ALGS['1.3.14.3.2.3'] = 'rsa-md5';
71890SIGN_ALGS['1.3.14.3.2.29'] = 'rsa-sha1';
71891
71892var EXTS = {
71893 'issuerKeyId': '2.5.29.35',
71894 'altName': '2.5.29.17',
71895 'basicConstraints': '2.5.29.19',
71896 'keyUsage': '2.5.29.15',
71897 'extKeyUsage': '2.5.29.37'
71898};
71899
71900function read(buf, options) {
71901 if (typeof (buf) === 'string') {
71902 buf = Buffer.from(buf, 'binary');
71903 }
71904 assert.buffer(buf, 'buf');
71905
71906 var der = new asn1.BerReader(buf);
71907
71908 der.readSequence();
71909 if (Math.abs(der.length - der.remain) > 1) {
71910 throw (new Error('DER sequence does not contain whole byte ' +
71911 'stream'));
71912 }
71913
71914 var tbsStart = der.offset;
71915 der.readSequence();
71916 var sigOffset = der.offset + der.length;
71917 var tbsEnd = sigOffset;
71918
71919 if (der.peek() === Local(0)) {
71920 der.readSequence(Local(0));
71921 var version = der.readInt();
71922 assert.ok(version <= 3,
71923 'only x.509 versions up to v3 supported');
71924 }
71925
71926 var cert = {};
71927 cert.signatures = {};
71928 var sig = (cert.signatures.x509 = {});
71929 sig.extras = {};
71930
71931 cert.serial = readMPInt(der, 'serial');
71932
71933 der.readSequence();
71934 var after = der.offset + der.length;
71935 var certAlgOid = der.readOID();
71936 var certAlg = SIGN_ALGS[certAlgOid];
71937 if (certAlg === undefined)
71938 throw (new Error('unknown signature algorithm ' + certAlgOid));
71939
71940 der._offset = after;
71941 cert.issuer = Identity.parseAsn1(der);
71942
71943 der.readSequence();
71944 cert.validFrom = readDate(der);
71945 cert.validUntil = readDate(der);
71946
71947 cert.subjects = [Identity.parseAsn1(der)];
71948
71949 der.readSequence();
71950 after = der.offset + der.length;
71951 cert.subjectKey = pkcs8.readPkcs8(undefined, 'public', der);
71952 der._offset = after;
71953
71954 /* issuerUniqueID */
71955 if (der.peek() === Local(1)) {
71956 der.readSequence(Local(1));
71957 sig.extras.issuerUniqueID =
71958 buf.slice(der.offset, der.offset + der.length);
71959 der._offset += der.length;
71960 }
71961
71962 /* subjectUniqueID */
71963 if (der.peek() === Local(2)) {
71964 der.readSequence(Local(2));
71965 sig.extras.subjectUniqueID =
71966 buf.slice(der.offset, der.offset + der.length);
71967 der._offset += der.length;
71968 }
71969
71970 /* extensions */
71971 if (der.peek() === Local(3)) {
71972 der.readSequence(Local(3));
71973 var extEnd = der.offset + der.length;
71974 der.readSequence();
71975
71976 while (der.offset < extEnd)
71977 readExtension(cert, buf, der);
71978
71979 assert.strictEqual(der.offset, extEnd);
71980 }
71981
71982 assert.strictEqual(der.offset, sigOffset);
71983
71984 der.readSequence();
71985 after = der.offset + der.length;
71986 var sigAlgOid = der.readOID();
71987 var sigAlg = SIGN_ALGS[sigAlgOid];
71988 if (sigAlg === undefined)
71989 throw (new Error('unknown signature algorithm ' + sigAlgOid));
71990 der._offset = after;
71991
71992 var sigData = der.readString(asn1.Ber.BitString, true);
71993 if (sigData[0] === 0)
71994 sigData = sigData.slice(1);
71995 var algParts = sigAlg.split('-');
71996
71997 sig.signature = Signature.parse(sigData, algParts[0], 'asn1');
71998 sig.signature.hashAlgorithm = algParts[1];
71999 sig.algo = sigAlg;
72000 sig.cache = buf.slice(tbsStart, tbsEnd);
72001
72002 return (new Certificate(cert));
72003}
72004
72005function readDate(der) {
72006 if (der.peek() === asn1.Ber.UTCTime) {
72007 return (utcTimeToDate(der.readString(asn1.Ber.UTCTime)));
72008 } else if (der.peek() === asn1.Ber.GeneralizedTime) {
72009 return (gTimeToDate(der.readString(asn1.Ber.GeneralizedTime)));
72010 } else {
72011 throw (new Error('Unsupported date format'));
72012 }
72013}
72014
72015function writeDate(der, date) {
72016 if (date.getUTCFullYear() >= 2050 || date.getUTCFullYear() < 1950) {
72017 der.writeString(dateToGTime(date), asn1.Ber.GeneralizedTime);
72018 } else {
72019 der.writeString(dateToUTCTime(date), asn1.Ber.UTCTime);
72020 }
72021}
72022
72023/* RFC5280, section 4.2.1.6 (GeneralName type) */
72024var ALTNAME = {
72025 OtherName: Local(0),
72026 RFC822Name: Context(1),
72027 DNSName: Context(2),
72028 X400Address: Local(3),
72029 DirectoryName: Local(4),
72030 EDIPartyName: Local(5),
72031 URI: Context(6),
72032 IPAddress: Context(7),
72033 OID: Context(8)
72034};
72035
72036/* RFC5280, section 4.2.1.12 (KeyPurposeId) */
72037var EXTPURPOSE = {
72038 'serverAuth': '1.3.6.1.5.5.7.3.1',
72039 'clientAuth': '1.3.6.1.5.5.7.3.2',
72040 'codeSigning': '1.3.6.1.5.5.7.3.3',
72041
72042 /* See https://github.com/joyent/oid-docs/blob/master/root.md */
72043 'joyentDocker': '1.3.6.1.4.1.38678.1.4.1',
72044 'joyentCmon': '1.3.6.1.4.1.38678.1.4.2'
72045};
72046var EXTPURPOSE_REV = {};
72047Object.keys(EXTPURPOSE).forEach(function (k) {
72048 EXTPURPOSE_REV[EXTPURPOSE[k]] = k;
72049});
72050
72051var KEYUSEBITS = [
72052 'signature', 'identity', 'keyEncryption',
72053 'encryption', 'keyAgreement', 'ca', 'crl'
72054];
72055
72056function readExtension(cert, buf, der) {
72057 der.readSequence();
72058 var after = der.offset + der.length;
72059 var extId = der.readOID();
72060 var id;
72061 var sig = cert.signatures.x509;
72062 if (!sig.extras.exts)
72063 sig.extras.exts = [];
72064
72065 var critical;
72066 if (der.peek() === asn1.Ber.Boolean)
72067 critical = der.readBoolean();
72068
72069 switch (extId) {
72070 case (EXTS.basicConstraints):
72071 der.readSequence(asn1.Ber.OctetString);
72072 der.readSequence();
72073 var bcEnd = der.offset + der.length;
72074 var ca = false;
72075 if (der.peek() === asn1.Ber.Boolean)
72076 ca = der.readBoolean();
72077 if (cert.purposes === undefined)
72078 cert.purposes = [];
72079 if (ca === true)
72080 cert.purposes.push('ca');
72081 var bc = { oid: extId, critical: critical };
72082 if (der.offset < bcEnd && der.peek() === asn1.Ber.Integer)
72083 bc.pathLen = der.readInt();
72084 sig.extras.exts.push(bc);
72085 break;
72086 case (EXTS.extKeyUsage):
72087 der.readSequence(asn1.Ber.OctetString);
72088 der.readSequence();
72089 if (cert.purposes === undefined)
72090 cert.purposes = [];
72091 var ekEnd = der.offset + der.length;
72092 while (der.offset < ekEnd) {
72093 var oid = der.readOID();
72094 cert.purposes.push(EXTPURPOSE_REV[oid] || oid);
72095 }
72096 /*
72097 * This is a bit of a hack: in the case where we have a cert
72098 * that's only allowed to do serverAuth or clientAuth (and not
72099 * the other), we want to make sure all our Subjects are of
72100 * the right type. But we already parsed our Subjects and
72101 * decided if they were hosts or users earlier (since it appears
72102 * first in the cert).
72103 *
72104 * So we go through and mutate them into the right kind here if
72105 * it doesn't match. This might not be hugely beneficial, as it
72106 * seems that single-purpose certs are not often seen in the
72107 * wild.
72108 */
72109 if (cert.purposes.indexOf('serverAuth') !== -1 &&
72110 cert.purposes.indexOf('clientAuth') === -1) {
72111 cert.subjects.forEach(function (ide) {
72112 if (ide.type !== 'host') {
72113 ide.type = 'host';
72114 ide.hostname = ide.uid ||
72115 ide.email ||
72116 ide.components[0].value;
72117 }
72118 });
72119 } else if (cert.purposes.indexOf('clientAuth') !== -1 &&
72120 cert.purposes.indexOf('serverAuth') === -1) {
72121 cert.subjects.forEach(function (ide) {
72122 if (ide.type !== 'user') {
72123 ide.type = 'user';
72124 ide.uid = ide.hostname ||
72125 ide.email ||
72126 ide.components[0].value;
72127 }
72128 });
72129 }
72130 sig.extras.exts.push({ oid: extId, critical: critical });
72131 break;
72132 case (EXTS.keyUsage):
72133 der.readSequence(asn1.Ber.OctetString);
72134 var bits = der.readString(asn1.Ber.BitString, true);
72135 var setBits = readBitField(bits, KEYUSEBITS);
72136 setBits.forEach(function (bit) {
72137 if (cert.purposes === undefined)
72138 cert.purposes = [];
72139 if (cert.purposes.indexOf(bit) === -1)
72140 cert.purposes.push(bit);
72141 });
72142 sig.extras.exts.push({ oid: extId, critical: critical,
72143 bits: bits });
72144 break;
72145 case (EXTS.altName):
72146 der.readSequence(asn1.Ber.OctetString);
72147 der.readSequence();
72148 var aeEnd = der.offset + der.length;
72149 while (der.offset < aeEnd) {
72150 switch (der.peek()) {
72151 case ALTNAME.OtherName:
72152 case ALTNAME.EDIPartyName:
72153 der.readSequence();
72154 der._offset += der.length;
72155 break;
72156 case ALTNAME.OID:
72157 der.readOID(ALTNAME.OID);
72158 break;
72159 case ALTNAME.RFC822Name:
72160 /* RFC822 specifies email addresses */
72161 var email = der.readString(ALTNAME.RFC822Name);
72162 id = Identity.forEmail(email);
72163 if (!cert.subjects[0].equals(id))
72164 cert.subjects.push(id);
72165 break;
72166 case ALTNAME.DirectoryName:
72167 der.readSequence(ALTNAME.DirectoryName);
72168 id = Identity.parseAsn1(der);
72169 if (!cert.subjects[0].equals(id))
72170 cert.subjects.push(id);
72171 break;
72172 case ALTNAME.DNSName:
72173 var host = der.readString(
72174 ALTNAME.DNSName);
72175 id = Identity.forHost(host);
72176 if (!cert.subjects[0].equals(id))
72177 cert.subjects.push(id);
72178 break;
72179 default:
72180 der.readString(der.peek());
72181 break;
72182 }
72183 }
72184 sig.extras.exts.push({ oid: extId, critical: critical });
72185 break;
72186 default:
72187 sig.extras.exts.push({
72188 oid: extId,
72189 critical: critical,
72190 data: der.readString(asn1.Ber.OctetString, true)
72191 });
72192 break;
72193 }
72194
72195 der._offset = after;
72196}
72197
72198var UTCTIME_RE =
72199 /^([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
72200function utcTimeToDate(t) {
72201 var m = t.match(UTCTIME_RE);
72202 assert.ok(m, 'timestamps must be in UTC');
72203 var d = new Date();
72204
72205 var thisYear = d.getUTCFullYear();
72206 var century = Math.floor(thisYear / 100) * 100;
72207
72208 var year = parseInt(m[1], 10);
72209 if (thisYear % 100 < 50 && year >= 60)
72210 year += (century - 1);
72211 else
72212 year += century;
72213 d.setUTCFullYear(year, parseInt(m[2], 10) - 1, parseInt(m[3], 10));
72214 d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
72215 if (m[6] && m[6].length > 0)
72216 d.setUTCSeconds(parseInt(m[6], 10));
72217 return (d);
72218}
72219
72220var GTIME_RE =
72221 /^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})?Z$/;
72222function gTimeToDate(t) {
72223 var m = t.match(GTIME_RE);
72224 assert.ok(m);
72225 var d = new Date();
72226
72227 d.setUTCFullYear(parseInt(m[1], 10), parseInt(m[2], 10) - 1,
72228 parseInt(m[3], 10));
72229 d.setUTCHours(parseInt(m[4], 10), parseInt(m[5], 10));
72230 if (m[6] && m[6].length > 0)
72231 d.setUTCSeconds(parseInt(m[6], 10));
72232 return (d);
72233}
72234
72235function zeroPad(n, m) {
72236 if (m === undefined)
72237 m = 2;
72238 var s = '' + n;
72239 while (s.length < m)
72240 s = '0' + s;
72241 return (s);
72242}
72243
72244function dateToUTCTime(d) {
72245 var s = '';
72246 s += zeroPad(d.getUTCFullYear() % 100);
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 dateToGTime(d) {
72257 var s = '';
72258 s += zeroPad(d.getUTCFullYear(), 4);
72259 s += zeroPad(d.getUTCMonth() + 1);
72260 s += zeroPad(d.getUTCDate());
72261 s += zeroPad(d.getUTCHours());
72262 s += zeroPad(d.getUTCMinutes());
72263 s += zeroPad(d.getUTCSeconds());
72264 s += 'Z';
72265 return (s);
72266}
72267
72268function sign(cert, key) {
72269 if (cert.signatures.x509 === undefined)
72270 cert.signatures.x509 = {};
72271 var sig = cert.signatures.x509;
72272
72273 sig.algo = key.type + '-' + key.defaultHashAlgorithm();
72274 if (SIGN_ALGS[sig.algo] === undefined)
72275 return (false);
72276
72277 var der = new asn1.BerWriter();
72278 writeTBSCert(cert, der);
72279 var blob = der.buffer;
72280 sig.cache = blob;
72281
72282 var signer = key.createSign();
72283 signer.write(blob);
72284 cert.signatures.x509.signature = signer.sign();
72285
72286 return (true);
72287}
72288
72289function signAsync(cert, signer, done) {
72290 if (cert.signatures.x509 === undefined)
72291 cert.signatures.x509 = {};
72292 var sig = cert.signatures.x509;
72293
72294 var der = new asn1.BerWriter();
72295 writeTBSCert(cert, der);
72296 var blob = der.buffer;
72297 sig.cache = blob;
72298
72299 signer(blob, function (err, signature) {
72300 if (err) {
72301 done(err);
72302 return;
72303 }
72304 sig.algo = signature.type + '-' + signature.hashAlgorithm;
72305 if (SIGN_ALGS[sig.algo] === undefined) {
72306 done(new Error('Invalid signing algorithm "' +
72307 sig.algo + '"'));
72308 return;
72309 }
72310 sig.signature = signature;
72311 done();
72312 });
72313}
72314
72315function write(cert, options) {
72316 var sig = cert.signatures.x509;
72317 assert.object(sig, 'x509 signature');
72318
72319 var der = new asn1.BerWriter();
72320 der.startSequence();
72321 if (sig.cache) {
72322 der._ensure(sig.cache.length);
72323 sig.cache.copy(der._buf, der._offset);
72324 der._offset += sig.cache.length;
72325 } else {
72326 writeTBSCert(cert, der);
72327 }
72328
72329 der.startSequence();
72330 der.writeOID(SIGN_ALGS[sig.algo]);
72331 if (sig.algo.match(/^rsa-/))
72332 der.writeNull();
72333 der.endSequence();
72334
72335 var sigData = sig.signature.toBuffer('asn1');
72336 var data = Buffer.alloc(sigData.length + 1);
72337 data[0] = 0;
72338 sigData.copy(data, 1);
72339 der.writeBuffer(data, asn1.Ber.BitString);
72340 der.endSequence();
72341
72342 return (der.buffer);
72343}
72344
72345function writeTBSCert(cert, der) {
72346 var sig = cert.signatures.x509;
72347 assert.object(sig, 'x509 signature');
72348
72349 der.startSequence();
72350
72351 der.startSequence(Local(0));
72352 der.writeInt(2);
72353 der.endSequence();
72354
72355 der.writeBuffer(utils.mpNormalize(cert.serial), asn1.Ber.Integer);
72356
72357 der.startSequence();
72358 der.writeOID(SIGN_ALGS[sig.algo]);
72359 if (sig.algo.match(/^rsa-/))
72360 der.writeNull();
72361 der.endSequence();
72362
72363 cert.issuer.toAsn1(der);
72364
72365 der.startSequence();
72366 writeDate(der, cert.validFrom);
72367 writeDate(der, cert.validUntil);
72368 der.endSequence();
72369
72370 var subject = cert.subjects[0];
72371 var altNames = cert.subjects.slice(1);
72372 subject.toAsn1(der);
72373
72374 pkcs8.writePkcs8(der, cert.subjectKey);
72375
72376 if (sig.extras && sig.extras.issuerUniqueID) {
72377 der.writeBuffer(sig.extras.issuerUniqueID, Local(1));
72378 }
72379
72380 if (sig.extras && sig.extras.subjectUniqueID) {
72381 der.writeBuffer(sig.extras.subjectUniqueID, Local(2));
72382 }
72383
72384 if (altNames.length > 0 || subject.type === 'host' ||
72385 (cert.purposes !== undefined && cert.purposes.length > 0) ||
72386 (sig.extras && sig.extras.exts)) {
72387 der.startSequence(Local(3));
72388 der.startSequence();
72389
72390 var exts = [];
72391 if (cert.purposes !== undefined && cert.purposes.length > 0) {
72392 exts.push({
72393 oid: EXTS.basicConstraints,
72394 critical: true
72395 });
72396 exts.push({
72397 oid: EXTS.keyUsage,
72398 critical: true
72399 });
72400 exts.push({
72401 oid: EXTS.extKeyUsage,
72402 critical: true
72403 });
72404 }
72405 exts.push({ oid: EXTS.altName });
72406 if (sig.extras && sig.extras.exts)
72407 exts = sig.extras.exts;
72408
72409 for (var i = 0; i < exts.length; ++i) {
72410 der.startSequence();
72411 der.writeOID(exts[i].oid);
72412
72413 if (exts[i].critical !== undefined)
72414 der.writeBoolean(exts[i].critical);
72415
72416 if (exts[i].oid === EXTS.altName) {
72417 der.startSequence(asn1.Ber.OctetString);
72418 der.startSequence();
72419 if (subject.type === 'host') {
72420 der.writeString(subject.hostname,
72421 Context(2));
72422 }
72423 for (var j = 0; j < altNames.length; ++j) {
72424 if (altNames[j].type === 'host') {
72425 der.writeString(
72426 altNames[j].hostname,
72427 ALTNAME.DNSName);
72428 } else if (altNames[j].type ===
72429 'email') {
72430 der.writeString(
72431 altNames[j].email,
72432 ALTNAME.RFC822Name);
72433 } else {
72434 /*
72435 * Encode anything else as a
72436 * DN style name for now.
72437 */
72438 der.startSequence(
72439 ALTNAME.DirectoryName);
72440 altNames[j].toAsn1(der);
72441 der.endSequence();
72442 }
72443 }
72444 der.endSequence();
72445 der.endSequence();
72446 } else if (exts[i].oid === EXTS.basicConstraints) {
72447 der.startSequence(asn1.Ber.OctetString);
72448 der.startSequence();
72449 var ca = (cert.purposes.indexOf('ca') !== -1);
72450 var pathLen = exts[i].pathLen;
72451 der.writeBoolean(ca);
72452 if (pathLen !== undefined)
72453 der.writeInt(pathLen);
72454 der.endSequence();
72455 der.endSequence();
72456 } else if (exts[i].oid === EXTS.extKeyUsage) {
72457 der.startSequence(asn1.Ber.OctetString);
72458 der.startSequence();
72459 cert.purposes.forEach(function (purpose) {
72460 if (purpose === 'ca')
72461 return;
72462 if (KEYUSEBITS.indexOf(purpose) !== -1)
72463 return;
72464 var oid = purpose;
72465 if (EXTPURPOSE[purpose] !== undefined)
72466 oid = EXTPURPOSE[purpose];
72467 der.writeOID(oid);
72468 });
72469 der.endSequence();
72470 der.endSequence();
72471 } else if (exts[i].oid === EXTS.keyUsage) {
72472 der.startSequence(asn1.Ber.OctetString);
72473 /*
72474 * If we parsed this certificate from a byte
72475 * stream (i.e. we didn't generate it in sshpk)
72476 * then we'll have a ".bits" property on the
72477 * ext with the original raw byte contents.
72478 *
72479 * If we have this, use it here instead of
72480 * regenerating it. This guarantees we output
72481 * the same data we parsed, so signatures still
72482 * validate.
72483 */
72484 if (exts[i].bits !== undefined) {
72485 der.writeBuffer(exts[i].bits,
72486 asn1.Ber.BitString);
72487 } else {
72488 var bits = writeBitField(cert.purposes,
72489 KEYUSEBITS);
72490 der.writeBuffer(bits,
72491 asn1.Ber.BitString);
72492 }
72493 der.endSequence();
72494 } else {
72495 der.writeBuffer(exts[i].data,
72496 asn1.Ber.OctetString);
72497 }
72498
72499 der.endSequence();
72500 }
72501
72502 der.endSequence();
72503 der.endSequence();
72504 }
72505
72506 der.endSequence();
72507}
72508
72509/*
72510 * Reads an ASN.1 BER bitfield out of the Buffer produced by doing
72511 * `BerReader#readString(asn1.Ber.BitString)`. That function gives us the raw
72512 * contents of the BitString tag, which is a count of unused bits followed by
72513 * the bits as a right-padded byte string.
72514 *
72515 * `bits` is the Buffer, `bitIndex` should contain an array of string names
72516 * for the bits in the string, ordered starting with bit #0 in the ASN.1 spec.
72517 *
72518 * Returns an array of Strings, the names of the bits that were set to 1.
72519 */
72520function readBitField(bits, bitIndex) {
72521 var bitLen = 8 * (bits.length - 1) - bits[0];
72522 var setBits = {};
72523 for (var i = 0; i < bitLen; ++i) {
72524 var byteN = 1 + Math.floor(i / 8);
72525 var bit = 7 - (i % 8);
72526 var mask = 1 << bit;
72527 var bitVal = ((bits[byteN] & mask) !== 0);
72528 var name = bitIndex[i];
72529 if (bitVal && typeof (name) === 'string') {
72530 setBits[name] = true;
72531 }
72532 }
72533 return (Object.keys(setBits));
72534}
72535
72536/*
72537 * `setBits` is an array of strings, containing the names for each bit that
72538 * sould be set to 1. `bitIndex` is same as in `readBitField()`.
72539 *
72540 * Returns a Buffer, ready to be written out with `BerWriter#writeString()`.
72541 */
72542function writeBitField(setBits, bitIndex) {
72543 var bitLen = bitIndex.length;
72544 var blen = Math.ceil(bitLen / 8);
72545 var unused = blen * 8 - bitLen;
72546 var bits = Buffer.alloc(1 + blen); // zero-filled
72547 bits[0] = unused;
72548 for (var i = 0; i < bitLen; ++i) {
72549 var byteN = 1 + Math.floor(i / 8);
72550 var bit = 7 - (i % 8);
72551 var mask = 1 << bit;
72552 var name = bitIndex[i];
72553 if (name === undefined)
72554 continue;
72555 var bitVal = (setBits.indexOf(name) !== -1);
72556 if (bitVal) {
72557 bits[byteN] |= mask;
72558 }
72559 }
72560 return (bits);
72561}
72562
72563},{"../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){
72564// Copyright 2017 Joyent, Inc.
72565
72566module.exports = Identity;
72567
72568var assert = require('assert-plus');
72569var algs = require('./algs');
72570var crypto = require('crypto');
72571var Fingerprint = require('./fingerprint');
72572var Signature = require('./signature');
72573var errs = require('./errors');
72574var util = require('util');
72575var utils = require('./utils');
72576var asn1 = require('asn1');
72577var Buffer = require('safer-buffer').Buffer;
72578
72579/*JSSTYLED*/
72580var DNS_NAME_RE = /^([*]|[a-z0-9][a-z0-9\-]{0,62})(?:\.([*]|[a-z0-9][a-z0-9\-]{0,62}))*$/i;
72581
72582var oids = {};
72583oids.cn = '2.5.4.3';
72584oids.o = '2.5.4.10';
72585oids.ou = '2.5.4.11';
72586oids.l = '2.5.4.7';
72587oids.s = '2.5.4.8';
72588oids.c = '2.5.4.6';
72589oids.sn = '2.5.4.4';
72590oids.postalCode = '2.5.4.17';
72591oids.serialNumber = '2.5.4.5';
72592oids.street = '2.5.4.9';
72593oids.x500UniqueIdentifier = '2.5.4.45';
72594oids.role = '2.5.4.72';
72595oids.telephoneNumber = '2.5.4.20';
72596oids.description = '2.5.4.13';
72597oids.dc = '0.9.2342.19200300.100.1.25';
72598oids.uid = '0.9.2342.19200300.100.1.1';
72599oids.mail = '0.9.2342.19200300.100.1.3';
72600oids.title = '2.5.4.12';
72601oids.gn = '2.5.4.42';
72602oids.initials = '2.5.4.43';
72603oids.pseudonym = '2.5.4.65';
72604oids.emailAddress = '1.2.840.113549.1.9.1';
72605
72606var unoids = {};
72607Object.keys(oids).forEach(function (k) {
72608 unoids[oids[k]] = k;
72609});
72610
72611function Identity(opts) {
72612 var self = this;
72613 assert.object(opts, 'options');
72614 assert.arrayOfObject(opts.components, 'options.components');
72615 this.components = opts.components;
72616 this.componentLookup = {};
72617 this.components.forEach(function (c) {
72618 if (c.name && !c.oid)
72619 c.oid = oids[c.name];
72620 if (c.oid && !c.name)
72621 c.name = unoids[c.oid];
72622 if (self.componentLookup[c.name] === undefined)
72623 self.componentLookup[c.name] = [];
72624 self.componentLookup[c.name].push(c);
72625 });
72626 if (this.componentLookup.cn && this.componentLookup.cn.length > 0) {
72627 this.cn = this.componentLookup.cn[0].value;
72628 }
72629 assert.optionalString(opts.type, 'options.type');
72630 if (opts.type === undefined) {
72631 if (this.components.length === 1 &&
72632 this.componentLookup.cn &&
72633 this.componentLookup.cn.length === 1 &&
72634 this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
72635 this.type = 'host';
72636 this.hostname = this.componentLookup.cn[0].value;
72637
72638 } else if (this.componentLookup.dc &&
72639 this.components.length === this.componentLookup.dc.length) {
72640 this.type = 'host';
72641 this.hostname = this.componentLookup.dc.map(
72642 function (c) {
72643 return (c.value);
72644 }).join('.');
72645
72646 } else if (this.componentLookup.uid &&
72647 this.components.length ===
72648 this.componentLookup.uid.length) {
72649 this.type = 'user';
72650 this.uid = this.componentLookup.uid[0].value;
72651
72652 } else if (this.componentLookup.cn &&
72653 this.componentLookup.cn.length === 1 &&
72654 this.componentLookup.cn[0].value.match(DNS_NAME_RE)) {
72655 this.type = 'host';
72656 this.hostname = this.componentLookup.cn[0].value;
72657
72658 } else if (this.componentLookup.uid &&
72659 this.componentLookup.uid.length === 1) {
72660 this.type = 'user';
72661 this.uid = this.componentLookup.uid[0].value;
72662
72663 } else if (this.componentLookup.mail &&
72664 this.componentLookup.mail.length === 1) {
72665 this.type = 'email';
72666 this.email = this.componentLookup.mail[0].value;
72667
72668 } else if (this.componentLookup.cn &&
72669 this.componentLookup.cn.length === 1) {
72670 this.type = 'user';
72671 this.uid = this.componentLookup.cn[0].value;
72672
72673 } else {
72674 this.type = 'unknown';
72675 }
72676 } else {
72677 this.type = opts.type;
72678 if (this.type === 'host')
72679 this.hostname = opts.hostname;
72680 else if (this.type === 'user')
72681 this.uid = opts.uid;
72682 else if (this.type === 'email')
72683 this.email = opts.email;
72684 else
72685 throw (new Error('Unknown type ' + this.type));
72686 }
72687}
72688
72689Identity.prototype.toString = function () {
72690 return (this.components.map(function (c) {
72691 var n = c.name.toUpperCase();
72692 /*JSSTYLED*/
72693 n = n.replace(/=/g, '\\=');
72694 var v = c.value;
72695 /*JSSTYLED*/
72696 v = v.replace(/,/g, '\\,');
72697 return (n + '=' + v);
72698 }).join(', '));
72699};
72700
72701Identity.prototype.get = function (name, asArray) {
72702 assert.string(name, 'name');
72703 var arr = this.componentLookup[name];
72704 if (arr === undefined || arr.length === 0)
72705 return (undefined);
72706 if (!asArray && arr.length > 1)
72707 throw (new Error('Multiple values for attribute ' + name));
72708 if (!asArray)
72709 return (arr[0].value);
72710 return (arr.map(function (c) {
72711 return (c.value);
72712 }));
72713};
72714
72715Identity.prototype.toArray = function (idx) {
72716 return (this.components.map(function (c) {
72717 return ({
72718 name: c.name,
72719 value: c.value
72720 });
72721 }));
72722};
72723
72724/*
72725 * These are from X.680 -- PrintableString allowed chars are in section 37.4
72726 * table 8. Spec for IA5Strings is "1,6 + SPACE + DEL" where 1 refers to
72727 * ISO IR #001 (standard ASCII control characters) and 6 refers to ISO IR #006
72728 * (the basic ASCII character set).
72729 */
72730/* JSSTYLED */
72731var NOT_PRINTABLE = /[^a-zA-Z0-9 '(),+.\/:=?-]/;
72732/* JSSTYLED */
72733var NOT_IA5 = /[^\x00-\x7f]/;
72734
72735Identity.prototype.toAsn1 = function (der, tag) {
72736 der.startSequence(tag);
72737 this.components.forEach(function (c) {
72738 der.startSequence(asn1.Ber.Constructor | asn1.Ber.Set);
72739 der.startSequence();
72740 der.writeOID(c.oid);
72741 /*
72742 * If we fit in a PrintableString, use that. Otherwise use an
72743 * IA5String or UTF8String.
72744 *
72745 * If this identity was parsed from a DN, use the ASN.1 types
72746 * from the original representation (otherwise this might not
72747 * be a full match for the original in some validators).
72748 */
72749 if (c.asn1type === asn1.Ber.Utf8String ||
72750 c.value.match(NOT_IA5)) {
72751 var v = Buffer.from(c.value, 'utf8');
72752 der.writeBuffer(v, asn1.Ber.Utf8String);
72753
72754 } else if (c.asn1type === asn1.Ber.IA5String ||
72755 c.value.match(NOT_PRINTABLE)) {
72756 der.writeString(c.value, asn1.Ber.IA5String);
72757
72758 } else {
72759 var type = asn1.Ber.PrintableString;
72760 if (c.asn1type !== undefined)
72761 type = c.asn1type;
72762 der.writeString(c.value, type);
72763 }
72764 der.endSequence();
72765 der.endSequence();
72766 });
72767 der.endSequence();
72768};
72769
72770function globMatch(a, b) {
72771 if (a === '**' || b === '**')
72772 return (true);
72773 var aParts = a.split('.');
72774 var bParts = b.split('.');
72775 if (aParts.length !== bParts.length)
72776 return (false);
72777 for (var i = 0; i < aParts.length; ++i) {
72778 if (aParts[i] === '*' || bParts[i] === '*')
72779 continue;
72780 if (aParts[i] !== bParts[i])
72781 return (false);
72782 }
72783 return (true);
72784}
72785
72786Identity.prototype.equals = function (other) {
72787 if (!Identity.isIdentity(other, [1, 0]))
72788 return (false);
72789 if (other.components.length !== this.components.length)
72790 return (false);
72791 for (var i = 0; i < this.components.length; ++i) {
72792 if (this.components[i].oid !== other.components[i].oid)
72793 return (false);
72794 if (!globMatch(this.components[i].value,
72795 other.components[i].value)) {
72796 return (false);
72797 }
72798 }
72799 return (true);
72800};
72801
72802Identity.forHost = function (hostname) {
72803 assert.string(hostname, 'hostname');
72804 return (new Identity({
72805 type: 'host',
72806 hostname: hostname,
72807 components: [ { name: 'cn', value: hostname } ]
72808 }));
72809};
72810
72811Identity.forUser = function (uid) {
72812 assert.string(uid, 'uid');
72813 return (new Identity({
72814 type: 'user',
72815 uid: uid,
72816 components: [ { name: 'uid', value: uid } ]
72817 }));
72818};
72819
72820Identity.forEmail = function (email) {
72821 assert.string(email, 'email');
72822 return (new Identity({
72823 type: 'email',
72824 email: email,
72825 components: [ { name: 'mail', value: email } ]
72826 }));
72827};
72828
72829Identity.parseDN = function (dn) {
72830 assert.string(dn, 'dn');
72831 var parts = [''];
72832 var idx = 0;
72833 var rem = dn;
72834 while (rem.length > 0) {
72835 var m;
72836 /*JSSTYLED*/
72837 if ((m = /^,/.exec(rem)) !== null) {
72838 parts[++idx] = '';
72839 rem = rem.slice(m[0].length);
72840 /*JSSTYLED*/
72841 } else if ((m = /^\\,/.exec(rem)) !== null) {
72842 parts[idx] += ',';
72843 rem = rem.slice(m[0].length);
72844 /*JSSTYLED*/
72845 } else if ((m = /^\\./.exec(rem)) !== null) {
72846 parts[idx] += m[0];
72847 rem = rem.slice(m[0].length);
72848 /*JSSTYLED*/
72849 } else if ((m = /^[^\\,]+/.exec(rem)) !== null) {
72850 parts[idx] += m[0];
72851 rem = rem.slice(m[0].length);
72852 } else {
72853 throw (new Error('Failed to parse DN'));
72854 }
72855 }
72856 var cmps = parts.map(function (c) {
72857 c = c.trim();
72858 var eqPos = c.indexOf('=');
72859 while (eqPos > 0 && c.charAt(eqPos - 1) === '\\')
72860 eqPos = c.indexOf('=', eqPos + 1);
72861 if (eqPos === -1) {
72862 throw (new Error('Failed to parse DN'));
72863 }
72864 /*JSSTYLED*/
72865 var name = c.slice(0, eqPos).toLowerCase().replace(/\\=/g, '=');
72866 var value = c.slice(eqPos + 1);
72867 return ({ name: name, value: value });
72868 });
72869 return (new Identity({ components: cmps }));
72870};
72871
72872Identity.fromArray = function (components) {
72873 assert.arrayOfObject(components, 'components');
72874 components.forEach(function (cmp) {
72875 assert.object(cmp, 'component');
72876 assert.string(cmp.name, 'component.name');
72877 if (!Buffer.isBuffer(cmp.value) &&
72878 !(typeof (cmp.value) === 'string')) {
72879 throw (new Error('Invalid component value'));
72880 }
72881 });
72882 return (new Identity({ components: components }));
72883};
72884
72885Identity.parseAsn1 = function (der, top) {
72886 var components = [];
72887 der.readSequence(top);
72888 var end = der.offset + der.length;
72889 while (der.offset < end) {
72890 der.readSequence(asn1.Ber.Constructor | asn1.Ber.Set);
72891 var after = der.offset + der.length;
72892 der.readSequence();
72893 var oid = der.readOID();
72894 var type = der.peek();
72895 var value;
72896 switch (type) {
72897 case asn1.Ber.PrintableString:
72898 case asn1.Ber.IA5String:
72899 case asn1.Ber.OctetString:
72900 case asn1.Ber.T61String:
72901 value = der.readString(type);
72902 break;
72903 case asn1.Ber.Utf8String:
72904 value = der.readString(type, true);
72905 value = value.toString('utf8');
72906 break;
72907 case asn1.Ber.CharacterString:
72908 case asn1.Ber.BMPString:
72909 value = der.readString(type, true);
72910 value = value.toString('utf16le');
72911 break;
72912 default:
72913 throw (new Error('Unknown asn1 type ' + type));
72914 }
72915 components.push({ oid: oid, asn1type: type, value: value });
72916 der._offset = after;
72917 }
72918 der._offset = end;
72919 return (new Identity({
72920 components: components
72921 }));
72922};
72923
72924Identity.isIdentity = function (obj, ver) {
72925 return (utils.isCompatible(obj, Identity, ver));
72926};
72927
72928/*
72929 * API versions for Identity:
72930 * [1,0] -- initial ver
72931 */
72932Identity.prototype._sshpkApiVersion = [1, 0];
72933
72934Identity._oldVersionDetect = function (obj) {
72935 return ([1, 0]);
72936};
72937
72938},{"./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){
72939// Copyright 2015 Joyent, Inc.
72940
72941var Key = require('./key');
72942var Fingerprint = require('./fingerprint');
72943var Signature = require('./signature');
72944var PrivateKey = require('./private-key');
72945var Certificate = require('./certificate');
72946var Identity = require('./identity');
72947var errs = require('./errors');
72948
72949module.exports = {
72950 /* top-level classes */
72951 Key: Key,
72952 parseKey: Key.parse,
72953 Fingerprint: Fingerprint,
72954 parseFingerprint: Fingerprint.parse,
72955 Signature: Signature,
72956 parseSignature: Signature.parse,
72957 PrivateKey: PrivateKey,
72958 parsePrivateKey: PrivateKey.parse,
72959 generatePrivateKey: PrivateKey.generate,
72960 Certificate: Certificate,
72961 parseCertificate: Certificate.parse,
72962 createSelfSignedCertificate: Certificate.createSelfSigned,
72963 createCertificate: Certificate.create,
72964 Identity: Identity,
72965 identityFromDN: Identity.parseDN,
72966 identityForHost: Identity.forHost,
72967 identityForUser: Identity.forUser,
72968 identityForEmail: Identity.forEmail,
72969 identityFromArray: Identity.fromArray,
72970
72971 /* errors */
72972 FingerprintFormatError: errs.FingerprintFormatError,
72973 InvalidAlgorithmError: errs.InvalidAlgorithmError,
72974 KeyParseError: errs.KeyParseError,
72975 SignatureParseError: errs.SignatureParseError,
72976 KeyEncryptedError: errs.KeyEncryptedError,
72977 CertificateParseError: errs.CertificateParseError
72978};
72979
72980},{"./certificate":336,"./errors":339,"./fingerprint":340,"./identity":353,"./key":355,"./private-key":356,"./signature":357}],355:[function(require,module,exports){
72981(function (Buffer){
72982// Copyright 2018 Joyent, Inc.
72983
72984module.exports = Key;
72985
72986var assert = require('assert-plus');
72987var algs = require('./algs');
72988var crypto = require('crypto');
72989var Fingerprint = require('./fingerprint');
72990var Signature = require('./signature');
72991var DiffieHellman = require('./dhe').DiffieHellman;
72992var errs = require('./errors');
72993var utils = require('./utils');
72994var PrivateKey = require('./private-key');
72995var edCompat;
72996
72997try {
72998 edCompat = require('./ed-compat');
72999} catch (e) {
73000 /* Just continue through, and bail out if we try to use it. */
73001}
73002
73003var InvalidAlgorithmError = errs.InvalidAlgorithmError;
73004var KeyParseError = errs.KeyParseError;
73005
73006var formats = {};
73007formats['auto'] = require('./formats/auto');
73008formats['pem'] = require('./formats/pem');
73009formats['pkcs1'] = require('./formats/pkcs1');
73010formats['pkcs8'] = require('./formats/pkcs8');
73011formats['rfc4253'] = require('./formats/rfc4253');
73012formats['ssh'] = require('./formats/ssh');
73013formats['ssh-private'] = require('./formats/ssh-private');
73014formats['openssh'] = formats['ssh-private'];
73015formats['dnssec'] = require('./formats/dnssec');
73016formats['putty'] = require('./formats/putty');
73017formats['ppk'] = formats['putty'];
73018
73019function Key(opts) {
73020 assert.object(opts, 'options');
73021 assert.arrayOfObject(opts.parts, 'options.parts');
73022 assert.string(opts.type, 'options.type');
73023 assert.optionalString(opts.comment, 'options.comment');
73024
73025 var algInfo = algs.info[opts.type];
73026 if (typeof (algInfo) !== 'object')
73027 throw (new InvalidAlgorithmError(opts.type));
73028
73029 var partLookup = {};
73030 for (var i = 0; i < opts.parts.length; ++i) {
73031 var part = opts.parts[i];
73032 partLookup[part.name] = part;
73033 }
73034
73035 this.type = opts.type;
73036 this.parts = opts.parts;
73037 this.part = partLookup;
73038 this.comment = undefined;
73039 this.source = opts.source;
73040
73041 /* for speeding up hashing/fingerprint operations */
73042 this._rfc4253Cache = opts._rfc4253Cache;
73043 this._hashCache = {};
73044
73045 var sz;
73046 this.curve = undefined;
73047 if (this.type === 'ecdsa') {
73048 var curve = this.part.curve.data.toString();
73049 this.curve = curve;
73050 sz = algs.curves[curve].size;
73051 } else if (this.type === 'ed25519' || this.type === 'curve25519') {
73052 sz = 256;
73053 this.curve = 'curve25519';
73054 } else {
73055 var szPart = this.part[algInfo.sizePart];
73056 sz = szPart.data.length;
73057 sz = sz * 8 - utils.countZeros(szPart.data);
73058 }
73059 this.size = sz;
73060}
73061
73062Key.formats = formats;
73063
73064Key.prototype.toBuffer = function (format, options) {
73065 if (format === undefined)
73066 format = 'ssh';
73067 assert.string(format, 'format');
73068 assert.object(formats[format], 'formats[format]');
73069 assert.optionalObject(options, 'options');
73070
73071 if (format === 'rfc4253') {
73072 if (this._rfc4253Cache === undefined)
73073 this._rfc4253Cache = formats['rfc4253'].write(this);
73074 return (this._rfc4253Cache);
73075 }
73076
73077 return (formats[format].write(this, options));
73078};
73079
73080Key.prototype.toString = function (format, options) {
73081 return (this.toBuffer(format, options).toString());
73082};
73083
73084Key.prototype.hash = function (algo, type) {
73085 assert.string(algo, 'algorithm');
73086 assert.optionalString(type, 'type');
73087 if (type === undefined)
73088 type = 'ssh';
73089 algo = algo.toLowerCase();
73090 if (algs.hashAlgs[algo] === undefined)
73091 throw (new InvalidAlgorithmError(algo));
73092
73093 var cacheKey = algo + '||' + type;
73094 if (this._hashCache[cacheKey])
73095 return (this._hashCache[cacheKey]);
73096
73097 var buf;
73098 if (type === 'ssh') {
73099 buf = this.toBuffer('rfc4253');
73100 } else if (type === 'spki') {
73101 buf = formats.pkcs8.pkcs8ToBuffer(this);
73102 } else {
73103 throw (new Error('Hash type ' + type + ' not supported'));
73104 }
73105 var hash = crypto.createHash(algo).update(buf).digest();
73106 this._hashCache[cacheKey] = hash;
73107 return (hash);
73108};
73109
73110Key.prototype.fingerprint = function (algo, type) {
73111 if (algo === undefined)
73112 algo = 'sha256';
73113 if (type === undefined)
73114 type = 'ssh';
73115 assert.string(algo, 'algorithm');
73116 assert.string(type, 'type');
73117 var opts = {
73118 type: 'key',
73119 hash: this.hash(algo, type),
73120 algorithm: algo,
73121 hashType: type
73122 };
73123 return (new Fingerprint(opts));
73124};
73125
73126Key.prototype.defaultHashAlgorithm = function () {
73127 var hashAlgo = 'sha1';
73128 if (this.type === 'rsa')
73129 hashAlgo = 'sha256';
73130 if (this.type === 'dsa' && this.size > 1024)
73131 hashAlgo = 'sha256';
73132 if (this.type === 'ed25519')
73133 hashAlgo = 'sha512';
73134 if (this.type === 'ecdsa') {
73135 if (this.size <= 256)
73136 hashAlgo = 'sha256';
73137 else if (this.size <= 384)
73138 hashAlgo = 'sha384';
73139 else
73140 hashAlgo = 'sha512';
73141 }
73142 return (hashAlgo);
73143};
73144
73145Key.prototype.createVerify = function (hashAlgo) {
73146 if (hashAlgo === undefined)
73147 hashAlgo = this.defaultHashAlgorithm();
73148 assert.string(hashAlgo, 'hash algorithm');
73149
73150 /* ED25519 is not supported by OpenSSL, use a javascript impl. */
73151 if (this.type === 'ed25519' && edCompat !== undefined)
73152 return (new edCompat.Verifier(this, hashAlgo));
73153 if (this.type === 'curve25519')
73154 throw (new Error('Curve25519 keys are not suitable for ' +
73155 'signing or verification'));
73156
73157 var v, nm, err;
73158 try {
73159 nm = hashAlgo.toUpperCase();
73160 v = crypto.createVerify(nm);
73161 } catch (e) {
73162 err = e;
73163 }
73164 if (v === undefined || (err instanceof Error &&
73165 err.message.match(/Unknown message digest/))) {
73166 nm = 'RSA-';
73167 nm += hashAlgo.toUpperCase();
73168 v = crypto.createVerify(nm);
73169 }
73170 assert.ok(v, 'failed to create verifier');
73171 var oldVerify = v.verify.bind(v);
73172 var key = this.toBuffer('pkcs8');
73173 var curve = this.curve;
73174 var self = this;
73175 v.verify = function (signature, fmt) {
73176 if (Signature.isSignature(signature, [2, 0])) {
73177 if (signature.type !== self.type)
73178 return (false);
73179 if (signature.hashAlgorithm &&
73180 signature.hashAlgorithm !== hashAlgo)
73181 return (false);
73182 if (signature.curve && self.type === 'ecdsa' &&
73183 signature.curve !== curve)
73184 return (false);
73185 return (oldVerify(key, signature.toBuffer('asn1')));
73186
73187 } else if (typeof (signature) === 'string' ||
73188 Buffer.isBuffer(signature)) {
73189 return (oldVerify(key, signature, fmt));
73190
73191 /*
73192 * Avoid doing this on valid arguments, walking the prototype
73193 * chain can be quite slow.
73194 */
73195 } else if (Signature.isSignature(signature, [1, 0])) {
73196 throw (new Error('signature was created by too old ' +
73197 'a version of sshpk and cannot be verified'));
73198
73199 } else {
73200 throw (new TypeError('signature must be a string, ' +
73201 'Buffer, or Signature object'));
73202 }
73203 };
73204 return (v);
73205};
73206
73207Key.prototype.createDiffieHellman = function () {
73208 if (this.type === 'rsa')
73209 throw (new Error('RSA keys do not support Diffie-Hellman'));
73210
73211 return (new DiffieHellman(this));
73212};
73213Key.prototype.createDH = Key.prototype.createDiffieHellman;
73214
73215Key.parse = function (data, format, options) {
73216 if (typeof (data) !== 'string')
73217 assert.buffer(data, 'data');
73218 if (format === undefined)
73219 format = 'auto';
73220 assert.string(format, 'format');
73221 if (typeof (options) === 'string')
73222 options = { filename: options };
73223 assert.optionalObject(options, 'options');
73224 if (options === undefined)
73225 options = {};
73226 assert.optionalString(options.filename, 'options.filename');
73227 if (options.filename === undefined)
73228 options.filename = '(unnamed)';
73229
73230 assert.object(formats[format], 'formats[format]');
73231
73232 try {
73233 var k = formats[format].read(data, options);
73234 if (k instanceof PrivateKey)
73235 k = k.toPublic();
73236 if (!k.comment)
73237 k.comment = options.filename;
73238 return (k);
73239 } catch (e) {
73240 if (e.name === 'KeyEncryptedError')
73241 throw (e);
73242 throw (new KeyParseError(options.filename, format, e));
73243 }
73244};
73245
73246Key.isKey = function (obj, ver) {
73247 return (utils.isCompatible(obj, Key, ver));
73248};
73249
73250/*
73251 * API versions for Key:
73252 * [1,0] -- initial ver, may take Signature for createVerify or may not
73253 * [1,1] -- added pkcs1, pkcs8 formats
73254 * [1,2] -- added auto, ssh-private, openssh formats
73255 * [1,3] -- added defaultHashAlgorithm
73256 * [1,4] -- added ed support, createDH
73257 * [1,5] -- first explicitly tagged version
73258 * [1,6] -- changed ed25519 part names
73259 * [1,7] -- spki hash types
73260 */
73261Key.prototype._sshpkApiVersion = [1, 7];
73262
73263Key._oldVersionDetect = function (obj) {
73264 assert.func(obj.toBuffer);
73265 assert.func(obj.fingerprint);
73266 if (obj.createDH)
73267 return ([1, 4]);
73268 if (obj.defaultHashAlgorithm)
73269 return ([1, 3]);
73270 if (obj.formats['auto'])
73271 return ([1, 2]);
73272 if (obj.formats['pkcs1'])
73273 return ([1, 1]);
73274 return ([1, 0]);
73275};
73276
73277}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
73278},{"../../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){
73279// Copyright 2017 Joyent, Inc.
73280
73281module.exports = PrivateKey;
73282
73283var assert = require('assert-plus');
73284var Buffer = require('safer-buffer').Buffer;
73285var algs = require('./algs');
73286var crypto = require('crypto');
73287var Fingerprint = require('./fingerprint');
73288var Signature = require('./signature');
73289var errs = require('./errors');
73290var util = require('util');
73291var utils = require('./utils');
73292var dhe = require('./dhe');
73293var generateECDSA = dhe.generateECDSA;
73294var generateED25519 = dhe.generateED25519;
73295var edCompat = require('./ed-compat');
73296var nacl = require('tweetnacl');
73297
73298var Key = require('./key');
73299
73300var InvalidAlgorithmError = errs.InvalidAlgorithmError;
73301var KeyParseError = errs.KeyParseError;
73302var KeyEncryptedError = errs.KeyEncryptedError;
73303
73304var formats = {};
73305formats['auto'] = require('./formats/auto');
73306formats['pem'] = require('./formats/pem');
73307formats['pkcs1'] = require('./formats/pkcs1');
73308formats['pkcs8'] = require('./formats/pkcs8');
73309formats['rfc4253'] = require('./formats/rfc4253');
73310formats['ssh-private'] = require('./formats/ssh-private');
73311formats['openssh'] = formats['ssh-private'];
73312formats['ssh'] = formats['ssh-private'];
73313formats['dnssec'] = require('./formats/dnssec');
73314
73315function PrivateKey(opts) {
73316 assert.object(opts, 'options');
73317 Key.call(this, opts);
73318
73319 this._pubCache = undefined;
73320}
73321util.inherits(PrivateKey, Key);
73322
73323PrivateKey.formats = formats;
73324
73325PrivateKey.prototype.toBuffer = function (format, options) {
73326 if (format === undefined)
73327 format = 'pkcs1';
73328 assert.string(format, 'format');
73329 assert.object(formats[format], 'formats[format]');
73330 assert.optionalObject(options, 'options');
73331
73332 return (formats[format].write(this, options));
73333};
73334
73335PrivateKey.prototype.hash = function (algo, type) {
73336 return (this.toPublic().hash(algo, type));
73337};
73338
73339PrivateKey.prototype.fingerprint = function (algo, type) {
73340 return (this.toPublic().fingerprint(algo, type));
73341};
73342
73343PrivateKey.prototype.toPublic = function () {
73344 if (this._pubCache)
73345 return (this._pubCache);
73346
73347 var algInfo = algs.info[this.type];
73348 var pubParts = [];
73349 for (var i = 0; i < algInfo.parts.length; ++i) {
73350 var p = algInfo.parts[i];
73351 pubParts.push(this.part[p]);
73352 }
73353
73354 this._pubCache = new Key({
73355 type: this.type,
73356 source: this,
73357 parts: pubParts
73358 });
73359 if (this.comment)
73360 this._pubCache.comment = this.comment;
73361 return (this._pubCache);
73362};
73363
73364PrivateKey.prototype.derive = function (newType) {
73365 assert.string(newType, 'type');
73366 var priv, pub, pair;
73367
73368 if (this.type === 'ed25519' && newType === 'curve25519') {
73369 priv = this.part.k.data;
73370 if (priv[0] === 0x00)
73371 priv = priv.slice(1);
73372
73373 pair = nacl.box.keyPair.fromSecretKey(new Uint8Array(priv));
73374 pub = Buffer.from(pair.publicKey);
73375
73376 return (new PrivateKey({
73377 type: 'curve25519',
73378 parts: [
73379 { name: 'A', data: utils.mpNormalize(pub) },
73380 { name: 'k', data: utils.mpNormalize(priv) }
73381 ]
73382 }));
73383 } else if (this.type === 'curve25519' && newType === 'ed25519') {
73384 priv = this.part.k.data;
73385 if (priv[0] === 0x00)
73386 priv = priv.slice(1);
73387
73388 pair = nacl.sign.keyPair.fromSeed(new Uint8Array(priv));
73389 pub = Buffer.from(pair.publicKey);
73390
73391 return (new PrivateKey({
73392 type: 'ed25519',
73393 parts: [
73394 { name: 'A', data: utils.mpNormalize(pub) },
73395 { name: 'k', data: utils.mpNormalize(priv) }
73396 ]
73397 }));
73398 }
73399 throw (new Error('Key derivation not supported from ' + this.type +
73400 ' to ' + newType));
73401};
73402
73403PrivateKey.prototype.createVerify = function (hashAlgo) {
73404 return (this.toPublic().createVerify(hashAlgo));
73405};
73406
73407PrivateKey.prototype.createSign = function (hashAlgo) {
73408 if (hashAlgo === undefined)
73409 hashAlgo = this.defaultHashAlgorithm();
73410 assert.string(hashAlgo, 'hash algorithm');
73411
73412 /* ED25519 is not supported by OpenSSL, use a javascript impl. */
73413 if (this.type === 'ed25519' && edCompat !== undefined)
73414 return (new edCompat.Signer(this, hashAlgo));
73415 if (this.type === 'curve25519')
73416 throw (new Error('Curve25519 keys are not suitable for ' +
73417 'signing or verification'));
73418
73419 var v, nm, err;
73420 try {
73421 nm = hashAlgo.toUpperCase();
73422 v = crypto.createSign(nm);
73423 } catch (e) {
73424 err = e;
73425 }
73426 if (v === undefined || (err instanceof Error &&
73427 err.message.match(/Unknown message digest/))) {
73428 nm = 'RSA-';
73429 nm += hashAlgo.toUpperCase();
73430 v = crypto.createSign(nm);
73431 }
73432 assert.ok(v, 'failed to create verifier');
73433 var oldSign = v.sign.bind(v);
73434 var key = this.toBuffer('pkcs1');
73435 var type = this.type;
73436 var curve = this.curve;
73437 v.sign = function () {
73438 var sig = oldSign(key);
73439 if (typeof (sig) === 'string')
73440 sig = Buffer.from(sig, 'binary');
73441 sig = Signature.parse(sig, type, 'asn1');
73442 sig.hashAlgorithm = hashAlgo;
73443 sig.curve = curve;
73444 return (sig);
73445 };
73446 return (v);
73447};
73448
73449PrivateKey.parse = function (data, format, options) {
73450 if (typeof (data) !== 'string')
73451 assert.buffer(data, 'data');
73452 if (format === undefined)
73453 format = 'auto';
73454 assert.string(format, 'format');
73455 if (typeof (options) === 'string')
73456 options = { filename: options };
73457 assert.optionalObject(options, 'options');
73458 if (options === undefined)
73459 options = {};
73460 assert.optionalString(options.filename, 'options.filename');
73461 if (options.filename === undefined)
73462 options.filename = '(unnamed)';
73463
73464 assert.object(formats[format], 'formats[format]');
73465
73466 try {
73467 var k = formats[format].read(data, options);
73468 assert.ok(k instanceof PrivateKey, 'key is not a private key');
73469 if (!k.comment)
73470 k.comment = options.filename;
73471 return (k);
73472 } catch (e) {
73473 if (e.name === 'KeyEncryptedError')
73474 throw (e);
73475 throw (new KeyParseError(options.filename, format, e));
73476 }
73477};
73478
73479PrivateKey.isPrivateKey = function (obj, ver) {
73480 return (utils.isCompatible(obj, PrivateKey, ver));
73481};
73482
73483PrivateKey.generate = function (type, options) {
73484 if (options === undefined)
73485 options = {};
73486 assert.object(options, 'options');
73487
73488 switch (type) {
73489 case 'ecdsa':
73490 if (options.curve === undefined)
73491 options.curve = 'nistp256';
73492 assert.string(options.curve, 'options.curve');
73493 return (generateECDSA(options.curve));
73494 case 'ed25519':
73495 return (generateED25519());
73496 default:
73497 throw (new Error('Key generation not supported with key ' +
73498 'type "' + type + '"'));
73499 }
73500};
73501
73502/*
73503 * API versions for PrivateKey:
73504 * [1,0] -- initial ver
73505 * [1,1] -- added auto, pkcs[18], openssh/ssh-private formats
73506 * [1,2] -- added defaultHashAlgorithm
73507 * [1,3] -- added derive, ed, createDH
73508 * [1,4] -- first tagged version
73509 * [1,5] -- changed ed25519 part names and format
73510 * [1,6] -- type arguments for hash() and fingerprint()
73511 */
73512PrivateKey.prototype._sshpkApiVersion = [1, 6];
73513
73514PrivateKey._oldVersionDetect = function (obj) {
73515 assert.func(obj.toPublic);
73516 assert.func(obj.createSign);
73517 if (obj.derive)
73518 return ([1, 3]);
73519 if (obj.defaultHashAlgorithm)
73520 return ([1, 2]);
73521 if (obj.formats['auto'])
73522 return ([1, 1]);
73523 return ([1, 0]);
73524};
73525
73526},{"./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){
73527// Copyright 2015 Joyent, Inc.
73528
73529module.exports = Signature;
73530
73531var assert = require('assert-plus');
73532var Buffer = require('safer-buffer').Buffer;
73533var algs = require('./algs');
73534var crypto = require('crypto');
73535var errs = require('./errors');
73536var utils = require('./utils');
73537var asn1 = require('asn1');
73538var SSHBuffer = require('./ssh-buffer');
73539
73540var InvalidAlgorithmError = errs.InvalidAlgorithmError;
73541var SignatureParseError = errs.SignatureParseError;
73542
73543function Signature(opts) {
73544 assert.object(opts, 'options');
73545 assert.arrayOfObject(opts.parts, 'options.parts');
73546 assert.string(opts.type, 'options.type');
73547
73548 var partLookup = {};
73549 for (var i = 0; i < opts.parts.length; ++i) {
73550 var part = opts.parts[i];
73551 partLookup[part.name] = part;
73552 }
73553
73554 this.type = opts.type;
73555 this.hashAlgorithm = opts.hashAlgo;
73556 this.curve = opts.curve;
73557 this.parts = opts.parts;
73558 this.part = partLookup;
73559}
73560
73561Signature.prototype.toBuffer = function (format) {
73562 if (format === undefined)
73563 format = 'asn1';
73564 assert.string(format, 'format');
73565
73566 var buf;
73567 var stype = 'ssh-' + this.type;
73568
73569 switch (this.type) {
73570 case 'rsa':
73571 switch (this.hashAlgorithm) {
73572 case 'sha256':
73573 stype = 'rsa-sha2-256';
73574 break;
73575 case 'sha512':
73576 stype = 'rsa-sha2-512';
73577 break;
73578 case 'sha1':
73579 case undefined:
73580 break;
73581 default:
73582 throw (new Error('SSH signature ' +
73583 'format does not support hash ' +
73584 'algorithm ' + this.hashAlgorithm));
73585 }
73586 if (format === 'ssh') {
73587 buf = new SSHBuffer({});
73588 buf.writeString(stype);
73589 buf.writePart(this.part.sig);
73590 return (buf.toBuffer());
73591 } else {
73592 return (this.part.sig.data);
73593 }
73594 break;
73595
73596 case 'ed25519':
73597 if (format === 'ssh') {
73598 buf = new SSHBuffer({});
73599 buf.writeString(stype);
73600 buf.writePart(this.part.sig);
73601 return (buf.toBuffer());
73602 } else {
73603 return (this.part.sig.data);
73604 }
73605 break;
73606
73607 case 'dsa':
73608 case 'ecdsa':
73609 var r, s;
73610 if (format === 'asn1') {
73611 var der = new asn1.BerWriter();
73612 der.startSequence();
73613 r = utils.mpNormalize(this.part.r.data);
73614 s = utils.mpNormalize(this.part.s.data);
73615 der.writeBuffer(r, asn1.Ber.Integer);
73616 der.writeBuffer(s, asn1.Ber.Integer);
73617 der.endSequence();
73618 return (der.buffer);
73619 } else if (format === 'ssh' && this.type === 'dsa') {
73620 buf = new SSHBuffer({});
73621 buf.writeString('ssh-dss');
73622 r = this.part.r.data;
73623 if (r.length > 20 && r[0] === 0x00)
73624 r = r.slice(1);
73625 s = this.part.s.data;
73626 if (s.length > 20 && s[0] === 0x00)
73627 s = s.slice(1);
73628 if ((this.hashAlgorithm &&
73629 this.hashAlgorithm !== 'sha1') ||
73630 r.length + s.length !== 40) {
73631 throw (new Error('OpenSSH only supports ' +
73632 'DSA signatures with SHA1 hash'));
73633 }
73634 buf.writeBuffer(Buffer.concat([r, s]));
73635 return (buf.toBuffer());
73636 } else if (format === 'ssh' && this.type === 'ecdsa') {
73637 var inner = new SSHBuffer({});
73638 r = this.part.r.data;
73639 inner.writeBuffer(r);
73640 inner.writePart(this.part.s);
73641
73642 buf = new SSHBuffer({});
73643 /* XXX: find a more proper way to do this? */
73644 var curve;
73645 if (r[0] === 0x00)
73646 r = r.slice(1);
73647 var sz = r.length * 8;
73648 if (sz === 256)
73649 curve = 'nistp256';
73650 else if (sz === 384)
73651 curve = 'nistp384';
73652 else if (sz === 528)
73653 curve = 'nistp521';
73654 buf.writeString('ecdsa-sha2-' + curve);
73655 buf.writeBuffer(inner.toBuffer());
73656 return (buf.toBuffer());
73657 }
73658 throw (new Error('Invalid signature format'));
73659 default:
73660 throw (new Error('Invalid signature data'));
73661 }
73662};
73663
73664Signature.prototype.toString = function (format) {
73665 assert.optionalString(format, 'format');
73666 return (this.toBuffer(format).toString('base64'));
73667};
73668
73669Signature.parse = function (data, type, format) {
73670 if (typeof (data) === 'string')
73671 data = Buffer.from(data, 'base64');
73672 assert.buffer(data, 'data');
73673 assert.string(format, 'format');
73674 assert.string(type, 'type');
73675
73676 var opts = {};
73677 opts.type = type.toLowerCase();
73678 opts.parts = [];
73679
73680 try {
73681 assert.ok(data.length > 0, 'signature must not be empty');
73682 switch (opts.type) {
73683 case 'rsa':
73684 return (parseOneNum(data, type, format, opts));
73685 case 'ed25519':
73686 return (parseOneNum(data, type, format, opts));
73687
73688 case 'dsa':
73689 case 'ecdsa':
73690 if (format === 'asn1')
73691 return (parseDSAasn1(data, type, format, opts));
73692 else if (opts.type === 'dsa')
73693 return (parseDSA(data, type, format, opts));
73694 else
73695 return (parseECDSA(data, type, format, opts));
73696
73697 default:
73698 throw (new InvalidAlgorithmError(type));
73699 }
73700
73701 } catch (e) {
73702 if (e instanceof InvalidAlgorithmError)
73703 throw (e);
73704 throw (new SignatureParseError(type, format, e));
73705 }
73706};
73707
73708function parseOneNum(data, type, format, opts) {
73709 if (format === 'ssh') {
73710 try {
73711 var buf = new SSHBuffer({buffer: data});
73712 var head = buf.readString();
73713 } catch (e) {
73714 /* fall through */
73715 }
73716 if (buf !== undefined) {
73717 var msg = 'SSH signature does not match expected ' +
73718 'type (expected ' + type + ', got ' + head + ')';
73719 switch (head) {
73720 case 'ssh-rsa':
73721 assert.strictEqual(type, 'rsa', msg);
73722 opts.hashAlgo = 'sha1';
73723 break;
73724 case 'rsa-sha2-256':
73725 assert.strictEqual(type, 'rsa', msg);
73726 opts.hashAlgo = 'sha256';
73727 break;
73728 case 'rsa-sha2-512':
73729 assert.strictEqual(type, 'rsa', msg);
73730 opts.hashAlgo = 'sha512';
73731 break;
73732 case 'ssh-ed25519':
73733 assert.strictEqual(type, 'ed25519', msg);
73734 opts.hashAlgo = 'sha512';
73735 break;
73736 default:
73737 throw (new Error('Unknown SSH signature ' +
73738 'type: ' + head));
73739 }
73740 var sig = buf.readPart();
73741 assert.ok(buf.atEnd(), 'extra trailing bytes');
73742 sig.name = 'sig';
73743 opts.parts.push(sig);
73744 return (new Signature(opts));
73745 }
73746 }
73747 opts.parts.push({name: 'sig', data: data});
73748 return (new Signature(opts));
73749}
73750
73751function parseDSAasn1(data, type, format, opts) {
73752 var der = new asn1.BerReader(data);
73753 der.readSequence();
73754 var r = der.readString(asn1.Ber.Integer, true);
73755 var s = der.readString(asn1.Ber.Integer, true);
73756
73757 opts.parts.push({name: 'r', data: utils.mpNormalize(r)});
73758 opts.parts.push({name: 's', data: utils.mpNormalize(s)});
73759
73760 return (new Signature(opts));
73761}
73762
73763function parseDSA(data, type, format, opts) {
73764 if (data.length != 40) {
73765 var buf = new SSHBuffer({buffer: data});
73766 var d = buf.readBuffer();
73767 if (d.toString('ascii') === 'ssh-dss')
73768 d = buf.readBuffer();
73769 assert.ok(buf.atEnd(), 'extra trailing bytes');
73770 assert.strictEqual(d.length, 40, 'invalid inner length');
73771 data = d;
73772 }
73773 opts.parts.push({name: 'r', data: data.slice(0, 20)});
73774 opts.parts.push({name: 's', data: data.slice(20, 40)});
73775 return (new Signature(opts));
73776}
73777
73778function parseECDSA(data, type, format, opts) {
73779 var buf = new SSHBuffer({buffer: data});
73780
73781 var r, s;
73782 var inner = buf.readBuffer();
73783 var stype = inner.toString('ascii');
73784 if (stype.slice(0, 6) === 'ecdsa-') {
73785 var parts = stype.split('-');
73786 assert.strictEqual(parts[0], 'ecdsa');
73787 assert.strictEqual(parts[1], 'sha2');
73788 opts.curve = parts[2];
73789 switch (opts.curve) {
73790 case 'nistp256':
73791 opts.hashAlgo = 'sha256';
73792 break;
73793 case 'nistp384':
73794 opts.hashAlgo = 'sha384';
73795 break;
73796 case 'nistp521':
73797 opts.hashAlgo = 'sha512';
73798 break;
73799 default:
73800 throw (new Error('Unsupported ECDSA curve: ' +
73801 opts.curve));
73802 }
73803 inner = buf.readBuffer();
73804 assert.ok(buf.atEnd(), 'extra trailing bytes on outer');
73805 buf = new SSHBuffer({buffer: inner});
73806 r = buf.readPart();
73807 } else {
73808 r = {data: inner};
73809 }
73810
73811 s = buf.readPart();
73812 assert.ok(buf.atEnd(), 'extra trailing bytes');
73813
73814 r.name = 'r';
73815 s.name = 's';
73816
73817 opts.parts.push(r);
73818 opts.parts.push(s);
73819 return (new Signature(opts));
73820}
73821
73822Signature.isSignature = function (obj, ver) {
73823 return (utils.isCompatible(obj, Signature, ver));
73824};
73825
73826/*
73827 * API versions for Signature:
73828 * [1,0] -- initial ver
73829 * [2,0] -- support for rsa in full ssh format, compat with sshpk-agent
73830 * hashAlgorithm property
73831 * [2,1] -- first tagged version
73832 */
73833Signature.prototype._sshpkApiVersion = [2, 1];
73834
73835Signature._oldVersionDetect = function (obj) {
73836 assert.func(obj.toBuffer);
73837 if (obj.hasOwnProperty('hashAlgorithm'))
73838 return ([2, 0]);
73839 return ([1, 0]);
73840};
73841
73842},{"./algs":335,"./errors":339,"./ssh-buffer":358,"./utils":359,"asn1":66,"assert-plus":67,"crypto":126,"safer-buffer":326}],358:[function(require,module,exports){
73843// Copyright 2015 Joyent, Inc.
73844
73845module.exports = SSHBuffer;
73846
73847var assert = require('assert-plus');
73848var Buffer = require('safer-buffer').Buffer;
73849
73850function SSHBuffer(opts) {
73851 assert.object(opts, 'options');
73852 if (opts.buffer !== undefined)
73853 assert.buffer(opts.buffer, 'options.buffer');
73854
73855 this._size = opts.buffer ? opts.buffer.length : 1024;
73856 this._buffer = opts.buffer || Buffer.alloc(this._size);
73857 this._offset = 0;
73858}
73859
73860SSHBuffer.prototype.toBuffer = function () {
73861 return (this._buffer.slice(0, this._offset));
73862};
73863
73864SSHBuffer.prototype.atEnd = function () {
73865 return (this._offset >= this._buffer.length);
73866};
73867
73868SSHBuffer.prototype.remainder = function () {
73869 return (this._buffer.slice(this._offset));
73870};
73871
73872SSHBuffer.prototype.skip = function (n) {
73873 this._offset += n;
73874};
73875
73876SSHBuffer.prototype.expand = function () {
73877 this._size *= 2;
73878 var buf = Buffer.alloc(this._size);
73879 this._buffer.copy(buf, 0);
73880 this._buffer = buf;
73881};
73882
73883SSHBuffer.prototype.readPart = function () {
73884 return ({data: this.readBuffer()});
73885};
73886
73887SSHBuffer.prototype.readBuffer = function () {
73888 var len = this._buffer.readUInt32BE(this._offset);
73889 this._offset += 4;
73890 assert.ok(this._offset + len <= this._buffer.length,
73891 'length out of bounds at +0x' + this._offset.toString(16) +
73892 ' (data truncated?)');
73893 var buf = this._buffer.slice(this._offset, this._offset + len);
73894 this._offset += len;
73895 return (buf);
73896};
73897
73898SSHBuffer.prototype.readString = function () {
73899 return (this.readBuffer().toString());
73900};
73901
73902SSHBuffer.prototype.readCString = function () {
73903 var offset = this._offset;
73904 while (offset < this._buffer.length &&
73905 this._buffer[offset] !== 0x00)
73906 offset++;
73907 assert.ok(offset < this._buffer.length, 'c string does not terminate');
73908 var str = this._buffer.slice(this._offset, offset).toString();
73909 this._offset = offset + 1;
73910 return (str);
73911};
73912
73913SSHBuffer.prototype.readInt = function () {
73914 var v = this._buffer.readUInt32BE(this._offset);
73915 this._offset += 4;
73916 return (v);
73917};
73918
73919SSHBuffer.prototype.readInt64 = function () {
73920 assert.ok(this._offset + 8 < this._buffer.length,
73921 'buffer not long enough to read Int64');
73922 var v = this._buffer.slice(this._offset, this._offset + 8);
73923 this._offset += 8;
73924 return (v);
73925};
73926
73927SSHBuffer.prototype.readChar = function () {
73928 var v = this._buffer[this._offset++];
73929 return (v);
73930};
73931
73932SSHBuffer.prototype.writeBuffer = function (buf) {
73933 while (this._offset + 4 + buf.length > this._size)
73934 this.expand();
73935 this._buffer.writeUInt32BE(buf.length, this._offset);
73936 this._offset += 4;
73937 buf.copy(this._buffer, this._offset);
73938 this._offset += buf.length;
73939};
73940
73941SSHBuffer.prototype.writeString = function (str) {
73942 this.writeBuffer(Buffer.from(str, 'utf8'));
73943};
73944
73945SSHBuffer.prototype.writeCString = function (str) {
73946 while (this._offset + 1 + str.length > this._size)
73947 this.expand();
73948 this._buffer.write(str, this._offset);
73949 this._offset += str.length;
73950 this._buffer[this._offset++] = 0;
73951};
73952
73953SSHBuffer.prototype.writeInt = function (v) {
73954 while (this._offset + 4 > this._size)
73955 this.expand();
73956 this._buffer.writeUInt32BE(v, this._offset);
73957 this._offset += 4;
73958};
73959
73960SSHBuffer.prototype.writeInt64 = function (v) {
73961 assert.buffer(v, 'value');
73962 if (v.length > 8) {
73963 var lead = v.slice(0, v.length - 8);
73964 for (var i = 0; i < lead.length; ++i) {
73965 assert.strictEqual(lead[i], 0,
73966 'must fit in 64 bits of precision');
73967 }
73968 v = v.slice(v.length - 8, v.length);
73969 }
73970 while (this._offset + 8 > this._size)
73971 this.expand();
73972 v.copy(this._buffer, this._offset);
73973 this._offset += 8;
73974};
73975
73976SSHBuffer.prototype.writeChar = function (v) {
73977 while (this._offset + 1 > this._size)
73978 this.expand();
73979 this._buffer[this._offset++] = v;
73980};
73981
73982SSHBuffer.prototype.writePart = function (p) {
73983 this.writeBuffer(p.data);
73984};
73985
73986SSHBuffer.prototype.write = function (buf) {
73987 while (this._offset + buf.length > this._size)
73988 this.expand();
73989 buf.copy(this._buffer, this._offset);
73990 this._offset += buf.length;
73991};
73992
73993},{"assert-plus":67,"safer-buffer":326}],359:[function(require,module,exports){
73994// Copyright 2015 Joyent, Inc.
73995
73996module.exports = {
73997 bufferSplit: bufferSplit,
73998 addRSAMissing: addRSAMissing,
73999 calculateDSAPublic: calculateDSAPublic,
74000 calculateED25519Public: calculateED25519Public,
74001 calculateX25519Public: calculateX25519Public,
74002 mpNormalize: mpNormalize,
74003 mpDenormalize: mpDenormalize,
74004 ecNormalize: ecNormalize,
74005 countZeros: countZeros,
74006 assertCompatible: assertCompatible,
74007 isCompatible: isCompatible,
74008 opensslKeyDeriv: opensslKeyDeriv,
74009 opensshCipherInfo: opensshCipherInfo,
74010 publicFromPrivateECDSA: publicFromPrivateECDSA,
74011 zeroPadToLength: zeroPadToLength,
74012 writeBitString: writeBitString,
74013 readBitString: readBitString,
74014 pbkdf2: pbkdf2
74015};
74016
74017var assert = require('assert-plus');
74018var Buffer = require('safer-buffer').Buffer;
74019var PrivateKey = require('./private-key');
74020var Key = require('./key');
74021var crypto = require('crypto');
74022var algs = require('./algs');
74023var asn1 = require('asn1');
74024
74025var ec = require('ecc-jsbn/lib/ec');
74026var jsbn = require('jsbn').BigInteger;
74027var nacl = require('tweetnacl');
74028
74029var MAX_CLASS_DEPTH = 3;
74030
74031function isCompatible(obj, klass, needVer) {
74032 if (obj === null || typeof (obj) !== 'object')
74033 return (false);
74034 if (needVer === undefined)
74035 needVer = klass.prototype._sshpkApiVersion;
74036 if (obj instanceof klass &&
74037 klass.prototype._sshpkApiVersion[0] == needVer[0])
74038 return (true);
74039 var proto = Object.getPrototypeOf(obj);
74040 var depth = 0;
74041 while (proto.constructor.name !== klass.name) {
74042 proto = Object.getPrototypeOf(proto);
74043 if (!proto || ++depth > MAX_CLASS_DEPTH)
74044 return (false);
74045 }
74046 if (proto.constructor.name !== klass.name)
74047 return (false);
74048 var ver = proto._sshpkApiVersion;
74049 if (ver === undefined)
74050 ver = klass._oldVersionDetect(obj);
74051 if (ver[0] != needVer[0] || ver[1] < needVer[1])
74052 return (false);
74053 return (true);
74054}
74055
74056function assertCompatible(obj, klass, needVer, name) {
74057 if (name === undefined)
74058 name = 'object';
74059 assert.ok(obj, name + ' must not be null');
74060 assert.object(obj, name + ' must be an object');
74061 if (needVer === undefined)
74062 needVer = klass.prototype._sshpkApiVersion;
74063 if (obj instanceof klass &&
74064 klass.prototype._sshpkApiVersion[0] == needVer[0])
74065 return;
74066 var proto = Object.getPrototypeOf(obj);
74067 var depth = 0;
74068 while (proto.constructor.name !== klass.name) {
74069 proto = Object.getPrototypeOf(proto);
74070 assert.ok(proto && ++depth <= MAX_CLASS_DEPTH,
74071 name + ' must be a ' + klass.name + ' instance');
74072 }
74073 assert.strictEqual(proto.constructor.name, klass.name,
74074 name + ' must be a ' + klass.name + ' instance');
74075 var ver = proto._sshpkApiVersion;
74076 if (ver === undefined)
74077 ver = klass._oldVersionDetect(obj);
74078 assert.ok(ver[0] == needVer[0] && ver[1] >= needVer[1],
74079 name + ' must be compatible with ' + klass.name + ' klass ' +
74080 'version ' + needVer[0] + '.' + needVer[1]);
74081}
74082
74083var CIPHER_LEN = {
74084 'des-ede3-cbc': { key: 24, iv: 8 },
74085 'aes-128-cbc': { key: 16, iv: 16 },
74086 'aes-256-cbc': { key: 32, iv: 16 }
74087};
74088var PKCS5_SALT_LEN = 8;
74089
74090function opensslKeyDeriv(cipher, salt, passphrase, count) {
74091 assert.buffer(salt, 'salt');
74092 assert.buffer(passphrase, 'passphrase');
74093 assert.number(count, 'iteration count');
74094
74095 var clen = CIPHER_LEN[cipher];
74096 assert.object(clen, 'supported cipher');
74097
74098 salt = salt.slice(0, PKCS5_SALT_LEN);
74099
74100 var D, D_prev, bufs;
74101 var material = Buffer.alloc(0);
74102 while (material.length < clen.key + clen.iv) {
74103 bufs = [];
74104 if (D_prev)
74105 bufs.push(D_prev);
74106 bufs.push(passphrase);
74107 bufs.push(salt);
74108 D = Buffer.concat(bufs);
74109 for (var j = 0; j < count; ++j)
74110 D = crypto.createHash('md5').update(D).digest();
74111 material = Buffer.concat([material, D]);
74112 D_prev = D;
74113 }
74114
74115 return ({
74116 key: material.slice(0, clen.key),
74117 iv: material.slice(clen.key, clen.key + clen.iv)
74118 });
74119}
74120
74121/* See: RFC2898 */
74122function pbkdf2(hashAlg, salt, iterations, size, passphrase) {
74123 var hkey = Buffer.alloc(salt.length + 4);
74124 salt.copy(hkey);
74125
74126 var gen = 0, ts = [];
74127 var i = 1;
74128 while (gen < size) {
74129 var t = T(i++);
74130 gen += t.length;
74131 ts.push(t);
74132 }
74133 return (Buffer.concat(ts).slice(0, size));
74134
74135 function T(I) {
74136 hkey.writeUInt32BE(I, hkey.length - 4);
74137
74138 var hmac = crypto.createHmac(hashAlg, passphrase);
74139 hmac.update(hkey);
74140
74141 var Ti = hmac.digest();
74142 var Uc = Ti;
74143 var c = 1;
74144 while (c++ < iterations) {
74145 hmac = crypto.createHmac(hashAlg, passphrase);
74146 hmac.update(Uc);
74147 Uc = hmac.digest();
74148 for (var x = 0; x < Ti.length; ++x)
74149 Ti[x] ^= Uc[x];
74150 }
74151 return (Ti);
74152 }
74153}
74154
74155/* Count leading zero bits on a buffer */
74156function countZeros(buf) {
74157 var o = 0, obit = 8;
74158 while (o < buf.length) {
74159 var mask = (1 << obit);
74160 if ((buf[o] & mask) === mask)
74161 break;
74162 obit--;
74163 if (obit < 0) {
74164 o++;
74165 obit = 8;
74166 }
74167 }
74168 return (o*8 + (8 - obit) - 1);
74169}
74170
74171function bufferSplit(buf, chr) {
74172 assert.buffer(buf);
74173 assert.string(chr);
74174
74175 var parts = [];
74176 var lastPart = 0;
74177 var matches = 0;
74178 for (var i = 0; i < buf.length; ++i) {
74179 if (buf[i] === chr.charCodeAt(matches))
74180 ++matches;
74181 else if (buf[i] === chr.charCodeAt(0))
74182 matches = 1;
74183 else
74184 matches = 0;
74185
74186 if (matches >= chr.length) {
74187 var newPart = i + 1;
74188 parts.push(buf.slice(lastPart, newPart - matches));
74189 lastPart = newPart;
74190 matches = 0;
74191 }
74192 }
74193 if (lastPart <= buf.length)
74194 parts.push(buf.slice(lastPart, buf.length));
74195
74196 return (parts);
74197}
74198
74199function ecNormalize(buf, addZero) {
74200 assert.buffer(buf);
74201 if (buf[0] === 0x00 && buf[1] === 0x04) {
74202 if (addZero)
74203 return (buf);
74204 return (buf.slice(1));
74205 } else if (buf[0] === 0x04) {
74206 if (!addZero)
74207 return (buf);
74208 } else {
74209 while (buf[0] === 0x00)
74210 buf = buf.slice(1);
74211 if (buf[0] === 0x02 || buf[0] === 0x03)
74212 throw (new Error('Compressed elliptic curve points ' +
74213 'are not supported'));
74214 if (buf[0] !== 0x04)
74215 throw (new Error('Not a valid elliptic curve point'));
74216 if (!addZero)
74217 return (buf);
74218 }
74219 var b = Buffer.alloc(buf.length + 1);
74220 b[0] = 0x0;
74221 buf.copy(b, 1);
74222 return (b);
74223}
74224
74225function readBitString(der, tag) {
74226 if (tag === undefined)
74227 tag = asn1.Ber.BitString;
74228 var buf = der.readString(tag, true);
74229 assert.strictEqual(buf[0], 0x00, 'bit strings with unused bits are ' +
74230 'not supported (0x' + buf[0].toString(16) + ')');
74231 return (buf.slice(1));
74232}
74233
74234function writeBitString(der, buf, tag) {
74235 if (tag === undefined)
74236 tag = asn1.Ber.BitString;
74237 var b = Buffer.alloc(buf.length + 1);
74238 b[0] = 0x00;
74239 buf.copy(b, 1);
74240 der.writeBuffer(b, tag);
74241}
74242
74243function mpNormalize(buf) {
74244 assert.buffer(buf);
74245 while (buf.length > 1 && buf[0] === 0x00 && (buf[1] & 0x80) === 0x00)
74246 buf = buf.slice(1);
74247 if ((buf[0] & 0x80) === 0x80) {
74248 var b = Buffer.alloc(buf.length + 1);
74249 b[0] = 0x00;
74250 buf.copy(b, 1);
74251 buf = b;
74252 }
74253 return (buf);
74254}
74255
74256function mpDenormalize(buf) {
74257 assert.buffer(buf);
74258 while (buf.length > 1 && buf[0] === 0x00)
74259 buf = buf.slice(1);
74260 return (buf);
74261}
74262
74263function zeroPadToLength(buf, len) {
74264 assert.buffer(buf);
74265 assert.number(len);
74266 while (buf.length > len) {
74267 assert.equal(buf[0], 0x00);
74268 buf = buf.slice(1);
74269 }
74270 while (buf.length < len) {
74271 var b = Buffer.alloc(buf.length + 1);
74272 b[0] = 0x00;
74273 buf.copy(b, 1);
74274 buf = b;
74275 }
74276 return (buf);
74277}
74278
74279function bigintToMpBuf(bigint) {
74280 var buf = Buffer.from(bigint.toByteArray());
74281 buf = mpNormalize(buf);
74282 return (buf);
74283}
74284
74285function calculateDSAPublic(g, p, x) {
74286 assert.buffer(g);
74287 assert.buffer(p);
74288 assert.buffer(x);
74289 g = new jsbn(g);
74290 p = new jsbn(p);
74291 x = new jsbn(x);
74292 var y = g.modPow(x, p);
74293 var ybuf = bigintToMpBuf(y);
74294 return (ybuf);
74295}
74296
74297function calculateED25519Public(k) {
74298 assert.buffer(k);
74299
74300 var kp = nacl.sign.keyPair.fromSeed(new Uint8Array(k));
74301 return (Buffer.from(kp.publicKey));
74302}
74303
74304function calculateX25519Public(k) {
74305 assert.buffer(k);
74306
74307 var kp = nacl.box.keyPair.fromSeed(new Uint8Array(k));
74308 return (Buffer.from(kp.publicKey));
74309}
74310
74311function addRSAMissing(key) {
74312 assert.object(key);
74313 assertCompatible(key, PrivateKey, [1, 1]);
74314
74315 var d = new jsbn(key.part.d.data);
74316 var buf;
74317
74318 if (!key.part.dmodp) {
74319 var p = new jsbn(key.part.p.data);
74320 var dmodp = d.mod(p.subtract(1));
74321
74322 buf = bigintToMpBuf(dmodp);
74323 key.part.dmodp = {name: 'dmodp', data: buf};
74324 key.parts.push(key.part.dmodp);
74325 }
74326 if (!key.part.dmodq) {
74327 var q = new jsbn(key.part.q.data);
74328 var dmodq = d.mod(q.subtract(1));
74329
74330 buf = bigintToMpBuf(dmodq);
74331 key.part.dmodq = {name: 'dmodq', data: buf};
74332 key.parts.push(key.part.dmodq);
74333 }
74334}
74335
74336function publicFromPrivateECDSA(curveName, priv) {
74337 assert.string(curveName, 'curveName');
74338 assert.buffer(priv);
74339 var params = algs.curves[curveName];
74340 var p = new jsbn(params.p);
74341 var a = new jsbn(params.a);
74342 var b = new jsbn(params.b);
74343 var curve = new ec.ECCurveFp(p, a, b);
74344 var G = curve.decodePointHex(params.G.toString('hex'));
74345
74346 var d = new jsbn(mpNormalize(priv));
74347 var pub = G.multiply(d);
74348 pub = Buffer.from(curve.encodePointHex(pub), 'hex');
74349
74350 var parts = [];
74351 parts.push({name: 'curve', data: Buffer.from(curveName)});
74352 parts.push({name: 'Q', data: pub});
74353
74354 var key = new Key({type: 'ecdsa', curve: curve, parts: parts});
74355 return (key);
74356}
74357
74358function opensshCipherInfo(cipher) {
74359 var inf = {};
74360 switch (cipher) {
74361 case '3des-cbc':
74362 inf.keySize = 24;
74363 inf.blockSize = 8;
74364 inf.opensslName = 'des-ede3-cbc';
74365 break;
74366 case 'blowfish-cbc':
74367 inf.keySize = 16;
74368 inf.blockSize = 8;
74369 inf.opensslName = 'bf-cbc';
74370 break;
74371 case 'aes128-cbc':
74372 case 'aes128-ctr':
74373 case 'aes128-gcm@openssh.com':
74374 inf.keySize = 16;
74375 inf.blockSize = 16;
74376 inf.opensslName = 'aes-128-' + cipher.slice(7, 10);
74377 break;
74378 case 'aes192-cbc':
74379 case 'aes192-ctr':
74380 case 'aes192-gcm@openssh.com':
74381 inf.keySize = 24;
74382 inf.blockSize = 16;
74383 inf.opensslName = 'aes-192-' + cipher.slice(7, 10);
74384 break;
74385 case 'aes256-cbc':
74386 case 'aes256-ctr':
74387 case 'aes256-gcm@openssh.com':
74388 inf.keySize = 32;
74389 inf.blockSize = 16;
74390 inf.opensslName = 'aes-256-' + cipher.slice(7, 10);
74391 break;
74392 default:
74393 throw (new Error(
74394 'Unsupported openssl cipher "' + cipher + '"'));
74395 }
74396 return (inf);
74397}
74398
74399},{"./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){
74400'use strict';
74401
74402var isNative = /\.node$/;
74403
74404function forEach(obj, callback) {
74405 for ( var key in obj ) {
74406 if (!Object.prototype.hasOwnProperty.call(obj, key)) {
74407 continue;
74408 }
74409 callback(key);
74410 }
74411}
74412
74413function assign(target, source) {
74414 forEach(source, function (key) {
74415 target[key] = source[key];
74416 });
74417 return target;
74418}
74419
74420function clearCache(requireCache) {
74421 forEach(requireCache, function (resolvedPath) {
74422 if (!isNative.test(resolvedPath)) {
74423 delete requireCache[resolvedPath];
74424 }
74425 });
74426}
74427
74428module.exports = function (requireCache, callback, callbackForModulesToKeep, module) {
74429
74430 var originalCache = assign({}, requireCache);
74431 clearCache(requireCache);
74432
74433 if (callbackForModulesToKeep) {
74434
74435 var originalModuleChildren = module.children ? module.children.slice() : false; // Creates a shallow copy of module.children
74436
74437 callbackForModulesToKeep();
74438
74439 // Lists the cache entries made by callbackForModulesToKeep()
74440 var modulesToKeep = [];
74441 forEach(requireCache, function (key) {
74442 modulesToKeep.push(key);
74443 });
74444
74445 // Discards the modules required in callbackForModulesToKeep()
74446 clearCache(requireCache);
74447
74448 if (module.children) { // Only true for node.js
74449 module.children = originalModuleChildren; // Removes last references to modules required in callbackForModulesToKeep() -> No memory leak
74450 }
74451
74452 // Takes the cache entries of the original cache in case the modules where required before
74453 for ( var i = 0; i < modulesToKeep.length; i+=1 ) {
74454 if (originalCache[modulesToKeep[i]]) {
74455 requireCache[modulesToKeep[i]] = originalCache[modulesToKeep[i]];
74456 }
74457 }
74458
74459 }
74460
74461 var freshModule = callback();
74462
74463 var stealthCache = callbackForModulesToKeep ? assign({}, requireCache) : false;
74464
74465 clearCache(requireCache);
74466
74467 if (callbackForModulesToKeep) {
74468 // In case modules to keep were required inside the stealthy require for the first time, copy them to the restored cache
74469 for ( var k = 0; k < modulesToKeep.length; k+=1 ) {
74470 if (stealthCache[modulesToKeep[k]]) {
74471 requireCache[modulesToKeep[k]] = stealthCache[modulesToKeep[k]];
74472 }
74473 }
74474 }
74475
74476 assign(requireCache, originalCache);
74477
74478 return freshModule;
74479
74480};
74481
74482},{}],361:[function(require,module,exports){
74483// Copyright Joyent, Inc. and other Node contributors.
74484//
74485// Permission is hereby granted, free of charge, to any person obtaining a
74486// copy of this software and associated documentation files (the
74487// "Software"), to deal in the Software without restriction, including
74488// without limitation the rights to use, copy, modify, merge, publish,
74489// distribute, sublicense, and/or sell copies of the Software, and to permit
74490// persons to whom the Software is furnished to do so, subject to the
74491// following conditions:
74492//
74493// The above copyright notice and this permission notice shall be included
74494// in all copies or substantial portions of the Software.
74495//
74496// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
74497// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
74498// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
74499// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
74500// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
74501// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
74502// USE OR OTHER DEALINGS IN THE SOFTWARE.
74503
74504module.exports = Stream;
74505
74506var EE = require('events').EventEmitter;
74507var inherits = require('inherits');
74508
74509inherits(Stream, EE);
74510Stream.Readable = require('readable-stream/readable.js');
74511Stream.Writable = require('readable-stream/writable.js');
74512Stream.Duplex = require('readable-stream/duplex.js');
74513Stream.Transform = require('readable-stream/transform.js');
74514Stream.PassThrough = require('readable-stream/passthrough.js');
74515
74516// Backwards-compat with node 0.4.x
74517Stream.Stream = Stream;
74518
74519
74520
74521// old-style streams. Note that the pipe method (the only relevant
74522// part of this class) is overridden in the Readable class.
74523
74524function Stream() {
74525 EE.call(this);
74526}
74527
74528Stream.prototype.pipe = function(dest, options) {
74529 var source = this;
74530
74531 function ondata(chunk) {
74532 if (dest.writable) {
74533 if (false === dest.write(chunk) && source.pause) {
74534 source.pause();
74535 }
74536 }
74537 }
74538
74539 source.on('data', ondata);
74540
74541 function ondrain() {
74542 if (source.readable && source.resume) {
74543 source.resume();
74544 }
74545 }
74546
74547 dest.on('drain', ondrain);
74548
74549 // If the 'end' option is not supplied, dest.end() will be called when
74550 // source gets the 'end' or 'close' events. Only dest.end() once.
74551 if (!dest._isStdio && (!options || options.end !== false)) {
74552 source.on('end', onend);
74553 source.on('close', onclose);
74554 }
74555
74556 var didOnEnd = false;
74557 function onend() {
74558 if (didOnEnd) return;
74559 didOnEnd = true;
74560
74561 dest.end();
74562 }
74563
74564
74565 function onclose() {
74566 if (didOnEnd) return;
74567 didOnEnd = true;
74568
74569 if (typeof dest.destroy === 'function') dest.destroy();
74570 }
74571
74572 // don't leave dangling pipes when there are errors.
74573 function onerror(er) {
74574 cleanup();
74575 if (EE.listenerCount(this, 'error') === 0) {
74576 throw er; // Unhandled stream error in pipe.
74577 }
74578 }
74579
74580 source.on('error', onerror);
74581 dest.on('error', onerror);
74582
74583 // remove all the event listeners that were added.
74584 function cleanup() {
74585 source.removeListener('data', ondata);
74586 dest.removeListener('drain', ondrain);
74587
74588 source.removeListener('end', onend);
74589 source.removeListener('close', onclose);
74590
74591 source.removeListener('error', onerror);
74592 dest.removeListener('error', onerror);
74593
74594 source.removeListener('end', cleanup);
74595 source.removeListener('close', cleanup);
74596
74597 dest.removeListener('close', cleanup);
74598 }
74599
74600 source.on('end', cleanup);
74601 source.on('close', cleanup);
74602
74603 dest.on('close', cleanup);
74604
74605 dest.emit('pipe', source);
74606
74607 // Allow for unix-like usage: A.pipe(B).pipe(C)
74608 return dest;
74609};
74610
74611},{"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){
74612(function (global){
74613var ClientRequest = require('./lib/request')
74614var response = require('./lib/response')
74615var extend = require('xtend')
74616var statusCodes = require('builtin-status-codes')
74617var url = require('url')
74618
74619var http = exports
74620
74621http.request = function (opts, cb) {
74622 if (typeof opts === 'string')
74623 opts = url.parse(opts)
74624 else
74625 opts = extend(opts)
74626
74627 // Normally, the page is loaded from http or https, so not specifying a protocol
74628 // will result in a (valid) protocol-relative url. However, this won't work if
74629 // the protocol is something else, like 'file:'
74630 var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
74631
74632 var protocol = opts.protocol || defaultProtocol
74633 var host = opts.hostname || opts.host
74634 var port = opts.port
74635 var path = opts.path || '/'
74636
74637 // Necessary for IPv6 addresses
74638 if (host && host.indexOf(':') !== -1)
74639 host = '[' + host + ']'
74640
74641 // This may be a relative url. The browser should always be able to interpret it correctly.
74642 opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
74643 opts.method = (opts.method || 'GET').toUpperCase()
74644 opts.headers = opts.headers || {}
74645
74646 // Also valid opts.auth, opts.mode
74647
74648 var req = new ClientRequest(opts)
74649 if (cb)
74650 req.on('response', cb)
74651 return req
74652}
74653
74654http.get = function get (opts, cb) {
74655 var req = http.request(opts, cb)
74656 req.end()
74657 return req
74658}
74659
74660http.ClientRequest = ClientRequest
74661http.IncomingMessage = response.IncomingMessage
74662
74663http.Agent = function () {}
74664http.Agent.defaultMaxSockets = 4
74665
74666http.globalAgent = new http.Agent()
74667
74668http.STATUS_CODES = statusCodes
74669
74670http.METHODS = [
74671 'CHECKOUT',
74672 'CONNECT',
74673 'COPY',
74674 'DELETE',
74675 'GET',
74676 'HEAD',
74677 'LOCK',
74678 'M-SEARCH',
74679 'MERGE',
74680 'MKACTIVITY',
74681 'MKCOL',
74682 'MOVE',
74683 'NOTIFY',
74684 'OPTIONS',
74685 'PATCH',
74686 'POST',
74687 'PROPFIND',
74688 'PROPPATCH',
74689 'PURGE',
74690 'PUT',
74691 'REPORT',
74692 'SEARCH',
74693 'SUBSCRIBE',
74694 'TRACE',
74695 'UNLOCK',
74696 'UNSUBSCRIBE'
74697]
74698}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
74699},{"./lib/request":364,"./lib/response":365,"builtin-status-codes":115,"url":393,"xtend":406}],363:[function(require,module,exports){
74700(function (global){
74701exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
74702
74703exports.writableStream = isFunction(global.WritableStream)
74704
74705exports.abortController = isFunction(global.AbortController)
74706
74707// The xhr request to example.com may violate some restrictive CSP configurations,
74708// so if we're running in a browser that supports `fetch`, avoid calling getXHR()
74709// and assume support for certain features below.
74710var xhr
74711function getXHR () {
74712 // Cache the xhr value
74713 if (xhr !== undefined) return xhr
74714
74715 if (global.XMLHttpRequest) {
74716 xhr = new global.XMLHttpRequest()
74717 // If XDomainRequest is available (ie only, where xhr might not work
74718 // cross domain), use the page location. Otherwise use example.com
74719 // Note: this doesn't actually make an http request.
74720 try {
74721 xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
74722 } catch(e) {
74723 xhr = null
74724 }
74725 } else {
74726 // Service workers don't have XHR
74727 xhr = null
74728 }
74729 return xhr
74730}
74731
74732function checkTypeSupport (type) {
74733 var xhr = getXHR()
74734 if (!xhr) return false
74735 try {
74736 xhr.responseType = type
74737 return xhr.responseType === type
74738 } catch (e) {}
74739 return false
74740}
74741
74742// If fetch is supported, then arraybuffer will be supported too. Skip calling
74743// checkTypeSupport(), since that calls getXHR().
74744exports.arraybuffer = exports.fetch || checkTypeSupport('arraybuffer')
74745
74746// These next two tests unavoidably show warnings in Chrome. Since fetch will always
74747// be used if it's available, just return false for these to avoid the warnings.
74748exports.msstream = !exports.fetch && checkTypeSupport('ms-stream')
74749exports.mozchunkedarraybuffer = !exports.fetch && checkTypeSupport('moz-chunked-arraybuffer')
74750
74751// If fetch is supported, then overrideMimeType will be supported too. Skip calling
74752// getXHR().
74753exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
74754
74755function isFunction (value) {
74756 return typeof value === 'function'
74757}
74758
74759xhr = null // Help gc
74760
74761}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
74762},{}],364:[function(require,module,exports){
74763(function (process,global,Buffer){
74764var capability = require('./capability')
74765var inherits = require('inherits')
74766var response = require('./response')
74767var stream = require('readable-stream')
74768
74769var IncomingMessage = response.IncomingMessage
74770var rStates = response.readyStates
74771
74772function decideMode (preferBinary, useFetch) {
74773 if (capability.fetch && useFetch) {
74774 return 'fetch'
74775 } else if (capability.mozchunkedarraybuffer) {
74776 return 'moz-chunked-arraybuffer'
74777 } else if (capability.msstream) {
74778 return 'ms-stream'
74779 } else if (capability.arraybuffer && preferBinary) {
74780 return 'arraybuffer'
74781 } else {
74782 return 'text'
74783 }
74784}
74785
74786var ClientRequest = module.exports = function (opts) {
74787 var self = this
74788 stream.Writable.call(self)
74789
74790 self._opts = opts
74791 self._body = []
74792 self._headers = {}
74793 if (opts.auth)
74794 self.setHeader('Authorization', 'Basic ' + Buffer.from(opts.auth).toString('base64'))
74795 Object.keys(opts.headers).forEach(function (name) {
74796 self.setHeader(name, opts.headers[name])
74797 })
74798
74799 var preferBinary
74800 var useFetch = true
74801 if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) {
74802 // If the use of XHR should be preferred. Not typically needed.
74803 useFetch = false
74804 preferBinary = true
74805 } else if (opts.mode === 'prefer-streaming') {
74806 // If streaming is a high priority but binary compatibility and
74807 // the accuracy of the 'content-type' header aren't
74808 preferBinary = false
74809 } else if (opts.mode === 'allow-wrong-content-type') {
74810 // If streaming is more important than preserving the 'content-type' header
74811 preferBinary = !capability.overrideMimeType
74812 } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
74813 // Use binary if text streaming may corrupt data or the content-type header, or for speed
74814 preferBinary = true
74815 } else {
74816 throw new Error('Invalid value for opts.mode')
74817 }
74818 self._mode = decideMode(preferBinary, useFetch)
74819 self._fetchTimer = null
74820
74821 self.on('finish', function () {
74822 self._onFinish()
74823 })
74824}
74825
74826inherits(ClientRequest, stream.Writable)
74827
74828ClientRequest.prototype.setHeader = function (name, value) {
74829 var self = this
74830 var lowerName = name.toLowerCase()
74831 // This check is not necessary, but it prevents warnings from browsers about setting unsafe
74832 // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
74833 // http-browserify did it, so I will too.
74834 if (unsafeHeaders.indexOf(lowerName) !== -1)
74835 return
74836
74837 self._headers[lowerName] = {
74838 name: name,
74839 value: value
74840 }
74841}
74842
74843ClientRequest.prototype.getHeader = function (name) {
74844 var header = this._headers[name.toLowerCase()]
74845 if (header)
74846 return header.value
74847 return null
74848}
74849
74850ClientRequest.prototype.removeHeader = function (name) {
74851 var self = this
74852 delete self._headers[name.toLowerCase()]
74853}
74854
74855ClientRequest.prototype._onFinish = function () {
74856 var self = this
74857
74858 if (self._destroyed)
74859 return
74860 var opts = self._opts
74861
74862 var headersObj = self._headers
74863 var body = null
74864 if (opts.method !== 'GET' && opts.method !== 'HEAD') {
74865 body = new Blob(self._body, {
74866 type: (headersObj['content-type'] || {}).value || ''
74867 });
74868 }
74869
74870 // create flattened list of headers
74871 var headersList = []
74872 Object.keys(headersObj).forEach(function (keyName) {
74873 var name = headersObj[keyName].name
74874 var value = headersObj[keyName].value
74875 if (Array.isArray(value)) {
74876 value.forEach(function (v) {
74877 headersList.push([name, v])
74878 })
74879 } else {
74880 headersList.push([name, value])
74881 }
74882 })
74883
74884 if (self._mode === 'fetch') {
74885 var signal = null
74886 var fetchTimer = null
74887 if (capability.abortController) {
74888 var controller = new AbortController()
74889 signal = controller.signal
74890 self._fetchAbortController = controller
74891
74892 if ('requestTimeout' in opts && opts.requestTimeout !== 0) {
74893 self._fetchTimer = global.setTimeout(function () {
74894 self.emit('requestTimeout')
74895 if (self._fetchAbortController)
74896 self._fetchAbortController.abort()
74897 }, opts.requestTimeout)
74898 }
74899 }
74900
74901 global.fetch(self._opts.url, {
74902 method: self._opts.method,
74903 headers: headersList,
74904 body: body || undefined,
74905 mode: 'cors',
74906 credentials: opts.withCredentials ? 'include' : 'same-origin',
74907 signal: signal
74908 }).then(function (response) {
74909 self._fetchResponse = response
74910 self._connect()
74911 }, function (reason) {
74912 global.clearTimeout(self._fetchTimer)
74913 if (!self._destroyed)
74914 self.emit('error', reason)
74915 })
74916 } else {
74917 var xhr = self._xhr = new global.XMLHttpRequest()
74918 try {
74919 xhr.open(self._opts.method, self._opts.url, true)
74920 } catch (err) {
74921 process.nextTick(function () {
74922 self.emit('error', err)
74923 })
74924 return
74925 }
74926
74927 // Can't set responseType on really old browsers
74928 if ('responseType' in xhr)
74929 xhr.responseType = self._mode
74930
74931 if ('withCredentials' in xhr)
74932 xhr.withCredentials = !!opts.withCredentials
74933
74934 if (self._mode === 'text' && 'overrideMimeType' in xhr)
74935 xhr.overrideMimeType('text/plain; charset=x-user-defined')
74936
74937 if ('requestTimeout' in opts) {
74938 xhr.timeout = opts.requestTimeout
74939 xhr.ontimeout = function () {
74940 self.emit('requestTimeout')
74941 }
74942 }
74943
74944 headersList.forEach(function (header) {
74945 xhr.setRequestHeader(header[0], header[1])
74946 })
74947
74948 self._response = null
74949 xhr.onreadystatechange = function () {
74950 switch (xhr.readyState) {
74951 case rStates.LOADING:
74952 case rStates.DONE:
74953 self._onXHRProgress()
74954 break
74955 }
74956 }
74957 // Necessary for streaming in Firefox, since xhr.response is ONLY defined
74958 // in onprogress, not in onreadystatechange with xhr.readyState = 3
74959 if (self._mode === 'moz-chunked-arraybuffer') {
74960 xhr.onprogress = function () {
74961 self._onXHRProgress()
74962 }
74963 }
74964
74965 xhr.onerror = function () {
74966 if (self._destroyed)
74967 return
74968 self.emit('error', new Error('XHR error'))
74969 }
74970
74971 try {
74972 xhr.send(body)
74973 } catch (err) {
74974 process.nextTick(function () {
74975 self.emit('error', err)
74976 })
74977 return
74978 }
74979 }
74980}
74981
74982/**
74983 * Checks if xhr.status is readable and non-zero, indicating no error.
74984 * Even though the spec says it should be available in readyState 3,
74985 * accessing it throws an exception in IE8
74986 */
74987function statusValid (xhr) {
74988 try {
74989 var status = xhr.status
74990 return (status !== null && status !== 0)
74991 } catch (e) {
74992 return false
74993 }
74994}
74995
74996ClientRequest.prototype._onXHRProgress = function () {
74997 var self = this
74998
74999 if (!statusValid(self._xhr) || self._destroyed)
75000 return
75001
75002 if (!self._response)
75003 self._connect()
75004
75005 self._response._onXHRProgress()
75006}
75007
75008ClientRequest.prototype._connect = function () {
75009 var self = this
75010
75011 if (self._destroyed)
75012 return
75013
75014 self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode, self._fetchTimer)
75015 self._response.on('error', function(err) {
75016 self.emit('error', err)
75017 })
75018
75019 self.emit('response', self._response)
75020}
75021
75022ClientRequest.prototype._write = function (chunk, encoding, cb) {
75023 var self = this
75024
75025 self._body.push(chunk)
75026 cb()
75027}
75028
75029ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
75030 var self = this
75031 self._destroyed = true
75032 global.clearTimeout(self._fetchTimer)
75033 if (self._response)
75034 self._response._destroyed = true
75035 if (self._xhr)
75036 self._xhr.abort()
75037 else if (self._fetchAbortController)
75038 self._fetchAbortController.abort()
75039}
75040
75041ClientRequest.prototype.end = function (data, encoding, cb) {
75042 var self = this
75043 if (typeof data === 'function') {
75044 cb = data
75045 data = undefined
75046 }
75047
75048 stream.Writable.prototype.end.call(self, data, encoding, cb)
75049}
75050
75051ClientRequest.prototype.flushHeaders = function () {}
75052ClientRequest.prototype.setTimeout = function () {}
75053ClientRequest.prototype.setNoDelay = function () {}
75054ClientRequest.prototype.setSocketKeepAlive = function () {}
75055
75056// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
75057var unsafeHeaders = [
75058 'accept-charset',
75059 'accept-encoding',
75060 'access-control-request-headers',
75061 'access-control-request-method',
75062 'connection',
75063 'content-length',
75064 'cookie',
75065 'cookie2',
75066 'date',
75067 'dnt',
75068 'expect',
75069 'host',
75070 'keep-alive',
75071 'origin',
75072 'referer',
75073 'te',
75074 'trailer',
75075 'transfer-encoding',
75076 'upgrade',
75077 'via'
75078]
75079
75080}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
75081},{"./capability":363,"./response":365,"_process":265,"buffer":114,"inherits":210,"readable-stream":380}],365:[function(require,module,exports){
75082(function (process,global,Buffer){
75083var capability = require('./capability')
75084var inherits = require('inherits')
75085var stream = require('readable-stream')
75086
75087var rStates = exports.readyStates = {
75088 UNSENT: 0,
75089 OPENED: 1,
75090 HEADERS_RECEIVED: 2,
75091 LOADING: 3,
75092 DONE: 4
75093}
75094
75095var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode, fetchTimer) {
75096 var self = this
75097 stream.Readable.call(self)
75098
75099 self._mode = mode
75100 self.headers = {}
75101 self.rawHeaders = []
75102 self.trailers = {}
75103 self.rawTrailers = []
75104
75105 // Fake the 'close' event, but only once 'end' fires
75106 self.on('end', function () {
75107 // The nextTick is necessary to prevent the 'request' module from causing an infinite loop
75108 process.nextTick(function () {
75109 self.emit('close')
75110 })
75111 })
75112
75113 if (mode === 'fetch') {
75114 self._fetchResponse = response
75115
75116 self.url = response.url
75117 self.statusCode = response.status
75118 self.statusMessage = response.statusText
75119
75120 response.headers.forEach(function (header, key){
75121 self.headers[key.toLowerCase()] = header
75122 self.rawHeaders.push(key, header)
75123 })
75124
75125 if (capability.writableStream) {
75126 var writable = new WritableStream({
75127 write: function (chunk) {
75128 return new Promise(function (resolve, reject) {
75129 if (self._destroyed) {
75130 reject()
75131 } else if(self.push(Buffer.from(chunk))) {
75132 resolve()
75133 } else {
75134 self._resumeFetch = resolve
75135 }
75136 })
75137 },
75138 close: function () {
75139 global.clearTimeout(fetchTimer)
75140 if (!self._destroyed)
75141 self.push(null)
75142 },
75143 abort: function (err) {
75144 if (!self._destroyed)
75145 self.emit('error', err)
75146 }
75147 })
75148
75149 try {
75150 response.body.pipeTo(writable).catch(function (err) {
75151 global.clearTimeout(fetchTimer)
75152 if (!self._destroyed)
75153 self.emit('error', err)
75154 })
75155 return
75156 } catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
75157 }
75158 // fallback for when writableStream or pipeTo aren't available
75159 var reader = response.body.getReader()
75160 function read () {
75161 reader.read().then(function (result) {
75162 if (self._destroyed)
75163 return
75164 if (result.done) {
75165 global.clearTimeout(fetchTimer)
75166 self.push(null)
75167 return
75168 }
75169 self.push(Buffer.from(result.value))
75170 read()
75171 }).catch(function (err) {
75172 global.clearTimeout(fetchTimer)
75173 if (!self._destroyed)
75174 self.emit('error', err)
75175 })
75176 }
75177 read()
75178 } else {
75179 self._xhr = xhr
75180 self._pos = 0
75181
75182 self.url = xhr.responseURL
75183 self.statusCode = xhr.status
75184 self.statusMessage = xhr.statusText
75185 var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
75186 headers.forEach(function (header) {
75187 var matches = header.match(/^([^:]+):\s*(.*)/)
75188 if (matches) {
75189 var key = matches[1].toLowerCase()
75190 if (key === 'set-cookie') {
75191 if (self.headers[key] === undefined) {
75192 self.headers[key] = []
75193 }
75194 self.headers[key].push(matches[2])
75195 } else if (self.headers[key] !== undefined) {
75196 self.headers[key] += ', ' + matches[2]
75197 } else {
75198 self.headers[key] = matches[2]
75199 }
75200 self.rawHeaders.push(matches[1], matches[2])
75201 }
75202 })
75203
75204 self._charset = 'x-user-defined'
75205 if (!capability.overrideMimeType) {
75206 var mimeType = self.rawHeaders['mime-type']
75207 if (mimeType) {
75208 var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
75209 if (charsetMatch) {
75210 self._charset = charsetMatch[1].toLowerCase()
75211 }
75212 }
75213 if (!self._charset)
75214 self._charset = 'utf-8' // best guess
75215 }
75216 }
75217}
75218
75219inherits(IncomingMessage, stream.Readable)
75220
75221IncomingMessage.prototype._read = function () {
75222 var self = this
75223
75224 var resolve = self._resumeFetch
75225 if (resolve) {
75226 self._resumeFetch = null
75227 resolve()
75228 }
75229}
75230
75231IncomingMessage.prototype._onXHRProgress = function () {
75232 var self = this
75233
75234 var xhr = self._xhr
75235
75236 var response = null
75237 switch (self._mode) {
75238 case 'text':
75239 response = xhr.responseText
75240 if (response.length > self._pos) {
75241 var newData = response.substr(self._pos)
75242 if (self._charset === 'x-user-defined') {
75243 var buffer = Buffer.alloc(newData.length)
75244 for (var i = 0; i < newData.length; i++)
75245 buffer[i] = newData.charCodeAt(i) & 0xff
75246
75247 self.push(buffer)
75248 } else {
75249 self.push(newData, self._charset)
75250 }
75251 self._pos = response.length
75252 }
75253 break
75254 case 'arraybuffer':
75255 if (xhr.readyState !== rStates.DONE || !xhr.response)
75256 break
75257 response = xhr.response
75258 self.push(Buffer.from(new Uint8Array(response)))
75259 break
75260 case 'moz-chunked-arraybuffer': // take whole
75261 response = xhr.response
75262 if (xhr.readyState !== rStates.LOADING || !response)
75263 break
75264 self.push(Buffer.from(new Uint8Array(response)))
75265 break
75266 case 'ms-stream':
75267 response = xhr.response
75268 if (xhr.readyState !== rStates.LOADING)
75269 break
75270 var reader = new global.MSStreamReader()
75271 reader.onprogress = function () {
75272 if (reader.result.byteLength > self._pos) {
75273 self.push(Buffer.from(new Uint8Array(reader.result.slice(self._pos))))
75274 self._pos = reader.result.byteLength
75275 }
75276 }
75277 reader.onload = function () {
75278 self.push(null)
75279 }
75280 // reader.onerror = ??? // TODO: this
75281 reader.readAsArrayBuffer(response)
75282 break
75283 }
75284
75285 // The ms-stream case handles end separately in reader.onload()
75286 if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
75287 self.push(null)
75288 }
75289}
75290
75291}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
75292},{"./capability":363,"_process":265,"buffer":114,"inherits":210,"readable-stream":380}],366:[function(require,module,exports){
75293'use strict';
75294
75295function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
75296
75297var codes = {};
75298
75299function createErrorType(code, message, Base) {
75300 if (!Base) {
75301 Base = Error;
75302 }
75303
75304 function getMessage(arg1, arg2, arg3) {
75305 if (typeof message === 'string') {
75306 return message;
75307 } else {
75308 return message(arg1, arg2, arg3);
75309 }
75310 }
75311
75312 var NodeError =
75313 /*#__PURE__*/
75314 function (_Base) {
75315 _inheritsLoose(NodeError, _Base);
75316
75317 function NodeError(arg1, arg2, arg3) {
75318 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
75319 }
75320
75321 return NodeError;
75322 }(Base);
75323
75324 NodeError.prototype.name = Base.name;
75325 NodeError.prototype.code = code;
75326 codes[code] = NodeError;
75327} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
75328
75329
75330function oneOf(expected, thing) {
75331 if (Array.isArray(expected)) {
75332 var len = expected.length;
75333 expected = expected.map(function (i) {
75334 return String(i);
75335 });
75336
75337 if (len > 2) {
75338 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
75339 } else if (len === 2) {
75340 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
75341 } else {
75342 return "of ".concat(thing, " ").concat(expected[0]);
75343 }
75344 } else {
75345 return "of ".concat(thing, " ").concat(String(expected));
75346 }
75347} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
75348
75349
75350function startsWith(str, search, pos) {
75351 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
75352} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
75353
75354
75355function endsWith(str, search, this_len) {
75356 if (this_len === undefined || this_len > str.length) {
75357 this_len = str.length;
75358 }
75359
75360 return str.substring(this_len - search.length, this_len) === search;
75361} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
75362
75363
75364function includes(str, search, start) {
75365 if (typeof start !== 'number') {
75366 start = 0;
75367 }
75368
75369 if (start + search.length > str.length) {
75370 return false;
75371 } else {
75372 return str.indexOf(search, start) !== -1;
75373 }
75374}
75375
75376createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
75377 return 'The value "' + value + '" is invalid for option "' + name + '"';
75378}, TypeError);
75379createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
75380 // determiner: 'must be' or 'must not be'
75381 var determiner;
75382
75383 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
75384 determiner = 'must not be';
75385 expected = expected.replace(/^not /, '');
75386 } else {
75387 determiner = 'must be';
75388 }
75389
75390 var msg;
75391
75392 if (endsWith(name, ' argument')) {
75393 // For cases like 'first argument'
75394 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
75395 } else {
75396 var type = includes(name, '.') ? 'property' : 'argument';
75397 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
75398 }
75399
75400 msg += ". Received type ".concat(typeof actual);
75401 return msg;
75402}, TypeError);
75403createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
75404createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
75405 return 'The ' + name + ' method is not implemented';
75406});
75407createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
75408createErrorType('ERR_STREAM_DESTROYED', function (name) {
75409 return 'Cannot call ' + name + ' after a stream was destroyed';
75410});
75411createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
75412createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
75413createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
75414createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
75415createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
75416 return 'Unknown encoding: ' + arg;
75417}, TypeError);
75418createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
75419module.exports.codes = codes;
75420
75421},{}],367:[function(require,module,exports){
75422(function (process){
75423'use strict'
75424
75425var experimentalWarnings = new Set();
75426
75427function emitExperimentalWarning(feature) {
75428 if (experimentalWarnings.has(feature)) return;
75429 var msg = feature + ' is an experimental feature. This feature could ' +
75430 'change at any time';
75431 experimentalWarnings.add(feature);
75432 process.emitWarning(msg, 'ExperimentalWarning');
75433}
75434
75435function noop() {}
75436
75437module.exports.emitExperimentalWarning = process.emitWarning
75438 ? emitExperimentalWarning
75439 : noop;
75440
75441}).call(this,require('_process'))
75442},{"_process":265}],368:[function(require,module,exports){
75443(function (process){
75444// Copyright Joyent, Inc. and other Node contributors.
75445//
75446// Permission is hereby granted, free of charge, to any person obtaining a
75447// copy of this software and associated documentation files (the
75448// "Software"), to deal in the Software without restriction, including
75449// without limitation the rights to use, copy, modify, merge, publish,
75450// distribute, sublicense, and/or sell copies of the Software, and to permit
75451// persons to whom the Software is furnished to do so, subject to the
75452// following conditions:
75453//
75454// The above copyright notice and this permission notice shall be included
75455// in all copies or substantial portions of the Software.
75456//
75457// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
75458// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
75459// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
75460// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
75461// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
75462// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
75463// USE OR OTHER DEALINGS IN THE SOFTWARE.
75464// a duplex stream is just a stream that is both readable and writable.
75465// Since JS doesn't have multiple prototypal inheritance, this class
75466// prototypally inherits from Readable, and then parasitically from
75467// Writable.
75468'use strict';
75469/*<replacement>*/
75470
75471var objectKeys = Object.keys || function (obj) {
75472 var keys = [];
75473
75474 for (var key in obj) {
75475 keys.push(key);
75476 }
75477
75478 return keys;
75479};
75480/*</replacement>*/
75481
75482
75483module.exports = Duplex;
75484
75485var Readable = require('./_stream_readable');
75486
75487var Writable = require('./_stream_writable');
75488
75489require('inherits')(Duplex, Readable);
75490
75491{
75492 // Allow the keys array to be GC'ed.
75493 var keys = objectKeys(Writable.prototype);
75494
75495 for (var v = 0; v < keys.length; v++) {
75496 var method = keys[v];
75497 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
75498 }
75499}
75500
75501function Duplex(options) {
75502 if (!(this instanceof Duplex)) return new Duplex(options);
75503 Readable.call(this, options);
75504 Writable.call(this, options);
75505 this.allowHalfOpen = true;
75506
75507 if (options) {
75508 if (options.readable === false) this.readable = false;
75509 if (options.writable === false) this.writable = false;
75510
75511 if (options.allowHalfOpen === false) {
75512 this.allowHalfOpen = false;
75513 this.once('end', onend);
75514 }
75515 }
75516}
75517
75518Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
75519 // making it explicit this property is not enumerable
75520 // because otherwise some prototype manipulation in
75521 // userland will fail
75522 enumerable: false,
75523 get: function get() {
75524 return this._writableState.highWaterMark;
75525 }
75526});
75527Object.defineProperty(Duplex.prototype, 'writableBuffer', {
75528 // making it explicit this property is not enumerable
75529 // because otherwise some prototype manipulation in
75530 // userland will fail
75531 enumerable: false,
75532 get: function get() {
75533 return this._writableState && this._writableState.getBuffer();
75534 }
75535});
75536Object.defineProperty(Duplex.prototype, 'writableLength', {
75537 // making it explicit this property is not enumerable
75538 // because otherwise some prototype manipulation in
75539 // userland will fail
75540 enumerable: false,
75541 get: function get() {
75542 return this._writableState.length;
75543 }
75544}); // the no-half-open enforcer
75545
75546function onend() {
75547 // If the writable side ended, then we're ok.
75548 if (this._writableState.ended) return; // no more data can be written.
75549 // But allow more writes to happen in this tick.
75550
75551 process.nextTick(onEndNT, this);
75552}
75553
75554function onEndNT(self) {
75555 self.end();
75556}
75557
75558Object.defineProperty(Duplex.prototype, 'destroyed', {
75559 // making it explicit this property is not enumerable
75560 // because otherwise some prototype manipulation in
75561 // userland will fail
75562 enumerable: false,
75563 get: function get() {
75564 if (this._readableState === undefined || this._writableState === undefined) {
75565 return false;
75566 }
75567
75568 return this._readableState.destroyed && this._writableState.destroyed;
75569 },
75570 set: function set(value) {
75571 // we ignore the value if the stream
75572 // has not been initialized yet
75573 if (this._readableState === undefined || this._writableState === undefined) {
75574 return;
75575 } // backward compatibility, the user is explicitly
75576 // managing destroyed
75577
75578
75579 this._readableState.destroyed = value;
75580 this._writableState.destroyed = value;
75581 }
75582});
75583}).call(this,require('_process'))
75584},{"./_stream_readable":370,"./_stream_writable":372,"_process":265,"inherits":210}],369:[function(require,module,exports){
75585// Copyright Joyent, Inc. and other Node contributors.
75586//
75587// Permission is hereby granted, free of charge, to any person obtaining a
75588// copy of this software and associated documentation files (the
75589// "Software"), to deal in the Software without restriction, including
75590// without limitation the rights to use, copy, modify, merge, publish,
75591// distribute, sublicense, and/or sell copies of the Software, and to permit
75592// persons to whom the Software is furnished to do so, subject to the
75593// following conditions:
75594//
75595// The above copyright notice and this permission notice shall be included
75596// in all copies or substantial portions of the Software.
75597//
75598// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
75599// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
75600// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
75601// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
75602// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
75603// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
75604// USE OR OTHER DEALINGS IN THE SOFTWARE.
75605// a passthrough stream.
75606// basically just the most minimal sort of Transform stream.
75607// Every written chunk gets output as-is.
75608'use strict';
75609
75610module.exports = PassThrough;
75611
75612var Transform = require('./_stream_transform');
75613
75614require('inherits')(PassThrough, Transform);
75615
75616function PassThrough(options) {
75617 if (!(this instanceof PassThrough)) return new PassThrough(options);
75618 Transform.call(this, options);
75619}
75620
75621PassThrough.prototype._transform = function (chunk, encoding, cb) {
75622 cb(null, chunk);
75623};
75624},{"./_stream_transform":371,"inherits":210}],370:[function(require,module,exports){
75625(function (process,global){
75626// Copyright Joyent, Inc. and other Node contributors.
75627//
75628// Permission is hereby granted, free of charge, to any person obtaining a
75629// copy of this software and associated documentation files (the
75630// "Software"), to deal in the Software without restriction, including
75631// without limitation the rights to use, copy, modify, merge, publish,
75632// distribute, sublicense, and/or sell copies of the Software, and to permit
75633// persons to whom the Software is furnished to do so, subject to the
75634// following conditions:
75635//
75636// The above copyright notice and this permission notice shall be included
75637// in all copies or substantial portions of the Software.
75638//
75639// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
75640// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
75641// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
75642// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
75643// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
75644// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
75645// USE OR OTHER DEALINGS IN THE SOFTWARE.
75646'use strict';
75647
75648module.exports = Readable;
75649/*<replacement>*/
75650
75651var Duplex;
75652/*</replacement>*/
75653
75654Readable.ReadableState = ReadableState;
75655/*<replacement>*/
75656
75657var EE = require('events').EventEmitter;
75658
75659var EElistenerCount = function EElistenerCount(emitter, type) {
75660 return emitter.listeners(type).length;
75661};
75662/*</replacement>*/
75663
75664/*<replacement>*/
75665
75666
75667var Stream = require('./internal/streams/stream');
75668/*</replacement>*/
75669
75670
75671var Buffer = require('buffer').Buffer;
75672
75673var OurUint8Array = global.Uint8Array || function () {};
75674
75675function _uint8ArrayToBuffer(chunk) {
75676 return Buffer.from(chunk);
75677}
75678
75679function _isUint8Array(obj) {
75680 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
75681}
75682/*<replacement>*/
75683
75684
75685var debugUtil = require('util');
75686
75687var debug;
75688
75689if (debugUtil && debugUtil.debuglog) {
75690 debug = debugUtil.debuglog('stream');
75691} else {
75692 debug = function debug() {};
75693}
75694/*</replacement>*/
75695
75696
75697var BufferList = require('./internal/streams/buffer_list');
75698
75699var destroyImpl = require('./internal/streams/destroy');
75700
75701var _require = require('./internal/streams/state'),
75702 getHighWaterMark = _require.getHighWaterMark;
75703
75704var _require$codes = require('../errors').codes,
75705 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
75706 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
75707 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
75708 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
75709
75710var _require2 = require('../experimentalWarning'),
75711 emitExperimentalWarning = _require2.emitExperimentalWarning; // Lazy loaded to improve the startup performance.
75712
75713
75714var StringDecoder;
75715var createReadableStreamAsyncIterator;
75716
75717require('inherits')(Readable, Stream);
75718
75719var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
75720
75721function prependListener(emitter, event, fn) {
75722 // Sadly this is not cacheable as some libraries bundle their own
75723 // event emitter implementation with them.
75724 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
75725 // userland ones. NEVER DO THIS. This is here only because this code needs
75726 // to continue to work with older versions of Node.js that do not include
75727 // the prependListener() method. The goal is to eventually remove this hack.
75728
75729 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]];
75730}
75731
75732function ReadableState(options, stream, isDuplex) {
75733 Duplex = Duplex || require('./_stream_duplex');
75734 options = options || {}; // Duplex streams are both readable and writable, but share
75735 // the same options object.
75736 // However, some cases require setting options to different
75737 // values for the readable and the writable sides of the duplex stream.
75738 // These options can be provided separately as readableXXX and writableXXX.
75739
75740 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
75741 // make all the buffer merging and length checks go away
75742
75743 this.objectMode = !!options.objectMode;
75744 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
75745 // Note: 0 is a valid value, means "don't call _read preemptively ever"
75746
75747 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
75748 // linked list can remove elements from the beginning faster than
75749 // array.shift()
75750
75751 this.buffer = new BufferList();
75752 this.length = 0;
75753 this.pipes = null;
75754 this.pipesCount = 0;
75755 this.flowing = null;
75756 this.ended = false;
75757 this.endEmitted = false;
75758 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
75759 // immediately, or on a later tick. We set this to true at first, because
75760 // any actions that shouldn't happen until "later" should generally also
75761 // not happen before the first read call.
75762
75763 this.sync = true; // whenever we return null, then we set a flag to say
75764 // that we're awaiting a 'readable' event emission.
75765
75766 this.needReadable = false;
75767 this.emittedReadable = false;
75768 this.readableListening = false;
75769 this.resumeScheduled = false;
75770 this.paused = true; // Should close be emitted on destroy. Defaults to true.
75771
75772 this.emitClose = options.emitClose !== false; // has it been destroyed
75773
75774 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
75775 // encoding is 'binary' so we have to make this configurable.
75776 // Everything else in the universe uses 'utf8', though.
75777
75778 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
75779
75780 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
75781
75782 this.readingMore = false;
75783 this.decoder = null;
75784 this.encoding = null;
75785
75786 if (options.encoding) {
75787 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
75788 this.decoder = new StringDecoder(options.encoding);
75789 this.encoding = options.encoding;
75790 }
75791}
75792
75793function Readable(options) {
75794 Duplex = Duplex || require('./_stream_duplex');
75795 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
75796 // the ReadableState constructor, at least with V8 6.5
75797
75798 var isDuplex = this instanceof Duplex;
75799 this._readableState = new ReadableState(options, this, isDuplex); // legacy
75800
75801 this.readable = true;
75802
75803 if (options) {
75804 if (typeof options.read === 'function') this._read = options.read;
75805 if (typeof options.destroy === 'function') this._destroy = options.destroy;
75806 }
75807
75808 Stream.call(this);
75809}
75810
75811Object.defineProperty(Readable.prototype, 'destroyed', {
75812 // making it explicit this property is not enumerable
75813 // because otherwise some prototype manipulation in
75814 // userland will fail
75815 enumerable: false,
75816 get: function get() {
75817 if (this._readableState === undefined) {
75818 return false;
75819 }
75820
75821 return this._readableState.destroyed;
75822 },
75823 set: function set(value) {
75824 // we ignore the value if the stream
75825 // has not been initialized yet
75826 if (!this._readableState) {
75827 return;
75828 } // backward compatibility, the user is explicitly
75829 // managing destroyed
75830
75831
75832 this._readableState.destroyed = value;
75833 }
75834});
75835Readable.prototype.destroy = destroyImpl.destroy;
75836Readable.prototype._undestroy = destroyImpl.undestroy;
75837
75838Readable.prototype._destroy = function (err, cb) {
75839 cb(err);
75840}; // Manually shove something into the read() buffer.
75841// This returns true if the highWaterMark has not been hit yet,
75842// similar to how Writable.write() returns true if you should
75843// write() some more.
75844
75845
75846Readable.prototype.push = function (chunk, encoding) {
75847 var state = this._readableState;
75848 var skipChunkCheck;
75849
75850 if (!state.objectMode) {
75851 if (typeof chunk === 'string') {
75852 encoding = encoding || state.defaultEncoding;
75853
75854 if (encoding !== state.encoding) {
75855 chunk = Buffer.from(chunk, encoding);
75856 encoding = '';
75857 }
75858
75859 skipChunkCheck = true;
75860 }
75861 } else {
75862 skipChunkCheck = true;
75863 }
75864
75865 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
75866}; // Unshift should *always* be something directly out of read()
75867
75868
75869Readable.prototype.unshift = function (chunk) {
75870 return readableAddChunk(this, chunk, null, true, false);
75871};
75872
75873function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
75874 debug('readableAddChunk', chunk);
75875 var state = stream._readableState;
75876
75877 if (chunk === null) {
75878 state.reading = false;
75879 onEofChunk(stream, state);
75880 } else {
75881 var er;
75882 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
75883
75884 if (er) {
75885 stream.emit('error', er);
75886 } else if (state.objectMode || chunk && chunk.length > 0) {
75887 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
75888 chunk = _uint8ArrayToBuffer(chunk);
75889 }
75890
75891 if (addToFront) {
75892 if (state.endEmitted) stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
75893 } else if (state.ended) {
75894 stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF());
75895 } else if (state.destroyed) {
75896 return false;
75897 } else {
75898 state.reading = false;
75899
75900 if (state.decoder && !encoding) {
75901 chunk = state.decoder.write(chunk);
75902 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
75903 } else {
75904 addChunk(stream, state, chunk, false);
75905 }
75906 }
75907 } else if (!addToFront) {
75908 state.reading = false;
75909 maybeReadMore(stream, state);
75910 }
75911 } // We can push more data if we are below the highWaterMark.
75912 // Also, if we have no data yet, we can stand some more bytes.
75913 // This is to work around cases where hwm=0, such as the repl.
75914
75915
75916 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
75917}
75918
75919function addChunk(stream, state, chunk, addToFront) {
75920 if (state.flowing && state.length === 0 && !state.sync) {
75921 state.awaitDrain = 0;
75922 stream.emit('data', chunk);
75923 } else {
75924 // update the buffer info.
75925 state.length += state.objectMode ? 1 : chunk.length;
75926 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
75927 if (state.needReadable) emitReadable(stream);
75928 }
75929
75930 maybeReadMore(stream, state);
75931}
75932
75933function chunkInvalid(state, chunk) {
75934 var er;
75935
75936 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
75937 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
75938 }
75939
75940 return er;
75941}
75942
75943Readable.prototype.isPaused = function () {
75944 return this._readableState.flowing === false;
75945}; // backwards compatibility.
75946
75947
75948Readable.prototype.setEncoding = function (enc) {
75949 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
75950 this._readableState.decoder = new StringDecoder(enc); // if setEncoding(null), decoder.encoding equals utf8
75951
75952 this._readableState.encoding = this._readableState.decoder.encoding;
75953 return this;
75954}; // Don't raise the hwm > 8MB
75955
75956
75957var MAX_HWM = 0x800000;
75958
75959function computeNewHighWaterMark(n) {
75960 if (n >= MAX_HWM) {
75961 n = MAX_HWM;
75962 } else {
75963 // Get the next highest power of 2 to prevent increasing hwm excessively in
75964 // tiny amounts
75965 n--;
75966 n |= n >>> 1;
75967 n |= n >>> 2;
75968 n |= n >>> 4;
75969 n |= n >>> 8;
75970 n |= n >>> 16;
75971 n++;
75972 }
75973
75974 return n;
75975} // This function is designed to be inlinable, so please take care when making
75976// changes to the function body.
75977
75978
75979function howMuchToRead(n, state) {
75980 if (n <= 0 || state.length === 0 && state.ended) return 0;
75981 if (state.objectMode) return 1;
75982
75983 if (n !== n) {
75984 // Only flow one buffer at a time
75985 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
75986 } // If we're asking for more than the current hwm, then raise the hwm.
75987
75988
75989 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
75990 if (n <= state.length) return n; // Don't have enough
75991
75992 if (!state.ended) {
75993 state.needReadable = true;
75994 return 0;
75995 }
75996
75997 return state.length;
75998} // you can override either this method, or the async _read(n) below.
75999
76000
76001Readable.prototype.read = function (n) {
76002 debug('read', n);
76003 n = parseInt(n, 10);
76004 var state = this._readableState;
76005 var nOrig = n;
76006 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
76007 // already have a bunch of data in the buffer, then just trigger
76008 // the 'readable' event and move on.
76009
76010 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
76011 debug('read: emitReadable', state.length, state.ended);
76012 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
76013 return null;
76014 }
76015
76016 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
76017
76018 if (n === 0 && state.ended) {
76019 if (state.length === 0) endReadable(this);
76020 return null;
76021 } // All the actual chunk generation logic needs to be
76022 // *below* the call to _read. The reason is that in certain
76023 // synthetic stream cases, such as passthrough streams, _read
76024 // may be a completely synchronous operation which may change
76025 // the state of the read buffer, providing enough data when
76026 // before there was *not* enough.
76027 //
76028 // So, the steps are:
76029 // 1. Figure out what the state of things will be after we do
76030 // a read from the buffer.
76031 //
76032 // 2. If that resulting state will trigger a _read, then call _read.
76033 // Note that this may be asynchronous, or synchronous. Yes, it is
76034 // deeply ugly to write APIs this way, but that still doesn't mean
76035 // that the Readable class should behave improperly, as streams are
76036 // designed to be sync/async agnostic.
76037 // Take note if the _read call is sync or async (ie, if the read call
76038 // has returned yet), so that we know whether or not it's safe to emit
76039 // 'readable' etc.
76040 //
76041 // 3. Actually pull the requested chunks out of the buffer and return.
76042 // if we need a readable event, then we need to do some reading.
76043
76044
76045 var doRead = state.needReadable;
76046 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
76047
76048 if (state.length === 0 || state.length - n < state.highWaterMark) {
76049 doRead = true;
76050 debug('length less than watermark', doRead);
76051 } // however, if we've ended, then there's no point, and if we're already
76052 // reading, then it's unnecessary.
76053
76054
76055 if (state.ended || state.reading) {
76056 doRead = false;
76057 debug('reading or ended', doRead);
76058 } else if (doRead) {
76059 debug('do read');
76060 state.reading = true;
76061 state.sync = true; // if the length is currently zero, then we *need* a readable event.
76062
76063 if (state.length === 0) state.needReadable = true; // call internal read method
76064
76065 this._read(state.highWaterMark);
76066
76067 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
76068 // and we need to re-evaluate how much data we can return to the user.
76069
76070 if (!state.reading) n = howMuchToRead(nOrig, state);
76071 }
76072
76073 var ret;
76074 if (n > 0) ret = fromList(n, state);else ret = null;
76075
76076 if (ret === null) {
76077 state.needReadable = true;
76078 n = 0;
76079 } else {
76080 state.length -= n;
76081 state.awaitDrain = 0;
76082 }
76083
76084 if (state.length === 0) {
76085 // If we have nothing in the buffer, then we want to know
76086 // as soon as we *do* get something into the buffer.
76087 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
76088
76089 if (nOrig !== n && state.ended) endReadable(this);
76090 }
76091
76092 if (ret !== null) this.emit('data', ret);
76093 return ret;
76094};
76095
76096function onEofChunk(stream, state) {
76097 if (state.ended) return;
76098
76099 if (state.decoder) {
76100 var chunk = state.decoder.end();
76101
76102 if (chunk && chunk.length) {
76103 state.buffer.push(chunk);
76104 state.length += state.objectMode ? 1 : chunk.length;
76105 }
76106 }
76107
76108 state.ended = true;
76109
76110 if (state.sync) {
76111 // if we are sync, wait until next tick to emit the data.
76112 // Otherwise we risk emitting data in the flow()
76113 // the readable code triggers during a read() call
76114 emitReadable(stream);
76115 } else {
76116 // emit 'readable' now to make sure it gets picked up.
76117 state.needReadable = false;
76118
76119 if (!state.emittedReadable) {
76120 state.emittedReadable = true;
76121 emitReadable_(stream);
76122 }
76123 }
76124} // Don't emit readable right away in sync mode, because this can trigger
76125// another read() call => stack overflow. This way, it might trigger
76126// a nextTick recursion warning, but that's not so bad.
76127
76128
76129function emitReadable(stream) {
76130 var state = stream._readableState;
76131 state.needReadable = false;
76132
76133 if (!state.emittedReadable) {
76134 debug('emitReadable', state.flowing);
76135 state.emittedReadable = true;
76136 process.nextTick(emitReadable_, stream);
76137 }
76138}
76139
76140function emitReadable_(stream) {
76141 var state = stream._readableState;
76142 debug('emitReadable_', state.destroyed, state.length, state.ended);
76143
76144 if (!state.destroyed && (state.length || state.ended)) {
76145 stream.emit('readable');
76146 } // The stream needs another readable event if
76147 // 1. It is not flowing, as the flow mechanism will take
76148 // care of it.
76149 // 2. It is not ended.
76150 // 3. It is below the highWaterMark, so we can schedule
76151 // another readable later.
76152
76153
76154 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
76155 flow(stream);
76156} // at this point, the user has presumably seen the 'readable' event,
76157// and called read() to consume some data. that may have triggered
76158// in turn another _read(n) call, in which case reading = true if
76159// it's in progress.
76160// However, if we're not ended, or reading, and the length < hwm,
76161// then go ahead and try to read some more preemptively.
76162
76163
76164function maybeReadMore(stream, state) {
76165 if (!state.readingMore) {
76166 state.readingMore = true;
76167 process.nextTick(maybeReadMore_, stream, state);
76168 }
76169}
76170
76171function maybeReadMore_(stream, state) {
76172 // Attempt to read more data if we should.
76173 //
76174 // The conditions for reading more data are (one of):
76175 // - Not enough data buffered (state.length < state.highWaterMark). The loop
76176 // is responsible for filling the buffer with enough data if such data
76177 // is available. If highWaterMark is 0 and we are not in the flowing mode
76178 // we should _not_ attempt to buffer any extra data. We'll get more data
76179 // when the stream consumer calls read() instead.
76180 // - No data in the buffer, and the stream is in flowing mode. In this mode
76181 // the loop below is responsible for ensuring read() is called. Failing to
76182 // call read here would abort the flow and there's no other mechanism for
76183 // continuing the flow if the stream consumer has just subscribed to the
76184 // 'data' event.
76185 //
76186 // In addition to the above conditions to keep reading data, the following
76187 // conditions prevent the data from being read:
76188 // - The stream has ended (state.ended).
76189 // - There is already a pending 'read' operation (state.reading). This is a
76190 // case where the the stream has called the implementation defined _read()
76191 // method, but they are processing the call asynchronously and have _not_
76192 // called push() with new data. In this case we skip performing more
76193 // read()s. The execution ends in this method again after the _read() ends
76194 // up calling push() with more data.
76195 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
76196 var len = state.length;
76197 debug('maybeReadMore read 0');
76198 stream.read(0);
76199 if (len === state.length) // didn't get any data, stop spinning.
76200 break;
76201 }
76202
76203 state.readingMore = false;
76204} // abstract method. to be overridden in specific implementation classes.
76205// call cb(er, data) where data is <= n in length.
76206// for virtual (non-string, non-buffer) streams, "length" is somewhat
76207// arbitrary, and perhaps not very meaningful.
76208
76209
76210Readable.prototype._read = function (n) {
76211 this.emit('error', new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
76212};
76213
76214Readable.prototype.pipe = function (dest, pipeOpts) {
76215 var src = this;
76216 var state = this._readableState;
76217
76218 switch (state.pipesCount) {
76219 case 0:
76220 state.pipes = dest;
76221 break;
76222
76223 case 1:
76224 state.pipes = [state.pipes, dest];
76225 break;
76226
76227 default:
76228 state.pipes.push(dest);
76229 break;
76230 }
76231
76232 state.pipesCount += 1;
76233 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
76234 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
76235 var endFn = doEnd ? onend : unpipe;
76236 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
76237 dest.on('unpipe', onunpipe);
76238
76239 function onunpipe(readable, unpipeInfo) {
76240 debug('onunpipe');
76241
76242 if (readable === src) {
76243 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
76244 unpipeInfo.hasUnpiped = true;
76245 cleanup();
76246 }
76247 }
76248 }
76249
76250 function onend() {
76251 debug('onend');
76252 dest.end();
76253 } // when the dest drains, it reduces the awaitDrain counter
76254 // on the source. This would be more elegant with a .once()
76255 // handler in flow(), but adding and removing repeatedly is
76256 // too slow.
76257
76258
76259 var ondrain = pipeOnDrain(src);
76260 dest.on('drain', ondrain);
76261 var cleanedUp = false;
76262
76263 function cleanup() {
76264 debug('cleanup'); // cleanup event handlers once the pipe is broken
76265
76266 dest.removeListener('close', onclose);
76267 dest.removeListener('finish', onfinish);
76268 dest.removeListener('drain', ondrain);
76269 dest.removeListener('error', onerror);
76270 dest.removeListener('unpipe', onunpipe);
76271 src.removeListener('end', onend);
76272 src.removeListener('end', unpipe);
76273 src.removeListener('data', ondata);
76274 cleanedUp = true; // if the reader is waiting for a drain event from this
76275 // specific writer, then it would cause it to never start
76276 // flowing again.
76277 // So, if this is awaiting a drain, then we just call it now.
76278 // If we don't know, then assume that we are waiting for one.
76279
76280 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
76281 }
76282
76283 src.on('data', ondata);
76284
76285 function ondata(chunk) {
76286 debug('ondata');
76287 var ret = dest.write(chunk);
76288 debug('dest.write', ret);
76289
76290 if (ret === false) {
76291 // If the user unpiped during `dest.write()`, it is possible
76292 // to get stuck in a permanently paused state if that write
76293 // also returned false.
76294 // => Check whether `dest` is still a piping destination.
76295 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
76296 debug('false write response, pause', state.awaitDrain);
76297 state.awaitDrain++;
76298 }
76299
76300 src.pause();
76301 }
76302 } // if the dest has an error, then stop piping into it.
76303 // however, don't suppress the throwing behavior for this.
76304
76305
76306 function onerror(er) {
76307 debug('onerror', er);
76308 unpipe();
76309 dest.removeListener('error', onerror);
76310 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
76311 } // Make sure our error handler is attached before userland ones.
76312
76313
76314 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
76315
76316 function onclose() {
76317 dest.removeListener('finish', onfinish);
76318 unpipe();
76319 }
76320
76321 dest.once('close', onclose);
76322
76323 function onfinish() {
76324 debug('onfinish');
76325 dest.removeListener('close', onclose);
76326 unpipe();
76327 }
76328
76329 dest.once('finish', onfinish);
76330
76331 function unpipe() {
76332 debug('unpipe');
76333 src.unpipe(dest);
76334 } // tell the dest that it's being piped to
76335
76336
76337 dest.emit('pipe', src); // start the flow if it hasn't been started already.
76338
76339 if (!state.flowing) {
76340 debug('pipe resume');
76341 src.resume();
76342 }
76343
76344 return dest;
76345};
76346
76347function pipeOnDrain(src) {
76348 return function pipeOnDrainFunctionResult() {
76349 var state = src._readableState;
76350 debug('pipeOnDrain', state.awaitDrain);
76351 if (state.awaitDrain) state.awaitDrain--;
76352
76353 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
76354 state.flowing = true;
76355 flow(src);
76356 }
76357 };
76358}
76359
76360Readable.prototype.unpipe = function (dest) {
76361 var state = this._readableState;
76362 var unpipeInfo = {
76363 hasUnpiped: false
76364 }; // if we're not piping anywhere, then do nothing.
76365
76366 if (state.pipesCount === 0) return this; // just one destination. most common case.
76367
76368 if (state.pipesCount === 1) {
76369 // passed in one, but it's not the right one.
76370 if (dest && dest !== state.pipes) return this;
76371 if (!dest) dest = state.pipes; // got a match.
76372
76373 state.pipes = null;
76374 state.pipesCount = 0;
76375 state.flowing = false;
76376 if (dest) dest.emit('unpipe', this, unpipeInfo);
76377 return this;
76378 } // slow case. multiple pipe destinations.
76379
76380
76381 if (!dest) {
76382 // remove all.
76383 var dests = state.pipes;
76384 var len = state.pipesCount;
76385 state.pipes = null;
76386 state.pipesCount = 0;
76387 state.flowing = false;
76388
76389 for (var i = 0; i < len; i++) {
76390 dests[i].emit('unpipe', this, {
76391 hasUnpiped: false
76392 });
76393 }
76394
76395 return this;
76396 } // try to find the right one.
76397
76398
76399 var index = indexOf(state.pipes, dest);
76400 if (index === -1) return this;
76401 state.pipes.splice(index, 1);
76402 state.pipesCount -= 1;
76403 if (state.pipesCount === 1) state.pipes = state.pipes[0];
76404 dest.emit('unpipe', this, unpipeInfo);
76405 return this;
76406}; // set up data events if they are asked for
76407// Ensure readable listeners eventually get something
76408
76409
76410Readable.prototype.on = function (ev, fn) {
76411 var res = Stream.prototype.on.call(this, ev, fn);
76412 var state = this._readableState;
76413
76414 if (ev === 'data') {
76415 // update readableListening so that resume() may be a no-op
76416 // a few lines down. This is needed to support once('readable').
76417 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
76418
76419 if (state.flowing !== false) this.resume();
76420 } else if (ev === 'readable') {
76421 if (!state.endEmitted && !state.readableListening) {
76422 state.readableListening = state.needReadable = true;
76423 state.flowing = false;
76424 state.emittedReadable = false;
76425 debug('on readable', state.length, state.reading);
76426
76427 if (state.length) {
76428 emitReadable(this);
76429 } else if (!state.reading) {
76430 process.nextTick(nReadingNextTick, this);
76431 }
76432 }
76433 }
76434
76435 return res;
76436};
76437
76438Readable.prototype.addListener = Readable.prototype.on;
76439
76440Readable.prototype.removeListener = function (ev, fn) {
76441 var res = Stream.prototype.removeListener.call(this, ev, fn);
76442
76443 if (ev === 'readable') {
76444 // We need to check if there is someone still listening to
76445 // readable and reset the state. However this needs to happen
76446 // after readable has been emitted but before I/O (nextTick) to
76447 // support once('readable', fn) cycles. This means that calling
76448 // resume within the same tick will have no
76449 // effect.
76450 process.nextTick(updateReadableListening, this);
76451 }
76452
76453 return res;
76454};
76455
76456Readable.prototype.removeAllListeners = function (ev) {
76457 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
76458
76459 if (ev === 'readable' || ev === undefined) {
76460 // We need to check if there is someone still listening to
76461 // readable and reset the state. However this needs to happen
76462 // after readable has been emitted but before I/O (nextTick) to
76463 // support once('readable', fn) cycles. This means that calling
76464 // resume within the same tick will have no
76465 // effect.
76466 process.nextTick(updateReadableListening, this);
76467 }
76468
76469 return res;
76470};
76471
76472function updateReadableListening(self) {
76473 var state = self._readableState;
76474 state.readableListening = self.listenerCount('readable') > 0;
76475
76476 if (state.resumeScheduled && !state.paused) {
76477 // flowing needs to be set to true now, otherwise
76478 // the upcoming resume will not flow.
76479 state.flowing = true; // crude way to check if we should resume
76480 } else if (self.listenerCount('data') > 0) {
76481 self.resume();
76482 }
76483}
76484
76485function nReadingNextTick(self) {
76486 debug('readable nexttick read 0');
76487 self.read(0);
76488} // pause() and resume() are remnants of the legacy readable stream API
76489// If the user uses them, then switch into old mode.
76490
76491
76492Readable.prototype.resume = function () {
76493 var state = this._readableState;
76494
76495 if (!state.flowing) {
76496 debug('resume'); // we flow only if there is no one listening
76497 // for readable, but we still have to call
76498 // resume()
76499
76500 state.flowing = !state.readableListening;
76501 resume(this, state);
76502 }
76503
76504 state.paused = false;
76505 return this;
76506};
76507
76508function resume(stream, state) {
76509 if (!state.resumeScheduled) {
76510 state.resumeScheduled = true;
76511 process.nextTick(resume_, stream, state);
76512 }
76513}
76514
76515function resume_(stream, state) {
76516 debug('resume', state.reading);
76517
76518 if (!state.reading) {
76519 stream.read(0);
76520 }
76521
76522 state.resumeScheduled = false;
76523 stream.emit('resume');
76524 flow(stream);
76525 if (state.flowing && !state.reading) stream.read(0);
76526}
76527
76528Readable.prototype.pause = function () {
76529 debug('call pause flowing=%j', this._readableState.flowing);
76530
76531 if (this._readableState.flowing !== false) {
76532 debug('pause');
76533 this._readableState.flowing = false;
76534 this.emit('pause');
76535 }
76536
76537 this._readableState.paused = true;
76538 return this;
76539};
76540
76541function flow(stream) {
76542 var state = stream._readableState;
76543 debug('flow', state.flowing);
76544
76545 while (state.flowing && stream.read() !== null) {
76546 ;
76547 }
76548} // wrap an old-style stream as the async data source.
76549// This is *not* part of the readable stream interface.
76550// It is an ugly unfortunate mess of history.
76551
76552
76553Readable.prototype.wrap = function (stream) {
76554 var _this = this;
76555
76556 var state = this._readableState;
76557 var paused = false;
76558 stream.on('end', function () {
76559 debug('wrapped end');
76560
76561 if (state.decoder && !state.ended) {
76562 var chunk = state.decoder.end();
76563 if (chunk && chunk.length) _this.push(chunk);
76564 }
76565
76566 _this.push(null);
76567 });
76568 stream.on('data', function (chunk) {
76569 debug('wrapped data');
76570 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
76571
76572 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
76573
76574 var ret = _this.push(chunk);
76575
76576 if (!ret) {
76577 paused = true;
76578 stream.pause();
76579 }
76580 }); // proxy all the other methods.
76581 // important when wrapping filters and duplexes.
76582
76583 for (var i in stream) {
76584 if (this[i] === undefined && typeof stream[i] === 'function') {
76585 this[i] = function methodWrap(method) {
76586 return function methodWrapReturnFunction() {
76587 return stream[method].apply(stream, arguments);
76588 };
76589 }(i);
76590 }
76591 } // proxy certain important events.
76592
76593
76594 for (var n = 0; n < kProxyEvents.length; n++) {
76595 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
76596 } // when we try to consume some more bytes, simply unpause the
76597 // underlying stream.
76598
76599
76600 this._read = function (n) {
76601 debug('wrapped _read', n);
76602
76603 if (paused) {
76604 paused = false;
76605 stream.resume();
76606 }
76607 };
76608
76609 return this;
76610};
76611
76612if (typeof Symbol === 'function') {
76613 Readable.prototype[Symbol.asyncIterator] = function () {
76614 emitExperimentalWarning('Readable[Symbol.asyncIterator]');
76615
76616 if (createReadableStreamAsyncIterator === undefined) {
76617 createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
76618 }
76619
76620 return createReadableStreamAsyncIterator(this);
76621 };
76622}
76623
76624Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
76625 // making it explicit this property is not enumerable
76626 // because otherwise some prototype manipulation in
76627 // userland will fail
76628 enumerable: false,
76629 get: function get() {
76630 return this._readableState.highWaterMark;
76631 }
76632});
76633Object.defineProperty(Readable.prototype, 'readableBuffer', {
76634 // making it explicit this property is not enumerable
76635 // because otherwise some prototype manipulation in
76636 // userland will fail
76637 enumerable: false,
76638 get: function get() {
76639 return this._readableState && this._readableState.buffer;
76640 }
76641});
76642Object.defineProperty(Readable.prototype, 'readableFlowing', {
76643 // making it explicit this property is not enumerable
76644 // because otherwise some prototype manipulation in
76645 // userland will fail
76646 enumerable: false,
76647 get: function get() {
76648 return this._readableState.flowing;
76649 },
76650 set: function set(state) {
76651 if (this._readableState) {
76652 this._readableState.flowing = state;
76653 }
76654 }
76655}); // exposed for testing purposes only.
76656
76657Readable._fromList = fromList;
76658Object.defineProperty(Readable.prototype, 'readableLength', {
76659 // making it explicit this property is not enumerable
76660 // because otherwise some prototype manipulation in
76661 // userland will fail
76662 enumerable: false,
76663 get: function get() {
76664 return this._readableState.length;
76665 }
76666}); // Pluck off n bytes from an array of buffers.
76667// Length is the combined lengths of all the buffers in the list.
76668// This function is designed to be inlinable, so please take care when making
76669// changes to the function body.
76670
76671function fromList(n, state) {
76672 // nothing buffered
76673 if (state.length === 0) return null;
76674 var ret;
76675 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
76676 // read it all, truncate the list
76677 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
76678 state.buffer.clear();
76679 } else {
76680 // read part of list
76681 ret = state.buffer.consume(n, state.decoder);
76682 }
76683 return ret;
76684}
76685
76686function endReadable(stream) {
76687 var state = stream._readableState;
76688 debug('endReadable', state.endEmitted);
76689
76690 if (!state.endEmitted) {
76691 state.ended = true;
76692 process.nextTick(endReadableNT, state, stream);
76693 }
76694}
76695
76696function endReadableNT(state, stream) {
76697 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
76698
76699 if (!state.endEmitted && state.length === 0) {
76700 state.endEmitted = true;
76701 stream.readable = false;
76702 stream.emit('end');
76703 }
76704}
76705
76706function indexOf(xs, x) {
76707 for (var i = 0, l = xs.length; i < l; i++) {
76708 if (xs[i] === x) return i;
76709 }
76710
76711 return -1;
76712}
76713}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
76714},{"../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){
76715// Copyright Joyent, Inc. and other Node contributors.
76716//
76717// Permission is hereby granted, free of charge, to any person obtaining a
76718// copy of this software and associated documentation files (the
76719// "Software"), to deal in the Software without restriction, including
76720// without limitation the rights to use, copy, modify, merge, publish,
76721// distribute, sublicense, and/or sell copies of the Software, and to permit
76722// persons to whom the Software is furnished to do so, subject to the
76723// following conditions:
76724//
76725// The above copyright notice and this permission notice shall be included
76726// in all copies or substantial portions of the Software.
76727//
76728// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
76729// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
76730// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
76731// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
76732// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
76733// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
76734// USE OR OTHER DEALINGS IN THE SOFTWARE.
76735// a transform stream is a readable/writable stream where you do
76736// something with the data. Sometimes it's called a "filter",
76737// but that's not a great name for it, since that implies a thing where
76738// some bits pass through, and others are simply ignored. (That would
76739// be a valid example of a transform, of course.)
76740//
76741// While the output is causally related to the input, it's not a
76742// necessarily symmetric or synchronous transformation. For example,
76743// a zlib stream might take multiple plain-text writes(), and then
76744// emit a single compressed chunk some time in the future.
76745//
76746// Here's how this works:
76747//
76748// The Transform stream has all the aspects of the readable and writable
76749// stream classes. When you write(chunk), that calls _write(chunk,cb)
76750// internally, and returns false if there's a lot of pending writes
76751// buffered up. When you call read(), that calls _read(n) until
76752// there's enough pending readable data buffered up.
76753//
76754// In a transform stream, the written data is placed in a buffer. When
76755// _read(n) is called, it transforms the queued up data, calling the
76756// buffered _write cb's as it consumes chunks. If consuming a single
76757// written chunk would result in multiple output chunks, then the first
76758// outputted bit calls the readcb, and subsequent chunks just go into
76759// the read buffer, and will cause it to emit 'readable' if necessary.
76760//
76761// This way, back-pressure is actually determined by the reading side,
76762// since _read has to be called to start processing a new chunk. However,
76763// a pathological inflate type of transform can cause excessive buffering
76764// here. For example, imagine a stream where every byte of input is
76765// interpreted as an integer from 0-255, and then results in that many
76766// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
76767// 1kb of data being output. In this case, you could write a very small
76768// amount of input, and end up with a very large amount of output. In
76769// such a pathological inflating mechanism, there'd be no way to tell
76770// the system to stop doing the transform. A single 4MB write could
76771// cause the system to run out of memory.
76772//
76773// However, even in such a pathological case, only a single written chunk
76774// would be consumed, and then the rest would wait (un-transformed) until
76775// the results of the previous transformed chunk were consumed.
76776'use strict';
76777
76778module.exports = Transform;
76779
76780var _require$codes = require('../errors').codes,
76781 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
76782 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
76783 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
76784 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
76785
76786var Duplex = require('./_stream_duplex');
76787
76788require('inherits')(Transform, Duplex);
76789
76790function afterTransform(er, data) {
76791 var ts = this._transformState;
76792 ts.transforming = false;
76793 var cb = ts.writecb;
76794
76795 if (cb === null) {
76796 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
76797 }
76798
76799 ts.writechunk = null;
76800 ts.writecb = null;
76801 if (data != null) // single equals check for both `null` and `undefined`
76802 this.push(data);
76803 cb(er);
76804 var rs = this._readableState;
76805 rs.reading = false;
76806
76807 if (rs.needReadable || rs.length < rs.highWaterMark) {
76808 this._read(rs.highWaterMark);
76809 }
76810}
76811
76812function Transform(options) {
76813 if (!(this instanceof Transform)) return new Transform(options);
76814 Duplex.call(this, options);
76815 this._transformState = {
76816 afterTransform: afterTransform.bind(this),
76817 needTransform: false,
76818 transforming: false,
76819 writecb: null,
76820 writechunk: null,
76821 writeencoding: null
76822 }; // start out asking for a readable event once data is transformed.
76823
76824 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
76825 // that Readable wants before the first _read call, so unset the
76826 // sync guard flag.
76827
76828 this._readableState.sync = false;
76829
76830 if (options) {
76831 if (typeof options.transform === 'function') this._transform = options.transform;
76832 if (typeof options.flush === 'function') this._flush = options.flush;
76833 } // When the writable side finishes, then flush out anything remaining.
76834
76835
76836 this.on('prefinish', prefinish);
76837}
76838
76839function prefinish() {
76840 var _this = this;
76841
76842 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
76843 this._flush(function (er, data) {
76844 done(_this, er, data);
76845 });
76846 } else {
76847 done(this, null, null);
76848 }
76849}
76850
76851Transform.prototype.push = function (chunk, encoding) {
76852 this._transformState.needTransform = false;
76853 return Duplex.prototype.push.call(this, chunk, encoding);
76854}; // This is the part where you do stuff!
76855// override this function in implementation classes.
76856// 'chunk' is an input chunk.
76857//
76858// Call `push(newChunk)` to pass along transformed output
76859// to the readable side. You may call 'push' zero or more times.
76860//
76861// Call `cb(err)` when you are done with this chunk. If you pass
76862// an error, then that'll put the hurt on the whole operation. If you
76863// never call cb(), then you'll never get another chunk.
76864
76865
76866Transform.prototype._transform = function (chunk, encoding, cb) {
76867 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
76868};
76869
76870Transform.prototype._write = function (chunk, encoding, cb) {
76871 var ts = this._transformState;
76872 ts.writecb = cb;
76873 ts.writechunk = chunk;
76874 ts.writeencoding = encoding;
76875
76876 if (!ts.transforming) {
76877 var rs = this._readableState;
76878 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
76879 }
76880}; // Doesn't matter what the args are here.
76881// _transform does all the work.
76882// That we got here means that the readable side wants more data.
76883
76884
76885Transform.prototype._read = function (n) {
76886 var ts = this._transformState;
76887
76888 if (ts.writechunk !== null && !ts.transforming) {
76889 ts.transforming = true;
76890
76891 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
76892 } else {
76893 // mark that we need a transform, so that any data that comes in
76894 // will get processed, now that we've asked for it.
76895 ts.needTransform = true;
76896 }
76897};
76898
76899Transform.prototype._destroy = function (err, cb) {
76900 Duplex.prototype._destroy.call(this, err, function (err2) {
76901 cb(err2);
76902 });
76903};
76904
76905function done(stream, er, data) {
76906 if (er) return stream.emit('error', er);
76907 if (data != null) // single equals check for both `null` and `undefined`
76908 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
76909 // if there's nothing in the write buffer, then that means
76910 // that nothing more will ever be provided
76911
76912 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
76913 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
76914 return stream.push(null);
76915}
76916},{"../errors":366,"./_stream_duplex":368,"inherits":210}],372:[function(require,module,exports){
76917(function (process,global){
76918// Copyright Joyent, Inc. and other Node contributors.
76919//
76920// Permission is hereby granted, free of charge, to any person obtaining a
76921// copy of this software and associated documentation files (the
76922// "Software"), to deal in the Software without restriction, including
76923// without limitation the rights to use, copy, modify, merge, publish,
76924// distribute, sublicense, and/or sell copies of the Software, and to permit
76925// persons to whom the Software is furnished to do so, subject to the
76926// following conditions:
76927//
76928// The above copyright notice and this permission notice shall be included
76929// in all copies or substantial portions of the Software.
76930//
76931// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
76932// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
76933// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
76934// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
76935// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
76936// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
76937// USE OR OTHER DEALINGS IN THE SOFTWARE.
76938// A bit simpler than readable streams.
76939// Implement an async ._write(chunk, encoding, cb), and it'll handle all
76940// the drain event emission and buffering.
76941'use strict';
76942
76943module.exports = Writable;
76944/* <replacement> */
76945
76946function WriteReq(chunk, encoding, cb) {
76947 this.chunk = chunk;
76948 this.encoding = encoding;
76949 this.callback = cb;
76950 this.next = null;
76951} // It seems a linked list but it is not
76952// there will be only 2 of these for each stream
76953
76954
76955function CorkedRequest(state) {
76956 var _this = this;
76957
76958 this.next = null;
76959 this.entry = null;
76960
76961 this.finish = function () {
76962 onCorkedFinish(_this, state);
76963 };
76964}
76965/* </replacement> */
76966
76967/*<replacement>*/
76968
76969
76970var Duplex;
76971/*</replacement>*/
76972
76973Writable.WritableState = WritableState;
76974/*<replacement>*/
76975
76976var internalUtil = {
76977 deprecate: require('util-deprecate')
76978};
76979/*</replacement>*/
76980
76981/*<replacement>*/
76982
76983var Stream = require('./internal/streams/stream');
76984/*</replacement>*/
76985
76986
76987var Buffer = require('buffer').Buffer;
76988
76989var OurUint8Array = global.Uint8Array || function () {};
76990
76991function _uint8ArrayToBuffer(chunk) {
76992 return Buffer.from(chunk);
76993}
76994
76995function _isUint8Array(obj) {
76996 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
76997}
76998
76999var destroyImpl = require('./internal/streams/destroy');
77000
77001var _require = require('./internal/streams/state'),
77002 getHighWaterMark = _require.getHighWaterMark;
77003
77004var _require$codes = require('../errors').codes,
77005 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
77006 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
77007 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
77008 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
77009 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
77010 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
77011 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
77012 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
77013
77014require('inherits')(Writable, Stream);
77015
77016function nop() {}
77017
77018function WritableState(options, stream, isDuplex) {
77019 Duplex = Duplex || require('./_stream_duplex');
77020 options = options || {}; // Duplex streams are both readable and writable, but share
77021 // the same options object.
77022 // However, some cases require setting options to different
77023 // values for the readable and the writable sides of the duplex stream,
77024 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
77025
77026 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
77027 // contains buffers or objects.
77028
77029 this.objectMode = !!options.objectMode;
77030 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
77031 // Note: 0 is a valid value, means that we always return false if
77032 // the entire buffer is not flushed immediately on write()
77033
77034 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
77035
77036 this.finalCalled = false; // drain event flag.
77037
77038 this.needDrain = false; // at the start of calling end()
77039
77040 this.ending = false; // when end() has been called, and returned
77041
77042 this.ended = false; // when 'finish' is emitted
77043
77044 this.finished = false; // has it been destroyed
77045
77046 this.destroyed = false; // should we decode strings into buffers before passing to _write?
77047 // this is here so that some node-core streams can optimize string
77048 // handling at a lower level.
77049
77050 var noDecode = options.decodeStrings === false;
77051 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
77052 // encoding is 'binary' so we have to make this configurable.
77053 // Everything else in the universe uses 'utf8', though.
77054
77055 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
77056 // of how much we're waiting to get pushed to some underlying
77057 // socket or file.
77058
77059 this.length = 0; // a flag to see when we're in the middle of a write.
77060
77061 this.writing = false; // when true all writes will be buffered until .uncork() call
77062
77063 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
77064 // or on a later tick. We set this to true at first, because any
77065 // actions that shouldn't happen until "later" should generally also
77066 // not happen before the first write call.
77067
77068 this.sync = true; // a flag to know if we're processing previously buffered items, which
77069 // may call the _write() callback in the same tick, so that we don't
77070 // end up in an overlapped onwrite situation.
77071
77072 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
77073
77074 this.onwrite = function (er) {
77075 onwrite(stream, er);
77076 }; // the callback that the user supplies to write(chunk,encoding,cb)
77077
77078
77079 this.writecb = null; // the amount that is being written when _write is called.
77080
77081 this.writelen = 0;
77082 this.bufferedRequest = null;
77083 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
77084 // this must be 0 before 'finish' can be emitted
77085
77086 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
77087 // This is relevant for synchronous Transform streams
77088
77089 this.prefinished = false; // True if the error was already emitted and should not be thrown again
77090
77091 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
77092
77093 this.emitClose = options.emitClose !== false; // count buffered requests
77094
77095 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
77096 // one allocated and free to use, and we maintain at most two
77097
77098 this.corkedRequestsFree = new CorkedRequest(this);
77099}
77100
77101WritableState.prototype.getBuffer = function getBuffer() {
77102 var current = this.bufferedRequest;
77103 var out = [];
77104
77105 while (current) {
77106 out.push(current);
77107 current = current.next;
77108 }
77109
77110 return out;
77111};
77112
77113(function () {
77114 try {
77115 Object.defineProperty(WritableState.prototype, 'buffer', {
77116 get: internalUtil.deprecate(function writableStateBufferGetter() {
77117 return this.getBuffer();
77118 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
77119 });
77120 } catch (_) {}
77121})(); // Test _writableState for inheritance to account for Duplex streams,
77122// whose prototype chain only points to Readable.
77123
77124
77125var realHasInstance;
77126
77127if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
77128 realHasInstance = Function.prototype[Symbol.hasInstance];
77129 Object.defineProperty(Writable, Symbol.hasInstance, {
77130 value: function value(object) {
77131 if (realHasInstance.call(this, object)) return true;
77132 if (this !== Writable) return false;
77133 return object && object._writableState instanceof WritableState;
77134 }
77135 });
77136} else {
77137 realHasInstance = function realHasInstance(object) {
77138 return object instanceof this;
77139 };
77140}
77141
77142function Writable(options) {
77143 Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
77144 // `realHasInstance` is necessary because using plain `instanceof`
77145 // would return false, as no `_writableState` property is attached.
77146 // Trying to use the custom `instanceof` for Writable here will also break the
77147 // Node.js LazyTransform implementation, which has a non-trivial getter for
77148 // `_writableState` that would lead to infinite recursion.
77149 // Checking for a Stream.Duplex instance is faster here instead of inside
77150 // the WritableState constructor, at least with V8 6.5
77151
77152 var isDuplex = this instanceof Duplex;
77153 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
77154 this._writableState = new WritableState(options, this, isDuplex); // legacy.
77155
77156 this.writable = true;
77157
77158 if (options) {
77159 if (typeof options.write === 'function') this._write = options.write;
77160 if (typeof options.writev === 'function') this._writev = options.writev;
77161 if (typeof options.destroy === 'function') this._destroy = options.destroy;
77162 if (typeof options.final === 'function') this._final = options.final;
77163 }
77164
77165 Stream.call(this);
77166} // Otherwise people can pipe Writable streams, which is just wrong.
77167
77168
77169Writable.prototype.pipe = function () {
77170 this.emit('error', new ERR_STREAM_CANNOT_PIPE());
77171};
77172
77173function writeAfterEnd(stream, cb) {
77174 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
77175
77176 stream.emit('error', er);
77177 process.nextTick(cb, er);
77178} // Checks that a user-supplied chunk is valid, especially for the particular
77179// mode the stream is in. Currently this means that `null` is never accepted
77180// and undefined/non-string values are only allowed in object mode.
77181
77182
77183function validChunk(stream, state, chunk, cb) {
77184 var er;
77185
77186 if (chunk === null) {
77187 er = new ERR_STREAM_NULL_VALUES();
77188 } else if (typeof chunk !== 'string' && !state.objectMode) {
77189 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
77190 }
77191
77192 if (er) {
77193 stream.emit('error', er);
77194 process.nextTick(cb, er);
77195 return false;
77196 }
77197
77198 return true;
77199}
77200
77201Writable.prototype.write = function (chunk, encoding, cb) {
77202 var state = this._writableState;
77203 var ret = false;
77204
77205 var isBuf = !state.objectMode && _isUint8Array(chunk);
77206
77207 if (isBuf && !Buffer.isBuffer(chunk)) {
77208 chunk = _uint8ArrayToBuffer(chunk);
77209 }
77210
77211 if (typeof encoding === 'function') {
77212 cb = encoding;
77213 encoding = null;
77214 }
77215
77216 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
77217 if (typeof cb !== 'function') cb = nop;
77218 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
77219 state.pendingcb++;
77220 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
77221 }
77222 return ret;
77223};
77224
77225Writable.prototype.cork = function () {
77226 this._writableState.corked++;
77227};
77228
77229Writable.prototype.uncork = function () {
77230 var state = this._writableState;
77231
77232 if (state.corked) {
77233 state.corked--;
77234 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
77235 }
77236};
77237
77238Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
77239 // node::ParseEncoding() requires lower case.
77240 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
77241 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);
77242 this._writableState.defaultEncoding = encoding;
77243 return this;
77244};
77245
77246Object.defineProperty(Writable.prototype, 'writableBuffer', {
77247 // making it explicit this property is not enumerable
77248 // because otherwise some prototype manipulation in
77249 // userland will fail
77250 enumerable: false,
77251 get: function get() {
77252 return this._writableState && this._writableState.getBuffer();
77253 }
77254});
77255
77256function decodeChunk(state, chunk, encoding) {
77257 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
77258 chunk = Buffer.from(chunk, encoding);
77259 }
77260
77261 return chunk;
77262}
77263
77264Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
77265 // making it explicit this property is not enumerable
77266 // because otherwise some prototype manipulation in
77267 // userland will fail
77268 enumerable: false,
77269 get: function get() {
77270 return this._writableState.highWaterMark;
77271 }
77272}); // if we're already writing something, then just put this
77273// in the queue, and wait our turn. Otherwise, call _write
77274// If we return false, then we need a drain event, so set that flag.
77275
77276function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
77277 if (!isBuf) {
77278 var newChunk = decodeChunk(state, chunk, encoding);
77279
77280 if (chunk !== newChunk) {
77281 isBuf = true;
77282 encoding = 'buffer';
77283 chunk = newChunk;
77284 }
77285 }
77286
77287 var len = state.objectMode ? 1 : chunk.length;
77288 state.length += len;
77289 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
77290
77291 if (!ret) state.needDrain = true;
77292
77293 if (state.writing || state.corked) {
77294 var last = state.lastBufferedRequest;
77295 state.lastBufferedRequest = {
77296 chunk: chunk,
77297 encoding: encoding,
77298 isBuf: isBuf,
77299 callback: cb,
77300 next: null
77301 };
77302
77303 if (last) {
77304 last.next = state.lastBufferedRequest;
77305 } else {
77306 state.bufferedRequest = state.lastBufferedRequest;
77307 }
77308
77309 state.bufferedRequestCount += 1;
77310 } else {
77311 doWrite(stream, state, false, len, chunk, encoding, cb);
77312 }
77313
77314 return ret;
77315}
77316
77317function doWrite(stream, state, writev, len, chunk, encoding, cb) {
77318 state.writelen = len;
77319 state.writecb = cb;
77320 state.writing = true;
77321 state.sync = true;
77322 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);
77323 state.sync = false;
77324}
77325
77326function onwriteError(stream, state, sync, er, cb) {
77327 --state.pendingcb;
77328
77329 if (sync) {
77330 // defer the callback if we are being called synchronously
77331 // to avoid piling up things on the stack
77332 process.nextTick(cb, er); // this can emit finish, and it will always happen
77333 // after error
77334
77335 process.nextTick(finishMaybe, stream, state);
77336 stream._writableState.errorEmitted = true;
77337 stream.emit('error', er);
77338 } else {
77339 // the caller expect this to happen before if
77340 // it is async
77341 cb(er);
77342 stream._writableState.errorEmitted = true;
77343 stream.emit('error', er); // this can emit finish, but finish must
77344 // always follow error
77345
77346 finishMaybe(stream, state);
77347 }
77348}
77349
77350function onwriteStateUpdate(state) {
77351 state.writing = false;
77352 state.writecb = null;
77353 state.length -= state.writelen;
77354 state.writelen = 0;
77355}
77356
77357function onwrite(stream, er) {
77358 var state = stream._writableState;
77359 var sync = state.sync;
77360 var cb = state.writecb;
77361 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
77362 onwriteStateUpdate(state);
77363 if (er) onwriteError(stream, state, sync, er, cb);else {
77364 // Check if we're actually ready to finish, but don't emit yet
77365 var finished = needFinish(state) || stream.destroyed;
77366
77367 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
77368 clearBuffer(stream, state);
77369 }
77370
77371 if (sync) {
77372 process.nextTick(afterWrite, stream, state, finished, cb);
77373 } else {
77374 afterWrite(stream, state, finished, cb);
77375 }
77376 }
77377}
77378
77379function afterWrite(stream, state, finished, cb) {
77380 if (!finished) onwriteDrain(stream, state);
77381 state.pendingcb--;
77382 cb();
77383 finishMaybe(stream, state);
77384} // Must force callback to be called on nextTick, so that we don't
77385// emit 'drain' before the write() consumer gets the 'false' return
77386// value, and has a chance to attach a 'drain' listener.
77387
77388
77389function onwriteDrain(stream, state) {
77390 if (state.length === 0 && state.needDrain) {
77391 state.needDrain = false;
77392 stream.emit('drain');
77393 }
77394} // if there's something in the buffer waiting, then process it
77395
77396
77397function clearBuffer(stream, state) {
77398 state.bufferProcessing = true;
77399 var entry = state.bufferedRequest;
77400
77401 if (stream._writev && entry && entry.next) {
77402 // Fast case, write everything using _writev()
77403 var l = state.bufferedRequestCount;
77404 var buffer = new Array(l);
77405 var holder = state.corkedRequestsFree;
77406 holder.entry = entry;
77407 var count = 0;
77408 var allBuffers = true;
77409
77410 while (entry) {
77411 buffer[count] = entry;
77412 if (!entry.isBuf) allBuffers = false;
77413 entry = entry.next;
77414 count += 1;
77415 }
77416
77417 buffer.allBuffers = allBuffers;
77418 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
77419 // as the hot path ends with doWrite
77420
77421 state.pendingcb++;
77422 state.lastBufferedRequest = null;
77423
77424 if (holder.next) {
77425 state.corkedRequestsFree = holder.next;
77426 holder.next = null;
77427 } else {
77428 state.corkedRequestsFree = new CorkedRequest(state);
77429 }
77430
77431 state.bufferedRequestCount = 0;
77432 } else {
77433 // Slow case, write chunks one-by-one
77434 while (entry) {
77435 var chunk = entry.chunk;
77436 var encoding = entry.encoding;
77437 var cb = entry.callback;
77438 var len = state.objectMode ? 1 : chunk.length;
77439 doWrite(stream, state, false, len, chunk, encoding, cb);
77440 entry = entry.next;
77441 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
77442 // it means that we need to wait until it does.
77443 // also, that means that the chunk and cb are currently
77444 // being processed, so move the buffer counter past them.
77445
77446 if (state.writing) {
77447 break;
77448 }
77449 }
77450
77451 if (entry === null) state.lastBufferedRequest = null;
77452 }
77453
77454 state.bufferedRequest = entry;
77455 state.bufferProcessing = false;
77456}
77457
77458Writable.prototype._write = function (chunk, encoding, cb) {
77459 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
77460};
77461
77462Writable.prototype._writev = null;
77463
77464Writable.prototype.end = function (chunk, encoding, cb) {
77465 var state = this._writableState;
77466
77467 if (typeof chunk === 'function') {
77468 cb = chunk;
77469 chunk = null;
77470 encoding = null;
77471 } else if (typeof encoding === 'function') {
77472 cb = encoding;
77473 encoding = null;
77474 }
77475
77476 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
77477
77478 if (state.corked) {
77479 state.corked = 1;
77480 this.uncork();
77481 } // ignore unnecessary end() calls.
77482
77483
77484 if (!state.ending) endWritable(this, state, cb);
77485 return this;
77486};
77487
77488Object.defineProperty(Writable.prototype, 'writableLength', {
77489 // making it explicit this property is not enumerable
77490 // because otherwise some prototype manipulation in
77491 // userland will fail
77492 enumerable: false,
77493 get: function get() {
77494 return this._writableState.length;
77495 }
77496});
77497
77498function needFinish(state) {
77499 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
77500}
77501
77502function callFinal(stream, state) {
77503 stream._final(function (err) {
77504 state.pendingcb--;
77505
77506 if (err) {
77507 stream.emit('error', err);
77508 }
77509
77510 state.prefinished = true;
77511 stream.emit('prefinish');
77512 finishMaybe(stream, state);
77513 });
77514}
77515
77516function prefinish(stream, state) {
77517 if (!state.prefinished && !state.finalCalled) {
77518 if (typeof stream._final === 'function' && !state.destroyed) {
77519 state.pendingcb++;
77520 state.finalCalled = true;
77521 process.nextTick(callFinal, stream, state);
77522 } else {
77523 state.prefinished = true;
77524 stream.emit('prefinish');
77525 }
77526 }
77527}
77528
77529function finishMaybe(stream, state) {
77530 var need = needFinish(state);
77531
77532 if (need) {
77533 prefinish(stream, state);
77534
77535 if (state.pendingcb === 0) {
77536 state.finished = true;
77537 stream.emit('finish');
77538 }
77539 }
77540
77541 return need;
77542}
77543
77544function endWritable(stream, state, cb) {
77545 state.ending = true;
77546 finishMaybe(stream, state);
77547
77548 if (cb) {
77549 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
77550 }
77551
77552 state.ended = true;
77553 stream.writable = false;
77554}
77555
77556function onCorkedFinish(corkReq, state, err) {
77557 var entry = corkReq.entry;
77558 corkReq.entry = null;
77559
77560 while (entry) {
77561 var cb = entry.callback;
77562 state.pendingcb--;
77563 cb(err);
77564 entry = entry.next;
77565 } // reuse the free corkReq.
77566
77567
77568 state.corkedRequestsFree.next = corkReq;
77569}
77570
77571Object.defineProperty(Writable.prototype, 'destroyed', {
77572 // making it explicit this property is not enumerable
77573 // because otherwise some prototype manipulation in
77574 // userland will fail
77575 enumerable: false,
77576 get: function get() {
77577 if (this._writableState === undefined) {
77578 return false;
77579 }
77580
77581 return this._writableState.destroyed;
77582 },
77583 set: function set(value) {
77584 // we ignore the value if the stream
77585 // has not been initialized yet
77586 if (!this._writableState) {
77587 return;
77588 } // backward compatibility, the user is explicitly
77589 // managing destroyed
77590
77591
77592 this._writableState.destroyed = value;
77593 }
77594});
77595Writable.prototype.destroy = destroyImpl.destroy;
77596Writable.prototype._undestroy = destroyImpl.undestroy;
77597
77598Writable.prototype._destroy = function (err, cb) {
77599 cb(err);
77600};
77601}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
77602},{"../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){
77603(function (process){
77604'use strict';
77605
77606var _Object$setPrototypeO;
77607
77608function _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; }
77609
77610var finished = require('./end-of-stream');
77611
77612var kLastResolve = Symbol('lastResolve');
77613var kLastReject = Symbol('lastReject');
77614var kError = Symbol('error');
77615var kEnded = Symbol('ended');
77616var kLastPromise = Symbol('lastPromise');
77617var kHandlePromise = Symbol('handlePromise');
77618var kStream = Symbol('stream');
77619
77620function createIterResult(value, done) {
77621 return {
77622 value: value,
77623 done: done
77624 };
77625}
77626
77627function readAndResolve(iter) {
77628 var resolve = iter[kLastResolve];
77629
77630 if (resolve !== null) {
77631 var data = iter[kStream].read(); // we defer if data is null
77632 // we can be expecting either 'end' or
77633 // 'error'
77634
77635 if (data !== null) {
77636 iter[kLastPromise] = null;
77637 iter[kLastResolve] = null;
77638 iter[kLastReject] = null;
77639 resolve(createIterResult(data, false));
77640 }
77641 }
77642}
77643
77644function onReadable(iter) {
77645 // we wait for the next tick, because it might
77646 // emit an error with process.nextTick
77647 process.nextTick(readAndResolve, iter);
77648}
77649
77650function wrapForNext(lastPromise, iter) {
77651 return function (resolve, reject) {
77652 lastPromise.then(function () {
77653 if (iter[kEnded]) {
77654 resolve(createIterResult(undefined, true));
77655 return;
77656 }
77657
77658 iter[kHandlePromise](resolve, reject);
77659 }, reject);
77660 };
77661}
77662
77663var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
77664var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
77665 get stream() {
77666 return this[kStream];
77667 },
77668
77669 next: function next() {
77670 var _this = this;
77671
77672 // if we have detected an error in the meanwhile
77673 // reject straight away
77674 var error = this[kError];
77675
77676 if (error !== null) {
77677 return Promise.reject(error);
77678 }
77679
77680 if (this[kEnded]) {
77681 return Promise.resolve(createIterResult(undefined, true));
77682 }
77683
77684 if (this[kStream].destroyed) {
77685 // We need to defer via nextTick because if .destroy(err) is
77686 // called, the error will be emitted via nextTick, and
77687 // we cannot guarantee that there is no error lingering around
77688 // waiting to be emitted.
77689 return new Promise(function (resolve, reject) {
77690 process.nextTick(function () {
77691 if (_this[kError]) {
77692 reject(_this[kError]);
77693 } else {
77694 resolve(createIterResult(undefined, true));
77695 }
77696 });
77697 });
77698 } // if we have multiple next() calls
77699 // we will wait for the previous Promise to finish
77700 // this logic is optimized to support for await loops,
77701 // where next() is only called once at a time
77702
77703
77704 var lastPromise = this[kLastPromise];
77705 var promise;
77706
77707 if (lastPromise) {
77708 promise = new Promise(wrapForNext(lastPromise, this));
77709 } else {
77710 // fast path needed to support multiple this.push()
77711 // without triggering the next() queue
77712 var data = this[kStream].read();
77713
77714 if (data !== null) {
77715 return Promise.resolve(createIterResult(data, false));
77716 }
77717
77718 promise = new Promise(this[kHandlePromise]);
77719 }
77720
77721 this[kLastPromise] = promise;
77722 return promise;
77723 }
77724}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
77725 return this;
77726}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
77727 var _this2 = this;
77728
77729 // destroy(err, cb) is a private API
77730 // we can guarantee we have that here, because we control the
77731 // Readable class this is attached to
77732 return new Promise(function (resolve, reject) {
77733 _this2[kStream].destroy(null, function (err) {
77734 if (err) {
77735 reject(err);
77736 return;
77737 }
77738
77739 resolve(createIterResult(undefined, true));
77740 });
77741 });
77742}), _Object$setPrototypeO), AsyncIteratorPrototype);
77743
77744var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
77745 var _Object$create;
77746
77747 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
77748 value: stream,
77749 writable: true
77750 }), _defineProperty(_Object$create, kLastResolve, {
77751 value: null,
77752 writable: true
77753 }), _defineProperty(_Object$create, kLastReject, {
77754 value: null,
77755 writable: true
77756 }), _defineProperty(_Object$create, kError, {
77757 value: null,
77758 writable: true
77759 }), _defineProperty(_Object$create, kEnded, {
77760 value: stream._readableState.endEmitted,
77761 writable: true
77762 }), _defineProperty(_Object$create, kHandlePromise, {
77763 value: function value(resolve, reject) {
77764 var data = iterator[kStream].read();
77765
77766 if (data) {
77767 iterator[kLastPromise] = null;
77768 iterator[kLastResolve] = null;
77769 iterator[kLastReject] = null;
77770 resolve(createIterResult(data, false));
77771 } else {
77772 iterator[kLastResolve] = resolve;
77773 iterator[kLastReject] = reject;
77774 }
77775 },
77776 writable: true
77777 }), _Object$create));
77778 iterator[kLastPromise] = null;
77779 finished(stream, function (err) {
77780 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
77781 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
77782 // returned by next() and store the error
77783
77784 if (reject !== null) {
77785 iterator[kLastPromise] = null;
77786 iterator[kLastResolve] = null;
77787 iterator[kLastReject] = null;
77788 reject(err);
77789 }
77790
77791 iterator[kError] = err;
77792 return;
77793 }
77794
77795 var resolve = iterator[kLastResolve];
77796
77797 if (resolve !== null) {
77798 iterator[kLastPromise] = null;
77799 iterator[kLastResolve] = null;
77800 iterator[kLastReject] = null;
77801 resolve(createIterResult(undefined, true));
77802 }
77803
77804 iterator[kEnded] = true;
77805 });
77806 stream.on('readable', onReadable.bind(null, iterator));
77807 return iterator;
77808};
77809
77810module.exports = createReadableStreamAsyncIterator;
77811}).call(this,require('_process'))
77812},{"./end-of-stream":376,"_process":265}],374:[function(require,module,exports){
77813'use strict';
77814
77815function _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; }
77816
77817function _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; }
77818
77819var _require = require('buffer'),
77820 Buffer = _require.Buffer;
77821
77822var _require2 = require('util'),
77823 inspect = _require2.inspect;
77824
77825var custom = inspect && inspect.custom || 'inspect';
77826
77827function copyBuffer(src, target, offset) {
77828 Buffer.prototype.copy.call(src, target, offset);
77829}
77830
77831module.exports =
77832/*#__PURE__*/
77833function () {
77834 function BufferList() {
77835 this.head = null;
77836 this.tail = null;
77837 this.length = 0;
77838 }
77839
77840 var _proto = BufferList.prototype;
77841
77842 _proto.push = function push(v) {
77843 var entry = {
77844 data: v,
77845 next: null
77846 };
77847 if (this.length > 0) this.tail.next = entry;else this.head = entry;
77848 this.tail = entry;
77849 ++this.length;
77850 };
77851
77852 _proto.unshift = function unshift(v) {
77853 var entry = {
77854 data: v,
77855 next: this.head
77856 };
77857 if (this.length === 0) this.tail = entry;
77858 this.head = entry;
77859 ++this.length;
77860 };
77861
77862 _proto.shift = function shift() {
77863 if (this.length === 0) return;
77864 var ret = this.head.data;
77865 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
77866 --this.length;
77867 return ret;
77868 };
77869
77870 _proto.clear = function clear() {
77871 this.head = this.tail = null;
77872 this.length = 0;
77873 };
77874
77875 _proto.join = function join(s) {
77876 if (this.length === 0) return '';
77877 var p = this.head;
77878 var ret = '' + p.data;
77879
77880 while (p = p.next) {
77881 ret += s + p.data;
77882 }
77883
77884 return ret;
77885 };
77886
77887 _proto.concat = function concat(n) {
77888 if (this.length === 0) return Buffer.alloc(0);
77889 var ret = Buffer.allocUnsafe(n >>> 0);
77890 var p = this.head;
77891 var i = 0;
77892
77893 while (p) {
77894 copyBuffer(p.data, ret, i);
77895 i += p.data.length;
77896 p = p.next;
77897 }
77898
77899 return ret;
77900 } // Consumes a specified amount of bytes or characters from the buffered data.
77901 ;
77902
77903 _proto.consume = function consume(n, hasStrings) {
77904 var ret;
77905
77906 if (n < this.head.data.length) {
77907 // `slice` is the same for buffers and strings.
77908 ret = this.head.data.slice(0, n);
77909 this.head.data = this.head.data.slice(n);
77910 } else if (n === this.head.data.length) {
77911 // First chunk is a perfect match.
77912 ret = this.shift();
77913 } else {
77914 // Result spans more than one buffer.
77915 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
77916 }
77917
77918 return ret;
77919 };
77920
77921 _proto.first = function first() {
77922 return this.head.data;
77923 } // Consumes a specified amount of characters from the buffered data.
77924 ;
77925
77926 _proto._getString = function _getString(n) {
77927 var p = this.head;
77928 var c = 1;
77929 var ret = p.data;
77930 n -= ret.length;
77931
77932 while (p = p.next) {
77933 var str = p.data;
77934 var nb = n > str.length ? str.length : n;
77935 if (nb === str.length) ret += str;else ret += str.slice(0, n);
77936 n -= nb;
77937
77938 if (n === 0) {
77939 if (nb === str.length) {
77940 ++c;
77941 if (p.next) this.head = p.next;else this.head = this.tail = null;
77942 } else {
77943 this.head = p;
77944 p.data = str.slice(nb);
77945 }
77946
77947 break;
77948 }
77949
77950 ++c;
77951 }
77952
77953 this.length -= c;
77954 return ret;
77955 } // Consumes a specified amount of bytes from the buffered data.
77956 ;
77957
77958 _proto._getBuffer = function _getBuffer(n) {
77959 var ret = Buffer.allocUnsafe(n);
77960 var p = this.head;
77961 var c = 1;
77962 p.data.copy(ret);
77963 n -= p.data.length;
77964
77965 while (p = p.next) {
77966 var buf = p.data;
77967 var nb = n > buf.length ? buf.length : n;
77968 buf.copy(ret, ret.length - n, 0, nb);
77969 n -= nb;
77970
77971 if (n === 0) {
77972 if (nb === buf.length) {
77973 ++c;
77974 if (p.next) this.head = p.next;else this.head = this.tail = null;
77975 } else {
77976 this.head = p;
77977 p.data = buf.slice(nb);
77978 }
77979
77980 break;
77981 }
77982
77983 ++c;
77984 }
77985
77986 this.length -= c;
77987 return ret;
77988 } // Make sure the linked list only shows the minimal necessary information.
77989 ;
77990
77991 _proto[custom] = function (_, options) {
77992 return inspect(this, _objectSpread({}, options, {
77993 // Only inspect one level.
77994 depth: 0,
77995 // It should not recurse.
77996 customInspect: false
77997 }));
77998 };
77999
78000 return BufferList;
78001}();
78002},{"buffer":114,"util":82}],375:[function(require,module,exports){
78003(function (process){
78004'use strict'; // undocumented cb() API, needed for core, not for public API
78005
78006function destroy(err, cb) {
78007 var _this = this;
78008
78009 var readableDestroyed = this._readableState && this._readableState.destroyed;
78010 var writableDestroyed = this._writableState && this._writableState.destroyed;
78011
78012 if (readableDestroyed || writableDestroyed) {
78013 if (cb) {
78014 cb(err);
78015 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
78016 process.nextTick(emitErrorNT, this, err);
78017 }
78018
78019 return this;
78020 } // we set destroyed to true before firing error callbacks in order
78021 // to make it re-entrance safe in case destroy() is called within callbacks
78022
78023
78024 if (this._readableState) {
78025 this._readableState.destroyed = true;
78026 } // if this is a duplex stream mark the writable part as destroyed as well
78027
78028
78029 if (this._writableState) {
78030 this._writableState.destroyed = true;
78031 }
78032
78033 this._destroy(err || null, function (err) {
78034 if (!cb && err) {
78035 process.nextTick(emitErrorAndCloseNT, _this, err);
78036
78037 if (_this._writableState) {
78038 _this._writableState.errorEmitted = true;
78039 }
78040 } else if (cb) {
78041 process.nextTick(emitCloseNT, _this);
78042 cb(err);
78043 } else {
78044 process.nextTick(emitCloseNT, _this);
78045 }
78046 });
78047
78048 return this;
78049}
78050
78051function emitErrorAndCloseNT(self, err) {
78052 emitErrorNT(self, err);
78053 emitCloseNT(self);
78054}
78055
78056function emitCloseNT(self) {
78057 if (self._writableState && !self._writableState.emitClose) return;
78058 if (self._readableState && !self._readableState.emitClose) return;
78059 self.emit('close');
78060}
78061
78062function undestroy() {
78063 if (this._readableState) {
78064 this._readableState.destroyed = false;
78065 this._readableState.reading = false;
78066 this._readableState.ended = false;
78067 this._readableState.endEmitted = false;
78068 }
78069
78070 if (this._writableState) {
78071 this._writableState.destroyed = false;
78072 this._writableState.ended = false;
78073 this._writableState.ending = false;
78074 this._writableState.finalCalled = false;
78075 this._writableState.prefinished = false;
78076 this._writableState.finished = false;
78077 this._writableState.errorEmitted = false;
78078 }
78079}
78080
78081function emitErrorNT(self, err) {
78082 self.emit('error', err);
78083}
78084
78085module.exports = {
78086 destroy: destroy,
78087 undestroy: undestroy
78088};
78089}).call(this,require('_process'))
78090},{"_process":265}],376:[function(require,module,exports){
78091// Ported from https://github.com/mafintosh/end-of-stream with
78092// permission from the author, Mathias Buus (@mafintosh).
78093'use strict';
78094
78095var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
78096
78097function once(callback) {
78098 var called = false;
78099 return function () {
78100 if (called) return;
78101 called = true;
78102
78103 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
78104 args[_key] = arguments[_key];
78105 }
78106
78107 callback.apply(this, args);
78108 };
78109}
78110
78111function noop() {}
78112
78113function isRequest(stream) {
78114 return stream.setHeader && typeof stream.abort === 'function';
78115}
78116
78117function eos(stream, opts, callback) {
78118 if (typeof opts === 'function') return eos(stream, null, opts);
78119 if (!opts) opts = {};
78120 callback = once(callback || noop);
78121 var readable = opts.readable || opts.readable !== false && stream.readable;
78122 var writable = opts.writable || opts.writable !== false && stream.writable;
78123
78124 var onlegacyfinish = function onlegacyfinish() {
78125 if (!stream.writable) onfinish();
78126 };
78127
78128 var writableEnded = stream._writableState && stream._writableState.finished;
78129
78130 var onfinish = function onfinish() {
78131 writable = false;
78132 writableEnded = true;
78133 if (!readable) callback.call(stream);
78134 };
78135
78136 var readableEnded = stream._readableState && stream._readableState.endEmitted;
78137
78138 var onend = function onend() {
78139 readable = false;
78140 readableEnded = true;
78141 if (!writable) callback.call(stream);
78142 };
78143
78144 var onerror = function onerror(err) {
78145 callback.call(stream, err);
78146 };
78147
78148 var onclose = function onclose() {
78149 var err;
78150
78151 if (readable && !readableEnded) {
78152 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
78153 return callback.call(stream, err);
78154 }
78155
78156 if (writable && !writableEnded) {
78157 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
78158 return callback.call(stream, err);
78159 }
78160 };
78161
78162 var onrequest = function onrequest() {
78163 stream.req.on('finish', onfinish);
78164 };
78165
78166 if (isRequest(stream)) {
78167 stream.on('complete', onfinish);
78168 stream.on('abort', onclose);
78169 if (stream.req) onrequest();else stream.on('request', onrequest);
78170 } else if (writable && !stream._writableState) {
78171 // legacy streams
78172 stream.on('end', onlegacyfinish);
78173 stream.on('close', onlegacyfinish);
78174 }
78175
78176 stream.on('end', onend);
78177 stream.on('finish', onfinish);
78178 if (opts.error !== false) stream.on('error', onerror);
78179 stream.on('close', onclose);
78180 return function () {
78181 stream.removeListener('complete', onfinish);
78182 stream.removeListener('abort', onclose);
78183 stream.removeListener('request', onrequest);
78184 if (stream.req) stream.req.removeListener('finish', onfinish);
78185 stream.removeListener('end', onlegacyfinish);
78186 stream.removeListener('close', onlegacyfinish);
78187 stream.removeListener('finish', onfinish);
78188 stream.removeListener('end', onend);
78189 stream.removeListener('error', onerror);
78190 stream.removeListener('close', onclose);
78191 };
78192}
78193
78194module.exports = eos;
78195},{"../../../errors":366}],377:[function(require,module,exports){
78196// Ported from https://github.com/mafintosh/pump with
78197// permission from the author, Mathias Buus (@mafintosh).
78198'use strict';
78199
78200var eos;
78201
78202function once(callback) {
78203 var called = false;
78204 return function () {
78205 if (called) return;
78206 called = true;
78207 callback.apply(void 0, arguments);
78208 };
78209}
78210
78211var _require$codes = require('../../../errors').codes,
78212 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
78213 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
78214
78215function noop(err) {
78216 // Rethrow the error if it exists to avoid swallowing it
78217 if (err) throw err;
78218}
78219
78220function isRequest(stream) {
78221 return stream.setHeader && typeof stream.abort === 'function';
78222}
78223
78224function destroyer(stream, reading, writing, callback) {
78225 callback = once(callback);
78226 var closed = false;
78227 stream.on('close', function () {
78228 closed = true;
78229 });
78230 if (eos === undefined) eos = require('./end-of-stream');
78231 eos(stream, {
78232 readable: reading,
78233 writable: writing
78234 }, function (err) {
78235 if (err) return callback(err);
78236 closed = true;
78237 callback();
78238 });
78239 var destroyed = false;
78240 return function (err) {
78241 if (closed) return;
78242 if (destroyed) return;
78243 destroyed = true; // request.destroy just do .end - .abort is what we want
78244
78245 if (isRequest(stream)) return stream.abort();
78246 if (typeof stream.destroy === 'function') return stream.destroy();
78247 callback(err || new ERR_STREAM_DESTROYED('pipe'));
78248 };
78249}
78250
78251function call(fn) {
78252 fn();
78253}
78254
78255function pipe(from, to) {
78256 return from.pipe(to);
78257}
78258
78259function popCallback(streams) {
78260 if (!streams.length) return noop;
78261 if (typeof streams[streams.length - 1] !== 'function') return noop;
78262 return streams.pop();
78263}
78264
78265function pipeline() {
78266 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
78267 streams[_key] = arguments[_key];
78268 }
78269
78270 var callback = popCallback(streams);
78271 if (Array.isArray(streams[0])) streams = streams[0];
78272
78273 if (streams.length < 2) {
78274 throw new ERR_MISSING_ARGS('streams');
78275 }
78276
78277 var error;
78278 var destroys = streams.map(function (stream, i) {
78279 var reading = i < streams.length - 1;
78280 var writing = i > 0;
78281 return destroyer(stream, reading, writing, function (err) {
78282 if (!error) error = err;
78283 if (err) destroys.forEach(call);
78284 if (reading) return;
78285 destroys.forEach(call);
78286 callback(error);
78287 });
78288 });
78289 return streams.reduce(pipe);
78290}
78291
78292module.exports = pipeline;
78293},{"../../../errors":366,"./end-of-stream":376}],378:[function(require,module,exports){
78294'use strict';
78295
78296var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
78297
78298function highWaterMarkFrom(options, isDuplex, duplexKey) {
78299 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
78300}
78301
78302function getHighWaterMark(state, options, duplexKey, isDuplex) {
78303 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
78304
78305 if (hwm != null) {
78306 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
78307 var name = isDuplex ? duplexKey : 'highWaterMark';
78308 throw new ERR_INVALID_OPT_VALUE(name, hwm);
78309 }
78310
78311 return Math.floor(hwm);
78312 } // Default value
78313
78314
78315 return state.objectMode ? 16 : 16 * 1024;
78316}
78317
78318module.exports = {
78319 getHighWaterMark: getHighWaterMark
78320};
78321},{"../../../errors":366}],379:[function(require,module,exports){
78322arguments[4][288][0].apply(exports,arguments)
78323},{"dup":288,"events":159}],380:[function(require,module,exports){
78324exports = module.exports = require('./lib/_stream_readable.js');
78325exports.Stream = exports;
78326exports.Readable = exports;
78327exports.Writable = require('./lib/_stream_writable.js');
78328exports.Duplex = require('./lib/_stream_duplex.js');
78329exports.Transform = require('./lib/_stream_transform.js');
78330exports.PassThrough = require('./lib/_stream_passthrough.js');
78331exports.finished = require('./lib/internal/streams/end-of-stream.js');
78332exports.pipeline = require('./lib/internal/streams/pipeline.js');
78333
78334},{"./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){
78335arguments[4][289][0].apply(exports,arguments)
78336},{"dup":289,"safe-buffer":325}],382:[function(require,module,exports){
78337(function (setImmediate,clearImmediate){
78338var nextTick = require('process/browser.js').nextTick;
78339var apply = Function.prototype.apply;
78340var slice = Array.prototype.slice;
78341var immediateIds = {};
78342var nextImmediateId = 0;
78343
78344// DOM APIs, for completeness
78345
78346exports.setTimeout = function() {
78347 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
78348};
78349exports.setInterval = function() {
78350 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
78351};
78352exports.clearTimeout =
78353exports.clearInterval = function(timeout) { timeout.close(); };
78354
78355function Timeout(id, clearFn) {
78356 this._id = id;
78357 this._clearFn = clearFn;
78358}
78359Timeout.prototype.unref = Timeout.prototype.ref = function() {};
78360Timeout.prototype.close = function() {
78361 this._clearFn.call(window, this._id);
78362};
78363
78364// Does not start the time, just sets up the members needed.
78365exports.enroll = function(item, msecs) {
78366 clearTimeout(item._idleTimeoutId);
78367 item._idleTimeout = msecs;
78368};
78369
78370exports.unenroll = function(item) {
78371 clearTimeout(item._idleTimeoutId);
78372 item._idleTimeout = -1;
78373};
78374
78375exports._unrefActive = exports.active = function(item) {
78376 clearTimeout(item._idleTimeoutId);
78377
78378 var msecs = item._idleTimeout;
78379 if (msecs >= 0) {
78380 item._idleTimeoutId = setTimeout(function onTimeout() {
78381 if (item._onTimeout)
78382 item._onTimeout();
78383 }, msecs);
78384 }
78385};
78386
78387// That's not how node.js implements it but the exposed api is the same.
78388exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
78389 var id = nextImmediateId++;
78390 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
78391
78392 immediateIds[id] = true;
78393
78394 nextTick(function onNextTick() {
78395 if (immediateIds[id]) {
78396 // fn.call() is faster so we optimize for the common use-case
78397 // @see http://jsperf.com/call-apply-segu
78398 if (args) {
78399 fn.apply(null, args);
78400 } else {
78401 fn.call(null);
78402 }
78403 // Prevent ids from leaking
78404 exports.clearImmediate(id);
78405 }
78406 });
78407
78408 return id;
78409};
78410
78411exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
78412 delete immediateIds[id];
78413};
78414}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
78415},{"process/browser.js":265,"timers":382}],383:[function(require,module,exports){
78416/*!
78417 * Copyright (c) 2015, Salesforce.com, Inc.
78418 * All rights reserved.
78419 *
78420 * Redistribution and use in source and binary forms, with or without
78421 * modification, are permitted provided that the following conditions are met:
78422 *
78423 * 1. Redistributions of source code must retain the above copyright notice,
78424 * this list of conditions and the following disclaimer.
78425 *
78426 * 2. Redistributions in binary form must reproduce the above copyright notice,
78427 * this list of conditions and the following disclaimer in the documentation
78428 * and/or other materials provided with the distribution.
78429 *
78430 * 3. Neither the name of Salesforce.com nor the names of its contributors may
78431 * be used to endorse or promote products derived from this software without
78432 * specific prior written permission.
78433 *
78434 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
78435 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78436 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
78437 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
78438 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
78439 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
78440 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
78441 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
78442 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
78443 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
78444 * POSSIBILITY OF SUCH DAMAGE.
78445 */
78446'use strict';
78447var net = require('net');
78448var urlParse = require('url').parse;
78449var util = require('util');
78450var pubsuffix = require('./pubsuffix-psl');
78451var Store = require('./store').Store;
78452var MemoryCookieStore = require('./memstore').MemoryCookieStore;
78453var pathMatch = require('./pathMatch').pathMatch;
78454var VERSION = require('./version');
78455
78456var punycode;
78457try {
78458 punycode = require('punycode');
78459} catch(e) {
78460 console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization");
78461}
78462
78463// From RFC6265 S4.1.1
78464// note that it excludes \x3B ";"
78465var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/;
78466
78467var CONTROL_CHARS = /[\x00-\x1F]/;
78468
78469// From Chromium // '\r', '\n' and '\0' should be treated as a terminator in
78470// the "relaxed" mode, see:
78471// https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#L60
78472var TERMINATORS = ['\n', '\r', '\0'];
78473
78474// RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"'
78475// Note ';' is \x3B
78476var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/;
78477
78478// date-time parsing constants (RFC6265 S5.1.1)
78479
78480var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/;
78481
78482var MONTH_TO_NUM = {
78483 jan:0, feb:1, mar:2, apr:3, may:4, jun:5,
78484 jul:6, aug:7, sep:8, oct:9, nov:10, dec:11
78485};
78486var NUM_TO_MONTH = [
78487 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'
78488];
78489var NUM_TO_DAY = [
78490 'Sun','Mon','Tue','Wed','Thu','Fri','Sat'
78491];
78492
78493var MAX_TIME = 2147483647000; // 31-bit max
78494var MIN_TIME = 0; // 31-bit min
78495
78496/*
78497 * Parses a Natural number (i.e., non-negative integer) with either the
78498 * <min>*<max>DIGIT ( non-digit *OCTET )
78499 * or
78500 * <min>*<max>DIGIT
78501 * grammar (RFC6265 S5.1.1).
78502 *
78503 * The "trailingOK" boolean controls if the grammar accepts a
78504 * "( non-digit *OCTET )" trailer.
78505 */
78506function parseDigits(token, minDigits, maxDigits, trailingOK) {
78507 var count = 0;
78508 while (count < token.length) {
78509 var c = token.charCodeAt(count);
78510 // "non-digit = %x00-2F / %x3A-FF"
78511 if (c <= 0x2F || c >= 0x3A) {
78512 break;
78513 }
78514 count++;
78515 }
78516
78517 // constrain to a minimum and maximum number of digits.
78518 if (count < minDigits || count > maxDigits) {
78519 return null;
78520 }
78521
78522 if (!trailingOK && count != token.length) {
78523 return null;
78524 }
78525
78526 return parseInt(token.substr(0,count), 10);
78527}
78528
78529function parseTime(token) {
78530 var parts = token.split(':');
78531 var result = [0,0,0];
78532
78533 /* RF6256 S5.1.1:
78534 * time = hms-time ( non-digit *OCTET )
78535 * hms-time = time-field ":" time-field ":" time-field
78536 * time-field = 1*2DIGIT
78537 */
78538
78539 if (parts.length !== 3) {
78540 return null;
78541 }
78542
78543 for (var i = 0; i < 3; i++) {
78544 // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be
78545 // followed by "( non-digit *OCTET )" so therefore the last time-field can
78546 // have a trailer
78547 var trailingOK = (i == 2);
78548 var num = parseDigits(parts[i], 1, 2, trailingOK);
78549 if (num === null) {
78550 return null;
78551 }
78552 result[i] = num;
78553 }
78554
78555 return result;
78556}
78557
78558function parseMonth(token) {
78559 token = String(token).substr(0,3).toLowerCase();
78560 var num = MONTH_TO_NUM[token];
78561 return num >= 0 ? num : null;
78562}
78563
78564/*
78565 * RFC6265 S5.1.1 date parser (see RFC for full grammar)
78566 */
78567function parseDate(str) {
78568 if (!str) {
78569 return;
78570 }
78571
78572 /* RFC6265 S5.1.1:
78573 * 2. Process each date-token sequentially in the order the date-tokens
78574 * appear in the cookie-date
78575 */
78576 var tokens = str.split(DATE_DELIM);
78577 if (!tokens) {
78578 return;
78579 }
78580
78581 var hour = null;
78582 var minute = null;
78583 var second = null;
78584 var dayOfMonth = null;
78585 var month = null;
78586 var year = null;
78587
78588 for (var i=0; i<tokens.length; i++) {
78589 var token = tokens[i].trim();
78590 if (!token.length) {
78591 continue;
78592 }
78593
78594 var result;
78595
78596 /* 2.1. If the found-time flag is not set and the token matches the time
78597 * production, set the found-time flag and set the hour- value,
78598 * minute-value, and second-value to the numbers denoted by the digits in
78599 * the date-token, respectively. Skip the remaining sub-steps and continue
78600 * to the next date-token.
78601 */
78602 if (second === null) {
78603 result = parseTime(token);
78604 if (result) {
78605 hour = result[0];
78606 minute = result[1];
78607 second = result[2];
78608 continue;
78609 }
78610 }
78611
78612 /* 2.2. If the found-day-of-month flag is not set and the date-token matches
78613 * the day-of-month production, set the found-day-of- month flag and set
78614 * the day-of-month-value to the number denoted by the date-token. Skip
78615 * the remaining sub-steps and continue to the next date-token.
78616 */
78617 if (dayOfMonth === null) {
78618 // "day-of-month = 1*2DIGIT ( non-digit *OCTET )"
78619 result = parseDigits(token, 1, 2, true);
78620 if (result !== null) {
78621 dayOfMonth = result;
78622 continue;
78623 }
78624 }
78625
78626 /* 2.3. If the found-month flag is not set and the date-token matches the
78627 * month production, set the found-month flag and set the month-value to
78628 * the month denoted by the date-token. Skip the remaining sub-steps and
78629 * continue to the next date-token.
78630 */
78631 if (month === null) {
78632 result = parseMonth(token);
78633 if (result !== null) {
78634 month = result;
78635 continue;
78636 }
78637 }
78638
78639 /* 2.4. If the found-year flag is not set and the date-token matches the
78640 * year production, set the found-year flag and set the year-value to the
78641 * number denoted by the date-token. Skip the remaining sub-steps and
78642 * continue to the next date-token.
78643 */
78644 if (year === null) {
78645 // "year = 2*4DIGIT ( non-digit *OCTET )"
78646 result = parseDigits(token, 2, 4, true);
78647 if (result !== null) {
78648 year = result;
78649 /* From S5.1.1:
78650 * 3. If the year-value is greater than or equal to 70 and less
78651 * than or equal to 99, increment the year-value by 1900.
78652 * 4. If the year-value is greater than or equal to 0 and less
78653 * than or equal to 69, increment the year-value by 2000.
78654 */
78655 if (year >= 70 && year <= 99) {
78656 year += 1900;
78657 } else if (year >= 0 && year <= 69) {
78658 year += 2000;
78659 }
78660 }
78661 }
78662 }
78663
78664 /* RFC 6265 S5.1.1
78665 * "5. Abort these steps and fail to parse the cookie-date if:
78666 * * at least one of the found-day-of-month, found-month, found-
78667 * year, or found-time flags is not set,
78668 * * the day-of-month-value is less than 1 or greater than 31,
78669 * * the year-value is less than 1601,
78670 * * the hour-value is greater than 23,
78671 * * the minute-value is greater than 59, or
78672 * * the second-value is greater than 59.
78673 * (Note that leap seconds cannot be represented in this syntax.)"
78674 *
78675 * So, in order as above:
78676 */
78677 if (
78678 dayOfMonth === null || month === null || year === null || second === null ||
78679 dayOfMonth < 1 || dayOfMonth > 31 ||
78680 year < 1601 ||
78681 hour > 23 ||
78682 minute > 59 ||
78683 second > 59
78684 ) {
78685 return;
78686 }
78687
78688 return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second));
78689}
78690
78691function formatDate(date) {
78692 var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d;
78693 var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h;
78694 var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m;
78695 var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s;
78696 return NUM_TO_DAY[date.getUTCDay()] + ', ' +
78697 d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+
78698 h+':'+m+':'+s+' GMT';
78699}
78700
78701// S5.1.2 Canonicalized Host Names
78702function canonicalDomain(str) {
78703 if (str == null) {
78704 return null;
78705 }
78706 str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading .
78707
78708 // convert to IDN if any non-ASCII characters
78709 if (punycode && /[^\u0001-\u007f]/.test(str)) {
78710 str = punycode.toASCII(str);
78711 }
78712
78713 return str.toLowerCase();
78714}
78715
78716// S5.1.3 Domain Matching
78717function domainMatch(str, domStr, canonicalize) {
78718 if (str == null || domStr == null) {
78719 return null;
78720 }
78721 if (canonicalize !== false) {
78722 str = canonicalDomain(str);
78723 domStr = canonicalDomain(domStr);
78724 }
78725
78726 /*
78727 * "The domain string and the string are identical. (Note that both the
78728 * domain string and the string will have been canonicalized to lower case at
78729 * this point)"
78730 */
78731 if (str == domStr) {
78732 return true;
78733 }
78734
78735 /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */
78736
78737 /* "* The string is a host name (i.e., not an IP address)." */
78738 if (net.isIP(str)) {
78739 return false;
78740 }
78741
78742 /* "* The domain string is a suffix of the string" */
78743 var idx = str.indexOf(domStr);
78744 if (idx <= 0) {
78745 return false; // it's a non-match (-1) or prefix (0)
78746 }
78747
78748 // e.g "a.b.c".indexOf("b.c") === 2
78749 // 5 === 3+2
78750 if (str.length !== domStr.length + idx) { // it's not a suffix
78751 return false;
78752 }
78753
78754 /* "* The last character of the string that is not included in the domain
78755 * string is a %x2E (".") character." */
78756 if (str.substr(idx-1,1) !== '.') {
78757 return false;
78758 }
78759
78760 return true;
78761}
78762
78763
78764// RFC6265 S5.1.4 Paths and Path-Match
78765
78766/*
78767 * "The user agent MUST use an algorithm equivalent to the following algorithm
78768 * to compute the default-path of a cookie:"
78769 *
78770 * Assumption: the path (and not query part or absolute uri) is passed in.
78771 */
78772function defaultPath(path) {
78773 // "2. If the uri-path is empty or if the first character of the uri-path is not
78774 // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps.
78775 if (!path || path.substr(0,1) !== "/") {
78776 return "/";
78777 }
78778
78779 // "3. If the uri-path contains no more than one %x2F ("/") character, output
78780 // %x2F ("/") and skip the remaining step."
78781 if (path === "/") {
78782 return path;
78783 }
78784
78785 var rightSlash = path.lastIndexOf("/");
78786 if (rightSlash === 0) {
78787 return "/";
78788 }
78789
78790 // "4. Output the characters of the uri-path from the first character up to,
78791 // but not including, the right-most %x2F ("/")."
78792 return path.slice(0, rightSlash);
78793}
78794
78795function trimTerminator(str) {
78796 for (var t = 0; t < TERMINATORS.length; t++) {
78797 var terminatorIdx = str.indexOf(TERMINATORS[t]);
78798 if (terminatorIdx !== -1) {
78799 str = str.substr(0,terminatorIdx);
78800 }
78801 }
78802
78803 return str;
78804}
78805
78806function parseCookiePair(cookiePair, looseMode) {
78807 cookiePair = trimTerminator(cookiePair);
78808
78809 var firstEq = cookiePair.indexOf('=');
78810 if (looseMode) {
78811 if (firstEq === 0) { // '=' is immediately at start
78812 cookiePair = cookiePair.substr(1);
78813 firstEq = cookiePair.indexOf('='); // might still need to split on '='
78814 }
78815 } else { // non-loose mode
78816 if (firstEq <= 0) { // no '=' or is at start
78817 return; // needs to have non-empty "cookie-name"
78818 }
78819 }
78820
78821 var cookieName, cookieValue;
78822 if (firstEq <= 0) {
78823 cookieName = "";
78824 cookieValue = cookiePair.trim();
78825 } else {
78826 cookieName = cookiePair.substr(0, firstEq).trim();
78827 cookieValue = cookiePair.substr(firstEq+1).trim();
78828 }
78829
78830 if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) {
78831 return;
78832 }
78833
78834 var c = new Cookie();
78835 c.key = cookieName;
78836 c.value = cookieValue;
78837 return c;
78838}
78839
78840function parse(str, options) {
78841 if (!options || typeof options !== 'object') {
78842 options = {};
78843 }
78844 str = str.trim();
78845
78846 // We use a regex to parse the "name-value-pair" part of S5.2
78847 var firstSemi = str.indexOf(';'); // S5.2 step 1
78848 var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi);
78849 var c = parseCookiePair(cookiePair, !!options.loose);
78850 if (!c) {
78851 return;
78852 }
78853
78854 if (firstSemi === -1) {
78855 return c;
78856 }
78857
78858 // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string
78859 // (including the %x3B (";") in question)." plus later on in the same section
78860 // "discard the first ";" and trim".
78861 var unparsed = str.slice(firstSemi + 1).trim();
78862
78863 // "If the unparsed-attributes string is empty, skip the rest of these
78864 // steps."
78865 if (unparsed.length === 0) {
78866 return c;
78867 }
78868
78869 /*
78870 * S5.2 says that when looping over the items "[p]rocess the attribute-name
78871 * and attribute-value according to the requirements in the following
78872 * subsections" for every item. Plus, for many of the individual attributes
78873 * in S5.3 it says to use the "attribute-value of the last attribute in the
78874 * cookie-attribute-list". Therefore, in this implementation, we overwrite
78875 * the previous value.
78876 */
78877 var cookie_avs = unparsed.split(';');
78878 while (cookie_avs.length) {
78879 var av = cookie_avs.shift().trim();
78880 if (av.length === 0) { // happens if ";;" appears
78881 continue;
78882 }
78883 var av_sep = av.indexOf('=');
78884 var av_key, av_value;
78885
78886 if (av_sep === -1) {
78887 av_key = av;
78888 av_value = null;
78889 } else {
78890 av_key = av.substr(0,av_sep);
78891 av_value = av.substr(av_sep+1);
78892 }
78893
78894 av_key = av_key.trim().toLowerCase();
78895
78896 if (av_value) {
78897 av_value = av_value.trim();
78898 }
78899
78900 switch(av_key) {
78901 case 'expires': // S5.2.1
78902 if (av_value) {
78903 var exp = parseDate(av_value);
78904 // "If the attribute-value failed to parse as a cookie date, ignore the
78905 // cookie-av."
78906 if (exp) {
78907 // over and underflow not realistically a concern: V8's getTime() seems to
78908 // store something larger than a 32-bit time_t (even with 32-bit node)
78909 c.expires = exp;
78910 }
78911 }
78912 break;
78913
78914 case 'max-age': // S5.2.2
78915 if (av_value) {
78916 // "If the first character of the attribute-value is not a DIGIT or a "-"
78917 // character ...[or]... If the remainder of attribute-value contains a
78918 // non-DIGIT character, ignore the cookie-av."
78919 if (/^-?[0-9]+$/.test(av_value)) {
78920 var delta = parseInt(av_value, 10);
78921 // "If delta-seconds is less than or equal to zero (0), let expiry-time
78922 // be the earliest representable date and time."
78923 c.setMaxAge(delta);
78924 }
78925 }
78926 break;
78927
78928 case 'domain': // S5.2.3
78929 // "If the attribute-value is empty, the behavior is undefined. However,
78930 // the user agent SHOULD ignore the cookie-av entirely."
78931 if (av_value) {
78932 // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E
78933 // (".") character."
78934 var domain = av_value.trim().replace(/^\./, '');
78935 if (domain) {
78936 // "Convert the cookie-domain to lower case."
78937 c.domain = domain.toLowerCase();
78938 }
78939 }
78940 break;
78941
78942 case 'path': // S5.2.4
78943 /*
78944 * "If the attribute-value is empty or if the first character of the
78945 * attribute-value is not %x2F ("/"):
78946 * Let cookie-path be the default-path.
78947 * Otherwise:
78948 * Let cookie-path be the attribute-value."
78949 *
78950 * We'll represent the default-path as null since it depends on the
78951 * context of the parsing.
78952 */
78953 c.path = av_value && av_value[0] === "/" ? av_value : null;
78954 break;
78955
78956 case 'secure': // S5.2.5
78957 /*
78958 * "If the attribute-name case-insensitively matches the string "Secure",
78959 * the user agent MUST append an attribute to the cookie-attribute-list
78960 * with an attribute-name of Secure and an empty attribute-value."
78961 */
78962 c.secure = true;
78963 break;
78964
78965 case 'httponly': // S5.2.6 -- effectively the same as 'secure'
78966 c.httpOnly = true;
78967 break;
78968
78969 default:
78970 c.extensions = c.extensions || [];
78971 c.extensions.push(av);
78972 break;
78973 }
78974 }
78975
78976 return c;
78977}
78978
78979// avoid the V8 deoptimization monster!
78980function jsonParse(str) {
78981 var obj;
78982 try {
78983 obj = JSON.parse(str);
78984 } catch (e) {
78985 return e;
78986 }
78987 return obj;
78988}
78989
78990function fromJSON(str) {
78991 if (!str) {
78992 return null;
78993 }
78994
78995 var obj;
78996 if (typeof str === 'string') {
78997 obj = jsonParse(str);
78998 if (obj instanceof Error) {
78999 return null;
79000 }
79001 } else {
79002 // assume it's an Object
79003 obj = str;
79004 }
79005
79006 var c = new Cookie();
79007 for (var i=0; i<Cookie.serializableProperties.length; i++) {
79008 var prop = Cookie.serializableProperties[i];
79009 if (obj[prop] === undefined ||
79010 obj[prop] === Cookie.prototype[prop])
79011 {
79012 continue; // leave as prototype default
79013 }
79014
79015 if (prop === 'expires' ||
79016 prop === 'creation' ||
79017 prop === 'lastAccessed')
79018 {
79019 if (obj[prop] === null) {
79020 c[prop] = null;
79021 } else {
79022 c[prop] = obj[prop] == "Infinity" ?
79023 "Infinity" : new Date(obj[prop]);
79024 }
79025 } else {
79026 c[prop] = obj[prop];
79027 }
79028 }
79029
79030 return c;
79031}
79032
79033/* Section 5.4 part 2:
79034 * "* Cookies with longer paths are listed before cookies with
79035 * shorter paths.
79036 *
79037 * * Among cookies that have equal-length path fields, cookies with
79038 * earlier creation-times are listed before cookies with later
79039 * creation-times."
79040 */
79041
79042function cookieCompare(a,b) {
79043 var cmp = 0;
79044
79045 // descending for length: b CMP a
79046 var aPathLen = a.path ? a.path.length : 0;
79047 var bPathLen = b.path ? b.path.length : 0;
79048 cmp = bPathLen - aPathLen;
79049 if (cmp !== 0) {
79050 return cmp;
79051 }
79052
79053 // ascending for time: a CMP b
79054 var aTime = a.creation ? a.creation.getTime() : MAX_TIME;
79055 var bTime = b.creation ? b.creation.getTime() : MAX_TIME;
79056 cmp = aTime - bTime;
79057 if (cmp !== 0) {
79058 return cmp;
79059 }
79060
79061 // break ties for the same millisecond (precision of JavaScript's clock)
79062 cmp = a.creationIndex - b.creationIndex;
79063
79064 return cmp;
79065}
79066
79067// Gives the permutation of all possible pathMatch()es of a given path. The
79068// array is in longest-to-shortest order. Handy for indexing.
79069function permutePath(path) {
79070 if (path === '/') {
79071 return ['/'];
79072 }
79073 if (path.lastIndexOf('/') === path.length-1) {
79074 path = path.substr(0,path.length-1);
79075 }
79076 var permutations = [path];
79077 while (path.length > 1) {
79078 var lindex = path.lastIndexOf('/');
79079 if (lindex === 0) {
79080 break;
79081 }
79082 path = path.substr(0,lindex);
79083 permutations.push(path);
79084 }
79085 permutations.push('/');
79086 return permutations;
79087}
79088
79089function getCookieContext(url) {
79090 if (url instanceof Object) {
79091 return url;
79092 }
79093 // NOTE: decodeURI will throw on malformed URIs (see GH-32).
79094 // Therefore, we will just skip decoding for such URIs.
79095 try {
79096 url = decodeURI(url);
79097 }
79098 catch(err) {
79099 // Silently swallow error
79100 }
79101
79102 return urlParse(url);
79103}
79104
79105function Cookie(options) {
79106 options = options || {};
79107
79108 Object.keys(options).forEach(function(prop) {
79109 if (Cookie.prototype.hasOwnProperty(prop) &&
79110 Cookie.prototype[prop] !== options[prop] &&
79111 prop.substr(0,1) !== '_')
79112 {
79113 this[prop] = options[prop];
79114 }
79115 }, this);
79116
79117 this.creation = this.creation || new Date();
79118
79119 // used to break creation ties in cookieCompare():
79120 Object.defineProperty(this, 'creationIndex', {
79121 configurable: false,
79122 enumerable: false, // important for assert.deepEqual checks
79123 writable: true,
79124 value: ++Cookie.cookiesCreated
79125 });
79126}
79127
79128Cookie.cookiesCreated = 0; // incremented each time a cookie is created
79129
79130Cookie.parse = parse;
79131Cookie.fromJSON = fromJSON;
79132
79133Cookie.prototype.key = "";
79134Cookie.prototype.value = "";
79135
79136// the order in which the RFC has them:
79137Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity
79138Cookie.prototype.maxAge = null; // takes precedence over expires for TTL
79139Cookie.prototype.domain = null;
79140Cookie.prototype.path = null;
79141Cookie.prototype.secure = false;
79142Cookie.prototype.httpOnly = false;
79143Cookie.prototype.extensions = null;
79144
79145// set by the CookieJar:
79146Cookie.prototype.hostOnly = null; // boolean when set
79147Cookie.prototype.pathIsDefault = null; // boolean when set
79148Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse
79149Cookie.prototype.lastAccessed = null; // Date when set
79150Object.defineProperty(Cookie.prototype, 'creationIndex', {
79151 configurable: true,
79152 enumerable: false,
79153 writable: true,
79154 value: 0
79155});
79156
79157Cookie.serializableProperties = Object.keys(Cookie.prototype)
79158 .filter(function(prop) {
79159 return !(
79160 Cookie.prototype[prop] instanceof Function ||
79161 prop === 'creationIndex' ||
79162 prop.substr(0,1) === '_'
79163 );
79164 });
79165
79166Cookie.prototype.inspect = function inspect() {
79167 var now = Date.now();
79168 return 'Cookie="'+this.toString() +
79169 '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') +
79170 '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') +
79171 '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') +
79172 '"';
79173};
79174
79175// Use the new custom inspection symbol to add the custom inspect function if
79176// available.
79177if (util.inspect.custom) {
79178 Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect;
79179}
79180
79181Cookie.prototype.toJSON = function() {
79182 var obj = {};
79183
79184 var props = Cookie.serializableProperties;
79185 for (var i=0; i<props.length; i++) {
79186 var prop = props[i];
79187 if (this[prop] === Cookie.prototype[prop]) {
79188 continue; // leave as prototype default
79189 }
79190
79191 if (prop === 'expires' ||
79192 prop === 'creation' ||
79193 prop === 'lastAccessed')
79194 {
79195 if (this[prop] === null) {
79196 obj[prop] = null;
79197 } else {
79198 obj[prop] = this[prop] == "Infinity" ? // intentionally not ===
79199 "Infinity" : this[prop].toISOString();
79200 }
79201 } else if (prop === 'maxAge') {
79202 if (this[prop] !== null) {
79203 // again, intentionally not ===
79204 obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ?
79205 this[prop].toString() : this[prop];
79206 }
79207 } else {
79208 if (this[prop] !== Cookie.prototype[prop]) {
79209 obj[prop] = this[prop];
79210 }
79211 }
79212 }
79213
79214 return obj;
79215};
79216
79217Cookie.prototype.clone = function() {
79218 return fromJSON(this.toJSON());
79219};
79220
79221Cookie.prototype.validate = function validate() {
79222 if (!COOKIE_OCTETS.test(this.value)) {
79223 return false;
79224 }
79225 if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) {
79226 return false;
79227 }
79228 if (this.maxAge != null && this.maxAge <= 0) {
79229 return false; // "Max-Age=" non-zero-digit *DIGIT
79230 }
79231 if (this.path != null && !PATH_VALUE.test(this.path)) {
79232 return false;
79233 }
79234
79235 var cdomain = this.cdomain();
79236 if (cdomain) {
79237 if (cdomain.match(/\.$/)) {
79238 return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this
79239 }
79240 var suffix = pubsuffix.getPublicSuffix(cdomain);
79241 if (suffix == null) { // it's a public suffix
79242 return false;
79243 }
79244 }
79245 return true;
79246};
79247
79248Cookie.prototype.setExpires = function setExpires(exp) {
79249 if (exp instanceof Date) {
79250 this.expires = exp;
79251 } else {
79252 this.expires = parseDate(exp) || "Infinity";
79253 }
79254};
79255
79256Cookie.prototype.setMaxAge = function setMaxAge(age) {
79257 if (age === Infinity || age === -Infinity) {
79258 this.maxAge = age.toString(); // so JSON.stringify() works
79259 } else {
79260 this.maxAge = age;
79261 }
79262};
79263
79264// gives Cookie header format
79265Cookie.prototype.cookieString = function cookieString() {
79266 var val = this.value;
79267 if (val == null) {
79268 val = '';
79269 }
79270 if (this.key === '') {
79271 return val;
79272 }
79273 return this.key+'='+val;
79274};
79275
79276// gives Set-Cookie header format
79277Cookie.prototype.toString = function toString() {
79278 var str = this.cookieString();
79279
79280 if (this.expires != Infinity) {
79281 if (this.expires instanceof Date) {
79282 str += '; Expires='+formatDate(this.expires);
79283 } else {
79284 str += '; Expires='+this.expires;
79285 }
79286 }
79287
79288 if (this.maxAge != null && this.maxAge != Infinity) {
79289 str += '; Max-Age='+this.maxAge;
79290 }
79291
79292 if (this.domain && !this.hostOnly) {
79293 str += '; Domain='+this.domain;
79294 }
79295 if (this.path) {
79296 str += '; Path='+this.path;
79297 }
79298
79299 if (this.secure) {
79300 str += '; Secure';
79301 }
79302 if (this.httpOnly) {
79303 str += '; HttpOnly';
79304 }
79305 if (this.extensions) {
79306 this.extensions.forEach(function(ext) {
79307 str += '; '+ext;
79308 });
79309 }
79310
79311 return str;
79312};
79313
79314// TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
79315// elsewhere)
79316// S5.3 says to give the "latest representable date" for which we use Infinity
79317// For "expired" we use 0
79318Cookie.prototype.TTL = function TTL(now) {
79319 /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires
79320 * attribute, the Max-Age attribute has precedence and controls the
79321 * expiration date of the cookie.
79322 * (Concurs with S5.3 step 3)
79323 */
79324 if (this.maxAge != null) {
79325 return this.maxAge<=0 ? 0 : this.maxAge*1000;
79326 }
79327
79328 var expires = this.expires;
79329 if (expires != Infinity) {
79330 if (!(expires instanceof Date)) {
79331 expires = parseDate(expires) || Infinity;
79332 }
79333
79334 if (expires == Infinity) {
79335 return Infinity;
79336 }
79337
79338 return expires.getTime() - (now || Date.now());
79339 }
79340
79341 return Infinity;
79342};
79343
79344// expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
79345// elsewhere)
79346Cookie.prototype.expiryTime = function expiryTime(now) {
79347 if (this.maxAge != null) {
79348 var relativeTo = now || this.creation || new Date();
79349 var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000;
79350 return relativeTo.getTime() + age;
79351 }
79352
79353 if (this.expires == Infinity) {
79354 return Infinity;
79355 }
79356 return this.expires.getTime();
79357};
79358
79359// expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie()
79360// elsewhere), except it returns a Date
79361Cookie.prototype.expiryDate = function expiryDate(now) {
79362 var millisec = this.expiryTime(now);
79363 if (millisec == Infinity) {
79364 return new Date(MAX_TIME);
79365 } else if (millisec == -Infinity) {
79366 return new Date(MIN_TIME);
79367 } else {
79368 return new Date(millisec);
79369 }
79370};
79371
79372// This replaces the "persistent-flag" parts of S5.3 step 3
79373Cookie.prototype.isPersistent = function isPersistent() {
79374 return (this.maxAge != null || this.expires != Infinity);
79375};
79376
79377// Mostly S5.1.2 and S5.2.3:
79378Cookie.prototype.cdomain =
79379Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() {
79380 if (this.domain == null) {
79381 return null;
79382 }
79383 return canonicalDomain(this.domain);
79384};
79385
79386function CookieJar(store, options) {
79387 if (typeof options === "boolean") {
79388 options = {rejectPublicSuffixes: options};
79389 } else if (options == null) {
79390 options = {};
79391 }
79392 if (options.rejectPublicSuffixes != null) {
79393 this.rejectPublicSuffixes = options.rejectPublicSuffixes;
79394 }
79395 if (options.looseMode != null) {
79396 this.enableLooseMode = options.looseMode;
79397 }
79398
79399 if (!store) {
79400 store = new MemoryCookieStore();
79401 }
79402 this.store = store;
79403}
79404CookieJar.prototype.store = null;
79405CookieJar.prototype.rejectPublicSuffixes = true;
79406CookieJar.prototype.enableLooseMode = false;
79407var CAN_BE_SYNC = [];
79408
79409CAN_BE_SYNC.push('setCookie');
79410CookieJar.prototype.setCookie = function(cookie, url, options, cb) {
79411 var err;
79412 var context = getCookieContext(url);
79413 if (options instanceof Function) {
79414 cb = options;
79415 options = {};
79416 }
79417
79418 var host = canonicalDomain(context.hostname);
79419 var loose = this.enableLooseMode;
79420 if (options.loose != null) {
79421 loose = options.loose;
79422 }
79423
79424 // S5.3 step 1
79425 if (!(cookie instanceof Cookie)) {
79426 cookie = Cookie.parse(cookie, { loose: loose });
79427 }
79428 if (!cookie) {
79429 err = new Error("Cookie failed to parse");
79430 return cb(options.ignoreError ? null : err);
79431 }
79432
79433 // S5.3 step 2
79434 var now = options.now || new Date(); // will assign later to save effort in the face of errors
79435
79436 // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie()
79437
79438 // S5.3 step 4: NOOP; domain is null by default
79439
79440 // S5.3 step 5: public suffixes
79441 if (this.rejectPublicSuffixes && cookie.domain) {
79442 var suffix = pubsuffix.getPublicSuffix(cookie.cdomain());
79443 if (suffix == null) { // e.g. "com"
79444 err = new Error("Cookie has domain set to a public suffix");
79445 return cb(options.ignoreError ? null : err);
79446 }
79447 }
79448
79449 // S5.3 step 6:
79450 if (cookie.domain) {
79451 if (!domainMatch(host, cookie.cdomain(), false)) {
79452 err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host);
79453 return cb(options.ignoreError ? null : err);
79454 }
79455
79456 if (cookie.hostOnly == null) { // don't reset if already set
79457 cookie.hostOnly = false;
79458 }
79459
79460 } else {
79461 cookie.hostOnly = true;
79462 cookie.domain = host;
79463 }
79464
79465 //S5.2.4 If the attribute-value is empty or if the first character of the
79466 //attribute-value is not %x2F ("/"):
79467 //Let cookie-path be the default-path.
79468 if (!cookie.path || cookie.path[0] !== '/') {
79469 cookie.path = defaultPath(context.pathname);
79470 cookie.pathIsDefault = true;
79471 }
79472
79473 // S5.3 step 8: NOOP; secure attribute
79474 // S5.3 step 9: NOOP; httpOnly attribute
79475
79476 // S5.3 step 10
79477 if (options.http === false && cookie.httpOnly) {
79478 err = new Error("Cookie is HttpOnly and this isn't an HTTP API");
79479 return cb(options.ignoreError ? null : err);
79480 }
79481
79482 var store = this.store;
79483
79484 if (!store.updateCookie) {
79485 store.updateCookie = function(oldCookie, newCookie, cb) {
79486 this.putCookie(newCookie, cb);
79487 };
79488 }
79489
79490 function withCookie(err, oldCookie) {
79491 if (err) {
79492 return cb(err);
79493 }
79494
79495 var next = function(err) {
79496 if (err) {
79497 return cb(err);
79498 } else {
79499 cb(null, cookie);
79500 }
79501 };
79502
79503 if (oldCookie) {
79504 // S5.3 step 11 - "If the cookie store contains a cookie with the same name,
79505 // domain, and path as the newly created cookie:"
79506 if (options.http === false && oldCookie.httpOnly) { // step 11.2
79507 err = new Error("old Cookie is HttpOnly and this isn't an HTTP API");
79508 return cb(options.ignoreError ? null : err);
79509 }
79510 cookie.creation = oldCookie.creation; // step 11.3
79511 cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker
79512 cookie.lastAccessed = now;
79513 // Step 11.4 (delete cookie) is implied by just setting the new one:
79514 store.updateCookie(oldCookie, cookie, next); // step 12
79515
79516 } else {
79517 cookie.creation = cookie.lastAccessed = now;
79518 store.putCookie(cookie, next); // step 12
79519 }
79520 }
79521
79522 store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie);
79523};
79524
79525// RFC6365 S5.4
79526CAN_BE_SYNC.push('getCookies');
79527CookieJar.prototype.getCookies = function(url, options, cb) {
79528 var context = getCookieContext(url);
79529 if (options instanceof Function) {
79530 cb = options;
79531 options = {};
79532 }
79533
79534 var host = canonicalDomain(context.hostname);
79535 var path = context.pathname || '/';
79536
79537 var secure = options.secure;
79538 if (secure == null && context.protocol &&
79539 (context.protocol == 'https:' || context.protocol == 'wss:'))
79540 {
79541 secure = true;
79542 }
79543
79544 var http = options.http;
79545 if (http == null) {
79546 http = true;
79547 }
79548
79549 var now = options.now || Date.now();
79550 var expireCheck = options.expire !== false;
79551 var allPaths = !!options.allPaths;
79552 var store = this.store;
79553
79554 function matchingCookie(c) {
79555 // "Either:
79556 // The cookie's host-only-flag is true and the canonicalized
79557 // request-host is identical to the cookie's domain.
79558 // Or:
79559 // The cookie's host-only-flag is false and the canonicalized
79560 // request-host domain-matches the cookie's domain."
79561 if (c.hostOnly) {
79562 if (c.domain != host) {
79563 return false;
79564 }
79565 } else {
79566 if (!domainMatch(host, c.domain, false)) {
79567 return false;
79568 }
79569 }
79570
79571 // "The request-uri's path path-matches the cookie's path."
79572 if (!allPaths && !pathMatch(path, c.path)) {
79573 return false;
79574 }
79575
79576 // "If the cookie's secure-only-flag is true, then the request-uri's
79577 // scheme must denote a "secure" protocol"
79578 if (c.secure && !secure) {
79579 return false;
79580 }
79581
79582 // "If the cookie's http-only-flag is true, then exclude the cookie if the
79583 // cookie-string is being generated for a "non-HTTP" API"
79584 if (c.httpOnly && !http) {
79585 return false;
79586 }
79587
79588 // deferred from S5.3
79589 // non-RFC: allow retention of expired cookies by choice
79590 if (expireCheck && c.expiryTime() <= now) {
79591 store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored
79592 return false;
79593 }
79594
79595 return true;
79596 }
79597
79598 store.findCookies(host, allPaths ? null : path, function(err,cookies) {
79599 if (err) {
79600 return cb(err);
79601 }
79602
79603 cookies = cookies.filter(matchingCookie);
79604
79605 // sorting of S5.4 part 2
79606 if (options.sort !== false) {
79607 cookies = cookies.sort(cookieCompare);
79608 }
79609
79610 // S5.4 part 3
79611 var now = new Date();
79612 cookies.forEach(function(c) {
79613 c.lastAccessed = now;
79614 });
79615 // TODO persist lastAccessed
79616
79617 cb(null,cookies);
79618 });
79619};
79620
79621CAN_BE_SYNC.push('getCookieString');
79622CookieJar.prototype.getCookieString = function(/*..., cb*/) {
79623 var args = Array.prototype.slice.call(arguments,0);
79624 var cb = args.pop();
79625 var next = function(err,cookies) {
79626 if (err) {
79627 cb(err);
79628 } else {
79629 cb(null, cookies
79630 .sort(cookieCompare)
79631 .map(function(c){
79632 return c.cookieString();
79633 })
79634 .join('; '));
79635 }
79636 };
79637 args.push(next);
79638 this.getCookies.apply(this,args);
79639};
79640
79641CAN_BE_SYNC.push('getSetCookieStrings');
79642CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) {
79643 var args = Array.prototype.slice.call(arguments,0);
79644 var cb = args.pop();
79645 var next = function(err,cookies) {
79646 if (err) {
79647 cb(err);
79648 } else {
79649 cb(null, cookies.map(function(c){
79650 return c.toString();
79651 }));
79652 }
79653 };
79654 args.push(next);
79655 this.getCookies.apply(this,args);
79656};
79657
79658CAN_BE_SYNC.push('serialize');
79659CookieJar.prototype.serialize = function(cb) {
79660 var type = this.store.constructor.name;
79661 if (type === 'Object') {
79662 type = null;
79663 }
79664
79665 // update README.md "Serialization Format" if you change this, please!
79666 var serialized = {
79667 // The version of tough-cookie that serialized this jar. Generally a good
79668 // practice since future versions can make data import decisions based on
79669 // known past behavior. When/if this matters, use `semver`.
79670 version: 'tough-cookie@'+VERSION,
79671
79672 // add the store type, to make humans happy:
79673 storeType: type,
79674
79675 // CookieJar configuration:
79676 rejectPublicSuffixes: !!this.rejectPublicSuffixes,
79677
79678 // this gets filled from getAllCookies:
79679 cookies: []
79680 };
79681
79682 if (!(this.store.getAllCookies &&
79683 typeof this.store.getAllCookies === 'function'))
79684 {
79685 return cb(new Error('store does not support getAllCookies and cannot be serialized'));
79686 }
79687
79688 this.store.getAllCookies(function(err,cookies) {
79689 if (err) {
79690 return cb(err);
79691 }
79692
79693 serialized.cookies = cookies.map(function(cookie) {
79694 // convert to serialized 'raw' cookies
79695 cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie;
79696
79697 // Remove the index so new ones get assigned during deserialization
79698 delete cookie.creationIndex;
79699
79700 return cookie;
79701 });
79702
79703 return cb(null, serialized);
79704 });
79705};
79706
79707// well-known name that JSON.stringify calls
79708CookieJar.prototype.toJSON = function() {
79709 return this.serializeSync();
79710};
79711
79712// use the class method CookieJar.deserialize instead of calling this directly
79713CAN_BE_SYNC.push('_importCookies');
79714CookieJar.prototype._importCookies = function(serialized, cb) {
79715 var jar = this;
79716 var cookies = serialized.cookies;
79717 if (!cookies || !Array.isArray(cookies)) {
79718 return cb(new Error('serialized jar has no cookies array'));
79719 }
79720 cookies = cookies.slice(); // do not modify the original
79721
79722 function putNext(err) {
79723 if (err) {
79724 return cb(err);
79725 }
79726
79727 if (!cookies.length) {
79728 return cb(err, jar);
79729 }
79730
79731 var cookie;
79732 try {
79733 cookie = fromJSON(cookies.shift());
79734 } catch (e) {
79735 return cb(e);
79736 }
79737
79738 if (cookie === null) {
79739 return putNext(null); // skip this cookie
79740 }
79741
79742 jar.store.putCookie(cookie, putNext);
79743 }
79744
79745 putNext();
79746};
79747
79748CookieJar.deserialize = function(strOrObj, store, cb) {
79749 if (arguments.length !== 3) {
79750 // store is optional
79751 cb = store;
79752 store = null;
79753 }
79754
79755 var serialized;
79756 if (typeof strOrObj === 'string') {
79757 serialized = jsonParse(strOrObj);
79758 if (serialized instanceof Error) {
79759 return cb(serialized);
79760 }
79761 } else {
79762 serialized = strOrObj;
79763 }
79764
79765 var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
79766 jar._importCookies(serialized, function(err) {
79767 if (err) {
79768 return cb(err);
79769 }
79770 cb(null, jar);
79771 });
79772};
79773
79774CookieJar.deserializeSync = function(strOrObj, store) {
79775 var serialized = typeof strOrObj === 'string' ?
79776 JSON.parse(strOrObj) : strOrObj;
79777 var jar = new CookieJar(store, serialized.rejectPublicSuffixes);
79778
79779 // catch this mistake early:
79780 if (!jar.store.synchronous) {
79781 throw new Error('CookieJar store is not synchronous; use async API instead.');
79782 }
79783
79784 jar._importCookiesSync(serialized);
79785 return jar;
79786};
79787CookieJar.fromJSON = CookieJar.deserializeSync;
79788
79789CookieJar.prototype.clone = function(newStore, cb) {
79790 if (arguments.length === 1) {
79791 cb = newStore;
79792 newStore = null;
79793 }
79794
79795 this.serialize(function(err,serialized) {
79796 if (err) {
79797 return cb(err);
79798 }
79799 CookieJar.deserialize(serialized, newStore, cb);
79800 });
79801};
79802
79803CAN_BE_SYNC.push('removeAllCookies');
79804CookieJar.prototype.removeAllCookies = function(cb) {
79805 var store = this.store;
79806
79807 // Check that the store implements its own removeAllCookies(). The default
79808 // implementation in Store will immediately call the callback with a "not
79809 // implemented" Error.
79810 if (store.removeAllCookies instanceof Function &&
79811 store.removeAllCookies !== Store.prototype.removeAllCookies)
79812 {
79813 return store.removeAllCookies(cb);
79814 }
79815
79816 store.getAllCookies(function(err, cookies) {
79817 if (err) {
79818 return cb(err);
79819 }
79820
79821 if (cookies.length === 0) {
79822 return cb(null);
79823 }
79824
79825 var completedCount = 0;
79826 var removeErrors = [];
79827
79828 function removeCookieCb(removeErr) {
79829 if (removeErr) {
79830 removeErrors.push(removeErr);
79831 }
79832
79833 completedCount++;
79834
79835 if (completedCount === cookies.length) {
79836 return cb(removeErrors.length ? removeErrors[0] : null);
79837 }
79838 }
79839
79840 cookies.forEach(function(cookie) {
79841 store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb);
79842 });
79843 });
79844};
79845
79846CookieJar.prototype._cloneSync = syncWrap('clone');
79847CookieJar.prototype.cloneSync = function(newStore) {
79848 if (!newStore.synchronous) {
79849 throw new Error('CookieJar clone destination store is not synchronous; use async API instead.');
79850 }
79851 return this._cloneSync(newStore);
79852};
79853
79854// Use a closure to provide a true imperative API for synchronous stores.
79855function syncWrap(method) {
79856 return function() {
79857 if (!this.store.synchronous) {
79858 throw new Error('CookieJar store is not synchronous; use async API instead.');
79859 }
79860
79861 var args = Array.prototype.slice.call(arguments);
79862 var syncErr, syncResult;
79863 args.push(function syncCb(err, result) {
79864 syncErr = err;
79865 syncResult = result;
79866 });
79867 this[method].apply(this, args);
79868
79869 if (syncErr) {
79870 throw syncErr;
79871 }
79872 return syncResult;
79873 };
79874}
79875
79876// wrap all declared CAN_BE_SYNC methods in the sync wrapper
79877CAN_BE_SYNC.forEach(function(method) {
79878 CookieJar.prototype[method+'Sync'] = syncWrap(method);
79879});
79880
79881exports.version = VERSION;
79882exports.CookieJar = CookieJar;
79883exports.Cookie = Cookie;
79884exports.Store = Store;
79885exports.MemoryCookieStore = MemoryCookieStore;
79886exports.parseDate = parseDate;
79887exports.formatDate = formatDate;
79888exports.parse = parse;
79889exports.fromJSON = fromJSON;
79890exports.domainMatch = domainMatch;
79891exports.defaultPath = defaultPath;
79892exports.pathMatch = pathMatch;
79893exports.getPublicSuffix = pubsuffix.getPublicSuffix;
79894exports.cookieCompare = cookieCompare;
79895exports.permuteDomain = require('./permuteDomain').permuteDomain;
79896exports.permutePath = permutePath;
79897exports.canonicalDomain = canonicalDomain;
79898
79899},{"./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){
79900/*!
79901 * Copyright (c) 2015, Salesforce.com, Inc.
79902 * All rights reserved.
79903 *
79904 * Redistribution and use in source and binary forms, with or without
79905 * modification, are permitted provided that the following conditions are met:
79906 *
79907 * 1. Redistributions of source code must retain the above copyright notice,
79908 * this list of conditions and the following disclaimer.
79909 *
79910 * 2. Redistributions in binary form must reproduce the above copyright notice,
79911 * this list of conditions and the following disclaimer in the documentation
79912 * and/or other materials provided with the distribution.
79913 *
79914 * 3. Neither the name of Salesforce.com nor the names of its contributors may
79915 * be used to endorse or promote products derived from this software without
79916 * specific prior written permission.
79917 *
79918 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
79919 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
79920 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79921 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
79922 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
79923 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
79924 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
79925 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
79926 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
79927 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
79928 * POSSIBILITY OF SUCH DAMAGE.
79929 */
79930'use strict';
79931var Store = require('./store').Store;
79932var permuteDomain = require('./permuteDomain').permuteDomain;
79933var pathMatch = require('./pathMatch').pathMatch;
79934var util = require('util');
79935
79936function MemoryCookieStore() {
79937 Store.call(this);
79938 this.idx = {};
79939}
79940util.inherits(MemoryCookieStore, Store);
79941exports.MemoryCookieStore = MemoryCookieStore;
79942MemoryCookieStore.prototype.idx = null;
79943
79944// Since it's just a struct in RAM, this Store is synchronous
79945MemoryCookieStore.prototype.synchronous = true;
79946
79947// force a default depth:
79948MemoryCookieStore.prototype.inspect = function() {
79949 return "{ idx: "+util.inspect(this.idx, false, 2)+' }';
79950};
79951
79952// Use the new custom inspection symbol to add the custom inspect function if
79953// available.
79954if (util.inspect.custom) {
79955 MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect;
79956}
79957
79958MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) {
79959 if (!this.idx[domain]) {
79960 return cb(null,undefined);
79961 }
79962 if (!this.idx[domain][path]) {
79963 return cb(null,undefined);
79964 }
79965 return cb(null,this.idx[domain][path][key]||null);
79966};
79967
79968MemoryCookieStore.prototype.findCookies = function(domain, path, cb) {
79969 var results = [];
79970 if (!domain) {
79971 return cb(null,[]);
79972 }
79973
79974 var pathMatcher;
79975 if (!path) {
79976 // null means "all paths"
79977 pathMatcher = function matchAll(domainIndex) {
79978 for (var curPath in domainIndex) {
79979 var pathIndex = domainIndex[curPath];
79980 for (var key in pathIndex) {
79981 results.push(pathIndex[key]);
79982 }
79983 }
79984 };
79985
79986 } else {
79987 pathMatcher = function matchRFC(domainIndex) {
79988 //NOTE: we should use path-match algorithm from S5.1.4 here
79989 //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299)
79990 Object.keys(domainIndex).forEach(function (cookiePath) {
79991 if (pathMatch(path, cookiePath)) {
79992 var pathIndex = domainIndex[cookiePath];
79993
79994 for (var key in pathIndex) {
79995 results.push(pathIndex[key]);
79996 }
79997 }
79998 });
79999 };
80000 }
80001
80002 var domains = permuteDomain(domain) || [domain];
80003 var idx = this.idx;
80004 domains.forEach(function(curDomain) {
80005 var domainIndex = idx[curDomain];
80006 if (!domainIndex) {
80007 return;
80008 }
80009 pathMatcher(domainIndex);
80010 });
80011
80012 cb(null,results);
80013};
80014
80015MemoryCookieStore.prototype.putCookie = function(cookie, cb) {
80016 if (!this.idx[cookie.domain]) {
80017 this.idx[cookie.domain] = {};
80018 }
80019 if (!this.idx[cookie.domain][cookie.path]) {
80020 this.idx[cookie.domain][cookie.path] = {};
80021 }
80022 this.idx[cookie.domain][cookie.path][cookie.key] = cookie;
80023 cb(null);
80024};
80025
80026MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) {
80027 // updateCookie() may avoid updating cookies that are identical. For example,
80028 // lastAccessed may not be important to some stores and an equality
80029 // comparison could exclude that field.
80030 this.putCookie(newCookie,cb);
80031};
80032
80033MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) {
80034 if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) {
80035 delete this.idx[domain][path][key];
80036 }
80037 cb(null);
80038};
80039
80040MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) {
80041 if (this.idx[domain]) {
80042 if (path) {
80043 delete this.idx[domain][path];
80044 } else {
80045 delete this.idx[domain];
80046 }
80047 }
80048 return cb(null);
80049};
80050
80051MemoryCookieStore.prototype.removeAllCookies = function(cb) {
80052 this.idx = {};
80053 return cb(null);
80054}
80055
80056MemoryCookieStore.prototype.getAllCookies = function(cb) {
80057 var cookies = [];
80058 var idx = this.idx;
80059
80060 var domains = Object.keys(idx);
80061 domains.forEach(function(domain) {
80062 var paths = Object.keys(idx[domain]);
80063 paths.forEach(function(path) {
80064 var keys = Object.keys(idx[domain][path]);
80065 keys.forEach(function(key) {
80066 if (key !== null) {
80067 cookies.push(idx[domain][path][key]);
80068 }
80069 });
80070 });
80071 });
80072
80073 // Sort by creationIndex so deserializing retains the creation order.
80074 // When implementing your own store, this SHOULD retain the order too
80075 cookies.sort(function(a,b) {
80076 return (a.creationIndex||0) - (b.creationIndex||0);
80077 });
80078
80079 cb(null, cookies);
80080};
80081
80082},{"./pathMatch":385,"./permuteDomain":386,"./store":388,"util":397}],385:[function(require,module,exports){
80083arguments[4][318][0].apply(exports,arguments)
80084},{"dup":318}],386:[function(require,module,exports){
80085arguments[4][319][0].apply(exports,arguments)
80086},{"./pubsuffix-psl":387,"dup":319}],387:[function(require,module,exports){
80087arguments[4][320][0].apply(exports,arguments)
80088},{"dup":320,"psl":267}],388:[function(require,module,exports){
80089/*!
80090 * Copyright (c) 2015, Salesforce.com, Inc.
80091 * All rights reserved.
80092 *
80093 * Redistribution and use in source and binary forms, with or without
80094 * modification, are permitted provided that the following conditions are met:
80095 *
80096 * 1. Redistributions of source code must retain the above copyright notice,
80097 * this list of conditions and the following disclaimer.
80098 *
80099 * 2. Redistributions in binary form must reproduce the above copyright notice,
80100 * this list of conditions and the following disclaimer in the documentation
80101 * and/or other materials provided with the distribution.
80102 *
80103 * 3. Neither the name of Salesforce.com nor the names of its contributors may
80104 * be used to endorse or promote products derived from this software without
80105 * specific prior written permission.
80106 *
80107 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
80108 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80109 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
80110 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
80111 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
80112 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
80113 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
80114 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
80115 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
80116 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
80117 * POSSIBILITY OF SUCH DAMAGE.
80118 */
80119'use strict';
80120/*jshint unused:false */
80121
80122function Store() {
80123}
80124exports.Store = Store;
80125
80126// Stores may be synchronous, but are still required to use a
80127// Continuation-Passing Style API. The CookieJar itself will expose a "*Sync"
80128// API that converts from synchronous-callbacks to imperative style.
80129Store.prototype.synchronous = false;
80130
80131Store.prototype.findCookie = function(domain, path, key, cb) {
80132 throw new Error('findCookie is not implemented');
80133};
80134
80135Store.prototype.findCookies = function(domain, path, cb) {
80136 throw new Error('findCookies is not implemented');
80137};
80138
80139Store.prototype.putCookie = function(cookie, cb) {
80140 throw new Error('putCookie is not implemented');
80141};
80142
80143Store.prototype.updateCookie = function(oldCookie, newCookie, cb) {
80144 // recommended default implementation:
80145 // return this.putCookie(newCookie, cb);
80146 throw new Error('updateCookie is not implemented');
80147};
80148
80149Store.prototype.removeCookie = function(domain, path, key, cb) {
80150 throw new Error('removeCookie is not implemented');
80151};
80152
80153Store.prototype.removeCookies = function(domain, path, cb) {
80154 throw new Error('removeCookies is not implemented');
80155};
80156
80157Store.prototype.removeAllCookies = function(cb) {
80158 throw new Error('removeAllCookies is not implemented');
80159}
80160
80161Store.prototype.getAllCookies = function(cb) {
80162 throw new Error('getAllCookies is not implemented (therefore jar cannot be serialized)');
80163};
80164
80165},{}],389:[function(require,module,exports){
80166// generated by genversion
80167module.exports = '2.5.0'
80168
80169},{}],390:[function(require,module,exports){
80170(function (process){
80171'use strict'
80172
80173var net = require('net')
80174 , tls = require('tls')
80175 , http = require('http')
80176 , https = require('https')
80177 , events = require('events')
80178 , assert = require('assert')
80179 , util = require('util')
80180 , Buffer = require('safe-buffer').Buffer
80181 ;
80182
80183exports.httpOverHttp = httpOverHttp
80184exports.httpsOverHttp = httpsOverHttp
80185exports.httpOverHttps = httpOverHttps
80186exports.httpsOverHttps = httpsOverHttps
80187
80188
80189function httpOverHttp(options) {
80190 var agent = new TunnelingAgent(options)
80191 agent.request = http.request
80192 return agent
80193}
80194
80195function httpsOverHttp(options) {
80196 var agent = new TunnelingAgent(options)
80197 agent.request = http.request
80198 agent.createSocket = createSecureSocket
80199 agent.defaultPort = 443
80200 return agent
80201}
80202
80203function httpOverHttps(options) {
80204 var agent = new TunnelingAgent(options)
80205 agent.request = https.request
80206 return agent
80207}
80208
80209function httpsOverHttps(options) {
80210 var agent = new TunnelingAgent(options)
80211 agent.request = https.request
80212 agent.createSocket = createSecureSocket
80213 agent.defaultPort = 443
80214 return agent
80215}
80216
80217
80218function TunnelingAgent(options) {
80219 var self = this
80220 self.options = options || {}
80221 self.proxyOptions = self.options.proxy || {}
80222 self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets
80223 self.requests = []
80224 self.sockets = []
80225
80226 self.on('free', function onFree(socket, host, port) {
80227 for (var i = 0, len = self.requests.length; i < len; ++i) {
80228 var pending = self.requests[i]
80229 if (pending.host === host && pending.port === port) {
80230 // Detect the request to connect same origin server,
80231 // reuse the connection.
80232 self.requests.splice(i, 1)
80233 pending.request.onSocket(socket)
80234 return
80235 }
80236 }
80237 socket.destroy()
80238 self.removeSocket(socket)
80239 })
80240}
80241util.inherits(TunnelingAgent, events.EventEmitter)
80242
80243TunnelingAgent.prototype.addRequest = function addRequest(req, options) {
80244 var self = this
80245
80246 // Legacy API: addRequest(req, host, port, path)
80247 if (typeof options === 'string') {
80248 options = {
80249 host: options,
80250 port: arguments[2],
80251 path: arguments[3]
80252 };
80253 }
80254
80255 if (self.sockets.length >= this.maxSockets) {
80256 // We are over limit so we'll add it to the queue.
80257 self.requests.push({host: options.host, port: options.port, request: req})
80258 return
80259 }
80260
80261 // If we are under maxSockets create a new one.
80262 self.createConnection({host: options.host, port: options.port, request: req})
80263}
80264
80265TunnelingAgent.prototype.createConnection = function createConnection(pending) {
80266 var self = this
80267
80268 self.createSocket(pending, function(socket) {
80269 socket.on('free', onFree)
80270 socket.on('close', onCloseOrRemove)
80271 socket.on('agentRemove', onCloseOrRemove)
80272 pending.request.onSocket(socket)
80273
80274 function onFree() {
80275 self.emit('free', socket, pending.host, pending.port)
80276 }
80277
80278 function onCloseOrRemove(err) {
80279 self.removeSocket(socket)
80280 socket.removeListener('free', onFree)
80281 socket.removeListener('close', onCloseOrRemove)
80282 socket.removeListener('agentRemove', onCloseOrRemove)
80283 }
80284 })
80285}
80286
80287TunnelingAgent.prototype.createSocket = function createSocket(options, cb) {
80288 var self = this
80289 var placeholder = {}
80290 self.sockets.push(placeholder)
80291
80292 var connectOptions = mergeOptions({}, self.proxyOptions,
80293 { method: 'CONNECT'
80294 , path: options.host + ':' + options.port
80295 , agent: false
80296 }
80297 )
80298 if (connectOptions.proxyAuth) {
80299 connectOptions.headers = connectOptions.headers || {}
80300 connectOptions.headers['Proxy-Authorization'] = 'Basic ' +
80301 Buffer.from(connectOptions.proxyAuth).toString('base64')
80302 }
80303
80304 debug('making CONNECT request')
80305 var connectReq = self.request(connectOptions)
80306 connectReq.useChunkedEncodingByDefault = false // for v0.6
80307 connectReq.once('response', onResponse) // for v0.6
80308 connectReq.once('upgrade', onUpgrade) // for v0.6
80309 connectReq.once('connect', onConnect) // for v0.7 or later
80310 connectReq.once('error', onError)
80311 connectReq.end()
80312
80313 function onResponse(res) {
80314 // Very hacky. This is necessary to avoid http-parser leaks.
80315 res.upgrade = true
80316 }
80317
80318 function onUpgrade(res, socket, head) {
80319 // Hacky.
80320 process.nextTick(function() {
80321 onConnect(res, socket, head)
80322 })
80323 }
80324
80325 function onConnect(res, socket, head) {
80326 connectReq.removeAllListeners()
80327 socket.removeAllListeners()
80328
80329 if (res.statusCode === 200) {
80330 assert.equal(head.length, 0)
80331 debug('tunneling connection has established')
80332 self.sockets[self.sockets.indexOf(placeholder)] = socket
80333 cb(socket)
80334 } else {
80335 debug('tunneling socket could not be established, statusCode=%d', res.statusCode)
80336 var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode)
80337 error.code = 'ECONNRESET'
80338 options.request.emit('error', error)
80339 self.removeSocket(placeholder)
80340 }
80341 }
80342
80343 function onError(cause) {
80344 connectReq.removeAllListeners()
80345
80346 debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack)
80347 var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message)
80348 error.code = 'ECONNRESET'
80349 options.request.emit('error', error)
80350 self.removeSocket(placeholder)
80351 }
80352}
80353
80354TunnelingAgent.prototype.removeSocket = function removeSocket(socket) {
80355 var pos = this.sockets.indexOf(socket)
80356 if (pos === -1) return
80357
80358 this.sockets.splice(pos, 1)
80359
80360 var pending = this.requests.shift()
80361 if (pending) {
80362 // If we have pending requests and a socket gets closed a new one
80363 // needs to be created to take over in the pool for the one that closed.
80364 this.createConnection(pending)
80365 }
80366}
80367
80368function createSecureSocket(options, cb) {
80369 var self = this
80370 TunnelingAgent.prototype.createSocket.call(self, options, function(socket) {
80371 // 0 is dummy port for v0.6
80372 var secureSocket = tls.connect(0, mergeOptions({}, self.options,
80373 { servername: options.host
80374 , socket: socket
80375 }
80376 ))
80377 self.sockets[self.sockets.indexOf(socket)] = secureSocket
80378 cb(secureSocket)
80379 })
80380}
80381
80382
80383function mergeOptions(target) {
80384 for (var i = 1, len = arguments.length; i < len; ++i) {
80385 var overrides = arguments[i]
80386 if (typeof overrides === 'object') {
80387 var keys = Object.keys(overrides)
80388 for (var j = 0, keyLen = keys.length; j < keyLen; ++j) {
80389 var k = keys[j]
80390 if (overrides[k] !== undefined) {
80391 target[k] = overrides[k]
80392 }
80393 }
80394 }
80395 }
80396 return target
80397}
80398
80399
80400var debug
80401if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) {
80402 debug = function() {
80403 var args = Array.prototype.slice.call(arguments)
80404 if (typeof args[0] === 'string') {
80405 args[0] = 'TUNNEL: ' + args[0]
80406 } else {
80407 args.unshift('TUNNEL:')
80408 }
80409 console.error.apply(console, args)
80410 }
80411} else {
80412 debug = function() {}
80413}
80414exports.debug = debug // for test
80415
80416}).call(this,require('_process'))
80417},{"_process":265,"assert":68,"events":159,"http":362,"https":208,"net":112,"safe-buffer":325,"tls":112,"util":397}],391:[function(require,module,exports){
80418(function(nacl) {
80419'use strict';
80420
80421// Ported in 2014 by Dmitry Chestnykh and Devi Mandiri.
80422// Public domain.
80423//
80424// Implementation derived from TweetNaCl version 20140427.
80425// See for details: http://tweetnacl.cr.yp.to/
80426
80427var gf = function(init) {
80428 var i, r = new Float64Array(16);
80429 if (init) for (i = 0; i < init.length; i++) r[i] = init[i];
80430 return r;
80431};
80432
80433// Pluggable, initialized in high-level API below.
80434var randombytes = function(/* x, n */) { throw new Error('no PRNG'); };
80435
80436var _0 = new Uint8Array(16);
80437var _9 = new Uint8Array(32); _9[0] = 9;
80438
80439var gf0 = gf(),
80440 gf1 = gf([1]),
80441 _121665 = gf([0xdb41, 1]),
80442 D = gf([0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]),
80443 D2 = gf([0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]),
80444 X = gf([0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]),
80445 Y = gf([0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]),
80446 I = gf([0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]);
80447
80448function ts64(x, i, h, l) {
80449 x[i] = (h >> 24) & 0xff;
80450 x[i+1] = (h >> 16) & 0xff;
80451 x[i+2] = (h >> 8) & 0xff;
80452 x[i+3] = h & 0xff;
80453 x[i+4] = (l >> 24) & 0xff;
80454 x[i+5] = (l >> 16) & 0xff;
80455 x[i+6] = (l >> 8) & 0xff;
80456 x[i+7] = l & 0xff;
80457}
80458
80459function vn(x, xi, y, yi, n) {
80460 var i,d = 0;
80461 for (i = 0; i < n; i++) d |= x[xi+i]^y[yi+i];
80462 return (1 & ((d - 1) >>> 8)) - 1;
80463}
80464
80465function crypto_verify_16(x, xi, y, yi) {
80466 return vn(x,xi,y,yi,16);
80467}
80468
80469function crypto_verify_32(x, xi, y, yi) {
80470 return vn(x,xi,y,yi,32);
80471}
80472
80473function core_salsa20(o, p, k, c) {
80474 var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
80475 j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
80476 j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
80477 j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
80478 j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
80479 j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
80480 j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
80481 j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
80482 j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
80483 j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
80484 j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
80485 j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
80486 j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
80487 j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
80488 j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
80489 j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
80490
80491 var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
80492 x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
80493 x15 = j15, u;
80494
80495 for (var i = 0; i < 20; i += 2) {
80496 u = x0 + x12 | 0;
80497 x4 ^= u<<7 | u>>>(32-7);
80498 u = x4 + x0 | 0;
80499 x8 ^= u<<9 | u>>>(32-9);
80500 u = x8 + x4 | 0;
80501 x12 ^= u<<13 | u>>>(32-13);
80502 u = x12 + x8 | 0;
80503 x0 ^= u<<18 | u>>>(32-18);
80504
80505 u = x5 + x1 | 0;
80506 x9 ^= u<<7 | u>>>(32-7);
80507 u = x9 + x5 | 0;
80508 x13 ^= u<<9 | u>>>(32-9);
80509 u = x13 + x9 | 0;
80510 x1 ^= u<<13 | u>>>(32-13);
80511 u = x1 + x13 | 0;
80512 x5 ^= u<<18 | u>>>(32-18);
80513
80514 u = x10 + x6 | 0;
80515 x14 ^= u<<7 | u>>>(32-7);
80516 u = x14 + x10 | 0;
80517 x2 ^= u<<9 | u>>>(32-9);
80518 u = x2 + x14 | 0;
80519 x6 ^= u<<13 | u>>>(32-13);
80520 u = x6 + x2 | 0;
80521 x10 ^= u<<18 | u>>>(32-18);
80522
80523 u = x15 + x11 | 0;
80524 x3 ^= u<<7 | u>>>(32-7);
80525 u = x3 + x15 | 0;
80526 x7 ^= u<<9 | u>>>(32-9);
80527 u = x7 + x3 | 0;
80528 x11 ^= u<<13 | u>>>(32-13);
80529 u = x11 + x7 | 0;
80530 x15 ^= u<<18 | u>>>(32-18);
80531
80532 u = x0 + x3 | 0;
80533 x1 ^= u<<7 | u>>>(32-7);
80534 u = x1 + x0 | 0;
80535 x2 ^= u<<9 | u>>>(32-9);
80536 u = x2 + x1 | 0;
80537 x3 ^= u<<13 | u>>>(32-13);
80538 u = x3 + x2 | 0;
80539 x0 ^= u<<18 | u>>>(32-18);
80540
80541 u = x5 + x4 | 0;
80542 x6 ^= u<<7 | u>>>(32-7);
80543 u = x6 + x5 | 0;
80544 x7 ^= u<<9 | u>>>(32-9);
80545 u = x7 + x6 | 0;
80546 x4 ^= u<<13 | u>>>(32-13);
80547 u = x4 + x7 | 0;
80548 x5 ^= u<<18 | u>>>(32-18);
80549
80550 u = x10 + x9 | 0;
80551 x11 ^= u<<7 | u>>>(32-7);
80552 u = x11 + x10 | 0;
80553 x8 ^= u<<9 | u>>>(32-9);
80554 u = x8 + x11 | 0;
80555 x9 ^= u<<13 | u>>>(32-13);
80556 u = x9 + x8 | 0;
80557 x10 ^= u<<18 | u>>>(32-18);
80558
80559 u = x15 + x14 | 0;
80560 x12 ^= u<<7 | u>>>(32-7);
80561 u = x12 + x15 | 0;
80562 x13 ^= u<<9 | u>>>(32-9);
80563 u = x13 + x12 | 0;
80564 x14 ^= u<<13 | u>>>(32-13);
80565 u = x14 + x13 | 0;
80566 x15 ^= u<<18 | u>>>(32-18);
80567 }
80568 x0 = x0 + j0 | 0;
80569 x1 = x1 + j1 | 0;
80570 x2 = x2 + j2 | 0;
80571 x3 = x3 + j3 | 0;
80572 x4 = x4 + j4 | 0;
80573 x5 = x5 + j5 | 0;
80574 x6 = x6 + j6 | 0;
80575 x7 = x7 + j7 | 0;
80576 x8 = x8 + j8 | 0;
80577 x9 = x9 + j9 | 0;
80578 x10 = x10 + j10 | 0;
80579 x11 = x11 + j11 | 0;
80580 x12 = x12 + j12 | 0;
80581 x13 = x13 + j13 | 0;
80582 x14 = x14 + j14 | 0;
80583 x15 = x15 + j15 | 0;
80584
80585 o[ 0] = x0 >>> 0 & 0xff;
80586 o[ 1] = x0 >>> 8 & 0xff;
80587 o[ 2] = x0 >>> 16 & 0xff;
80588 o[ 3] = x0 >>> 24 & 0xff;
80589
80590 o[ 4] = x1 >>> 0 & 0xff;
80591 o[ 5] = x1 >>> 8 & 0xff;
80592 o[ 6] = x1 >>> 16 & 0xff;
80593 o[ 7] = x1 >>> 24 & 0xff;
80594
80595 o[ 8] = x2 >>> 0 & 0xff;
80596 o[ 9] = x2 >>> 8 & 0xff;
80597 o[10] = x2 >>> 16 & 0xff;
80598 o[11] = x2 >>> 24 & 0xff;
80599
80600 o[12] = x3 >>> 0 & 0xff;
80601 o[13] = x3 >>> 8 & 0xff;
80602 o[14] = x3 >>> 16 & 0xff;
80603 o[15] = x3 >>> 24 & 0xff;
80604
80605 o[16] = x4 >>> 0 & 0xff;
80606 o[17] = x4 >>> 8 & 0xff;
80607 o[18] = x4 >>> 16 & 0xff;
80608 o[19] = x4 >>> 24 & 0xff;
80609
80610 o[20] = x5 >>> 0 & 0xff;
80611 o[21] = x5 >>> 8 & 0xff;
80612 o[22] = x5 >>> 16 & 0xff;
80613 o[23] = x5 >>> 24 & 0xff;
80614
80615 o[24] = x6 >>> 0 & 0xff;
80616 o[25] = x6 >>> 8 & 0xff;
80617 o[26] = x6 >>> 16 & 0xff;
80618 o[27] = x6 >>> 24 & 0xff;
80619
80620 o[28] = x7 >>> 0 & 0xff;
80621 o[29] = x7 >>> 8 & 0xff;
80622 o[30] = x7 >>> 16 & 0xff;
80623 o[31] = x7 >>> 24 & 0xff;
80624
80625 o[32] = x8 >>> 0 & 0xff;
80626 o[33] = x8 >>> 8 & 0xff;
80627 o[34] = x8 >>> 16 & 0xff;
80628 o[35] = x8 >>> 24 & 0xff;
80629
80630 o[36] = x9 >>> 0 & 0xff;
80631 o[37] = x9 >>> 8 & 0xff;
80632 o[38] = x9 >>> 16 & 0xff;
80633 o[39] = x9 >>> 24 & 0xff;
80634
80635 o[40] = x10 >>> 0 & 0xff;
80636 o[41] = x10 >>> 8 & 0xff;
80637 o[42] = x10 >>> 16 & 0xff;
80638 o[43] = x10 >>> 24 & 0xff;
80639
80640 o[44] = x11 >>> 0 & 0xff;
80641 o[45] = x11 >>> 8 & 0xff;
80642 o[46] = x11 >>> 16 & 0xff;
80643 o[47] = x11 >>> 24 & 0xff;
80644
80645 o[48] = x12 >>> 0 & 0xff;
80646 o[49] = x12 >>> 8 & 0xff;
80647 o[50] = x12 >>> 16 & 0xff;
80648 o[51] = x12 >>> 24 & 0xff;
80649
80650 o[52] = x13 >>> 0 & 0xff;
80651 o[53] = x13 >>> 8 & 0xff;
80652 o[54] = x13 >>> 16 & 0xff;
80653 o[55] = x13 >>> 24 & 0xff;
80654
80655 o[56] = x14 >>> 0 & 0xff;
80656 o[57] = x14 >>> 8 & 0xff;
80657 o[58] = x14 >>> 16 & 0xff;
80658 o[59] = x14 >>> 24 & 0xff;
80659
80660 o[60] = x15 >>> 0 & 0xff;
80661 o[61] = x15 >>> 8 & 0xff;
80662 o[62] = x15 >>> 16 & 0xff;
80663 o[63] = x15 >>> 24 & 0xff;
80664}
80665
80666function core_hsalsa20(o,p,k,c) {
80667 var j0 = c[ 0] & 0xff | (c[ 1] & 0xff)<<8 | (c[ 2] & 0xff)<<16 | (c[ 3] & 0xff)<<24,
80668 j1 = k[ 0] & 0xff | (k[ 1] & 0xff)<<8 | (k[ 2] & 0xff)<<16 | (k[ 3] & 0xff)<<24,
80669 j2 = k[ 4] & 0xff | (k[ 5] & 0xff)<<8 | (k[ 6] & 0xff)<<16 | (k[ 7] & 0xff)<<24,
80670 j3 = k[ 8] & 0xff | (k[ 9] & 0xff)<<8 | (k[10] & 0xff)<<16 | (k[11] & 0xff)<<24,
80671 j4 = k[12] & 0xff | (k[13] & 0xff)<<8 | (k[14] & 0xff)<<16 | (k[15] & 0xff)<<24,
80672 j5 = c[ 4] & 0xff | (c[ 5] & 0xff)<<8 | (c[ 6] & 0xff)<<16 | (c[ 7] & 0xff)<<24,
80673 j6 = p[ 0] & 0xff | (p[ 1] & 0xff)<<8 | (p[ 2] & 0xff)<<16 | (p[ 3] & 0xff)<<24,
80674 j7 = p[ 4] & 0xff | (p[ 5] & 0xff)<<8 | (p[ 6] & 0xff)<<16 | (p[ 7] & 0xff)<<24,
80675 j8 = p[ 8] & 0xff | (p[ 9] & 0xff)<<8 | (p[10] & 0xff)<<16 | (p[11] & 0xff)<<24,
80676 j9 = p[12] & 0xff | (p[13] & 0xff)<<8 | (p[14] & 0xff)<<16 | (p[15] & 0xff)<<24,
80677 j10 = c[ 8] & 0xff | (c[ 9] & 0xff)<<8 | (c[10] & 0xff)<<16 | (c[11] & 0xff)<<24,
80678 j11 = k[16] & 0xff | (k[17] & 0xff)<<8 | (k[18] & 0xff)<<16 | (k[19] & 0xff)<<24,
80679 j12 = k[20] & 0xff | (k[21] & 0xff)<<8 | (k[22] & 0xff)<<16 | (k[23] & 0xff)<<24,
80680 j13 = k[24] & 0xff | (k[25] & 0xff)<<8 | (k[26] & 0xff)<<16 | (k[27] & 0xff)<<24,
80681 j14 = k[28] & 0xff | (k[29] & 0xff)<<8 | (k[30] & 0xff)<<16 | (k[31] & 0xff)<<24,
80682 j15 = c[12] & 0xff | (c[13] & 0xff)<<8 | (c[14] & 0xff)<<16 | (c[15] & 0xff)<<24;
80683
80684 var x0 = j0, x1 = j1, x2 = j2, x3 = j3, x4 = j4, x5 = j5, x6 = j6, x7 = j7,
80685 x8 = j8, x9 = j9, x10 = j10, x11 = j11, x12 = j12, x13 = j13, x14 = j14,
80686 x15 = j15, u;
80687
80688 for (var i = 0; i < 20; i += 2) {
80689 u = x0 + x12 | 0;
80690 x4 ^= u<<7 | u>>>(32-7);
80691 u = x4 + x0 | 0;
80692 x8 ^= u<<9 | u>>>(32-9);
80693 u = x8 + x4 | 0;
80694 x12 ^= u<<13 | u>>>(32-13);
80695 u = x12 + x8 | 0;
80696 x0 ^= u<<18 | u>>>(32-18);
80697
80698 u = x5 + x1 | 0;
80699 x9 ^= u<<7 | u>>>(32-7);
80700 u = x9 + x5 | 0;
80701 x13 ^= u<<9 | u>>>(32-9);
80702 u = x13 + x9 | 0;
80703 x1 ^= u<<13 | u>>>(32-13);
80704 u = x1 + x13 | 0;
80705 x5 ^= u<<18 | u>>>(32-18);
80706
80707 u = x10 + x6 | 0;
80708 x14 ^= u<<7 | u>>>(32-7);
80709 u = x14 + x10 | 0;
80710 x2 ^= u<<9 | u>>>(32-9);
80711 u = x2 + x14 | 0;
80712 x6 ^= u<<13 | u>>>(32-13);
80713 u = x6 + x2 | 0;
80714 x10 ^= u<<18 | u>>>(32-18);
80715
80716 u = x15 + x11 | 0;
80717 x3 ^= u<<7 | u>>>(32-7);
80718 u = x3 + x15 | 0;
80719 x7 ^= u<<9 | u>>>(32-9);
80720 u = x7 + x3 | 0;
80721 x11 ^= u<<13 | u>>>(32-13);
80722 u = x11 + x7 | 0;
80723 x15 ^= u<<18 | u>>>(32-18);
80724
80725 u = x0 + x3 | 0;
80726 x1 ^= u<<7 | u>>>(32-7);
80727 u = x1 + x0 | 0;
80728 x2 ^= u<<9 | u>>>(32-9);
80729 u = x2 + x1 | 0;
80730 x3 ^= u<<13 | u>>>(32-13);
80731 u = x3 + x2 | 0;
80732 x0 ^= u<<18 | u>>>(32-18);
80733
80734 u = x5 + x4 | 0;
80735 x6 ^= u<<7 | u>>>(32-7);
80736 u = x6 + x5 | 0;
80737 x7 ^= u<<9 | u>>>(32-9);
80738 u = x7 + x6 | 0;
80739 x4 ^= u<<13 | u>>>(32-13);
80740 u = x4 + x7 | 0;
80741 x5 ^= u<<18 | u>>>(32-18);
80742
80743 u = x10 + x9 | 0;
80744 x11 ^= u<<7 | u>>>(32-7);
80745 u = x11 + x10 | 0;
80746 x8 ^= u<<9 | u>>>(32-9);
80747 u = x8 + x11 | 0;
80748 x9 ^= u<<13 | u>>>(32-13);
80749 u = x9 + x8 | 0;
80750 x10 ^= u<<18 | u>>>(32-18);
80751
80752 u = x15 + x14 | 0;
80753 x12 ^= u<<7 | u>>>(32-7);
80754 u = x12 + x15 | 0;
80755 x13 ^= u<<9 | u>>>(32-9);
80756 u = x13 + x12 | 0;
80757 x14 ^= u<<13 | u>>>(32-13);
80758 u = x14 + x13 | 0;
80759 x15 ^= u<<18 | u>>>(32-18);
80760 }
80761
80762 o[ 0] = x0 >>> 0 & 0xff;
80763 o[ 1] = x0 >>> 8 & 0xff;
80764 o[ 2] = x0 >>> 16 & 0xff;
80765 o[ 3] = x0 >>> 24 & 0xff;
80766
80767 o[ 4] = x5 >>> 0 & 0xff;
80768 o[ 5] = x5 >>> 8 & 0xff;
80769 o[ 6] = x5 >>> 16 & 0xff;
80770 o[ 7] = x5 >>> 24 & 0xff;
80771
80772 o[ 8] = x10 >>> 0 & 0xff;
80773 o[ 9] = x10 >>> 8 & 0xff;
80774 o[10] = x10 >>> 16 & 0xff;
80775 o[11] = x10 >>> 24 & 0xff;
80776
80777 o[12] = x15 >>> 0 & 0xff;
80778 o[13] = x15 >>> 8 & 0xff;
80779 o[14] = x15 >>> 16 & 0xff;
80780 o[15] = x15 >>> 24 & 0xff;
80781
80782 o[16] = x6 >>> 0 & 0xff;
80783 o[17] = x6 >>> 8 & 0xff;
80784 o[18] = x6 >>> 16 & 0xff;
80785 o[19] = x6 >>> 24 & 0xff;
80786
80787 o[20] = x7 >>> 0 & 0xff;
80788 o[21] = x7 >>> 8 & 0xff;
80789 o[22] = x7 >>> 16 & 0xff;
80790 o[23] = x7 >>> 24 & 0xff;
80791
80792 o[24] = x8 >>> 0 & 0xff;
80793 o[25] = x8 >>> 8 & 0xff;
80794 o[26] = x8 >>> 16 & 0xff;
80795 o[27] = x8 >>> 24 & 0xff;
80796
80797 o[28] = x9 >>> 0 & 0xff;
80798 o[29] = x9 >>> 8 & 0xff;
80799 o[30] = x9 >>> 16 & 0xff;
80800 o[31] = x9 >>> 24 & 0xff;
80801}
80802
80803function crypto_core_salsa20(out,inp,k,c) {
80804 core_salsa20(out,inp,k,c);
80805}
80806
80807function crypto_core_hsalsa20(out,inp,k,c) {
80808 core_hsalsa20(out,inp,k,c);
80809}
80810
80811var sigma = new Uint8Array([101, 120, 112, 97, 110, 100, 32, 51, 50, 45, 98, 121, 116, 101, 32, 107]);
80812 // "expand 32-byte k"
80813
80814function crypto_stream_salsa20_xor(c,cpos,m,mpos,b,n,k) {
80815 var z = new Uint8Array(16), x = new Uint8Array(64);
80816 var u, i;
80817 for (i = 0; i < 16; i++) z[i] = 0;
80818 for (i = 0; i < 8; i++) z[i] = n[i];
80819 while (b >= 64) {
80820 crypto_core_salsa20(x,z,k,sigma);
80821 for (i = 0; i < 64; i++) c[cpos+i] = m[mpos+i] ^ x[i];
80822 u = 1;
80823 for (i = 8; i < 16; i++) {
80824 u = u + (z[i] & 0xff) | 0;
80825 z[i] = u & 0xff;
80826 u >>>= 8;
80827 }
80828 b -= 64;
80829 cpos += 64;
80830 mpos += 64;
80831 }
80832 if (b > 0) {
80833 crypto_core_salsa20(x,z,k,sigma);
80834 for (i = 0; i < b; i++) c[cpos+i] = m[mpos+i] ^ x[i];
80835 }
80836 return 0;
80837}
80838
80839function crypto_stream_salsa20(c,cpos,b,n,k) {
80840 var z = new Uint8Array(16), x = new Uint8Array(64);
80841 var u, i;
80842 for (i = 0; i < 16; i++) z[i] = 0;
80843 for (i = 0; i < 8; i++) z[i] = n[i];
80844 while (b >= 64) {
80845 crypto_core_salsa20(x,z,k,sigma);
80846 for (i = 0; i < 64; i++) c[cpos+i] = x[i];
80847 u = 1;
80848 for (i = 8; i < 16; i++) {
80849 u = u + (z[i] & 0xff) | 0;
80850 z[i] = u & 0xff;
80851 u >>>= 8;
80852 }
80853 b -= 64;
80854 cpos += 64;
80855 }
80856 if (b > 0) {
80857 crypto_core_salsa20(x,z,k,sigma);
80858 for (i = 0; i < b; i++) c[cpos+i] = x[i];
80859 }
80860 return 0;
80861}
80862
80863function crypto_stream(c,cpos,d,n,k) {
80864 var s = new Uint8Array(32);
80865 crypto_core_hsalsa20(s,n,k,sigma);
80866 var sn = new Uint8Array(8);
80867 for (var i = 0; i < 8; i++) sn[i] = n[i+16];
80868 return crypto_stream_salsa20(c,cpos,d,sn,s);
80869}
80870
80871function crypto_stream_xor(c,cpos,m,mpos,d,n,k) {
80872 var s = new Uint8Array(32);
80873 crypto_core_hsalsa20(s,n,k,sigma);
80874 var sn = new Uint8Array(8);
80875 for (var i = 0; i < 8; i++) sn[i] = n[i+16];
80876 return crypto_stream_salsa20_xor(c,cpos,m,mpos,d,sn,s);
80877}
80878
80879/*
80880* Port of Andrew Moon's Poly1305-donna-16. Public domain.
80881* https://github.com/floodyberry/poly1305-donna
80882*/
80883
80884var poly1305 = function(key) {
80885 this.buffer = new Uint8Array(16);
80886 this.r = new Uint16Array(10);
80887 this.h = new Uint16Array(10);
80888 this.pad = new Uint16Array(8);
80889 this.leftover = 0;
80890 this.fin = 0;
80891
80892 var t0, t1, t2, t3, t4, t5, t6, t7;
80893
80894 t0 = key[ 0] & 0xff | (key[ 1] & 0xff) << 8; this.r[0] = ( t0 ) & 0x1fff;
80895 t1 = key[ 2] & 0xff | (key[ 3] & 0xff) << 8; this.r[1] = ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
80896 t2 = key[ 4] & 0xff | (key[ 5] & 0xff) << 8; this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
80897 t3 = key[ 6] & 0xff | (key[ 7] & 0xff) << 8; this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
80898 t4 = key[ 8] & 0xff | (key[ 9] & 0xff) << 8; this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
80899 this.r[5] = ((t4 >>> 1)) & 0x1ffe;
80900 t5 = key[10] & 0xff | (key[11] & 0xff) << 8; this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
80901 t6 = key[12] & 0xff | (key[13] & 0xff) << 8; this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
80902 t7 = key[14] & 0xff | (key[15] & 0xff) << 8; this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
80903 this.r[9] = ((t7 >>> 5)) & 0x007f;
80904
80905 this.pad[0] = key[16] & 0xff | (key[17] & 0xff) << 8;
80906 this.pad[1] = key[18] & 0xff | (key[19] & 0xff) << 8;
80907 this.pad[2] = key[20] & 0xff | (key[21] & 0xff) << 8;
80908 this.pad[3] = key[22] & 0xff | (key[23] & 0xff) << 8;
80909 this.pad[4] = key[24] & 0xff | (key[25] & 0xff) << 8;
80910 this.pad[5] = key[26] & 0xff | (key[27] & 0xff) << 8;
80911 this.pad[6] = key[28] & 0xff | (key[29] & 0xff) << 8;
80912 this.pad[7] = key[30] & 0xff | (key[31] & 0xff) << 8;
80913};
80914
80915poly1305.prototype.blocks = function(m, mpos, bytes) {
80916 var hibit = this.fin ? 0 : (1 << 11);
80917 var t0, t1, t2, t3, t4, t5, t6, t7, c;
80918 var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
80919
80920 var h0 = this.h[0],
80921 h1 = this.h[1],
80922 h2 = this.h[2],
80923 h3 = this.h[3],
80924 h4 = this.h[4],
80925 h5 = this.h[5],
80926 h6 = this.h[6],
80927 h7 = this.h[7],
80928 h8 = this.h[8],
80929 h9 = this.h[9];
80930
80931 var r0 = this.r[0],
80932 r1 = this.r[1],
80933 r2 = this.r[2],
80934 r3 = this.r[3],
80935 r4 = this.r[4],
80936 r5 = this.r[5],
80937 r6 = this.r[6],
80938 r7 = this.r[7],
80939 r8 = this.r[8],
80940 r9 = this.r[9];
80941
80942 while (bytes >= 16) {
80943 t0 = m[mpos+ 0] & 0xff | (m[mpos+ 1] & 0xff) << 8; h0 += ( t0 ) & 0x1fff;
80944 t1 = m[mpos+ 2] & 0xff | (m[mpos+ 3] & 0xff) << 8; h1 += ((t0 >>> 13) | (t1 << 3)) & 0x1fff;
80945 t2 = m[mpos+ 4] & 0xff | (m[mpos+ 5] & 0xff) << 8; h2 += ((t1 >>> 10) | (t2 << 6)) & 0x1fff;
80946 t3 = m[mpos+ 6] & 0xff | (m[mpos+ 7] & 0xff) << 8; h3 += ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
80947 t4 = m[mpos+ 8] & 0xff | (m[mpos+ 9] & 0xff) << 8; h4 += ((t3 >>> 4) | (t4 << 12)) & 0x1fff;
80948 h5 += ((t4 >>> 1)) & 0x1fff;
80949 t5 = m[mpos+10] & 0xff | (m[mpos+11] & 0xff) << 8; h6 += ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
80950 t6 = m[mpos+12] & 0xff | (m[mpos+13] & 0xff) << 8; h7 += ((t5 >>> 11) | (t6 << 5)) & 0x1fff;
80951 t7 = m[mpos+14] & 0xff | (m[mpos+15] & 0xff) << 8; h8 += ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
80952 h9 += ((t7 >>> 5)) | hibit;
80953
80954 c = 0;
80955
80956 d0 = c;
80957 d0 += h0 * r0;
80958 d0 += h1 * (5 * r9);
80959 d0 += h2 * (5 * r8);
80960 d0 += h3 * (5 * r7);
80961 d0 += h4 * (5 * r6);
80962 c = (d0 >>> 13); d0 &= 0x1fff;
80963 d0 += h5 * (5 * r5);
80964 d0 += h6 * (5 * r4);
80965 d0 += h7 * (5 * r3);
80966 d0 += h8 * (5 * r2);
80967 d0 += h9 * (5 * r1);
80968 c += (d0 >>> 13); d0 &= 0x1fff;
80969
80970 d1 = c;
80971 d1 += h0 * r1;
80972 d1 += h1 * r0;
80973 d1 += h2 * (5 * r9);
80974 d1 += h3 * (5 * r8);
80975 d1 += h4 * (5 * r7);
80976 c = (d1 >>> 13); d1 &= 0x1fff;
80977 d1 += h5 * (5 * r6);
80978 d1 += h6 * (5 * r5);
80979 d1 += h7 * (5 * r4);
80980 d1 += h8 * (5 * r3);
80981 d1 += h9 * (5 * r2);
80982 c += (d1 >>> 13); d1 &= 0x1fff;
80983
80984 d2 = c;
80985 d2 += h0 * r2;
80986 d2 += h1 * r1;
80987 d2 += h2 * r0;
80988 d2 += h3 * (5 * r9);
80989 d2 += h4 * (5 * r8);
80990 c = (d2 >>> 13); d2 &= 0x1fff;
80991 d2 += h5 * (5 * r7);
80992 d2 += h6 * (5 * r6);
80993 d2 += h7 * (5 * r5);
80994 d2 += h8 * (5 * r4);
80995 d2 += h9 * (5 * r3);
80996 c += (d2 >>> 13); d2 &= 0x1fff;
80997
80998 d3 = c;
80999 d3 += h0 * r3;
81000 d3 += h1 * r2;
81001 d3 += h2 * r1;
81002 d3 += h3 * r0;
81003 d3 += h4 * (5 * r9);
81004 c = (d3 >>> 13); d3 &= 0x1fff;
81005 d3 += h5 * (5 * r8);
81006 d3 += h6 * (5 * r7);
81007 d3 += h7 * (5 * r6);
81008 d3 += h8 * (5 * r5);
81009 d3 += h9 * (5 * r4);
81010 c += (d3 >>> 13); d3 &= 0x1fff;
81011
81012 d4 = c;
81013 d4 += h0 * r4;
81014 d4 += h1 * r3;
81015 d4 += h2 * r2;
81016 d4 += h3 * r1;
81017 d4 += h4 * r0;
81018 c = (d4 >>> 13); d4 &= 0x1fff;
81019 d4 += h5 * (5 * r9);
81020 d4 += h6 * (5 * r8);
81021 d4 += h7 * (5 * r7);
81022 d4 += h8 * (5 * r6);
81023 d4 += h9 * (5 * r5);
81024 c += (d4 >>> 13); d4 &= 0x1fff;
81025
81026 d5 = c;
81027 d5 += h0 * r5;
81028 d5 += h1 * r4;
81029 d5 += h2 * r3;
81030 d5 += h3 * r2;
81031 d5 += h4 * r1;
81032 c = (d5 >>> 13); d5 &= 0x1fff;
81033 d5 += h5 * r0;
81034 d5 += h6 * (5 * r9);
81035 d5 += h7 * (5 * r8);
81036 d5 += h8 * (5 * r7);
81037 d5 += h9 * (5 * r6);
81038 c += (d5 >>> 13); d5 &= 0x1fff;
81039
81040 d6 = c;
81041 d6 += h0 * r6;
81042 d6 += h1 * r5;
81043 d6 += h2 * r4;
81044 d6 += h3 * r3;
81045 d6 += h4 * r2;
81046 c = (d6 >>> 13); d6 &= 0x1fff;
81047 d6 += h5 * r1;
81048 d6 += h6 * r0;
81049 d6 += h7 * (5 * r9);
81050 d6 += h8 * (5 * r8);
81051 d6 += h9 * (5 * r7);
81052 c += (d6 >>> 13); d6 &= 0x1fff;
81053
81054 d7 = c;
81055 d7 += h0 * r7;
81056 d7 += h1 * r6;
81057 d7 += h2 * r5;
81058 d7 += h3 * r4;
81059 d7 += h4 * r3;
81060 c = (d7 >>> 13); d7 &= 0x1fff;
81061 d7 += h5 * r2;
81062 d7 += h6 * r1;
81063 d7 += h7 * r0;
81064 d7 += h8 * (5 * r9);
81065 d7 += h9 * (5 * r8);
81066 c += (d7 >>> 13); d7 &= 0x1fff;
81067
81068 d8 = c;
81069 d8 += h0 * r8;
81070 d8 += h1 * r7;
81071 d8 += h2 * r6;
81072 d8 += h3 * r5;
81073 d8 += h4 * r4;
81074 c = (d8 >>> 13); d8 &= 0x1fff;
81075 d8 += h5 * r3;
81076 d8 += h6 * r2;
81077 d8 += h7 * r1;
81078 d8 += h8 * r0;
81079 d8 += h9 * (5 * r9);
81080 c += (d8 >>> 13); d8 &= 0x1fff;
81081
81082 d9 = c;
81083 d9 += h0 * r9;
81084 d9 += h1 * r8;
81085 d9 += h2 * r7;
81086 d9 += h3 * r6;
81087 d9 += h4 * r5;
81088 c = (d9 >>> 13); d9 &= 0x1fff;
81089 d9 += h5 * r4;
81090 d9 += h6 * r3;
81091 d9 += h7 * r2;
81092 d9 += h8 * r1;
81093 d9 += h9 * r0;
81094 c += (d9 >>> 13); d9 &= 0x1fff;
81095
81096 c = (((c << 2) + c)) | 0;
81097 c = (c + d0) | 0;
81098 d0 = c & 0x1fff;
81099 c = (c >>> 13);
81100 d1 += c;
81101
81102 h0 = d0;
81103 h1 = d1;
81104 h2 = d2;
81105 h3 = d3;
81106 h4 = d4;
81107 h5 = d5;
81108 h6 = d6;
81109 h7 = d7;
81110 h8 = d8;
81111 h9 = d9;
81112
81113 mpos += 16;
81114 bytes -= 16;
81115 }
81116 this.h[0] = h0;
81117 this.h[1] = h1;
81118 this.h[2] = h2;
81119 this.h[3] = h3;
81120 this.h[4] = h4;
81121 this.h[5] = h5;
81122 this.h[6] = h6;
81123 this.h[7] = h7;
81124 this.h[8] = h8;
81125 this.h[9] = h9;
81126};
81127
81128poly1305.prototype.finish = function(mac, macpos) {
81129 var g = new Uint16Array(10);
81130 var c, mask, f, i;
81131
81132 if (this.leftover) {
81133 i = this.leftover;
81134 this.buffer[i++] = 1;
81135 for (; i < 16; i++) this.buffer[i] = 0;
81136 this.fin = 1;
81137 this.blocks(this.buffer, 0, 16);
81138 }
81139
81140 c = this.h[1] >>> 13;
81141 this.h[1] &= 0x1fff;
81142 for (i = 2; i < 10; i++) {
81143 this.h[i] += c;
81144 c = this.h[i] >>> 13;
81145 this.h[i] &= 0x1fff;
81146 }
81147 this.h[0] += (c * 5);
81148 c = this.h[0] >>> 13;
81149 this.h[0] &= 0x1fff;
81150 this.h[1] += c;
81151 c = this.h[1] >>> 13;
81152 this.h[1] &= 0x1fff;
81153 this.h[2] += c;
81154
81155 g[0] = this.h[0] + 5;
81156 c = g[0] >>> 13;
81157 g[0] &= 0x1fff;
81158 for (i = 1; i < 10; i++) {
81159 g[i] = this.h[i] + c;
81160 c = g[i] >>> 13;
81161 g[i] &= 0x1fff;
81162 }
81163 g[9] -= (1 << 13);
81164
81165 mask = (c ^ 1) - 1;
81166 for (i = 0; i < 10; i++) g[i] &= mask;
81167 mask = ~mask;
81168 for (i = 0; i < 10; i++) this.h[i] = (this.h[i] & mask) | g[i];
81169
81170 this.h[0] = ((this.h[0] ) | (this.h[1] << 13) ) & 0xffff;
81171 this.h[1] = ((this.h[1] >>> 3) | (this.h[2] << 10) ) & 0xffff;
81172 this.h[2] = ((this.h[2] >>> 6) | (this.h[3] << 7) ) & 0xffff;
81173 this.h[3] = ((this.h[3] >>> 9) | (this.h[4] << 4) ) & 0xffff;
81174 this.h[4] = ((this.h[4] >>> 12) | (this.h[5] << 1) | (this.h[6] << 14)) & 0xffff;
81175 this.h[5] = ((this.h[6] >>> 2) | (this.h[7] << 11) ) & 0xffff;
81176 this.h[6] = ((this.h[7] >>> 5) | (this.h[8] << 8) ) & 0xffff;
81177 this.h[7] = ((this.h[8] >>> 8) | (this.h[9] << 5) ) & 0xffff;
81178
81179 f = this.h[0] + this.pad[0];
81180 this.h[0] = f & 0xffff;
81181 for (i = 1; i < 8; i++) {
81182 f = (((this.h[i] + this.pad[i]) | 0) + (f >>> 16)) | 0;
81183 this.h[i] = f & 0xffff;
81184 }
81185
81186 mac[macpos+ 0] = (this.h[0] >>> 0) & 0xff;
81187 mac[macpos+ 1] = (this.h[0] >>> 8) & 0xff;
81188 mac[macpos+ 2] = (this.h[1] >>> 0) & 0xff;
81189 mac[macpos+ 3] = (this.h[1] >>> 8) & 0xff;
81190 mac[macpos+ 4] = (this.h[2] >>> 0) & 0xff;
81191 mac[macpos+ 5] = (this.h[2] >>> 8) & 0xff;
81192 mac[macpos+ 6] = (this.h[3] >>> 0) & 0xff;
81193 mac[macpos+ 7] = (this.h[3] >>> 8) & 0xff;
81194 mac[macpos+ 8] = (this.h[4] >>> 0) & 0xff;
81195 mac[macpos+ 9] = (this.h[4] >>> 8) & 0xff;
81196 mac[macpos+10] = (this.h[5] >>> 0) & 0xff;
81197 mac[macpos+11] = (this.h[5] >>> 8) & 0xff;
81198 mac[macpos+12] = (this.h[6] >>> 0) & 0xff;
81199 mac[macpos+13] = (this.h[6] >>> 8) & 0xff;
81200 mac[macpos+14] = (this.h[7] >>> 0) & 0xff;
81201 mac[macpos+15] = (this.h[7] >>> 8) & 0xff;
81202};
81203
81204poly1305.prototype.update = function(m, mpos, bytes) {
81205 var i, want;
81206
81207 if (this.leftover) {
81208 want = (16 - this.leftover);
81209 if (want > bytes)
81210 want = bytes;
81211 for (i = 0; i < want; i++)
81212 this.buffer[this.leftover + i] = m[mpos+i];
81213 bytes -= want;
81214 mpos += want;
81215 this.leftover += want;
81216 if (this.leftover < 16)
81217 return;
81218 this.blocks(this.buffer, 0, 16);
81219 this.leftover = 0;
81220 }
81221
81222 if (bytes >= 16) {
81223 want = bytes - (bytes % 16);
81224 this.blocks(m, mpos, want);
81225 mpos += want;
81226 bytes -= want;
81227 }
81228
81229 if (bytes) {
81230 for (i = 0; i < bytes; i++)
81231 this.buffer[this.leftover + i] = m[mpos+i];
81232 this.leftover += bytes;
81233 }
81234};
81235
81236function crypto_onetimeauth(out, outpos, m, mpos, n, k) {
81237 var s = new poly1305(k);
81238 s.update(m, mpos, n);
81239 s.finish(out, outpos);
81240 return 0;
81241}
81242
81243function crypto_onetimeauth_verify(h, hpos, m, mpos, n, k) {
81244 var x = new Uint8Array(16);
81245 crypto_onetimeauth(x,0,m,mpos,n,k);
81246 return crypto_verify_16(h,hpos,x,0);
81247}
81248
81249function crypto_secretbox(c,m,d,n,k) {
81250 var i;
81251 if (d < 32) return -1;
81252 crypto_stream_xor(c,0,m,0,d,n,k);
81253 crypto_onetimeauth(c, 16, c, 32, d - 32, c);
81254 for (i = 0; i < 16; i++) c[i] = 0;
81255 return 0;
81256}
81257
81258function crypto_secretbox_open(m,c,d,n,k) {
81259 var i;
81260 var x = new Uint8Array(32);
81261 if (d < 32) return -1;
81262 crypto_stream(x,0,32,n,k);
81263 if (crypto_onetimeauth_verify(c, 16,c, 32,d - 32,x) !== 0) return -1;
81264 crypto_stream_xor(m,0,c,0,d,n,k);
81265 for (i = 0; i < 32; i++) m[i] = 0;
81266 return 0;
81267}
81268
81269function set25519(r, a) {
81270 var i;
81271 for (i = 0; i < 16; i++) r[i] = a[i]|0;
81272}
81273
81274function car25519(o) {
81275 var i, v, c = 1;
81276 for (i = 0; i < 16; i++) {
81277 v = o[i] + c + 65535;
81278 c = Math.floor(v / 65536);
81279 o[i] = v - c * 65536;
81280 }
81281 o[0] += c-1 + 37 * (c-1);
81282}
81283
81284function sel25519(p, q, b) {
81285 var t, c = ~(b-1);
81286 for (var i = 0; i < 16; i++) {
81287 t = c & (p[i] ^ q[i]);
81288 p[i] ^= t;
81289 q[i] ^= t;
81290 }
81291}
81292
81293function pack25519(o, n) {
81294 var i, j, b;
81295 var m = gf(), t = gf();
81296 for (i = 0; i < 16; i++) t[i] = n[i];
81297 car25519(t);
81298 car25519(t);
81299 car25519(t);
81300 for (j = 0; j < 2; j++) {
81301 m[0] = t[0] - 0xffed;
81302 for (i = 1; i < 15; i++) {
81303 m[i] = t[i] - 0xffff - ((m[i-1]>>16) & 1);
81304 m[i-1] &= 0xffff;
81305 }
81306 m[15] = t[15] - 0x7fff - ((m[14]>>16) & 1);
81307 b = (m[15]>>16) & 1;
81308 m[14] &= 0xffff;
81309 sel25519(t, m, 1-b);
81310 }
81311 for (i = 0; i < 16; i++) {
81312 o[2*i] = t[i] & 0xff;
81313 o[2*i+1] = t[i]>>8;
81314 }
81315}
81316
81317function neq25519(a, b) {
81318 var c = new Uint8Array(32), d = new Uint8Array(32);
81319 pack25519(c, a);
81320 pack25519(d, b);
81321 return crypto_verify_32(c, 0, d, 0);
81322}
81323
81324function par25519(a) {
81325 var d = new Uint8Array(32);
81326 pack25519(d, a);
81327 return d[0] & 1;
81328}
81329
81330function unpack25519(o, n) {
81331 var i;
81332 for (i = 0; i < 16; i++) o[i] = n[2*i] + (n[2*i+1] << 8);
81333 o[15] &= 0x7fff;
81334}
81335
81336function A(o, a, b) {
81337 for (var i = 0; i < 16; i++) o[i] = a[i] + b[i];
81338}
81339
81340function Z(o, a, b) {
81341 for (var i = 0; i < 16; i++) o[i] = a[i] - b[i];
81342}
81343
81344function M(o, a, b) {
81345 var v, c,
81346 t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0,
81347 t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0,
81348 t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0,
81349 t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0,
81350 b0 = b[0],
81351 b1 = b[1],
81352 b2 = b[2],
81353 b3 = b[3],
81354 b4 = b[4],
81355 b5 = b[5],
81356 b6 = b[6],
81357 b7 = b[7],
81358 b8 = b[8],
81359 b9 = b[9],
81360 b10 = b[10],
81361 b11 = b[11],
81362 b12 = b[12],
81363 b13 = b[13],
81364 b14 = b[14],
81365 b15 = b[15];
81366
81367 v = a[0];
81368 t0 += v * b0;
81369 t1 += v * b1;
81370 t2 += v * b2;
81371 t3 += v * b3;
81372 t4 += v * b4;
81373 t5 += v * b5;
81374 t6 += v * b6;
81375 t7 += v * b7;
81376 t8 += v * b8;
81377 t9 += v * b9;
81378 t10 += v * b10;
81379 t11 += v * b11;
81380 t12 += v * b12;
81381 t13 += v * b13;
81382 t14 += v * b14;
81383 t15 += v * b15;
81384 v = a[1];
81385 t1 += v * b0;
81386 t2 += v * b1;
81387 t3 += v * b2;
81388 t4 += v * b3;
81389 t5 += v * b4;
81390 t6 += v * b5;
81391 t7 += v * b6;
81392 t8 += v * b7;
81393 t9 += v * b8;
81394 t10 += v * b9;
81395 t11 += v * b10;
81396 t12 += v * b11;
81397 t13 += v * b12;
81398 t14 += v * b13;
81399 t15 += v * b14;
81400 t16 += v * b15;
81401 v = a[2];
81402 t2 += v * b0;
81403 t3 += v * b1;
81404 t4 += v * b2;
81405 t5 += v * b3;
81406 t6 += v * b4;
81407 t7 += v * b5;
81408 t8 += v * b6;
81409 t9 += v * b7;
81410 t10 += v * b8;
81411 t11 += v * b9;
81412 t12 += v * b10;
81413 t13 += v * b11;
81414 t14 += v * b12;
81415 t15 += v * b13;
81416 t16 += v * b14;
81417 t17 += v * b15;
81418 v = a[3];
81419 t3 += v * b0;
81420 t4 += v * b1;
81421 t5 += v * b2;
81422 t6 += v * b3;
81423 t7 += v * b4;
81424 t8 += v * b5;
81425 t9 += v * b6;
81426 t10 += v * b7;
81427 t11 += v * b8;
81428 t12 += v * b9;
81429 t13 += v * b10;
81430 t14 += v * b11;
81431 t15 += v * b12;
81432 t16 += v * b13;
81433 t17 += v * b14;
81434 t18 += v * b15;
81435 v = a[4];
81436 t4 += v * b0;
81437 t5 += v * b1;
81438 t6 += v * b2;
81439 t7 += v * b3;
81440 t8 += v * b4;
81441 t9 += v * b5;
81442 t10 += v * b6;
81443 t11 += v * b7;
81444 t12 += v * b8;
81445 t13 += v * b9;
81446 t14 += v * b10;
81447 t15 += v * b11;
81448 t16 += v * b12;
81449 t17 += v * b13;
81450 t18 += v * b14;
81451 t19 += v * b15;
81452 v = a[5];
81453 t5 += v * b0;
81454 t6 += v * b1;
81455 t7 += v * b2;
81456 t8 += v * b3;
81457 t9 += v * b4;
81458 t10 += v * b5;
81459 t11 += v * b6;
81460 t12 += v * b7;
81461 t13 += v * b8;
81462 t14 += v * b9;
81463 t15 += v * b10;
81464 t16 += v * b11;
81465 t17 += v * b12;
81466 t18 += v * b13;
81467 t19 += v * b14;
81468 t20 += v * b15;
81469 v = a[6];
81470 t6 += v * b0;
81471 t7 += v * b1;
81472 t8 += v * b2;
81473 t9 += v * b3;
81474 t10 += v * b4;
81475 t11 += v * b5;
81476 t12 += v * b6;
81477 t13 += v * b7;
81478 t14 += v * b8;
81479 t15 += v * b9;
81480 t16 += v * b10;
81481 t17 += v * b11;
81482 t18 += v * b12;
81483 t19 += v * b13;
81484 t20 += v * b14;
81485 t21 += v * b15;
81486 v = a[7];
81487 t7 += v * b0;
81488 t8 += v * b1;
81489 t9 += v * b2;
81490 t10 += v * b3;
81491 t11 += v * b4;
81492 t12 += v * b5;
81493 t13 += v * b6;
81494 t14 += v * b7;
81495 t15 += v * b8;
81496 t16 += v * b9;
81497 t17 += v * b10;
81498 t18 += v * b11;
81499 t19 += v * b12;
81500 t20 += v * b13;
81501 t21 += v * b14;
81502 t22 += v * b15;
81503 v = a[8];
81504 t8 += v * b0;
81505 t9 += v * b1;
81506 t10 += v * b2;
81507 t11 += v * b3;
81508 t12 += v * b4;
81509 t13 += v * b5;
81510 t14 += v * b6;
81511 t15 += v * b7;
81512 t16 += v * b8;
81513 t17 += v * b9;
81514 t18 += v * b10;
81515 t19 += v * b11;
81516 t20 += v * b12;
81517 t21 += v * b13;
81518 t22 += v * b14;
81519 t23 += v * b15;
81520 v = a[9];
81521 t9 += v * b0;
81522 t10 += v * b1;
81523 t11 += v * b2;
81524 t12 += v * b3;
81525 t13 += v * b4;
81526 t14 += v * b5;
81527 t15 += v * b6;
81528 t16 += v * b7;
81529 t17 += v * b8;
81530 t18 += v * b9;
81531 t19 += v * b10;
81532 t20 += v * b11;
81533 t21 += v * b12;
81534 t22 += v * b13;
81535 t23 += v * b14;
81536 t24 += v * b15;
81537 v = a[10];
81538 t10 += v * b0;
81539 t11 += v * b1;
81540 t12 += v * b2;
81541 t13 += v * b3;
81542 t14 += v * b4;
81543 t15 += v * b5;
81544 t16 += v * b6;
81545 t17 += v * b7;
81546 t18 += v * b8;
81547 t19 += v * b9;
81548 t20 += v * b10;
81549 t21 += v * b11;
81550 t22 += v * b12;
81551 t23 += v * b13;
81552 t24 += v * b14;
81553 t25 += v * b15;
81554 v = a[11];
81555 t11 += v * b0;
81556 t12 += v * b1;
81557 t13 += v * b2;
81558 t14 += v * b3;
81559 t15 += v * b4;
81560 t16 += v * b5;
81561 t17 += v * b6;
81562 t18 += v * b7;
81563 t19 += v * b8;
81564 t20 += v * b9;
81565 t21 += v * b10;
81566 t22 += v * b11;
81567 t23 += v * b12;
81568 t24 += v * b13;
81569 t25 += v * b14;
81570 t26 += v * b15;
81571 v = a[12];
81572 t12 += v * b0;
81573 t13 += v * b1;
81574 t14 += v * b2;
81575 t15 += v * b3;
81576 t16 += v * b4;
81577 t17 += v * b5;
81578 t18 += v * b6;
81579 t19 += v * b7;
81580 t20 += v * b8;
81581 t21 += v * b9;
81582 t22 += v * b10;
81583 t23 += v * b11;
81584 t24 += v * b12;
81585 t25 += v * b13;
81586 t26 += v * b14;
81587 t27 += v * b15;
81588 v = a[13];
81589 t13 += v * b0;
81590 t14 += v * b1;
81591 t15 += v * b2;
81592 t16 += v * b3;
81593 t17 += v * b4;
81594 t18 += v * b5;
81595 t19 += v * b6;
81596 t20 += v * b7;
81597 t21 += v * b8;
81598 t22 += v * b9;
81599 t23 += v * b10;
81600 t24 += v * b11;
81601 t25 += v * b12;
81602 t26 += v * b13;
81603 t27 += v * b14;
81604 t28 += v * b15;
81605 v = a[14];
81606 t14 += v * b0;
81607 t15 += v * b1;
81608 t16 += v * b2;
81609 t17 += v * b3;
81610 t18 += v * b4;
81611 t19 += v * b5;
81612 t20 += v * b6;
81613 t21 += v * b7;
81614 t22 += v * b8;
81615 t23 += v * b9;
81616 t24 += v * b10;
81617 t25 += v * b11;
81618 t26 += v * b12;
81619 t27 += v * b13;
81620 t28 += v * b14;
81621 t29 += v * b15;
81622 v = a[15];
81623 t15 += v * b0;
81624 t16 += v * b1;
81625 t17 += v * b2;
81626 t18 += v * b3;
81627 t19 += v * b4;
81628 t20 += v * b5;
81629 t21 += v * b6;
81630 t22 += v * b7;
81631 t23 += v * b8;
81632 t24 += v * b9;
81633 t25 += v * b10;
81634 t26 += v * b11;
81635 t27 += v * b12;
81636 t28 += v * b13;
81637 t29 += v * b14;
81638 t30 += v * b15;
81639
81640 t0 += 38 * t16;
81641 t1 += 38 * t17;
81642 t2 += 38 * t18;
81643 t3 += 38 * t19;
81644 t4 += 38 * t20;
81645 t5 += 38 * t21;
81646 t6 += 38 * t22;
81647 t7 += 38 * t23;
81648 t8 += 38 * t24;
81649 t9 += 38 * t25;
81650 t10 += 38 * t26;
81651 t11 += 38 * t27;
81652 t12 += 38 * t28;
81653 t13 += 38 * t29;
81654 t14 += 38 * t30;
81655 // t15 left as is
81656
81657 // first car
81658 c = 1;
81659 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
81660 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
81661 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
81662 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
81663 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
81664 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
81665 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
81666 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
81667 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
81668 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
81669 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
81670 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
81671 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
81672 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
81673 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
81674 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
81675 t0 += c-1 + 37 * (c-1);
81676
81677 // second car
81678 c = 1;
81679 v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536;
81680 v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536;
81681 v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536;
81682 v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536;
81683 v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536;
81684 v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536;
81685 v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536;
81686 v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536;
81687 v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536;
81688 v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536;
81689 v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536;
81690 v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536;
81691 v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536;
81692 v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536;
81693 v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536;
81694 v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536;
81695 t0 += c-1 + 37 * (c-1);
81696
81697 o[ 0] = t0;
81698 o[ 1] = t1;
81699 o[ 2] = t2;
81700 o[ 3] = t3;
81701 o[ 4] = t4;
81702 o[ 5] = t5;
81703 o[ 6] = t6;
81704 o[ 7] = t7;
81705 o[ 8] = t8;
81706 o[ 9] = t9;
81707 o[10] = t10;
81708 o[11] = t11;
81709 o[12] = t12;
81710 o[13] = t13;
81711 o[14] = t14;
81712 o[15] = t15;
81713}
81714
81715function S(o, a) {
81716 M(o, a, a);
81717}
81718
81719function inv25519(o, i) {
81720 var c = gf();
81721 var a;
81722 for (a = 0; a < 16; a++) c[a] = i[a];
81723 for (a = 253; a >= 0; a--) {
81724 S(c, c);
81725 if(a !== 2 && a !== 4) M(c, c, i);
81726 }
81727 for (a = 0; a < 16; a++) o[a] = c[a];
81728}
81729
81730function pow2523(o, i) {
81731 var c = gf();
81732 var a;
81733 for (a = 0; a < 16; a++) c[a] = i[a];
81734 for (a = 250; a >= 0; a--) {
81735 S(c, c);
81736 if(a !== 1) M(c, c, i);
81737 }
81738 for (a = 0; a < 16; a++) o[a] = c[a];
81739}
81740
81741function crypto_scalarmult(q, n, p) {
81742 var z = new Uint8Array(32);
81743 var x = new Float64Array(80), r, i;
81744 var a = gf(), b = gf(), c = gf(),
81745 d = gf(), e = gf(), f = gf();
81746 for (i = 0; i < 31; i++) z[i] = n[i];
81747 z[31]=(n[31]&127)|64;
81748 z[0]&=248;
81749 unpack25519(x,p);
81750 for (i = 0; i < 16; i++) {
81751 b[i]=x[i];
81752 d[i]=a[i]=c[i]=0;
81753 }
81754 a[0]=d[0]=1;
81755 for (i=254; i>=0; --i) {
81756 r=(z[i>>>3]>>>(i&7))&1;
81757 sel25519(a,b,r);
81758 sel25519(c,d,r);
81759 A(e,a,c);
81760 Z(a,a,c);
81761 A(c,b,d);
81762 Z(b,b,d);
81763 S(d,e);
81764 S(f,a);
81765 M(a,c,a);
81766 M(c,b,e);
81767 A(e,a,c);
81768 Z(a,a,c);
81769 S(b,a);
81770 Z(c,d,f);
81771 M(a,c,_121665);
81772 A(a,a,d);
81773 M(c,c,a);
81774 M(a,d,f);
81775 M(d,b,x);
81776 S(b,e);
81777 sel25519(a,b,r);
81778 sel25519(c,d,r);
81779 }
81780 for (i = 0; i < 16; i++) {
81781 x[i+16]=a[i];
81782 x[i+32]=c[i];
81783 x[i+48]=b[i];
81784 x[i+64]=d[i];
81785 }
81786 var x32 = x.subarray(32);
81787 var x16 = x.subarray(16);
81788 inv25519(x32,x32);
81789 M(x16,x16,x32);
81790 pack25519(q,x16);
81791 return 0;
81792}
81793
81794function crypto_scalarmult_base(q, n) {
81795 return crypto_scalarmult(q, n, _9);
81796}
81797
81798function crypto_box_keypair(y, x) {
81799 randombytes(x, 32);
81800 return crypto_scalarmult_base(y, x);
81801}
81802
81803function crypto_box_beforenm(k, y, x) {
81804 var s = new Uint8Array(32);
81805 crypto_scalarmult(s, x, y);
81806 return crypto_core_hsalsa20(k, _0, s, sigma);
81807}
81808
81809var crypto_box_afternm = crypto_secretbox;
81810var crypto_box_open_afternm = crypto_secretbox_open;
81811
81812function crypto_box(c, m, d, n, y, x) {
81813 var k = new Uint8Array(32);
81814 crypto_box_beforenm(k, y, x);
81815 return crypto_box_afternm(c, m, d, n, k);
81816}
81817
81818function crypto_box_open(m, c, d, n, y, x) {
81819 var k = new Uint8Array(32);
81820 crypto_box_beforenm(k, y, x);
81821 return crypto_box_open_afternm(m, c, d, n, k);
81822}
81823
81824var K = [
81825 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
81826 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
81827 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
81828 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
81829 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
81830 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
81831 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
81832 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
81833 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
81834 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
81835 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
81836 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
81837 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
81838 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
81839 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
81840 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
81841 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
81842 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
81843 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
81844 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
81845 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
81846 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
81847 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
81848 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
81849 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
81850 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
81851 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
81852 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
81853 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
81854 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
81855 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
81856 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
81857 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
81858 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
81859 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
81860 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
81861 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
81862 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
81863 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
81864 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
81865];
81866
81867function crypto_hashblocks_hl(hh, hl, m, n) {
81868 var wh = new Int32Array(16), wl = new Int32Array(16),
81869 bh0, bh1, bh2, bh3, bh4, bh5, bh6, bh7,
81870 bl0, bl1, bl2, bl3, bl4, bl5, bl6, bl7,
81871 th, tl, i, j, h, l, a, b, c, d;
81872
81873 var ah0 = hh[0],
81874 ah1 = hh[1],
81875 ah2 = hh[2],
81876 ah3 = hh[3],
81877 ah4 = hh[4],
81878 ah5 = hh[5],
81879 ah6 = hh[6],
81880 ah7 = hh[7],
81881
81882 al0 = hl[0],
81883 al1 = hl[1],
81884 al2 = hl[2],
81885 al3 = hl[3],
81886 al4 = hl[4],
81887 al5 = hl[5],
81888 al6 = hl[6],
81889 al7 = hl[7];
81890
81891 var pos = 0;
81892 while (n >= 128) {
81893 for (i = 0; i < 16; i++) {
81894 j = 8 * i + pos;
81895 wh[i] = (m[j+0] << 24) | (m[j+1] << 16) | (m[j+2] << 8) | m[j+3];
81896 wl[i] = (m[j+4] << 24) | (m[j+5] << 16) | (m[j+6] << 8) | m[j+7];
81897 }
81898 for (i = 0; i < 80; i++) {
81899 bh0 = ah0;
81900 bh1 = ah1;
81901 bh2 = ah2;
81902 bh3 = ah3;
81903 bh4 = ah4;
81904 bh5 = ah5;
81905 bh6 = ah6;
81906 bh7 = ah7;
81907
81908 bl0 = al0;
81909 bl1 = al1;
81910 bl2 = al2;
81911 bl3 = al3;
81912 bl4 = al4;
81913 bl5 = al5;
81914 bl6 = al6;
81915 bl7 = al7;
81916
81917 // add
81918 h = ah7;
81919 l = al7;
81920
81921 a = l & 0xffff; b = l >>> 16;
81922 c = h & 0xffff; d = h >>> 16;
81923
81924 // Sigma1
81925 h = ((ah4 >>> 14) | (al4 << (32-14))) ^ ((ah4 >>> 18) | (al4 << (32-18))) ^ ((al4 >>> (41-32)) | (ah4 << (32-(41-32))));
81926 l = ((al4 >>> 14) | (ah4 << (32-14))) ^ ((al4 >>> 18) | (ah4 << (32-18))) ^ ((ah4 >>> (41-32)) | (al4 << (32-(41-32))));
81927
81928 a += l & 0xffff; b += l >>> 16;
81929 c += h & 0xffff; d += h >>> 16;
81930
81931 // Ch
81932 h = (ah4 & ah5) ^ (~ah4 & ah6);
81933 l = (al4 & al5) ^ (~al4 & al6);
81934
81935 a += l & 0xffff; b += l >>> 16;
81936 c += h & 0xffff; d += h >>> 16;
81937
81938 // K
81939 h = K[i*2];
81940 l = K[i*2+1];
81941
81942 a += l & 0xffff; b += l >>> 16;
81943 c += h & 0xffff; d += h >>> 16;
81944
81945 // w
81946 h = wh[i%16];
81947 l = wl[i%16];
81948
81949 a += l & 0xffff; b += l >>> 16;
81950 c += h & 0xffff; d += h >>> 16;
81951
81952 b += a >>> 16;
81953 c += b >>> 16;
81954 d += c >>> 16;
81955
81956 th = c & 0xffff | d << 16;
81957 tl = a & 0xffff | b << 16;
81958
81959 // add
81960 h = th;
81961 l = tl;
81962
81963 a = l & 0xffff; b = l >>> 16;
81964 c = h & 0xffff; d = h >>> 16;
81965
81966 // Sigma0
81967 h = ((ah0 >>> 28) | (al0 << (32-28))) ^ ((al0 >>> (34-32)) | (ah0 << (32-(34-32)))) ^ ((al0 >>> (39-32)) | (ah0 << (32-(39-32))));
81968 l = ((al0 >>> 28) | (ah0 << (32-28))) ^ ((ah0 >>> (34-32)) | (al0 << (32-(34-32)))) ^ ((ah0 >>> (39-32)) | (al0 << (32-(39-32))));
81969
81970 a += l & 0xffff; b += l >>> 16;
81971 c += h & 0xffff; d += h >>> 16;
81972
81973 // Maj
81974 h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2);
81975 l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2);
81976
81977 a += l & 0xffff; b += l >>> 16;
81978 c += h & 0xffff; d += h >>> 16;
81979
81980 b += a >>> 16;
81981 c += b >>> 16;
81982 d += c >>> 16;
81983
81984 bh7 = (c & 0xffff) | (d << 16);
81985 bl7 = (a & 0xffff) | (b << 16);
81986
81987 // add
81988 h = bh3;
81989 l = bl3;
81990
81991 a = l & 0xffff; b = l >>> 16;
81992 c = h & 0xffff; d = h >>> 16;
81993
81994 h = th;
81995 l = tl;
81996
81997 a += l & 0xffff; b += l >>> 16;
81998 c += h & 0xffff; d += h >>> 16;
81999
82000 b += a >>> 16;
82001 c += b >>> 16;
82002 d += c >>> 16;
82003
82004 bh3 = (c & 0xffff) | (d << 16);
82005 bl3 = (a & 0xffff) | (b << 16);
82006
82007 ah1 = bh0;
82008 ah2 = bh1;
82009 ah3 = bh2;
82010 ah4 = bh3;
82011 ah5 = bh4;
82012 ah6 = bh5;
82013 ah7 = bh6;
82014 ah0 = bh7;
82015
82016 al1 = bl0;
82017 al2 = bl1;
82018 al3 = bl2;
82019 al4 = bl3;
82020 al5 = bl4;
82021 al6 = bl5;
82022 al7 = bl6;
82023 al0 = bl7;
82024
82025 if (i%16 === 15) {
82026 for (j = 0; j < 16; j++) {
82027 // add
82028 h = wh[j];
82029 l = wl[j];
82030
82031 a = l & 0xffff; b = l >>> 16;
82032 c = h & 0xffff; d = h >>> 16;
82033
82034 h = wh[(j+9)%16];
82035 l = wl[(j+9)%16];
82036
82037 a += l & 0xffff; b += l >>> 16;
82038 c += h & 0xffff; d += h >>> 16;
82039
82040 // sigma0
82041 th = wh[(j+1)%16];
82042 tl = wl[(j+1)%16];
82043 h = ((th >>> 1) | (tl << (32-1))) ^ ((th >>> 8) | (tl << (32-8))) ^ (th >>> 7);
82044 l = ((tl >>> 1) | (th << (32-1))) ^ ((tl >>> 8) | (th << (32-8))) ^ ((tl >>> 7) | (th << (32-7)));
82045
82046 a += l & 0xffff; b += l >>> 16;
82047 c += h & 0xffff; d += h >>> 16;
82048
82049 // sigma1
82050 th = wh[(j+14)%16];
82051 tl = wl[(j+14)%16];
82052 h = ((th >>> 19) | (tl << (32-19))) ^ ((tl >>> (61-32)) | (th << (32-(61-32)))) ^ (th >>> 6);
82053 l = ((tl >>> 19) | (th << (32-19))) ^ ((th >>> (61-32)) | (tl << (32-(61-32)))) ^ ((tl >>> 6) | (th << (32-6)));
82054
82055 a += l & 0xffff; b += l >>> 16;
82056 c += h & 0xffff; d += h >>> 16;
82057
82058 b += a >>> 16;
82059 c += b >>> 16;
82060 d += c >>> 16;
82061
82062 wh[j] = (c & 0xffff) | (d << 16);
82063 wl[j] = (a & 0xffff) | (b << 16);
82064 }
82065 }
82066 }
82067
82068 // add
82069 h = ah0;
82070 l = al0;
82071
82072 a = l & 0xffff; b = l >>> 16;
82073 c = h & 0xffff; d = h >>> 16;
82074
82075 h = hh[0];
82076 l = hl[0];
82077
82078 a += l & 0xffff; b += l >>> 16;
82079 c += h & 0xffff; d += h >>> 16;
82080
82081 b += a >>> 16;
82082 c += b >>> 16;
82083 d += c >>> 16;
82084
82085 hh[0] = ah0 = (c & 0xffff) | (d << 16);
82086 hl[0] = al0 = (a & 0xffff) | (b << 16);
82087
82088 h = ah1;
82089 l = al1;
82090
82091 a = l & 0xffff; b = l >>> 16;
82092 c = h & 0xffff; d = h >>> 16;
82093
82094 h = hh[1];
82095 l = hl[1];
82096
82097 a += l & 0xffff; b += l >>> 16;
82098 c += h & 0xffff; d += h >>> 16;
82099
82100 b += a >>> 16;
82101 c += b >>> 16;
82102 d += c >>> 16;
82103
82104 hh[1] = ah1 = (c & 0xffff) | (d << 16);
82105 hl[1] = al1 = (a & 0xffff) | (b << 16);
82106
82107 h = ah2;
82108 l = al2;
82109
82110 a = l & 0xffff; b = l >>> 16;
82111 c = h & 0xffff; d = h >>> 16;
82112
82113 h = hh[2];
82114 l = hl[2];
82115
82116 a += l & 0xffff; b += l >>> 16;
82117 c += h & 0xffff; d += h >>> 16;
82118
82119 b += a >>> 16;
82120 c += b >>> 16;
82121 d += c >>> 16;
82122
82123 hh[2] = ah2 = (c & 0xffff) | (d << 16);
82124 hl[2] = al2 = (a & 0xffff) | (b << 16);
82125
82126 h = ah3;
82127 l = al3;
82128
82129 a = l & 0xffff; b = l >>> 16;
82130 c = h & 0xffff; d = h >>> 16;
82131
82132 h = hh[3];
82133 l = hl[3];
82134
82135 a += l & 0xffff; b += l >>> 16;
82136 c += h & 0xffff; d += h >>> 16;
82137
82138 b += a >>> 16;
82139 c += b >>> 16;
82140 d += c >>> 16;
82141
82142 hh[3] = ah3 = (c & 0xffff) | (d << 16);
82143 hl[3] = al3 = (a & 0xffff) | (b << 16);
82144
82145 h = ah4;
82146 l = al4;
82147
82148 a = l & 0xffff; b = l >>> 16;
82149 c = h & 0xffff; d = h >>> 16;
82150
82151 h = hh[4];
82152 l = hl[4];
82153
82154 a += l & 0xffff; b += l >>> 16;
82155 c += h & 0xffff; d += h >>> 16;
82156
82157 b += a >>> 16;
82158 c += b >>> 16;
82159 d += c >>> 16;
82160
82161 hh[4] = ah4 = (c & 0xffff) | (d << 16);
82162 hl[4] = al4 = (a & 0xffff) | (b << 16);
82163
82164 h = ah5;
82165 l = al5;
82166
82167 a = l & 0xffff; b = l >>> 16;
82168 c = h & 0xffff; d = h >>> 16;
82169
82170 h = hh[5];
82171 l = hl[5];
82172
82173 a += l & 0xffff; b += l >>> 16;
82174 c += h & 0xffff; d += h >>> 16;
82175
82176 b += a >>> 16;
82177 c += b >>> 16;
82178 d += c >>> 16;
82179
82180 hh[5] = ah5 = (c & 0xffff) | (d << 16);
82181 hl[5] = al5 = (a & 0xffff) | (b << 16);
82182
82183 h = ah6;
82184 l = al6;
82185
82186 a = l & 0xffff; b = l >>> 16;
82187 c = h & 0xffff; d = h >>> 16;
82188
82189 h = hh[6];
82190 l = hl[6];
82191
82192 a += l & 0xffff; b += l >>> 16;
82193 c += h & 0xffff; d += h >>> 16;
82194
82195 b += a >>> 16;
82196 c += b >>> 16;
82197 d += c >>> 16;
82198
82199 hh[6] = ah6 = (c & 0xffff) | (d << 16);
82200 hl[6] = al6 = (a & 0xffff) | (b << 16);
82201
82202 h = ah7;
82203 l = al7;
82204
82205 a = l & 0xffff; b = l >>> 16;
82206 c = h & 0xffff; d = h >>> 16;
82207
82208 h = hh[7];
82209 l = hl[7];
82210
82211 a += l & 0xffff; b += l >>> 16;
82212 c += h & 0xffff; d += h >>> 16;
82213
82214 b += a >>> 16;
82215 c += b >>> 16;
82216 d += c >>> 16;
82217
82218 hh[7] = ah7 = (c & 0xffff) | (d << 16);
82219 hl[7] = al7 = (a & 0xffff) | (b << 16);
82220
82221 pos += 128;
82222 n -= 128;
82223 }
82224
82225 return n;
82226}
82227
82228function crypto_hash(out, m, n) {
82229 var hh = new Int32Array(8),
82230 hl = new Int32Array(8),
82231 x = new Uint8Array(256),
82232 i, b = n;
82233
82234 hh[0] = 0x6a09e667;
82235 hh[1] = 0xbb67ae85;
82236 hh[2] = 0x3c6ef372;
82237 hh[3] = 0xa54ff53a;
82238 hh[4] = 0x510e527f;
82239 hh[5] = 0x9b05688c;
82240 hh[6] = 0x1f83d9ab;
82241 hh[7] = 0x5be0cd19;
82242
82243 hl[0] = 0xf3bcc908;
82244 hl[1] = 0x84caa73b;
82245 hl[2] = 0xfe94f82b;
82246 hl[3] = 0x5f1d36f1;
82247 hl[4] = 0xade682d1;
82248 hl[5] = 0x2b3e6c1f;
82249 hl[6] = 0xfb41bd6b;
82250 hl[7] = 0x137e2179;
82251
82252 crypto_hashblocks_hl(hh, hl, m, n);
82253 n %= 128;
82254
82255 for (i = 0; i < n; i++) x[i] = m[b-n+i];
82256 x[n] = 128;
82257
82258 n = 256-128*(n<112?1:0);
82259 x[n-9] = 0;
82260 ts64(x, n-8, (b / 0x20000000) | 0, b << 3);
82261 crypto_hashblocks_hl(hh, hl, x, n);
82262
82263 for (i = 0; i < 8; i++) ts64(out, 8*i, hh[i], hl[i]);
82264
82265 return 0;
82266}
82267
82268function add(p, q) {
82269 var a = gf(), b = gf(), c = gf(),
82270 d = gf(), e = gf(), f = gf(),
82271 g = gf(), h = gf(), t = gf();
82272
82273 Z(a, p[1], p[0]);
82274 Z(t, q[1], q[0]);
82275 M(a, a, t);
82276 A(b, p[0], p[1]);
82277 A(t, q[0], q[1]);
82278 M(b, b, t);
82279 M(c, p[3], q[3]);
82280 M(c, c, D2);
82281 M(d, p[2], q[2]);
82282 A(d, d, d);
82283 Z(e, b, a);
82284 Z(f, d, c);
82285 A(g, d, c);
82286 A(h, b, a);
82287
82288 M(p[0], e, f);
82289 M(p[1], h, g);
82290 M(p[2], g, f);
82291 M(p[3], e, h);
82292}
82293
82294function cswap(p, q, b) {
82295 var i;
82296 for (i = 0; i < 4; i++) {
82297 sel25519(p[i], q[i], b);
82298 }
82299}
82300
82301function pack(r, p) {
82302 var tx = gf(), ty = gf(), zi = gf();
82303 inv25519(zi, p[2]);
82304 M(tx, p[0], zi);
82305 M(ty, p[1], zi);
82306 pack25519(r, ty);
82307 r[31] ^= par25519(tx) << 7;
82308}
82309
82310function scalarmult(p, q, s) {
82311 var b, i;
82312 set25519(p[0], gf0);
82313 set25519(p[1], gf1);
82314 set25519(p[2], gf1);
82315 set25519(p[3], gf0);
82316 for (i = 255; i >= 0; --i) {
82317 b = (s[(i/8)|0] >> (i&7)) & 1;
82318 cswap(p, q, b);
82319 add(q, p);
82320 add(p, p);
82321 cswap(p, q, b);
82322 }
82323}
82324
82325function scalarbase(p, s) {
82326 var q = [gf(), gf(), gf(), gf()];
82327 set25519(q[0], X);
82328 set25519(q[1], Y);
82329 set25519(q[2], gf1);
82330 M(q[3], X, Y);
82331 scalarmult(p, q, s);
82332}
82333
82334function crypto_sign_keypair(pk, sk, seeded) {
82335 var d = new Uint8Array(64);
82336 var p = [gf(), gf(), gf(), gf()];
82337 var i;
82338
82339 if (!seeded) randombytes(sk, 32);
82340 crypto_hash(d, sk, 32);
82341 d[0] &= 248;
82342 d[31] &= 127;
82343 d[31] |= 64;
82344
82345 scalarbase(p, d);
82346 pack(pk, p);
82347
82348 for (i = 0; i < 32; i++) sk[i+32] = pk[i];
82349 return 0;
82350}
82351
82352var 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]);
82353
82354function modL(r, x) {
82355 var carry, i, j, k;
82356 for (i = 63; i >= 32; --i) {
82357 carry = 0;
82358 for (j = i - 32, k = i - 12; j < k; ++j) {
82359 x[j] += carry - 16 * x[i] * L[j - (i - 32)];
82360 carry = (x[j] + 128) >> 8;
82361 x[j] -= carry * 256;
82362 }
82363 x[j] += carry;
82364 x[i] = 0;
82365 }
82366 carry = 0;
82367 for (j = 0; j < 32; j++) {
82368 x[j] += carry - (x[31] >> 4) * L[j];
82369 carry = x[j] >> 8;
82370 x[j] &= 255;
82371 }
82372 for (j = 0; j < 32; j++) x[j] -= carry * L[j];
82373 for (i = 0; i < 32; i++) {
82374 x[i+1] += x[i] >> 8;
82375 r[i] = x[i] & 255;
82376 }
82377}
82378
82379function reduce(r) {
82380 var x = new Float64Array(64), i;
82381 for (i = 0; i < 64; i++) x[i] = r[i];
82382 for (i = 0; i < 64; i++) r[i] = 0;
82383 modL(r, x);
82384}
82385
82386// Note: difference from C - smlen returned, not passed as argument.
82387function crypto_sign(sm, m, n, sk) {
82388 var d = new Uint8Array(64), h = new Uint8Array(64), r = new Uint8Array(64);
82389 var i, j, x = new Float64Array(64);
82390 var p = [gf(), gf(), gf(), gf()];
82391
82392 crypto_hash(d, sk, 32);
82393 d[0] &= 248;
82394 d[31] &= 127;
82395 d[31] |= 64;
82396
82397 var smlen = n + 64;
82398 for (i = 0; i < n; i++) sm[64 + i] = m[i];
82399 for (i = 0; i < 32; i++) sm[32 + i] = d[32 + i];
82400
82401 crypto_hash(r, sm.subarray(32), n+32);
82402 reduce(r);
82403 scalarbase(p, r);
82404 pack(sm, p);
82405
82406 for (i = 32; i < 64; i++) sm[i] = sk[i];
82407 crypto_hash(h, sm, n + 64);
82408 reduce(h);
82409
82410 for (i = 0; i < 64; i++) x[i] = 0;
82411 for (i = 0; i < 32; i++) x[i] = r[i];
82412 for (i = 0; i < 32; i++) {
82413 for (j = 0; j < 32; j++) {
82414 x[i+j] += h[i] * d[j];
82415 }
82416 }
82417
82418 modL(sm.subarray(32), x);
82419 return smlen;
82420}
82421
82422function unpackneg(r, p) {
82423 var t = gf(), chk = gf(), num = gf(),
82424 den = gf(), den2 = gf(), den4 = gf(),
82425 den6 = gf();
82426
82427 set25519(r[2], gf1);
82428 unpack25519(r[1], p);
82429 S(num, r[1]);
82430 M(den, num, D);
82431 Z(num, num, r[2]);
82432 A(den, r[2], den);
82433
82434 S(den2, den);
82435 S(den4, den2);
82436 M(den6, den4, den2);
82437 M(t, den6, num);
82438 M(t, t, den);
82439
82440 pow2523(t, t);
82441 M(t, t, num);
82442 M(t, t, den);
82443 M(t, t, den);
82444 M(r[0], t, den);
82445
82446 S(chk, r[0]);
82447 M(chk, chk, den);
82448 if (neq25519(chk, num)) M(r[0], r[0], I);
82449
82450 S(chk, r[0]);
82451 M(chk, chk, den);
82452 if (neq25519(chk, num)) return -1;
82453
82454 if (par25519(r[0]) === (p[31]>>7)) Z(r[0], gf0, r[0]);
82455
82456 M(r[3], r[0], r[1]);
82457 return 0;
82458}
82459
82460function crypto_sign_open(m, sm, n, pk) {
82461 var i, mlen;
82462 var t = new Uint8Array(32), h = new Uint8Array(64);
82463 var p = [gf(), gf(), gf(), gf()],
82464 q = [gf(), gf(), gf(), gf()];
82465
82466 mlen = -1;
82467 if (n < 64) return -1;
82468
82469 if (unpackneg(q, pk)) return -1;
82470
82471 for (i = 0; i < n; i++) m[i] = sm[i];
82472 for (i = 0; i < 32; i++) m[i+32] = pk[i];
82473 crypto_hash(h, m, n);
82474 reduce(h);
82475 scalarmult(p, q, h);
82476
82477 scalarbase(q, sm.subarray(32));
82478 add(p, q);
82479 pack(t, p);
82480
82481 n -= 64;
82482 if (crypto_verify_32(sm, 0, t, 0)) {
82483 for (i = 0; i < n; i++) m[i] = 0;
82484 return -1;
82485 }
82486
82487 for (i = 0; i < n; i++) m[i] = sm[i + 64];
82488 mlen = n;
82489 return mlen;
82490}
82491
82492var crypto_secretbox_KEYBYTES = 32,
82493 crypto_secretbox_NONCEBYTES = 24,
82494 crypto_secretbox_ZEROBYTES = 32,
82495 crypto_secretbox_BOXZEROBYTES = 16,
82496 crypto_scalarmult_BYTES = 32,
82497 crypto_scalarmult_SCALARBYTES = 32,
82498 crypto_box_PUBLICKEYBYTES = 32,
82499 crypto_box_SECRETKEYBYTES = 32,
82500 crypto_box_BEFORENMBYTES = 32,
82501 crypto_box_NONCEBYTES = crypto_secretbox_NONCEBYTES,
82502 crypto_box_ZEROBYTES = crypto_secretbox_ZEROBYTES,
82503 crypto_box_BOXZEROBYTES = crypto_secretbox_BOXZEROBYTES,
82504 crypto_sign_BYTES = 64,
82505 crypto_sign_PUBLICKEYBYTES = 32,
82506 crypto_sign_SECRETKEYBYTES = 64,
82507 crypto_sign_SEEDBYTES = 32,
82508 crypto_hash_BYTES = 64;
82509
82510nacl.lowlevel = {
82511 crypto_core_hsalsa20: crypto_core_hsalsa20,
82512 crypto_stream_xor: crypto_stream_xor,
82513 crypto_stream: crypto_stream,
82514 crypto_stream_salsa20_xor: crypto_stream_salsa20_xor,
82515 crypto_stream_salsa20: crypto_stream_salsa20,
82516 crypto_onetimeauth: crypto_onetimeauth,
82517 crypto_onetimeauth_verify: crypto_onetimeauth_verify,
82518 crypto_verify_16: crypto_verify_16,
82519 crypto_verify_32: crypto_verify_32,
82520 crypto_secretbox: crypto_secretbox,
82521 crypto_secretbox_open: crypto_secretbox_open,
82522 crypto_scalarmult: crypto_scalarmult,
82523 crypto_scalarmult_base: crypto_scalarmult_base,
82524 crypto_box_beforenm: crypto_box_beforenm,
82525 crypto_box_afternm: crypto_box_afternm,
82526 crypto_box: crypto_box,
82527 crypto_box_open: crypto_box_open,
82528 crypto_box_keypair: crypto_box_keypair,
82529 crypto_hash: crypto_hash,
82530 crypto_sign: crypto_sign,
82531 crypto_sign_keypair: crypto_sign_keypair,
82532 crypto_sign_open: crypto_sign_open,
82533
82534 crypto_secretbox_KEYBYTES: crypto_secretbox_KEYBYTES,
82535 crypto_secretbox_NONCEBYTES: crypto_secretbox_NONCEBYTES,
82536 crypto_secretbox_ZEROBYTES: crypto_secretbox_ZEROBYTES,
82537 crypto_secretbox_BOXZEROBYTES: crypto_secretbox_BOXZEROBYTES,
82538 crypto_scalarmult_BYTES: crypto_scalarmult_BYTES,
82539 crypto_scalarmult_SCALARBYTES: crypto_scalarmult_SCALARBYTES,
82540 crypto_box_PUBLICKEYBYTES: crypto_box_PUBLICKEYBYTES,
82541 crypto_box_SECRETKEYBYTES: crypto_box_SECRETKEYBYTES,
82542 crypto_box_BEFORENMBYTES: crypto_box_BEFORENMBYTES,
82543 crypto_box_NONCEBYTES: crypto_box_NONCEBYTES,
82544 crypto_box_ZEROBYTES: crypto_box_ZEROBYTES,
82545 crypto_box_BOXZEROBYTES: crypto_box_BOXZEROBYTES,
82546 crypto_sign_BYTES: crypto_sign_BYTES,
82547 crypto_sign_PUBLICKEYBYTES: crypto_sign_PUBLICKEYBYTES,
82548 crypto_sign_SECRETKEYBYTES: crypto_sign_SECRETKEYBYTES,
82549 crypto_sign_SEEDBYTES: crypto_sign_SEEDBYTES,
82550 crypto_hash_BYTES: crypto_hash_BYTES
82551};
82552
82553/* High-level API */
82554
82555function checkLengths(k, n) {
82556 if (k.length !== crypto_secretbox_KEYBYTES) throw new Error('bad key size');
82557 if (n.length !== crypto_secretbox_NONCEBYTES) throw new Error('bad nonce size');
82558}
82559
82560function checkBoxLengths(pk, sk) {
82561 if (pk.length !== crypto_box_PUBLICKEYBYTES) throw new Error('bad public key size');
82562 if (sk.length !== crypto_box_SECRETKEYBYTES) throw new Error('bad secret key size');
82563}
82564
82565function checkArrayTypes() {
82566 var t, i;
82567 for (i = 0; i < arguments.length; i++) {
82568 if ((t = Object.prototype.toString.call(arguments[i])) !== '[object Uint8Array]')
82569 throw new TypeError('unexpected type ' + t + ', use Uint8Array');
82570 }
82571}
82572
82573function cleanup(arr) {
82574 for (var i = 0; i < arr.length; i++) arr[i] = 0;
82575}
82576
82577// TODO: Completely remove this in v0.15.
82578if (!nacl.util) {
82579 nacl.util = {};
82580 nacl.util.decodeUTF8 = nacl.util.encodeUTF8 = nacl.util.encodeBase64 = nacl.util.decodeBase64 = function() {
82581 throw new Error('nacl.util moved into separate package: https://github.com/dchest/tweetnacl-util-js');
82582 };
82583}
82584
82585nacl.randomBytes = function(n) {
82586 var b = new Uint8Array(n);
82587 randombytes(b, n);
82588 return b;
82589};
82590
82591nacl.secretbox = function(msg, nonce, key) {
82592 checkArrayTypes(msg, nonce, key);
82593 checkLengths(key, nonce);
82594 var m = new Uint8Array(crypto_secretbox_ZEROBYTES + msg.length);
82595 var c = new Uint8Array(m.length);
82596 for (var i = 0; i < msg.length; i++) m[i+crypto_secretbox_ZEROBYTES] = msg[i];
82597 crypto_secretbox(c, m, m.length, nonce, key);
82598 return c.subarray(crypto_secretbox_BOXZEROBYTES);
82599};
82600
82601nacl.secretbox.open = function(box, nonce, key) {
82602 checkArrayTypes(box, nonce, key);
82603 checkLengths(key, nonce);
82604 var c = new Uint8Array(crypto_secretbox_BOXZEROBYTES + box.length);
82605 var m = new Uint8Array(c.length);
82606 for (var i = 0; i < box.length; i++) c[i+crypto_secretbox_BOXZEROBYTES] = box[i];
82607 if (c.length < 32) return false;
82608 if (crypto_secretbox_open(m, c, c.length, nonce, key) !== 0) return false;
82609 return m.subarray(crypto_secretbox_ZEROBYTES);
82610};
82611
82612nacl.secretbox.keyLength = crypto_secretbox_KEYBYTES;
82613nacl.secretbox.nonceLength = crypto_secretbox_NONCEBYTES;
82614nacl.secretbox.overheadLength = crypto_secretbox_BOXZEROBYTES;
82615
82616nacl.scalarMult = function(n, p) {
82617 checkArrayTypes(n, p);
82618 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
82619 if (p.length !== crypto_scalarmult_BYTES) throw new Error('bad p size');
82620 var q = new Uint8Array(crypto_scalarmult_BYTES);
82621 crypto_scalarmult(q, n, p);
82622 return q;
82623};
82624
82625nacl.scalarMult.base = function(n) {
82626 checkArrayTypes(n);
82627 if (n.length !== crypto_scalarmult_SCALARBYTES) throw new Error('bad n size');
82628 var q = new Uint8Array(crypto_scalarmult_BYTES);
82629 crypto_scalarmult_base(q, n);
82630 return q;
82631};
82632
82633nacl.scalarMult.scalarLength = crypto_scalarmult_SCALARBYTES;
82634nacl.scalarMult.groupElementLength = crypto_scalarmult_BYTES;
82635
82636nacl.box = function(msg, nonce, publicKey, secretKey) {
82637 var k = nacl.box.before(publicKey, secretKey);
82638 return nacl.secretbox(msg, nonce, k);
82639};
82640
82641nacl.box.before = function(publicKey, secretKey) {
82642 checkArrayTypes(publicKey, secretKey);
82643 checkBoxLengths(publicKey, secretKey);
82644 var k = new Uint8Array(crypto_box_BEFORENMBYTES);
82645 crypto_box_beforenm(k, publicKey, secretKey);
82646 return k;
82647};
82648
82649nacl.box.after = nacl.secretbox;
82650
82651nacl.box.open = function(msg, nonce, publicKey, secretKey) {
82652 var k = nacl.box.before(publicKey, secretKey);
82653 return nacl.secretbox.open(msg, nonce, k);
82654};
82655
82656nacl.box.open.after = nacl.secretbox.open;
82657
82658nacl.box.keyPair = function() {
82659 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
82660 var sk = new Uint8Array(crypto_box_SECRETKEYBYTES);
82661 crypto_box_keypair(pk, sk);
82662 return {publicKey: pk, secretKey: sk};
82663};
82664
82665nacl.box.keyPair.fromSecretKey = function(secretKey) {
82666 checkArrayTypes(secretKey);
82667 if (secretKey.length !== crypto_box_SECRETKEYBYTES)
82668 throw new Error('bad secret key size');
82669 var pk = new Uint8Array(crypto_box_PUBLICKEYBYTES);
82670 crypto_scalarmult_base(pk, secretKey);
82671 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
82672};
82673
82674nacl.box.publicKeyLength = crypto_box_PUBLICKEYBYTES;
82675nacl.box.secretKeyLength = crypto_box_SECRETKEYBYTES;
82676nacl.box.sharedKeyLength = crypto_box_BEFORENMBYTES;
82677nacl.box.nonceLength = crypto_box_NONCEBYTES;
82678nacl.box.overheadLength = nacl.secretbox.overheadLength;
82679
82680nacl.sign = function(msg, secretKey) {
82681 checkArrayTypes(msg, secretKey);
82682 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
82683 throw new Error('bad secret key size');
82684 var signedMsg = new Uint8Array(crypto_sign_BYTES+msg.length);
82685 crypto_sign(signedMsg, msg, msg.length, secretKey);
82686 return signedMsg;
82687};
82688
82689nacl.sign.open = function(signedMsg, publicKey) {
82690 if (arguments.length !== 2)
82691 throw new Error('nacl.sign.open accepts 2 arguments; did you mean to use nacl.sign.detached.verify?');
82692 checkArrayTypes(signedMsg, publicKey);
82693 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
82694 throw new Error('bad public key size');
82695 var tmp = new Uint8Array(signedMsg.length);
82696 var mlen = crypto_sign_open(tmp, signedMsg, signedMsg.length, publicKey);
82697 if (mlen < 0) return null;
82698 var m = new Uint8Array(mlen);
82699 for (var i = 0; i < m.length; i++) m[i] = tmp[i];
82700 return m;
82701};
82702
82703nacl.sign.detached = function(msg, secretKey) {
82704 var signedMsg = nacl.sign(msg, secretKey);
82705 var sig = new Uint8Array(crypto_sign_BYTES);
82706 for (var i = 0; i < sig.length; i++) sig[i] = signedMsg[i];
82707 return sig;
82708};
82709
82710nacl.sign.detached.verify = function(msg, sig, publicKey) {
82711 checkArrayTypes(msg, sig, publicKey);
82712 if (sig.length !== crypto_sign_BYTES)
82713 throw new Error('bad signature size');
82714 if (publicKey.length !== crypto_sign_PUBLICKEYBYTES)
82715 throw new Error('bad public key size');
82716 var sm = new Uint8Array(crypto_sign_BYTES + msg.length);
82717 var m = new Uint8Array(crypto_sign_BYTES + msg.length);
82718 var i;
82719 for (i = 0; i < crypto_sign_BYTES; i++) sm[i] = sig[i];
82720 for (i = 0; i < msg.length; i++) sm[i+crypto_sign_BYTES] = msg[i];
82721 return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0);
82722};
82723
82724nacl.sign.keyPair = function() {
82725 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
82726 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
82727 crypto_sign_keypair(pk, sk);
82728 return {publicKey: pk, secretKey: sk};
82729};
82730
82731nacl.sign.keyPair.fromSecretKey = function(secretKey) {
82732 checkArrayTypes(secretKey);
82733 if (secretKey.length !== crypto_sign_SECRETKEYBYTES)
82734 throw new Error('bad secret key size');
82735 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
82736 for (var i = 0; i < pk.length; i++) pk[i] = secretKey[32+i];
82737 return {publicKey: pk, secretKey: new Uint8Array(secretKey)};
82738};
82739
82740nacl.sign.keyPair.fromSeed = function(seed) {
82741 checkArrayTypes(seed);
82742 if (seed.length !== crypto_sign_SEEDBYTES)
82743 throw new Error('bad seed size');
82744 var pk = new Uint8Array(crypto_sign_PUBLICKEYBYTES);
82745 var sk = new Uint8Array(crypto_sign_SECRETKEYBYTES);
82746 for (var i = 0; i < 32; i++) sk[i] = seed[i];
82747 crypto_sign_keypair(pk, sk, true);
82748 return {publicKey: pk, secretKey: sk};
82749};
82750
82751nacl.sign.publicKeyLength = crypto_sign_PUBLICKEYBYTES;
82752nacl.sign.secretKeyLength = crypto_sign_SECRETKEYBYTES;
82753nacl.sign.seedLength = crypto_sign_SEEDBYTES;
82754nacl.sign.signatureLength = crypto_sign_BYTES;
82755
82756nacl.hash = function(msg) {
82757 checkArrayTypes(msg);
82758 var h = new Uint8Array(crypto_hash_BYTES);
82759 crypto_hash(h, msg, msg.length);
82760 return h;
82761};
82762
82763nacl.hash.hashLength = crypto_hash_BYTES;
82764
82765nacl.verify = function(x, y) {
82766 checkArrayTypes(x, y);
82767 // Zero length arguments are considered not equal.
82768 if (x.length === 0 || y.length === 0) return false;
82769 if (x.length !== y.length) return false;
82770 return (vn(x, 0, y, 0, x.length) === 0) ? true : false;
82771};
82772
82773nacl.setPRNG = function(fn) {
82774 randombytes = fn;
82775};
82776
82777(function() {
82778 // Initialize PRNG if environment provides CSPRNG.
82779 // If not, methods calling randombytes will throw.
82780 var crypto = typeof self !== 'undefined' ? (self.crypto || self.msCrypto) : null;
82781 if (crypto && crypto.getRandomValues) {
82782 // Browsers.
82783 var QUOTA = 65536;
82784 nacl.setPRNG(function(x, n) {
82785 var i, v = new Uint8Array(n);
82786 for (i = 0; i < n; i += QUOTA) {
82787 crypto.getRandomValues(v.subarray(i, i + Math.min(n - i, QUOTA)));
82788 }
82789 for (i = 0; i < n; i++) x[i] = v[i];
82790 cleanup(v);
82791 });
82792 } else if (typeof require !== 'undefined') {
82793 // Node.js.
82794 crypto = require('crypto');
82795 if (crypto && crypto.randomBytes) {
82796 nacl.setPRNG(function(x, n) {
82797 var i, v = crypto.randomBytes(n);
82798 for (i = 0; i < n; i++) x[i] = v[i];
82799 cleanup(v);
82800 });
82801 }
82802 }
82803})();
82804
82805})(typeof module !== 'undefined' && module.exports ? module.exports : (self.nacl = self.nacl || {}));
82806
82807},{"crypto":82}],392:[function(require,module,exports){
82808/** @license URI.js v4.2.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */
82809(function (global, factory) {
82810 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
82811 typeof define === 'function' && define.amd ? define(['exports'], factory) :
82812 (factory((global.URI = global.URI || {})));
82813}(this, (function (exports) { 'use strict';
82814
82815function merge() {
82816 for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) {
82817 sets[_key] = arguments[_key];
82818 }
82819
82820 if (sets.length > 1) {
82821 sets[0] = sets[0].slice(0, -1);
82822 var xl = sets.length - 1;
82823 for (var x = 1; x < xl; ++x) {
82824 sets[x] = sets[x].slice(1, -1);
82825 }
82826 sets[xl] = sets[xl].slice(1);
82827 return sets.join('');
82828 } else {
82829 return sets[0];
82830 }
82831}
82832function subexp(str) {
82833 return "(?:" + str + ")";
82834}
82835function typeOf(o) {
82836 return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
82837}
82838function toUpperCase(str) {
82839 return str.toUpperCase();
82840}
82841function toArray(obj) {
82842 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) : [];
82843}
82844function assign(target, source) {
82845 var obj = target;
82846 if (source) {
82847 for (var key in source) {
82848 obj[key] = source[key];
82849 }
82850 }
82851 return obj;
82852}
82853
82854function buildExps(isIRI) {
82855 var ALPHA$$ = "[A-Za-z]",
82856 CR$ = "[\\x0D]",
82857 DIGIT$$ = "[0-9]",
82858 DQUOTE$$ = "[\\x22]",
82859 HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"),
82860 //case-insensitive
82861 LF$$ = "[\\x0A]",
82862 SP$$ = "[\\x20]",
82863 PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)),
82864 //expanded
82865 GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]",
82866 SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",
82867 RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),
82868 UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]",
82869 //subset, excludes bidi control characters
82870 IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]",
82871 //subset
82872 UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$),
82873 SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"),
82874 USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"),
82875 DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$),
82876 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$$),
82877 //relaxed parsing rules
82878 IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$),
82879 H16$ = subexp(HEXDIG$$ + "{1,4}"),
82880 LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$),
82881 IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$),
82882 // 6( h16 ":" ) ls32
82883 IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$),
82884 // "::" 5( h16 ":" ) ls32
82885 IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$),
82886 //[ h16 ] "::" 4( h16 ":" ) ls32
82887 IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$),
82888 //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32
82889 IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$),
82890 //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32
82891 IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$),
82892 //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32
82893 IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$),
82894 //[ *4( h16 ":" ) h16 ] "::" ls32
82895 IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$),
82896 //[ *5( h16 ":" ) h16 ] "::" h16
82897 IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"),
82898 //[ *6( h16 ":" ) h16 ] "::"
82899 IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")),
82900 ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"),
82901 //RFC 6874
82902 IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$),
82903 //RFC 6874
82904 IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$),
82905 //RFC 6874, with relaxed parsing rules
82906 IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"),
82907 IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"),
82908 //RFC 6874
82909 REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"),
82910 HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")" + "|" + REG_NAME$),
82911 PORT$ = subexp(DIGIT$$ + "*"),
82912 AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"),
82913 PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")),
82914 SEGMENT$ = subexp(PCHAR$ + "*"),
82915 SEGMENT_NZ$ = subexp(PCHAR$ + "+"),
82916 SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"),
82917 PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"),
82918 PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"),
82919 //simplified
82920 PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$),
82921 //simplified
82922 PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$),
82923 //simplified
82924 PATH_EMPTY$ = "(?!" + PCHAR$ + ")",
82925 PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
82926 QUERY$ = subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"),
82927 FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"),
82928 HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$),
82929 URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
82930 RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$),
82931 RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"),
82932 URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$),
82933 ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"),
82934 GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
82935 RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
82936 ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$",
82937 SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$",
82938 AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
82939 return {
82940 NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
82941 NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82942 NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82943 NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82944 NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82945 NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
82946 NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
82947 ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
82948 UNRESERVED: new RegExp(UNRESERVED$$, "g"),
82949 OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
82950 PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"),
82951 IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
82952 IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules
82953 };
82954}
82955var URI_PROTOCOL = buildExps(false);
82956
82957var IRI_PROTOCOL = buildExps(true);
82958
82959var slicedToArray = function () {
82960 function sliceIterator(arr, i) {
82961 var _arr = [];
82962 var _n = true;
82963 var _d = false;
82964 var _e = undefined;
82965
82966 try {
82967 for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
82968 _arr.push(_s.value);
82969
82970 if (i && _arr.length === i) break;
82971 }
82972 } catch (err) {
82973 _d = true;
82974 _e = err;
82975 } finally {
82976 try {
82977 if (!_n && _i["return"]) _i["return"]();
82978 } finally {
82979 if (_d) throw _e;
82980 }
82981 }
82982
82983 return _arr;
82984 }
82985
82986 return function (arr, i) {
82987 if (Array.isArray(arr)) {
82988 return arr;
82989 } else if (Symbol.iterator in Object(arr)) {
82990 return sliceIterator(arr, i);
82991 } else {
82992 throw new TypeError("Invalid attempt to destructure non-iterable instance");
82993 }
82994 };
82995}();
82996
82997
82998
82999
83000
83001
83002
83003
83004
83005
83006
83007
83008
83009var toConsumableArray = function (arr) {
83010 if (Array.isArray(arr)) {
83011 for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
83012
83013 return arr2;
83014 } else {
83015 return Array.from(arr);
83016 }
83017};
83018
83019/** Highest positive signed 32-bit float value */
83020
83021var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1
83022
83023/** Bootstring parameters */
83024var base = 36;
83025var tMin = 1;
83026var tMax = 26;
83027var skew = 38;
83028var damp = 700;
83029var initialBias = 72;
83030var initialN = 128; // 0x80
83031var delimiter = '-'; // '\x2D'
83032
83033/** Regular expressions */
83034var regexPunycode = /^xn--/;
83035var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars
83036var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators
83037
83038/** Error messages */
83039var errors = {
83040 'overflow': 'Overflow: input needs wider integers to process',
83041 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
83042 'invalid-input': 'Invalid input'
83043};
83044
83045/** Convenience shortcuts */
83046var baseMinusTMin = base - tMin;
83047var floor = Math.floor;
83048var stringFromCharCode = String.fromCharCode;
83049
83050/*--------------------------------------------------------------------------*/
83051
83052/**
83053 * A generic error utility function.
83054 * @private
83055 * @param {String} type The error type.
83056 * @returns {Error} Throws a `RangeError` with the applicable error message.
83057 */
83058function error$1(type) {
83059 throw new RangeError(errors[type]);
83060}
83061
83062/**
83063 * A generic `Array#map` utility function.
83064 * @private
83065 * @param {Array} array The array to iterate over.
83066 * @param {Function} callback The function that gets called for every array
83067 * item.
83068 * @returns {Array} A new array of values returned by the callback function.
83069 */
83070function map(array, fn) {
83071 var result = [];
83072 var length = array.length;
83073 while (length--) {
83074 result[length] = fn(array[length]);
83075 }
83076 return result;
83077}
83078
83079/**
83080 * A simple `Array#map`-like wrapper to work with domain name strings or email
83081 * addresses.
83082 * @private
83083 * @param {String} domain The domain name or email address.
83084 * @param {Function} callback The function that gets called for every
83085 * character.
83086 * @returns {Array} A new string of characters returned by the callback
83087 * function.
83088 */
83089function mapDomain(string, fn) {
83090 var parts = string.split('@');
83091 var result = '';
83092 if (parts.length > 1) {
83093 // In email addresses, only the domain name should be punycoded. Leave
83094 // the local part (i.e. everything up to `@`) intact.
83095 result = parts[0] + '@';
83096 string = parts[1];
83097 }
83098 // Avoid `split(regex)` for IE8 compatibility. See #17.
83099 string = string.replace(regexSeparators, '\x2E');
83100 var labels = string.split('.');
83101 var encoded = map(labels, fn).join('.');
83102 return result + encoded;
83103}
83104
83105/**
83106 * Creates an array containing the numeric code points of each Unicode
83107 * character in the string. While JavaScript uses UCS-2 internally,
83108 * this function will convert a pair of surrogate halves (each of which
83109 * UCS-2 exposes as separate characters) into a single code point,
83110 * matching UTF-16.
83111 * @see `punycode.ucs2.encode`
83112 * @see <https://mathiasbynens.be/notes/javascript-encoding>
83113 * @memberOf punycode.ucs2
83114 * @name decode
83115 * @param {String} string The Unicode input string (UCS-2).
83116 * @returns {Array} The new array of code points.
83117 */
83118function ucs2decode(string) {
83119 var output = [];
83120 var counter = 0;
83121 var length = string.length;
83122 while (counter < length) {
83123 var value = string.charCodeAt(counter++);
83124 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
83125 // It's a high surrogate, and there is a next character.
83126 var extra = string.charCodeAt(counter++);
83127 if ((extra & 0xFC00) == 0xDC00) {
83128 // Low surrogate.
83129 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
83130 } else {
83131 // It's an unmatched surrogate; only append this code unit, in case the
83132 // next code unit is the high surrogate of a surrogate pair.
83133 output.push(value);
83134 counter--;
83135 }
83136 } else {
83137 output.push(value);
83138 }
83139 }
83140 return output;
83141}
83142
83143/**
83144 * Creates a string based on an array of numeric code points.
83145 * @see `punycode.ucs2.decode`
83146 * @memberOf punycode.ucs2
83147 * @name encode
83148 * @param {Array} codePoints The array of numeric code points.
83149 * @returns {String} The new Unicode string (UCS-2).
83150 */
83151var ucs2encode = function ucs2encode(array) {
83152 return String.fromCodePoint.apply(String, toConsumableArray(array));
83153};
83154
83155/**
83156 * Converts a basic code point into a digit/integer.
83157 * @see `digitToBasic()`
83158 * @private
83159 * @param {Number} codePoint The basic numeric code point value.
83160 * @returns {Number} The numeric value of a basic code point (for use in
83161 * representing integers) in the range `0` to `base - 1`, or `base` if
83162 * the code point does not represent a value.
83163 */
83164var basicToDigit = function basicToDigit(codePoint) {
83165 if (codePoint - 0x30 < 0x0A) {
83166 return codePoint - 0x16;
83167 }
83168 if (codePoint - 0x41 < 0x1A) {
83169 return codePoint - 0x41;
83170 }
83171 if (codePoint - 0x61 < 0x1A) {
83172 return codePoint - 0x61;
83173 }
83174 return base;
83175};
83176
83177/**
83178 * Converts a digit/integer into a basic code point.
83179 * @see `basicToDigit()`
83180 * @private
83181 * @param {Number} digit The numeric value of a basic code point.
83182 * @returns {Number} The basic code point whose value (when used for
83183 * representing integers) is `digit`, which needs to be in the range
83184 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
83185 * used; else, the lowercase form is used. The behavior is undefined
83186 * if `flag` is non-zero and `digit` has no uppercase form.
83187 */
83188var digitToBasic = function digitToBasic(digit, flag) {
83189 // 0..25 map to ASCII a..z or A..Z
83190 // 26..35 map to ASCII 0..9
83191 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
83192};
83193
83194/**
83195 * Bias adaptation function as per section 3.4 of RFC 3492.
83196 * https://tools.ietf.org/html/rfc3492#section-3.4
83197 * @private
83198 */
83199var adapt = function adapt(delta, numPoints, firstTime) {
83200 var k = 0;
83201 delta = firstTime ? floor(delta / damp) : delta >> 1;
83202 delta += floor(delta / numPoints);
83203 for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) {
83204 delta = floor(delta / baseMinusTMin);
83205 }
83206 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
83207};
83208
83209/**
83210 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
83211 * symbols.
83212 * @memberOf punycode
83213 * @param {String} input The Punycode string of ASCII-only symbols.
83214 * @returns {String} The resulting string of Unicode symbols.
83215 */
83216var decode = function decode(input) {
83217 // Don't use UCS-2.
83218 var output = [];
83219 var inputLength = input.length;
83220 var i = 0;
83221 var n = initialN;
83222 var bias = initialBias;
83223
83224 // Handle the basic code points: let `basic` be the number of input code
83225 // points before the last delimiter, or `0` if there is none, then copy
83226 // the first basic code points to the output.
83227
83228 var basic = input.lastIndexOf(delimiter);
83229 if (basic < 0) {
83230 basic = 0;
83231 }
83232
83233 for (var j = 0; j < basic; ++j) {
83234 // if it's not a basic code point
83235 if (input.charCodeAt(j) >= 0x80) {
83236 error$1('not-basic');
83237 }
83238 output.push(input.charCodeAt(j));
83239 }
83240
83241 // Main decoding loop: start just after the last delimiter if any basic code
83242 // points were copied; start at the beginning otherwise.
83243
83244 for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{
83245
83246 // `index` is the index of the next character to be consumed.
83247 // Decode a generalized variable-length integer into `delta`,
83248 // which gets added to `i`. The overflow checking is easier
83249 // if we increase `i` as we go, then subtract off its starting
83250 // value at the end to obtain `delta`.
83251 var oldi = i;
83252 for (var w = 1, k = base;; /* no condition */k += base) {
83253
83254 if (index >= inputLength) {
83255 error$1('invalid-input');
83256 }
83257
83258 var digit = basicToDigit(input.charCodeAt(index++));
83259
83260 if (digit >= base || digit > floor((maxInt - i) / w)) {
83261 error$1('overflow');
83262 }
83263
83264 i += digit * w;
83265 var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
83266
83267 if (digit < t) {
83268 break;
83269 }
83270
83271 var baseMinusT = base - t;
83272 if (w > floor(maxInt / baseMinusT)) {
83273 error$1('overflow');
83274 }
83275
83276 w *= baseMinusT;
83277 }
83278
83279 var out = output.length + 1;
83280 bias = adapt(i - oldi, out, oldi == 0);
83281
83282 // `i` was supposed to wrap around from `out` to `0`,
83283 // incrementing `n` each time, so we'll fix that now:
83284 if (floor(i / out) > maxInt - n) {
83285 error$1('overflow');
83286 }
83287
83288 n += floor(i / out);
83289 i %= out;
83290
83291 // Insert `n` at position `i` of the output.
83292 output.splice(i++, 0, n);
83293 }
83294
83295 return String.fromCodePoint.apply(String, output);
83296};
83297
83298/**
83299 * Converts a string of Unicode symbols (e.g. a domain name label) to a
83300 * Punycode string of ASCII-only symbols.
83301 * @memberOf punycode
83302 * @param {String} input The string of Unicode symbols.
83303 * @returns {String} The resulting Punycode string of ASCII-only symbols.
83304 */
83305var encode = function encode(input) {
83306 var output = [];
83307
83308 // Convert the input in UCS-2 to an array of Unicode code points.
83309 input = ucs2decode(input);
83310
83311 // Cache the length.
83312 var inputLength = input.length;
83313
83314 // Initialize the state.
83315 var n = initialN;
83316 var delta = 0;
83317 var bias = initialBias;
83318
83319 // Handle the basic code points.
83320 var _iteratorNormalCompletion = true;
83321 var _didIteratorError = false;
83322 var _iteratorError = undefined;
83323
83324 try {
83325 for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
83326 var _currentValue2 = _step.value;
83327
83328 if (_currentValue2 < 0x80) {
83329 output.push(stringFromCharCode(_currentValue2));
83330 }
83331 }
83332 } catch (err) {
83333 _didIteratorError = true;
83334 _iteratorError = err;
83335 } finally {
83336 try {
83337 if (!_iteratorNormalCompletion && _iterator.return) {
83338 _iterator.return();
83339 }
83340 } finally {
83341 if (_didIteratorError) {
83342 throw _iteratorError;
83343 }
83344 }
83345 }
83346
83347 var basicLength = output.length;
83348 var handledCPCount = basicLength;
83349
83350 // `handledCPCount` is the number of code points that have been handled;
83351 // `basicLength` is the number of basic code points.
83352
83353 // Finish the basic string with a delimiter unless it's empty.
83354 if (basicLength) {
83355 output.push(delimiter);
83356 }
83357
83358 // Main encoding loop:
83359 while (handledCPCount < inputLength) {
83360
83361 // All non-basic code points < n have been handled already. Find the next
83362 // larger one:
83363 var m = maxInt;
83364 var _iteratorNormalCompletion2 = true;
83365 var _didIteratorError2 = false;
83366 var _iteratorError2 = undefined;
83367
83368 try {
83369 for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
83370 var currentValue = _step2.value;
83371
83372 if (currentValue >= n && currentValue < m) {
83373 m = currentValue;
83374 }
83375 }
83376
83377 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
83378 // but guard against overflow.
83379 } catch (err) {
83380 _didIteratorError2 = true;
83381 _iteratorError2 = err;
83382 } finally {
83383 try {
83384 if (!_iteratorNormalCompletion2 && _iterator2.return) {
83385 _iterator2.return();
83386 }
83387 } finally {
83388 if (_didIteratorError2) {
83389 throw _iteratorError2;
83390 }
83391 }
83392 }
83393
83394 var handledCPCountPlusOne = handledCPCount + 1;
83395 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
83396 error$1('overflow');
83397 }
83398
83399 delta += (m - n) * handledCPCountPlusOne;
83400 n = m;
83401
83402 var _iteratorNormalCompletion3 = true;
83403 var _didIteratorError3 = false;
83404 var _iteratorError3 = undefined;
83405
83406 try {
83407 for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
83408 var _currentValue = _step3.value;
83409
83410 if (_currentValue < n && ++delta > maxInt) {
83411 error$1('overflow');
83412 }
83413 if (_currentValue == n) {
83414 // Represent delta as a generalized variable-length integer.
83415 var q = delta;
83416 for (var k = base;; /* no condition */k += base) {
83417 var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
83418 if (q < t) {
83419 break;
83420 }
83421 var qMinusT = q - t;
83422 var baseMinusT = base - t;
83423 output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
83424 q = floor(qMinusT / baseMinusT);
83425 }
83426
83427 output.push(stringFromCharCode(digitToBasic(q, 0)));
83428 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
83429 delta = 0;
83430 ++handledCPCount;
83431 }
83432 }
83433 } catch (err) {
83434 _didIteratorError3 = true;
83435 _iteratorError3 = err;
83436 } finally {
83437 try {
83438 if (!_iteratorNormalCompletion3 && _iterator3.return) {
83439 _iterator3.return();
83440 }
83441 } finally {
83442 if (_didIteratorError3) {
83443 throw _iteratorError3;
83444 }
83445 }
83446 }
83447
83448 ++delta;
83449 ++n;
83450 }
83451 return output.join('');
83452};
83453
83454/**
83455 * Converts a Punycode string representing a domain name or an email address
83456 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
83457 * it doesn't matter if you call it on a string that has already been
83458 * converted to Unicode.
83459 * @memberOf punycode
83460 * @param {String} input The Punycoded domain name or email address to
83461 * convert to Unicode.
83462 * @returns {String} The Unicode representation of the given Punycode
83463 * string.
83464 */
83465var toUnicode = function toUnicode(input) {
83466 return mapDomain(input, function (string) {
83467 return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
83468 });
83469};
83470
83471/**
83472 * Converts a Unicode string representing a domain name or an email address to
83473 * Punycode. Only the non-ASCII parts of the domain name will be converted,
83474 * i.e. it doesn't matter if you call it with a domain that's already in
83475 * ASCII.
83476 * @memberOf punycode
83477 * @param {String} input The domain name or email address to convert, as a
83478 * Unicode string.
83479 * @returns {String} The Punycode representation of the given domain name or
83480 * email address.
83481 */
83482var toASCII = function toASCII(input) {
83483 return mapDomain(input, function (string) {
83484 return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
83485 });
83486};
83487
83488/*--------------------------------------------------------------------------*/
83489
83490/** Define the public API */
83491var punycode = {
83492 /**
83493 * A string representing the current Punycode.js version number.
83494 * @memberOf punycode
83495 * @type String
83496 */
83497 'version': '2.1.0',
83498 /**
83499 * An object of methods to convert from JavaScript's internal character
83500 * representation (UCS-2) to Unicode code points, and back.
83501 * @see <https://mathiasbynens.be/notes/javascript-encoding>
83502 * @memberOf punycode
83503 * @type Object
83504 */
83505 'ucs2': {
83506 'decode': ucs2decode,
83507 'encode': ucs2encode
83508 },
83509 'decode': decode,
83510 'encode': encode,
83511 'toASCII': toASCII,
83512 'toUnicode': toUnicode
83513};
83514
83515/**
83516 * URI.js
83517 *
83518 * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.
83519 * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
83520 * @see http://github.com/garycourt/uri-js
83521 */
83522/**
83523 * Copyright 2011 Gary Court. All rights reserved.
83524 *
83525 * Redistribution and use in source and binary forms, with or without modification, are
83526 * permitted provided that the following conditions are met:
83527 *
83528 * 1. Redistributions of source code must retain the above copyright notice, this list of
83529 * conditions and the following disclaimer.
83530 *
83531 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
83532 * of conditions and the following disclaimer in the documentation and/or other materials
83533 * provided with the distribution.
83534 *
83535 * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED
83536 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
83537 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR
83538 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
83539 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
83540 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
83541 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
83542 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
83543 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
83544 *
83545 * The views and conclusions contained in the software and documentation are those of the
83546 * authors and should not be interpreted as representing official policies, either expressed
83547 * or implied, of Gary Court.
83548 */
83549var SCHEMES = {};
83550function pctEncChar(chr) {
83551 var c = chr.charCodeAt(0);
83552 var e = void 0;
83553 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();
83554 return e;
83555}
83556function pctDecChars(str) {
83557 var newStr = "";
83558 var i = 0;
83559 var il = str.length;
83560 while (i < il) {
83561 var c = parseInt(str.substr(i + 1, 2), 16);
83562 if (c < 128) {
83563 newStr += String.fromCharCode(c);
83564 i += 3;
83565 } else if (c >= 194 && c < 224) {
83566 if (il - i >= 6) {
83567 var c2 = parseInt(str.substr(i + 4, 2), 16);
83568 newStr += String.fromCharCode((c & 31) << 6 | c2 & 63);
83569 } else {
83570 newStr += str.substr(i, 6);
83571 }
83572 i += 6;
83573 } else if (c >= 224) {
83574 if (il - i >= 9) {
83575 var _c = parseInt(str.substr(i + 4, 2), 16);
83576 var c3 = parseInt(str.substr(i + 7, 2), 16);
83577 newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63);
83578 } else {
83579 newStr += str.substr(i, 9);
83580 }
83581 i += 9;
83582 } else {
83583 newStr += str.substr(i, 3);
83584 i += 3;
83585 }
83586 }
83587 return newStr;
83588}
83589function _normalizeComponentEncoding(components, protocol) {
83590 function decodeUnreserved(str) {
83591 var decStr = pctDecChars(str);
83592 return !decStr.match(protocol.UNRESERVED) ? str : decStr;
83593 }
83594 if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, "");
83595 if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
83596 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);
83597 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);
83598 if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
83599 if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
83600 return components;
83601}
83602
83603function _stripLeadingZeros(str) {
83604 return str.replace(/^0*(.*)/, "$1") || "0";
83605}
83606function _normalizeIPv4(host, protocol) {
83607 var matches = host.match(protocol.IPV4ADDRESS) || [];
83608
83609 var _matches = slicedToArray(matches, 2),
83610 address = _matches[1];
83611
83612 if (address) {
83613 return address.split(".").map(_stripLeadingZeros).join(".");
83614 } else {
83615 return host;
83616 }
83617}
83618function _normalizeIPv6(host, protocol) {
83619 var matches = host.match(protocol.IPV6ADDRESS) || [];
83620
83621 var _matches2 = slicedToArray(matches, 3),
83622 address = _matches2[1],
83623 zone = _matches2[2];
83624
83625 if (address) {
83626 var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(),
83627 _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2),
83628 last = _address$toLowerCase$2[0],
83629 first = _address$toLowerCase$2[1];
83630
83631 var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
83632 var lastFields = last.split(":").map(_stripLeadingZeros);
83633 var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
83634 var fieldCount = isLastFieldIPv4Address ? 7 : 8;
83635 var lastFieldsStart = lastFields.length - fieldCount;
83636 var fields = Array(fieldCount);
83637 for (var x = 0; x < fieldCount; ++x) {
83638 fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';
83639 }
83640 if (isLastFieldIPv4Address) {
83641 fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
83642 }
83643 var allZeroFields = fields.reduce(function (acc, field, index) {
83644 if (!field || field === "0") {
83645 var lastLongest = acc[acc.length - 1];
83646 if (lastLongest && lastLongest.index + lastLongest.length === index) {
83647 lastLongest.length++;
83648 } else {
83649 acc.push({ index: index, length: 1 });
83650 }
83651 }
83652 return acc;
83653 }, []);
83654 var longestZeroFields = allZeroFields.sort(function (a, b) {
83655 return b.length - a.length;
83656 })[0];
83657 var newHost = void 0;
83658 if (longestZeroFields && longestZeroFields.length > 1) {
83659 var newFirst = fields.slice(0, longestZeroFields.index);
83660 var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
83661 newHost = newFirst.join(":") + "::" + newLast.join(":");
83662 } else {
83663 newHost = fields.join(":");
83664 }
83665 if (zone) {
83666 newHost += "%" + zone;
83667 }
83668 return newHost;
83669 } else {
83670 return host;
83671 }
83672}
83673var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
83674var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined;
83675function parse(uriString) {
83676 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
83677
83678 var components = {};
83679 var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
83680 if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
83681 var matches = uriString.match(URI_PARSE);
83682 if (matches) {
83683 if (NO_MATCH_IS_UNDEFINED) {
83684 //store each component
83685 components.scheme = matches[1];
83686 components.userinfo = matches[3];
83687 components.host = matches[4];
83688 components.port = parseInt(matches[5], 10);
83689 components.path = matches[6] || "";
83690 components.query = matches[7];
83691 components.fragment = matches[8];
83692 //fix port number
83693 if (isNaN(components.port)) {
83694 components.port = matches[5];
83695 }
83696 } else {
83697 //IE FIX for improper RegExp matching
83698 //store each component
83699 components.scheme = matches[1] || undefined;
83700 components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined;
83701 components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined;
83702 components.port = parseInt(matches[5], 10);
83703 components.path = matches[6] || "";
83704 components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined;
83705 components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined;
83706 //fix port number
83707 if (isNaN(components.port)) {
83708 components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined;
83709 }
83710 }
83711 if (components.host) {
83712 //normalize IP hosts
83713 components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
83714 }
83715 //determine reference type
83716 if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {
83717 components.reference = "same-document";
83718 } else if (components.scheme === undefined) {
83719 components.reference = "relative";
83720 } else if (components.fragment === undefined) {
83721 components.reference = "absolute";
83722 } else {
83723 components.reference = "uri";
83724 }
83725 //check for reference errors
83726 if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) {
83727 components.error = components.error || "URI is not a " + options.reference + " reference.";
83728 }
83729 //find scheme handler
83730 var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
83731 //check if scheme can't handle IRIs
83732 if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
83733 //if host component is a domain name
83734 if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) {
83735 //convert Unicode IDN -> ASCII IDN
83736 try {
83737 components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
83738 } catch (e) {
83739 components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
83740 }
83741 }
83742 //convert IRI -> URI
83743 _normalizeComponentEncoding(components, URI_PROTOCOL);
83744 } else {
83745 //normalize encodings
83746 _normalizeComponentEncoding(components, protocol);
83747 }
83748 //perform scheme specific parsing
83749 if (schemeHandler && schemeHandler.parse) {
83750 schemeHandler.parse(components, options);
83751 }
83752 } else {
83753 components.error = components.error || "URI can not be parsed.";
83754 }
83755 return components;
83756}
83757
83758function _recomposeAuthority(components, options) {
83759 var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
83760 var uriTokens = [];
83761 if (components.userinfo !== undefined) {
83762 uriTokens.push(components.userinfo);
83763 uriTokens.push("@");
83764 }
83765 if (components.host !== undefined) {
83766 //normalize IP hosts, add brackets and escape zone separator for IPv6
83767 uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) {
83768 return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
83769 }));
83770 }
83771 if (typeof components.port === "number") {
83772 uriTokens.push(":");
83773 uriTokens.push(components.port.toString(10));
83774 }
83775 return uriTokens.length ? uriTokens.join("") : undefined;
83776}
83777
83778var RDS1 = /^\.\.?\//;
83779var RDS2 = /^\/\.(\/|$)/;
83780var RDS3 = /^\/\.\.(\/|$)/;
83781var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
83782function removeDotSegments(input) {
83783 var output = [];
83784 while (input.length) {
83785 if (input.match(RDS1)) {
83786 input = input.replace(RDS1, "");
83787 } else if (input.match(RDS2)) {
83788 input = input.replace(RDS2, "/");
83789 } else if (input.match(RDS3)) {
83790 input = input.replace(RDS3, "/");
83791 output.pop();
83792 } else if (input === "." || input === "..") {
83793 input = "";
83794 } else {
83795 var im = input.match(RDS5);
83796 if (im) {
83797 var s = im[0];
83798 input = input.slice(s.length);
83799 output.push(s);
83800 } else {
83801 throw new Error("Unexpected dot segment condition");
83802 }
83803 }
83804 }
83805 return output.join("");
83806}
83807
83808function serialize(components) {
83809 var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
83810
83811 var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
83812 var uriTokens = [];
83813 //find scheme handler
83814 var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
83815 //perform scheme specific serialization
83816 if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
83817 if (components.host) {
83818 //if host component is an IPv6 address
83819 if (protocol.IPV6ADDRESS.test(components.host)) {}
83820 //TODO: normalize IPv6 address as per RFC 5952
83821
83822 //if host component is a domain name
83823 else if (options.domainHost || schemeHandler && schemeHandler.domainHost) {
83824 //convert IDN via punycode
83825 try {
83826 components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
83827 } catch (e) {
83828 components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
83829 }
83830 }
83831 }
83832 //normalize encoding
83833 _normalizeComponentEncoding(components, protocol);
83834 if (options.reference !== "suffix" && components.scheme) {
83835 uriTokens.push(components.scheme);
83836 uriTokens.push(":");
83837 }
83838 var authority = _recomposeAuthority(components, options);
83839 if (authority !== undefined) {
83840 if (options.reference !== "suffix") {
83841 uriTokens.push("//");
83842 }
83843 uriTokens.push(authority);
83844 if (components.path && components.path.charAt(0) !== "/") {
83845 uriTokens.push("/");
83846 }
83847 }
83848 if (components.path !== undefined) {
83849 var s = components.path;
83850 if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
83851 s = removeDotSegments(s);
83852 }
83853 if (authority === undefined) {
83854 s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//"
83855 }
83856 uriTokens.push(s);
83857 }
83858 if (components.query !== undefined) {
83859 uriTokens.push("?");
83860 uriTokens.push(components.query);
83861 }
83862 if (components.fragment !== undefined) {
83863 uriTokens.push("#");
83864 uriTokens.push(components.fragment);
83865 }
83866 return uriTokens.join(""); //merge tokens into a string
83867}
83868
83869function resolveComponents(base, relative) {
83870 var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
83871 var skipNormalization = arguments[3];
83872
83873 var target = {};
83874 if (!skipNormalization) {
83875 base = parse(serialize(base, options), options); //normalize base components
83876 relative = parse(serialize(relative, options), options); //normalize relative components
83877 }
83878 options = options || {};
83879 if (!options.tolerant && relative.scheme) {
83880 target.scheme = relative.scheme;
83881 //target.authority = relative.authority;
83882 target.userinfo = relative.userinfo;
83883 target.host = relative.host;
83884 target.port = relative.port;
83885 target.path = removeDotSegments(relative.path || "");
83886 target.query = relative.query;
83887 } else {
83888 if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {
83889 //target.authority = relative.authority;
83890 target.userinfo = relative.userinfo;
83891 target.host = relative.host;
83892 target.port = relative.port;
83893 target.path = removeDotSegments(relative.path || "");
83894 target.query = relative.query;
83895 } else {
83896 if (!relative.path) {
83897 target.path = base.path;
83898 if (relative.query !== undefined) {
83899 target.query = relative.query;
83900 } else {
83901 target.query = base.query;
83902 }
83903 } else {
83904 if (relative.path.charAt(0) === "/") {
83905 target.path = removeDotSegments(relative.path);
83906 } else {
83907 if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {
83908 target.path = "/" + relative.path;
83909 } else if (!base.path) {
83910 target.path = relative.path;
83911 } else {
83912 target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
83913 }
83914 target.path = removeDotSegments(target.path);
83915 }
83916 target.query = relative.query;
83917 }
83918 //target.authority = base.authority;
83919 target.userinfo = base.userinfo;
83920 target.host = base.host;
83921 target.port = base.port;
83922 }
83923 target.scheme = base.scheme;
83924 }
83925 target.fragment = relative.fragment;
83926 return target;
83927}
83928
83929function resolve(baseURI, relativeURI, options) {
83930 var schemelessOptions = assign({ scheme: 'null' }, options);
83931 return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
83932}
83933
83934function normalize(uri, options) {
83935 if (typeof uri === "string") {
83936 uri = serialize(parse(uri, options), options);
83937 } else if (typeOf(uri) === "object") {
83938 uri = parse(serialize(uri, options), options);
83939 }
83940 return uri;
83941}
83942
83943function equal(uriA, uriB, options) {
83944 if (typeof uriA === "string") {
83945 uriA = serialize(parse(uriA, options), options);
83946 } else if (typeOf(uriA) === "object") {
83947 uriA = serialize(uriA, options);
83948 }
83949 if (typeof uriB === "string") {
83950 uriB = serialize(parse(uriB, options), options);
83951 } else if (typeOf(uriB) === "object") {
83952 uriB = serialize(uriB, options);
83953 }
83954 return uriA === uriB;
83955}
83956
83957function escapeComponent(str, options) {
83958 return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
83959}
83960
83961function unescapeComponent(str, options) {
83962 return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
83963}
83964
83965var handler = {
83966 scheme: "http",
83967 domainHost: true,
83968 parse: function parse(components, options) {
83969 //report missing host
83970 if (!components.host) {
83971 components.error = components.error || "HTTP URIs must have a host.";
83972 }
83973 return components;
83974 },
83975 serialize: function serialize(components, options) {
83976 //normalize the default port
83977 if (components.port === (String(components.scheme).toLowerCase() !== "https" ? 80 : 443) || components.port === "") {
83978 components.port = undefined;
83979 }
83980 //normalize the empty path
83981 if (!components.path) {
83982 components.path = "/";
83983 }
83984 //NOTE: We do not parse query strings for HTTP URIs
83985 //as WWW Form Url Encoded query strings are part of the HTML4+ spec,
83986 //and not the HTTP spec.
83987 return components;
83988 }
83989};
83990
83991var handler$1 = {
83992 scheme: "https",
83993 domainHost: handler.domainHost,
83994 parse: handler.parse,
83995 serialize: handler.serialize
83996};
83997
83998var O = {};
83999var isIRI = true;
84000//RFC 3986
84001var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
84002var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive
84003var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded
84004//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =
84005//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]";
84006//const WSP$$ = "[\\x20\\x09]";
84007//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127)
84008//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext
84009//const VCHAR$$ = "[\\x21-\\x7E]";
84010//const WSP$$ = "[\\x20\\x09]";
84011//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext
84012//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+");
84013//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$);
84014//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"');
84015var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
84016var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
84017var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
84018var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
84019var UNRESERVED = new RegExp(UNRESERVED$$, "g");
84020var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
84021var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
84022var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
84023var NOT_HFVALUE = NOT_HFNAME;
84024function decodeUnreserved(str) {
84025 var decStr = pctDecChars(str);
84026 return !decStr.match(UNRESERVED) ? str : decStr;
84027}
84028var handler$2 = {
84029 scheme: "mailto",
84030 parse: function parse$$1(components, options) {
84031 var mailtoComponents = components;
84032 var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
84033 mailtoComponents.path = undefined;
84034 if (mailtoComponents.query) {
84035 var unknownHeaders = false;
84036 var headers = {};
84037 var hfields = mailtoComponents.query.split("&");
84038 for (var x = 0, xl = hfields.length; x < xl; ++x) {
84039 var hfield = hfields[x].split("=");
84040 switch (hfield[0]) {
84041 case "to":
84042 var toAddrs = hfield[1].split(",");
84043 for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) {
84044 to.push(toAddrs[_x]);
84045 }
84046 break;
84047 case "subject":
84048 mailtoComponents.subject = unescapeComponent(hfield[1], options);
84049 break;
84050 case "body":
84051 mailtoComponents.body = unescapeComponent(hfield[1], options);
84052 break;
84053 default:
84054 unknownHeaders = true;
84055 headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
84056 break;
84057 }
84058 }
84059 if (unknownHeaders) mailtoComponents.headers = headers;
84060 }
84061 mailtoComponents.query = undefined;
84062 for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) {
84063 var addr = to[_x2].split("@");
84064 addr[0] = unescapeComponent(addr[0]);
84065 if (!options.unicodeSupport) {
84066 //convert Unicode IDN -> ASCII IDN
84067 try {
84068 addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
84069 } catch (e) {
84070 mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
84071 }
84072 } else {
84073 addr[1] = unescapeComponent(addr[1], options).toLowerCase();
84074 }
84075 to[_x2] = addr.join("@");
84076 }
84077 return mailtoComponents;
84078 },
84079 serialize: function serialize$$1(mailtoComponents, options) {
84080 var components = mailtoComponents;
84081 var to = toArray(mailtoComponents.to);
84082 if (to) {
84083 for (var x = 0, xl = to.length; x < xl; ++x) {
84084 var toAddr = String(to[x]);
84085 var atIdx = toAddr.lastIndexOf("@");
84086 var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
84087 var domain = toAddr.slice(atIdx + 1);
84088 //convert IDN via punycode
84089 try {
84090 domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain);
84091 } catch (e) {
84092 components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e;
84093 }
84094 to[x] = localPart + "@" + domain;
84095 }
84096 components.path = to.join(",");
84097 }
84098 var headers = mailtoComponents.headers = mailtoComponents.headers || {};
84099 if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
84100 if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
84101 var fields = [];
84102 for (var name in headers) {
84103 if (headers[name] !== O[name]) {
84104 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));
84105 }
84106 }
84107 if (fields.length) {
84108 components.query = fields.join("&");
84109 }
84110 return components;
84111 }
84112};
84113
84114var URN_PARSE = /^([^\:]+)\:(.*)/;
84115//RFC 2141
84116var handler$3 = {
84117 scheme: "urn",
84118 parse: function parse$$1(components, options) {
84119 var matches = components.path && components.path.match(URN_PARSE);
84120 var urnComponents = components;
84121 if (matches) {
84122 var scheme = options.scheme || urnComponents.scheme || "urn";
84123 var nid = matches[1].toLowerCase();
84124 var nss = matches[2];
84125 var urnScheme = scheme + ":" + (options.nid || nid);
84126 var schemeHandler = SCHEMES[urnScheme];
84127 urnComponents.nid = nid;
84128 urnComponents.nss = nss;
84129 urnComponents.path = undefined;
84130 if (schemeHandler) {
84131 urnComponents = schemeHandler.parse(urnComponents, options);
84132 }
84133 } else {
84134 urnComponents.error = urnComponents.error || "URN can not be parsed.";
84135 }
84136 return urnComponents;
84137 },
84138 serialize: function serialize$$1(urnComponents, options) {
84139 var scheme = options.scheme || urnComponents.scheme || "urn";
84140 var nid = urnComponents.nid;
84141 var urnScheme = scheme + ":" + (options.nid || nid);
84142 var schemeHandler = SCHEMES[urnScheme];
84143 if (schemeHandler) {
84144 urnComponents = schemeHandler.serialize(urnComponents, options);
84145 }
84146 var uriComponents = urnComponents;
84147 var nss = urnComponents.nss;
84148 uriComponents.path = (nid || options.nid) + ":" + nss;
84149 return uriComponents;
84150 }
84151};
84152
84153var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
84154//RFC 4122
84155var handler$4 = {
84156 scheme: "urn:uuid",
84157 parse: function parse(urnComponents, options) {
84158 var uuidComponents = urnComponents;
84159 uuidComponents.uuid = uuidComponents.nss;
84160 uuidComponents.nss = undefined;
84161 if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
84162 uuidComponents.error = uuidComponents.error || "UUID is not valid.";
84163 }
84164 return uuidComponents;
84165 },
84166 serialize: function serialize(uuidComponents, options) {
84167 var urnComponents = uuidComponents;
84168 //normalize UUID
84169 urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
84170 return urnComponents;
84171 }
84172};
84173
84174SCHEMES[handler.scheme] = handler;
84175SCHEMES[handler$1.scheme] = handler$1;
84176SCHEMES[handler$2.scheme] = handler$2;
84177SCHEMES[handler$3.scheme] = handler$3;
84178SCHEMES[handler$4.scheme] = handler$4;
84179
84180exports.SCHEMES = SCHEMES;
84181exports.pctEncChar = pctEncChar;
84182exports.pctDecChars = pctDecChars;
84183exports.parse = parse;
84184exports.removeDotSegments = removeDotSegments;
84185exports.serialize = serialize;
84186exports.resolveComponents = resolveComponents;
84187exports.resolve = resolve;
84188exports.normalize = normalize;
84189exports.equal = equal;
84190exports.escapeComponent = escapeComponent;
84191exports.unescapeComponent = unescapeComponent;
84192
84193Object.defineProperty(exports, '__esModule', { value: true });
84194
84195})));
84196
84197
84198},{}],393:[function(require,module,exports){
84199// Copyright Joyent, Inc. and other Node contributors.
84200//
84201// Permission is hereby granted, free of charge, to any person obtaining a
84202// copy of this software and associated documentation files (the
84203// "Software"), to deal in the Software without restriction, including
84204// without limitation the rights to use, copy, modify, merge, publish,
84205// distribute, sublicense, and/or sell copies of the Software, and to permit
84206// persons to whom the Software is furnished to do so, subject to the
84207// following conditions:
84208//
84209// The above copyright notice and this permission notice shall be included
84210// in all copies or substantial portions of the Software.
84211//
84212// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
84213// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
84214// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
84215// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
84216// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
84217// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
84218// USE OR OTHER DEALINGS IN THE SOFTWARE.
84219
84220'use strict';
84221
84222var punycode = require('punycode');
84223var util = require('./util');
84224
84225exports.parse = urlParse;
84226exports.resolve = urlResolve;
84227exports.resolveObject = urlResolveObject;
84228exports.format = urlFormat;
84229
84230exports.Url = Url;
84231
84232function Url() {
84233 this.protocol = null;
84234 this.slashes = null;
84235 this.auth = null;
84236 this.host = null;
84237 this.port = null;
84238 this.hostname = null;
84239 this.hash = null;
84240 this.search = null;
84241 this.query = null;
84242 this.pathname = null;
84243 this.path = null;
84244 this.href = null;
84245}
84246
84247// Reference: RFC 3986, RFC 1808, RFC 2396
84248
84249// define these here so at least they only have to be
84250// compiled once on the first module load.
84251var protocolPattern = /^([a-z0-9.+-]+:)/i,
84252 portPattern = /:[0-9]*$/,
84253
84254 // Special case for a simple path URL
84255 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
84256
84257 // RFC 2396: characters reserved for delimiting URLs.
84258 // We actually just auto-escape these.
84259 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
84260
84261 // RFC 2396: characters not allowed for various reasons.
84262 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
84263
84264 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
84265 autoEscape = ['\''].concat(unwise),
84266 // Characters that are never ever allowed in a hostname.
84267 // Note that any invalid chars are also handled, but these
84268 // are the ones that are *expected* to be seen, so we fast-path
84269 // them.
84270 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
84271 hostEndingChars = ['/', '?', '#'],
84272 hostnameMaxLen = 255,
84273 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
84274 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
84275 // protocols that can allow "unsafe" and "unwise" chars.
84276 unsafeProtocol = {
84277 'javascript': true,
84278 'javascript:': true
84279 },
84280 // protocols that never have a hostname.
84281 hostlessProtocol = {
84282 'javascript': true,
84283 'javascript:': true
84284 },
84285 // protocols that always contain a // bit.
84286 slashedProtocol = {
84287 'http': true,
84288 'https': true,
84289 'ftp': true,
84290 'gopher': true,
84291 'file': true,
84292 'http:': true,
84293 'https:': true,
84294 'ftp:': true,
84295 'gopher:': true,
84296 'file:': true
84297 },
84298 querystring = require('querystring');
84299
84300function urlParse(url, parseQueryString, slashesDenoteHost) {
84301 if (url && util.isObject(url) && url instanceof Url) return url;
84302
84303 var u = new Url;
84304 u.parse(url, parseQueryString, slashesDenoteHost);
84305 return u;
84306}
84307
84308Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
84309 if (!util.isString(url)) {
84310 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
84311 }
84312
84313 // Copy chrome, IE, opera backslash-handling behavior.
84314 // Back slashes before the query string get converted to forward slashes
84315 // See: https://code.google.com/p/chromium/issues/detail?id=25916
84316 var queryIndex = url.indexOf('?'),
84317 splitter =
84318 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
84319 uSplit = url.split(splitter),
84320 slashRegex = /\\/g;
84321 uSplit[0] = uSplit[0].replace(slashRegex, '/');
84322 url = uSplit.join(splitter);
84323
84324 var rest = url;
84325
84326 // trim before proceeding.
84327 // This is to support parse stuff like " http://foo.com \n"
84328 rest = rest.trim();
84329
84330 if (!slashesDenoteHost && url.split('#').length === 1) {
84331 // Try fast path regexp
84332 var simplePath = simplePathPattern.exec(rest);
84333 if (simplePath) {
84334 this.path = rest;
84335 this.href = rest;
84336 this.pathname = simplePath[1];
84337 if (simplePath[2]) {
84338 this.search = simplePath[2];
84339 if (parseQueryString) {
84340 this.query = querystring.parse(this.search.substr(1));
84341 } else {
84342 this.query = this.search.substr(1);
84343 }
84344 } else if (parseQueryString) {
84345 this.search = '';
84346 this.query = {};
84347 }
84348 return this;
84349 }
84350 }
84351
84352 var proto = protocolPattern.exec(rest);
84353 if (proto) {
84354 proto = proto[0];
84355 var lowerProto = proto.toLowerCase();
84356 this.protocol = lowerProto;
84357 rest = rest.substr(proto.length);
84358 }
84359
84360 // figure out if it's got a host
84361 // user@server is *always* interpreted as a hostname, and url
84362 // resolution will treat //foo/bar as host=foo,path=bar because that's
84363 // how the browser resolves relative URLs.
84364 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
84365 var slashes = rest.substr(0, 2) === '//';
84366 if (slashes && !(proto && hostlessProtocol[proto])) {
84367 rest = rest.substr(2);
84368 this.slashes = true;
84369 }
84370 }
84371
84372 if (!hostlessProtocol[proto] &&
84373 (slashes || (proto && !slashedProtocol[proto]))) {
84374
84375 // there's a hostname.
84376 // the first instance of /, ?, ;, or # ends the host.
84377 //
84378 // If there is an @ in the hostname, then non-host chars *are* allowed
84379 // to the left of the last @ sign, unless some host-ending character
84380 // comes *before* the @-sign.
84381 // URLs are obnoxious.
84382 //
84383 // ex:
84384 // http://a@b@c/ => user:a@b host:c
84385 // http://a@b?@c => user:a host:c path:/?@c
84386
84387 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
84388 // Review our test case against browsers more comprehensively.
84389
84390 // find the first instance of any hostEndingChars
84391 var hostEnd = -1;
84392 for (var i = 0; i < hostEndingChars.length; i++) {
84393 var hec = rest.indexOf(hostEndingChars[i]);
84394 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
84395 hostEnd = hec;
84396 }
84397
84398 // at this point, either we have an explicit point where the
84399 // auth portion cannot go past, or the last @ char is the decider.
84400 var auth, atSign;
84401 if (hostEnd === -1) {
84402 // atSign can be anywhere.
84403 atSign = rest.lastIndexOf('@');
84404 } else {
84405 // atSign must be in auth portion.
84406 // http://a@b/c@d => host:b auth:a path:/c@d
84407 atSign = rest.lastIndexOf('@', hostEnd);
84408 }
84409
84410 // Now we have a portion which is definitely the auth.
84411 // Pull that off.
84412 if (atSign !== -1) {
84413 auth = rest.slice(0, atSign);
84414 rest = rest.slice(atSign + 1);
84415 this.auth = decodeURIComponent(auth);
84416 }
84417
84418 // the host is the remaining to the left of the first non-host char
84419 hostEnd = -1;
84420 for (var i = 0; i < nonHostChars.length; i++) {
84421 var hec = rest.indexOf(nonHostChars[i]);
84422 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
84423 hostEnd = hec;
84424 }
84425 // if we still have not hit it, then the entire thing is a host.
84426 if (hostEnd === -1)
84427 hostEnd = rest.length;
84428
84429 this.host = rest.slice(0, hostEnd);
84430 rest = rest.slice(hostEnd);
84431
84432 // pull out port.
84433 this.parseHost();
84434
84435 // we've indicated that there is a hostname,
84436 // so even if it's empty, it has to be present.
84437 this.hostname = this.hostname || '';
84438
84439 // if hostname begins with [ and ends with ]
84440 // assume that it's an IPv6 address.
84441 var ipv6Hostname = this.hostname[0] === '[' &&
84442 this.hostname[this.hostname.length - 1] === ']';
84443
84444 // validate a little.
84445 if (!ipv6Hostname) {
84446 var hostparts = this.hostname.split(/\./);
84447 for (var i = 0, l = hostparts.length; i < l; i++) {
84448 var part = hostparts[i];
84449 if (!part) continue;
84450 if (!part.match(hostnamePartPattern)) {
84451 var newpart = '';
84452 for (var j = 0, k = part.length; j < k; j++) {
84453 if (part.charCodeAt(j) > 127) {
84454 // we replace non-ASCII char with a temporary placeholder
84455 // we need this to make sure size of hostname is not
84456 // broken by replacing non-ASCII by nothing
84457 newpart += 'x';
84458 } else {
84459 newpart += part[j];
84460 }
84461 }
84462 // we test again with ASCII char only
84463 if (!newpart.match(hostnamePartPattern)) {
84464 var validParts = hostparts.slice(0, i);
84465 var notHost = hostparts.slice(i + 1);
84466 var bit = part.match(hostnamePartStart);
84467 if (bit) {
84468 validParts.push(bit[1]);
84469 notHost.unshift(bit[2]);
84470 }
84471 if (notHost.length) {
84472 rest = '/' + notHost.join('.') + rest;
84473 }
84474 this.hostname = validParts.join('.');
84475 break;
84476 }
84477 }
84478 }
84479 }
84480
84481 if (this.hostname.length > hostnameMaxLen) {
84482 this.hostname = '';
84483 } else {
84484 // hostnames are always lower case.
84485 this.hostname = this.hostname.toLowerCase();
84486 }
84487
84488 if (!ipv6Hostname) {
84489 // IDNA Support: Returns a punycoded representation of "domain".
84490 // It only converts parts of the domain name that
84491 // have non-ASCII characters, i.e. it doesn't matter if
84492 // you call it with a domain that already is ASCII-only.
84493 this.hostname = punycode.toASCII(this.hostname);
84494 }
84495
84496 var p = this.port ? ':' + this.port : '';
84497 var h = this.hostname || '';
84498 this.host = h + p;
84499 this.href += this.host;
84500
84501 // strip [ and ] from the hostname
84502 // the host field still retains them, though
84503 if (ipv6Hostname) {
84504 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
84505 if (rest[0] !== '/') {
84506 rest = '/' + rest;
84507 }
84508 }
84509 }
84510
84511 // now rest is set to the post-host stuff.
84512 // chop off any delim chars.
84513 if (!unsafeProtocol[lowerProto]) {
84514
84515 // First, make 100% sure that any "autoEscape" chars get
84516 // escaped, even if encodeURIComponent doesn't think they
84517 // need to be.
84518 for (var i = 0, l = autoEscape.length; i < l; i++) {
84519 var ae = autoEscape[i];
84520 if (rest.indexOf(ae) === -1)
84521 continue;
84522 var esc = encodeURIComponent(ae);
84523 if (esc === ae) {
84524 esc = escape(ae);
84525 }
84526 rest = rest.split(ae).join(esc);
84527 }
84528 }
84529
84530
84531 // chop off from the tail first.
84532 var hash = rest.indexOf('#');
84533 if (hash !== -1) {
84534 // got a fragment string.
84535 this.hash = rest.substr(hash);
84536 rest = rest.slice(0, hash);
84537 }
84538 var qm = rest.indexOf('?');
84539 if (qm !== -1) {
84540 this.search = rest.substr(qm);
84541 this.query = rest.substr(qm + 1);
84542 if (parseQueryString) {
84543 this.query = querystring.parse(this.query);
84544 }
84545 rest = rest.slice(0, qm);
84546 } else if (parseQueryString) {
84547 // no query string, but parseQueryString still requested
84548 this.search = '';
84549 this.query = {};
84550 }
84551 if (rest) this.pathname = rest;
84552 if (slashedProtocol[lowerProto] &&
84553 this.hostname && !this.pathname) {
84554 this.pathname = '/';
84555 }
84556
84557 //to support http.request
84558 if (this.pathname || this.search) {
84559 var p = this.pathname || '';
84560 var s = this.search || '';
84561 this.path = p + s;
84562 }
84563
84564 // finally, reconstruct the href based on what has been validated.
84565 this.href = this.format();
84566 return this;
84567};
84568
84569// format a parsed object into a url string
84570function urlFormat(obj) {
84571 // ensure it's an object, and not a string url.
84572 // If it's an obj, this is a no-op.
84573 // this way, you can call url_format() on strings
84574 // to clean up potentially wonky urls.
84575 if (util.isString(obj)) obj = urlParse(obj);
84576 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
84577 return obj.format();
84578}
84579
84580Url.prototype.format = function() {
84581 var auth = this.auth || '';
84582 if (auth) {
84583 auth = encodeURIComponent(auth);
84584 auth = auth.replace(/%3A/i, ':');
84585 auth += '@';
84586 }
84587
84588 var protocol = this.protocol || '',
84589 pathname = this.pathname || '',
84590 hash = this.hash || '',
84591 host = false,
84592 query = '';
84593
84594 if (this.host) {
84595 host = auth + this.host;
84596 } else if (this.hostname) {
84597 host = auth + (this.hostname.indexOf(':') === -1 ?
84598 this.hostname :
84599 '[' + this.hostname + ']');
84600 if (this.port) {
84601 host += ':' + this.port;
84602 }
84603 }
84604
84605 if (this.query &&
84606 util.isObject(this.query) &&
84607 Object.keys(this.query).length) {
84608 query = querystring.stringify(this.query);
84609 }
84610
84611 var search = this.search || (query && ('?' + query)) || '';
84612
84613 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
84614
84615 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
84616 // unless they had them to begin with.
84617 if (this.slashes ||
84618 (!protocol || slashedProtocol[protocol]) && host !== false) {
84619 host = '//' + (host || '');
84620 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
84621 } else if (!host) {
84622 host = '';
84623 }
84624
84625 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
84626 if (search && search.charAt(0) !== '?') search = '?' + search;
84627
84628 pathname = pathname.replace(/[?#]/g, function(match) {
84629 return encodeURIComponent(match);
84630 });
84631 search = search.replace('#', '%23');
84632
84633 return protocol + host + pathname + search + hash;
84634};
84635
84636function urlResolve(source, relative) {
84637 return urlParse(source, false, true).resolve(relative);
84638}
84639
84640Url.prototype.resolve = function(relative) {
84641 return this.resolveObject(urlParse(relative, false, true)).format();
84642};
84643
84644function urlResolveObject(source, relative) {
84645 if (!source) return relative;
84646 return urlParse(source, false, true).resolveObject(relative);
84647}
84648
84649Url.prototype.resolveObject = function(relative) {
84650 if (util.isString(relative)) {
84651 var rel = new Url();
84652 rel.parse(relative, false, true);
84653 relative = rel;
84654 }
84655
84656 var result = new Url();
84657 var tkeys = Object.keys(this);
84658 for (var tk = 0; tk < tkeys.length; tk++) {
84659 var tkey = tkeys[tk];
84660 result[tkey] = this[tkey];
84661 }
84662
84663 // hash is always overridden, no matter what.
84664 // even href="" will remove it.
84665 result.hash = relative.hash;
84666
84667 // if the relative url is empty, then there's nothing left to do here.
84668 if (relative.href === '') {
84669 result.href = result.format();
84670 return result;
84671 }
84672
84673 // hrefs like //foo/bar always cut to the protocol.
84674 if (relative.slashes && !relative.protocol) {
84675 // take everything except the protocol from relative
84676 var rkeys = Object.keys(relative);
84677 for (var rk = 0; rk < rkeys.length; rk++) {
84678 var rkey = rkeys[rk];
84679 if (rkey !== 'protocol')
84680 result[rkey] = relative[rkey];
84681 }
84682
84683 //urlParse appends trailing / to urls like http://www.example.com
84684 if (slashedProtocol[result.protocol] &&
84685 result.hostname && !result.pathname) {
84686 result.path = result.pathname = '/';
84687 }
84688
84689 result.href = result.format();
84690 return result;
84691 }
84692
84693 if (relative.protocol && relative.protocol !== result.protocol) {
84694 // if it's a known url protocol, then changing
84695 // the protocol does weird things
84696 // first, if it's not file:, then we MUST have a host,
84697 // and if there was a path
84698 // to begin with, then we MUST have a path.
84699 // if it is file:, then the host is dropped,
84700 // because that's known to be hostless.
84701 // anything else is assumed to be absolute.
84702 if (!slashedProtocol[relative.protocol]) {
84703 var keys = Object.keys(relative);
84704 for (var v = 0; v < keys.length; v++) {
84705 var k = keys[v];
84706 result[k] = relative[k];
84707 }
84708 result.href = result.format();
84709 return result;
84710 }
84711
84712 result.protocol = relative.protocol;
84713 if (!relative.host && !hostlessProtocol[relative.protocol]) {
84714 var relPath = (relative.pathname || '').split('/');
84715 while (relPath.length && !(relative.host = relPath.shift()));
84716 if (!relative.host) relative.host = '';
84717 if (!relative.hostname) relative.hostname = '';
84718 if (relPath[0] !== '') relPath.unshift('');
84719 if (relPath.length < 2) relPath.unshift('');
84720 result.pathname = relPath.join('/');
84721 } else {
84722 result.pathname = relative.pathname;
84723 }
84724 result.search = relative.search;
84725 result.query = relative.query;
84726 result.host = relative.host || '';
84727 result.auth = relative.auth;
84728 result.hostname = relative.hostname || relative.host;
84729 result.port = relative.port;
84730 // to support http.request
84731 if (result.pathname || result.search) {
84732 var p = result.pathname || '';
84733 var s = result.search || '';
84734 result.path = p + s;
84735 }
84736 result.slashes = result.slashes || relative.slashes;
84737 result.href = result.format();
84738 return result;
84739 }
84740
84741 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
84742 isRelAbs = (
84743 relative.host ||
84744 relative.pathname && relative.pathname.charAt(0) === '/'
84745 ),
84746 mustEndAbs = (isRelAbs || isSourceAbs ||
84747 (result.host && relative.pathname)),
84748 removeAllDots = mustEndAbs,
84749 srcPath = result.pathname && result.pathname.split('/') || [],
84750 relPath = relative.pathname && relative.pathname.split('/') || [],
84751 psychotic = result.protocol && !slashedProtocol[result.protocol];
84752
84753 // if the url is a non-slashed url, then relative
84754 // links like ../.. should be able
84755 // to crawl up to the hostname, as well. This is strange.
84756 // result.protocol has already been set by now.
84757 // Later on, put the first path part into the host field.
84758 if (psychotic) {
84759 result.hostname = '';
84760 result.port = null;
84761 if (result.host) {
84762 if (srcPath[0] === '') srcPath[0] = result.host;
84763 else srcPath.unshift(result.host);
84764 }
84765 result.host = '';
84766 if (relative.protocol) {
84767 relative.hostname = null;
84768 relative.port = null;
84769 if (relative.host) {
84770 if (relPath[0] === '') relPath[0] = relative.host;
84771 else relPath.unshift(relative.host);
84772 }
84773 relative.host = null;
84774 }
84775 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
84776 }
84777
84778 if (isRelAbs) {
84779 // it's absolute.
84780 result.host = (relative.host || relative.host === '') ?
84781 relative.host : result.host;
84782 result.hostname = (relative.hostname || relative.hostname === '') ?
84783 relative.hostname : result.hostname;
84784 result.search = relative.search;
84785 result.query = relative.query;
84786 srcPath = relPath;
84787 // fall through to the dot-handling below.
84788 } else if (relPath.length) {
84789 // it's relative
84790 // throw away the existing file, and take the new path instead.
84791 if (!srcPath) srcPath = [];
84792 srcPath.pop();
84793 srcPath = srcPath.concat(relPath);
84794 result.search = relative.search;
84795 result.query = relative.query;
84796 } else if (!util.isNullOrUndefined(relative.search)) {
84797 // just pull out the search.
84798 // like href='?foo'.
84799 // Put this after the other two cases because it simplifies the booleans
84800 if (psychotic) {
84801 result.hostname = result.host = srcPath.shift();
84802 //occationaly the auth can get stuck only in host
84803 //this especially happens in cases like
84804 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
84805 var authInHost = result.host && result.host.indexOf('@') > 0 ?
84806 result.host.split('@') : false;
84807 if (authInHost) {
84808 result.auth = authInHost.shift();
84809 result.host = result.hostname = authInHost.shift();
84810 }
84811 }
84812 result.search = relative.search;
84813 result.query = relative.query;
84814 //to support http.request
84815 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
84816 result.path = (result.pathname ? result.pathname : '') +
84817 (result.search ? result.search : '');
84818 }
84819 result.href = result.format();
84820 return result;
84821 }
84822
84823 if (!srcPath.length) {
84824 // no path at all. easy.
84825 // we've already handled the other stuff above.
84826 result.pathname = null;
84827 //to support http.request
84828 if (result.search) {
84829 result.path = '/' + result.search;
84830 } else {
84831 result.path = null;
84832 }
84833 result.href = result.format();
84834 return result;
84835 }
84836
84837 // if a url ENDs in . or .., then it must get a trailing slash.
84838 // however, if it ends in anything else non-slashy,
84839 // then it must NOT get a trailing slash.
84840 var last = srcPath.slice(-1)[0];
84841 var hasTrailingSlash = (
84842 (result.host || relative.host || srcPath.length > 1) &&
84843 (last === '.' || last === '..') || last === '');
84844
84845 // strip single dots, resolve double dots to parent dir
84846 // if the path tries to go above the root, `up` ends up > 0
84847 var up = 0;
84848 for (var i = srcPath.length; i >= 0; i--) {
84849 last = srcPath[i];
84850 if (last === '.') {
84851 srcPath.splice(i, 1);
84852 } else if (last === '..') {
84853 srcPath.splice(i, 1);
84854 up++;
84855 } else if (up) {
84856 srcPath.splice(i, 1);
84857 up--;
84858 }
84859 }
84860
84861 // if the path is allowed to go above the root, restore leading ..s
84862 if (!mustEndAbs && !removeAllDots) {
84863 for (; up--; up) {
84864 srcPath.unshift('..');
84865 }
84866 }
84867
84868 if (mustEndAbs && srcPath[0] !== '' &&
84869 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
84870 srcPath.unshift('');
84871 }
84872
84873 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
84874 srcPath.push('');
84875 }
84876
84877 var isAbsolute = srcPath[0] === '' ||
84878 (srcPath[0] && srcPath[0].charAt(0) === '/');
84879
84880 // put the host back
84881 if (psychotic) {
84882 result.hostname = result.host = isAbsolute ? '' :
84883 srcPath.length ? srcPath.shift() : '';
84884 //occationaly the auth can get stuck only in host
84885 //this especially happens in cases like
84886 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
84887 var authInHost = result.host && result.host.indexOf('@') > 0 ?
84888 result.host.split('@') : false;
84889 if (authInHost) {
84890 result.auth = authInHost.shift();
84891 result.host = result.hostname = authInHost.shift();
84892 }
84893 }
84894
84895 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
84896
84897 if (mustEndAbs && !isAbsolute) {
84898 srcPath.unshift('');
84899 }
84900
84901 if (!srcPath.length) {
84902 result.pathname = null;
84903 result.path = null;
84904 } else {
84905 result.pathname = srcPath.join('/');
84906 }
84907
84908 //to support request.http
84909 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
84910 result.path = (result.pathname ? result.pathname : '') +
84911 (result.search ? result.search : '');
84912 }
84913 result.auth = relative.auth || result.auth;
84914 result.slashes = result.slashes || relative.slashes;
84915 result.href = result.format();
84916 return result;
84917};
84918
84919Url.prototype.parseHost = function() {
84920 var host = this.host;
84921 var port = portPattern.exec(host);
84922 if (port) {
84923 port = port[0];
84924 if (port !== ':') {
84925 this.port = port.substr(1);
84926 }
84927 host = host.substr(0, host.length - port.length);
84928 }
84929 if (host) this.hostname = host;
84930};
84931
84932},{"./util":394,"punycode":274,"querystring":277}],394:[function(require,module,exports){
84933'use strict';
84934
84935module.exports = {
84936 isString: function(arg) {
84937 return typeof(arg) === 'string';
84938 },
84939 isObject: function(arg) {
84940 return typeof(arg) === 'object' && arg !== null;
84941 },
84942 isNull: function(arg) {
84943 return arg === null;
84944 },
84945 isNullOrUndefined: function(arg) {
84946 return arg == null;
84947 }
84948};
84949
84950},{}],395:[function(require,module,exports){
84951(function (global){
84952
84953/**
84954 * Module exports.
84955 */
84956
84957module.exports = deprecate;
84958
84959/**
84960 * Mark that a method should not be used.
84961 * Returns a modified function which warns once by default.
84962 *
84963 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
84964 *
84965 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
84966 * will throw an Error when invoked.
84967 *
84968 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
84969 * will invoke `console.trace()` instead of `console.error()`.
84970 *
84971 * @param {Function} fn - the function to deprecate
84972 * @param {String} msg - the string to print to the console when `fn` is invoked
84973 * @returns {Function} a new "deprecated" version of `fn`
84974 * @api public
84975 */
84976
84977function deprecate (fn, msg) {
84978 if (config('noDeprecation')) {
84979 return fn;
84980 }
84981
84982 var warned = false;
84983 function deprecated() {
84984 if (!warned) {
84985 if (config('throwDeprecation')) {
84986 throw new Error(msg);
84987 } else if (config('traceDeprecation')) {
84988 console.trace(msg);
84989 } else {
84990 console.warn(msg);
84991 }
84992 warned = true;
84993 }
84994 return fn.apply(this, arguments);
84995 }
84996
84997 return deprecated;
84998}
84999
85000/**
85001 * Checks `localStorage` for boolean values for the given `name`.
85002 *
85003 * @param {String} name
85004 * @returns {Boolean}
85005 * @api private
85006 */
85007
85008function config (name) {
85009 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
85010 try {
85011 if (!global.localStorage) return false;
85012 } catch (_) {
85013 return false;
85014 }
85015 var val = global.localStorage[name];
85016 if (null == val) return false;
85017 return String(val).toLowerCase() === 'true';
85018}
85019
85020}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
85021},{}],396:[function(require,module,exports){
85022arguments[4][70][0].apply(exports,arguments)
85023},{"dup":70}],397:[function(require,module,exports){
85024arguments[4][71][0].apply(exports,arguments)
85025},{"./support/isBuffer":396,"_process":265,"dup":71,"inherits":210}],398:[function(require,module,exports){
85026/**
85027 * Convert array of 16 byte values to UUID string format of the form:
85028 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
85029 */
85030var byteToHex = [];
85031for (var i = 0; i < 256; ++i) {
85032 byteToHex[i] = (i + 0x100).toString(16).substr(1);
85033}
85034
85035function bytesToUuid(buf, offset) {
85036 var i = offset || 0;
85037 var bth = byteToHex;
85038 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
85039 return ([bth[buf[i++]], bth[buf[i++]],
85040 bth[buf[i++]], bth[buf[i++]], '-',
85041 bth[buf[i++]], bth[buf[i++]], '-',
85042 bth[buf[i++]], bth[buf[i++]], '-',
85043 bth[buf[i++]], bth[buf[i++]], '-',
85044 bth[buf[i++]], bth[buf[i++]],
85045 bth[buf[i++]], bth[buf[i++]],
85046 bth[buf[i++]], bth[buf[i++]]]).join('');
85047}
85048
85049module.exports = bytesToUuid;
85050
85051},{}],399:[function(require,module,exports){
85052// Unique ID creation requires a high quality random # generator. In the
85053// browser this is a little complicated due to unknown quality of Math.random()
85054// and inconsistent support for the `crypto` API. We do the best we can via
85055// feature-detection
85056
85057// getRandomValues needs to be invoked in a context where "this" is a Crypto
85058// implementation. Also, find the complete implementation of crypto on IE11.
85059var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
85060 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
85061
85062if (getRandomValues) {
85063 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
85064 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
85065
85066 module.exports = function whatwgRNG() {
85067 getRandomValues(rnds8);
85068 return rnds8;
85069 };
85070} else {
85071 // Math.random()-based (RNG)
85072 //
85073 // If all else fails, use Math.random(). It's fast, but is of unspecified
85074 // quality.
85075 var rnds = new Array(16);
85076
85077 module.exports = function mathRNG() {
85078 for (var i = 0, r; i < 16; i++) {
85079 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
85080 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
85081 }
85082
85083 return rnds;
85084 };
85085}
85086
85087},{}],400:[function(require,module,exports){
85088var rng = require('./lib/rng');
85089var bytesToUuid = require('./lib/bytesToUuid');
85090
85091function v4(options, buf, offset) {
85092 var i = buf && offset || 0;
85093
85094 if (typeof(options) == 'string') {
85095 buf = options === 'binary' ? new Array(16) : null;
85096 options = null;
85097 }
85098 options = options || {};
85099
85100 var rnds = options.random || (options.rng || rng)();
85101
85102 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
85103 rnds[6] = (rnds[6] & 0x0f) | 0x40;
85104 rnds[8] = (rnds[8] & 0x3f) | 0x80;
85105
85106 // Copy bytes to buffer, if provided
85107 if (buf) {
85108 for (var ii = 0; ii < 16; ++ii) {
85109 buf[i + ii] = rnds[ii];
85110 }
85111 }
85112
85113 return buf || bytesToUuid(rnds);
85114}
85115
85116module.exports = v4;
85117
85118},{"./lib/bytesToUuid":398,"./lib/rng":399}],401:[function(require,module,exports){
85119/*
85120 * verror.js: richer JavaScript errors
85121 */
85122
85123var mod_assertplus = require('assert-plus');
85124var mod_util = require('util');
85125
85126var mod_extsprintf = require('extsprintf');
85127var mod_isError = require('core-util-is').isError;
85128var sprintf = mod_extsprintf.sprintf;
85129
85130/*
85131 * Public interface
85132 */
85133
85134/* So you can 'var VError = require('verror')' */
85135module.exports = VError;
85136/* For compatibility */
85137VError.VError = VError;
85138/* Other exported classes */
85139VError.SError = SError;
85140VError.WError = WError;
85141VError.MultiError = MultiError;
85142
85143/*
85144 * Common function used to parse constructor arguments for VError, WError, and
85145 * SError. Named arguments to this function:
85146 *
85147 * strict force strict interpretation of sprintf arguments, even
85148 * if the options in "argv" don't say so
85149 *
85150 * argv error's constructor arguments, which are to be
85151 * interpreted as described in README.md. For quick
85152 * reference, "argv" has one of the following forms:
85153 *
85154 * [ sprintf_args... ] (argv[0] is a string)
85155 * [ cause, sprintf_args... ] (argv[0] is an Error)
85156 * [ options, sprintf_args... ] (argv[0] is an object)
85157 *
85158 * This function normalizes these forms, producing an object with the following
85159 * properties:
85160 *
85161 * options equivalent to "options" in third form. This will never
85162 * be a direct reference to what the caller passed in
85163 * (i.e., it may be a shallow copy), so it can be freely
85164 * modified.
85165 *
85166 * shortmessage result of sprintf(sprintf_args), taking options.strict
85167 * into account as described in README.md.
85168 */
85169function parseConstructorArguments(args)
85170{
85171 var argv, options, sprintf_args, shortmessage, k;
85172
85173 mod_assertplus.object(args, 'args');
85174 mod_assertplus.bool(args.strict, 'args.strict');
85175 mod_assertplus.array(args.argv, 'args.argv');
85176 argv = args.argv;
85177
85178 /*
85179 * First, figure out which form of invocation we've been given.
85180 */
85181 if (argv.length === 0) {
85182 options = {};
85183 sprintf_args = [];
85184 } else if (mod_isError(argv[0])) {
85185 options = { 'cause': argv[0] };
85186 sprintf_args = argv.slice(1);
85187 } else if (typeof (argv[0]) === 'object') {
85188 options = {};
85189 for (k in argv[0]) {
85190 options[k] = argv[0][k];
85191 }
85192 sprintf_args = argv.slice(1);
85193 } else {
85194 mod_assertplus.string(argv[0],
85195 'first argument to VError, SError, or WError ' +
85196 'constructor must be a string, object, or Error');
85197 options = {};
85198 sprintf_args = argv;
85199 }
85200
85201 /*
85202 * Now construct the error's message.
85203 *
85204 * extsprintf (which we invoke here with our caller's arguments in order
85205 * to construct this Error's message) is strict in its interpretation of
85206 * values to be processed by the "%s" specifier. The value passed to
85207 * extsprintf must actually be a string or something convertible to a
85208 * String using .toString(). Passing other values (notably "null" and
85209 * "undefined") is considered a programmer error. The assumption is
85210 * that if you actually want to print the string "null" or "undefined",
85211 * then that's easy to do that when you're calling extsprintf; on the
85212 * other hand, if you did NOT want that (i.e., there's actually a bug
85213 * where the program assumes some variable is non-null and tries to
85214 * print it, which might happen when constructing a packet or file in
85215 * some specific format), then it's better to stop immediately than
85216 * produce bogus output.
85217 *
85218 * However, sometimes the bug is only in the code calling VError, and a
85219 * programmer might prefer to have the error message contain "null" or
85220 * "undefined" rather than have the bug in the error path crash the
85221 * program (making the first bug harder to identify). For that reason,
85222 * by default VError converts "null" or "undefined" arguments to their
85223 * string representations and passes those to extsprintf. Programmers
85224 * desiring the strict behavior can use the SError class or pass the
85225 * "strict" option to the VError constructor.
85226 */
85227 mod_assertplus.object(options);
85228 if (!options.strict && !args.strict) {
85229 sprintf_args = sprintf_args.map(function (a) {
85230 return (a === null ? 'null' :
85231 a === undefined ? 'undefined' : a);
85232 });
85233 }
85234
85235 if (sprintf_args.length === 0) {
85236 shortmessage = '';
85237 } else {
85238 shortmessage = sprintf.apply(null, sprintf_args);
85239 }
85240
85241 return ({
85242 'options': options,
85243 'shortmessage': shortmessage
85244 });
85245}
85246
85247/*
85248 * See README.md for reference documentation.
85249 */
85250function VError()
85251{
85252 var args, obj, parsed, cause, ctor, message, k;
85253
85254 args = Array.prototype.slice.call(arguments, 0);
85255
85256 /*
85257 * This is a regrettable pattern, but JavaScript's built-in Error class
85258 * is defined to work this way, so we allow the constructor to be called
85259 * without "new".
85260 */
85261 if (!(this instanceof VError)) {
85262 obj = Object.create(VError.prototype);
85263 VError.apply(obj, arguments);
85264 return (obj);
85265 }
85266
85267 /*
85268 * For convenience and backwards compatibility, we support several
85269 * different calling forms. Normalize them here.
85270 */
85271 parsed = parseConstructorArguments({
85272 'argv': args,
85273 'strict': false
85274 });
85275
85276 /*
85277 * If we've been given a name, apply it now.
85278 */
85279 if (parsed.options.name) {
85280 mod_assertplus.string(parsed.options.name,
85281 'error\'s "name" must be a string');
85282 this.name = parsed.options.name;
85283 }
85284
85285 /*
85286 * For debugging, we keep track of the original short message (attached
85287 * this Error particularly) separately from the complete message (which
85288 * includes the messages of our cause chain).
85289 */
85290 this.jse_shortmsg = parsed.shortmessage;
85291 message = parsed.shortmessage;
85292
85293 /*
85294 * If we've been given a cause, record a reference to it and update our
85295 * message appropriately.
85296 */
85297 cause = parsed.options.cause;
85298 if (cause) {
85299 mod_assertplus.ok(mod_isError(cause), 'cause is not an Error');
85300 this.jse_cause = cause;
85301
85302 if (!parsed.options.skipCauseMessage) {
85303 message += ': ' + cause.message;
85304 }
85305 }
85306
85307 /*
85308 * If we've been given an object with properties, shallow-copy that
85309 * here. We don't want to use a deep copy in case there are non-plain
85310 * objects here, but we don't want to use the original object in case
85311 * the caller modifies it later.
85312 */
85313 this.jse_info = {};
85314 if (parsed.options.info) {
85315 for (k in parsed.options.info) {
85316 this.jse_info[k] = parsed.options.info[k];
85317 }
85318 }
85319
85320 this.message = message;
85321 Error.call(this, message);
85322
85323 if (Error.captureStackTrace) {
85324 ctor = parsed.options.constructorOpt || this.constructor;
85325 Error.captureStackTrace(this, ctor);
85326 }
85327
85328 return (this);
85329}
85330
85331mod_util.inherits(VError, Error);
85332VError.prototype.name = 'VError';
85333
85334VError.prototype.toString = function ve_toString()
85335{
85336 var str = (this.hasOwnProperty('name') && this.name ||
85337 this.constructor.name || this.constructor.prototype.name);
85338 if (this.message)
85339 str += ': ' + this.message;
85340
85341 return (str);
85342};
85343
85344/*
85345 * This method is provided for compatibility. New callers should use
85346 * VError.cause() instead. That method also uses the saner `null` return value
85347 * when there is no cause.
85348 */
85349VError.prototype.cause = function ve_cause()
85350{
85351 var cause = VError.cause(this);
85352 return (cause === null ? undefined : cause);
85353};
85354
85355/*
85356 * Static methods
85357 *
85358 * These class-level methods are provided so that callers can use them on
85359 * instances of Errors that are not VErrors. New interfaces should be provided
85360 * only using static methods to eliminate the class of programming mistake where
85361 * people fail to check whether the Error object has the corresponding methods.
85362 */
85363
85364VError.cause = function (err)
85365{
85366 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85367 return (mod_isError(err.jse_cause) ? err.jse_cause : null);
85368};
85369
85370VError.info = function (err)
85371{
85372 var rv, cause, k;
85373
85374 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85375 cause = VError.cause(err);
85376 if (cause !== null) {
85377 rv = VError.info(cause);
85378 } else {
85379 rv = {};
85380 }
85381
85382 if (typeof (err.jse_info) == 'object' && err.jse_info !== null) {
85383 for (k in err.jse_info) {
85384 rv[k] = err.jse_info[k];
85385 }
85386 }
85387
85388 return (rv);
85389};
85390
85391VError.findCauseByName = function (err, name)
85392{
85393 var cause;
85394
85395 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85396 mod_assertplus.string(name, 'name');
85397 mod_assertplus.ok(name.length > 0, 'name cannot be empty');
85398
85399 for (cause = err; cause !== null; cause = VError.cause(cause)) {
85400 mod_assertplus.ok(mod_isError(cause));
85401 if (cause.name == name) {
85402 return (cause);
85403 }
85404 }
85405
85406 return (null);
85407};
85408
85409VError.hasCauseWithName = function (err, name)
85410{
85411 return (VError.findCauseByName(err, name) !== null);
85412};
85413
85414VError.fullStack = function (err)
85415{
85416 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85417
85418 var cause = VError.cause(err);
85419
85420 if (cause) {
85421 return (err.stack + '\ncaused by: ' + VError.fullStack(cause));
85422 }
85423
85424 return (err.stack);
85425};
85426
85427VError.errorFromList = function (errors)
85428{
85429 mod_assertplus.arrayOfObject(errors, 'errors');
85430
85431 if (errors.length === 0) {
85432 return (null);
85433 }
85434
85435 errors.forEach(function (e) {
85436 mod_assertplus.ok(mod_isError(e));
85437 });
85438
85439 if (errors.length == 1) {
85440 return (errors[0]);
85441 }
85442
85443 return (new MultiError(errors));
85444};
85445
85446VError.errorForEach = function (err, func)
85447{
85448 mod_assertplus.ok(mod_isError(err), 'err must be an Error');
85449 mod_assertplus.func(func, 'func');
85450
85451 if (err instanceof MultiError) {
85452 err.errors().forEach(function iterError(e) { func(e); });
85453 } else {
85454 func(err);
85455 }
85456};
85457
85458
85459/*
85460 * SError is like VError, but stricter about types. You cannot pass "null" or
85461 * "undefined" as string arguments to the formatter.
85462 */
85463function SError()
85464{
85465 var args, obj, parsed, options;
85466
85467 args = Array.prototype.slice.call(arguments, 0);
85468 if (!(this instanceof SError)) {
85469 obj = Object.create(SError.prototype);
85470 SError.apply(obj, arguments);
85471 return (obj);
85472 }
85473
85474 parsed = parseConstructorArguments({
85475 'argv': args,
85476 'strict': true
85477 });
85478
85479 options = parsed.options;
85480 VError.call(this, options, '%s', parsed.shortmessage);
85481
85482 return (this);
85483}
85484
85485/*
85486 * We don't bother setting SError.prototype.name because once constructed,
85487 * SErrors are just like VErrors.
85488 */
85489mod_util.inherits(SError, VError);
85490
85491
85492/*
85493 * Represents a collection of errors for the purpose of consumers that generally
85494 * only deal with one error. Callers can extract the individual errors
85495 * contained in this object, but may also just treat it as a normal single
85496 * error, in which case a summary message will be printed.
85497 */
85498function MultiError(errors)
85499{
85500 mod_assertplus.array(errors, 'list of errors');
85501 mod_assertplus.ok(errors.length > 0, 'must be at least one error');
85502 this.ase_errors = errors;
85503
85504 VError.call(this, {
85505 'cause': errors[0]
85506 }, 'first of %d error%s', errors.length, errors.length == 1 ? '' : 's');
85507}
85508
85509mod_util.inherits(MultiError, VError);
85510MultiError.prototype.name = 'MultiError';
85511
85512MultiError.prototype.errors = function me_errors()
85513{
85514 return (this.ase_errors.slice(0));
85515};
85516
85517
85518/*
85519 * See README.md for reference details.
85520 */
85521function WError()
85522{
85523 var args, obj, parsed, options;
85524
85525 args = Array.prototype.slice.call(arguments, 0);
85526 if (!(this instanceof WError)) {
85527 obj = Object.create(WError.prototype);
85528 WError.apply(obj, args);
85529 return (obj);
85530 }
85531
85532 parsed = parseConstructorArguments({
85533 'argv': args,
85534 'strict': false
85535 });
85536
85537 options = parsed.options;
85538 options['skipCauseMessage'] = true;
85539 VError.call(this, options, '%s', parsed.shortmessage);
85540
85541 return (this);
85542}
85543
85544mod_util.inherits(WError, VError);
85545WError.prototype.name = 'WError';
85546
85547WError.prototype.toString = function we_toString()
85548{
85549 var str = (this.hasOwnProperty('name') && this.name ||
85550 this.constructor.name || this.constructor.prototype.name);
85551 if (this.message)
85552 str += ': ' + this.message;
85553 if (this.jse_cause && this.jse_cause.message)
85554 str += '; caused by ' + this.jse_cause.toString();
85555
85556 return (str);
85557};
85558
85559/*
85560 * For purely historical reasons, WError's cause() function allows you to set
85561 * the cause.
85562 */
85563WError.prototype.cause = function we_cause(c)
85564{
85565 if (mod_isError(c))
85566 this.jse_cause = c;
85567
85568 return (this.jse_cause);
85569};
85570
85571},{"assert-plus":67,"core-util-is":120,"extsprintf":402,"util":397}],402:[function(require,module,exports){
85572(function (process){
85573/*
85574 * extsprintf.js: extended POSIX-style sprintf
85575 */
85576
85577var mod_assert = require('assert');
85578var mod_util = require('util');
85579
85580/*
85581 * Public interface
85582 */
85583exports.sprintf = jsSprintf;
85584exports.printf = jsPrintf;
85585exports.fprintf = jsFprintf;
85586
85587/*
85588 * Stripped down version of s[n]printf(3c). We make a best effort to throw an
85589 * exception when given a format string we don't understand, rather than
85590 * ignoring it, so that we won't break existing programs if/when we go implement
85591 * the rest of this.
85592 *
85593 * This implementation currently supports specifying
85594 * - field alignment ('-' flag),
85595 * - zero-pad ('0' flag)
85596 * - always show numeric sign ('+' flag),
85597 * - field width
85598 * - conversions for strings, decimal integers, and floats (numbers).
85599 * - argument size specifiers. These are all accepted but ignored, since
85600 * Javascript has no notion of the physical size of an argument.
85601 *
85602 * Everything else is currently unsupported, most notably precision, unsigned
85603 * numbers, non-decimal numbers, and characters.
85604 */
85605function jsSprintf(ofmt)
85606{
85607 var regex = [
85608 '([^%]*)', /* normal text */
85609 '%', /* start of format */
85610 '([\'\\-+ #0]*?)', /* flags (optional) */
85611 '([1-9]\\d*)?', /* width (optional) */
85612 '(\\.([1-9]\\d*))?', /* precision (optional) */
85613 '[lhjztL]*?', /* length mods (ignored) */
85614 '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
85615 ].join('');
85616
85617 var re = new RegExp(regex);
85618
85619 /* variadic arguments used to fill in conversion specifiers */
85620 var args = Array.prototype.slice.call(arguments, 1);
85621 /* remaining format string */
85622 var fmt = ofmt;
85623
85624 /* components of the current conversion specifier */
85625 var flags, width, precision, conversion;
85626 var left, pad, sign, arg, match;
85627
85628 /* return value */
85629 var ret = '';
85630
85631 /* current variadic argument (1-based) */
85632 var argn = 1;
85633 /* 0-based position in the format string that we've read */
85634 var posn = 0;
85635 /* 1-based position in the format string of the current conversion */
85636 var convposn;
85637 /* current conversion specifier */
85638 var curconv;
85639
85640 mod_assert.equal('string', typeof (fmt),
85641 'first argument must be a format string');
85642
85643 while ((match = re.exec(fmt)) !== null) {
85644 ret += match[1];
85645 fmt = fmt.substring(match[0].length);
85646
85647 /*
85648 * Update flags related to the current conversion specifier's
85649 * position so that we can report clear error messages.
85650 */
85651 curconv = match[0].substring(match[1].length);
85652 convposn = posn + match[1].length + 1;
85653 posn += match[0].length;
85654
85655 flags = match[2] || '';
85656 width = match[3] || 0;
85657 precision = match[4] || '';
85658 conversion = match[6];
85659 left = false;
85660 sign = false;
85661 pad = ' ';
85662
85663 if (conversion == '%') {
85664 ret += '%';
85665 continue;
85666 }
85667
85668 if (args.length === 0) {
85669 throw (jsError(ofmt, convposn, curconv,
85670 'has no matching argument ' +
85671 '(too few arguments passed)'));
85672 }
85673
85674 arg = args.shift();
85675 argn++;
85676
85677 if (flags.match(/[\' #]/)) {
85678 throw (jsError(ofmt, convposn, curconv,
85679 'uses unsupported flags'));
85680 }
85681
85682 if (precision.length > 0) {
85683 throw (jsError(ofmt, convposn, curconv,
85684 'uses non-zero precision (not supported)'));
85685 }
85686
85687 if (flags.match(/-/))
85688 left = true;
85689
85690 if (flags.match(/0/))
85691 pad = '0';
85692
85693 if (flags.match(/\+/))
85694 sign = true;
85695
85696 switch (conversion) {
85697 case 's':
85698 if (arg === undefined || arg === null) {
85699 throw (jsError(ofmt, convposn, curconv,
85700 'attempted to print undefined or null ' +
85701 'as a string (argument ' + argn + ' to ' +
85702 'sprintf)'));
85703 }
85704 ret += doPad(pad, width, left, arg.toString());
85705 break;
85706
85707 case 'd':
85708 arg = Math.floor(arg);
85709 /*jsl:fallthru*/
85710 case 'f':
85711 sign = sign && arg > 0 ? '+' : '';
85712 ret += sign + doPad(pad, width, left,
85713 arg.toString());
85714 break;
85715
85716 case 'x':
85717 ret += doPad(pad, width, left, arg.toString(16));
85718 break;
85719
85720 case 'j': /* non-standard */
85721 if (width === 0)
85722 width = 10;
85723 ret += mod_util.inspect(arg, false, width);
85724 break;
85725
85726 case 'r': /* non-standard */
85727 ret += dumpException(arg);
85728 break;
85729
85730 default:
85731 throw (jsError(ofmt, convposn, curconv,
85732 'is not supported'));
85733 }
85734 }
85735
85736 ret += fmt;
85737 return (ret);
85738}
85739
85740function jsError(fmtstr, convposn, curconv, reason) {
85741 mod_assert.equal(typeof (fmtstr), 'string');
85742 mod_assert.equal(typeof (curconv), 'string');
85743 mod_assert.equal(typeof (convposn), 'number');
85744 mod_assert.equal(typeof (reason), 'string');
85745 return (new Error('format string "' + fmtstr +
85746 '": conversion specifier "' + curconv + '" at character ' +
85747 convposn + ' ' + reason));
85748}
85749
85750function jsPrintf() {
85751 var args = Array.prototype.slice.call(arguments);
85752 args.unshift(process.stdout);
85753 jsFprintf.apply(null, args);
85754}
85755
85756function jsFprintf(stream) {
85757 var args = Array.prototype.slice.call(arguments, 1);
85758 return (stream.write(jsSprintf.apply(this, args)));
85759}
85760
85761function doPad(chr, width, left, str)
85762{
85763 var ret = str;
85764
85765 while (ret.length < width) {
85766 if (left)
85767 ret += chr;
85768 else
85769 ret = chr + ret;
85770 }
85771
85772 return (ret);
85773}
85774
85775/*
85776 * This function dumps long stack traces for exceptions having a cause() method.
85777 * See node-verror for an example.
85778 */
85779function dumpException(ex)
85780{
85781 var ret;
85782
85783 if (!(ex instanceof Error))
85784 throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
85785
85786 /* Note that V8 prepends "ex.stack" with ex.toString(). */
85787 ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
85788
85789 if (ex.cause && typeof (ex.cause) === 'function') {
85790 var cex = ex.cause();
85791 if (cex) {
85792 ret += '\nCaused by: ' + dumpException(cex);
85793 }
85794 }
85795
85796 return (ret);
85797}
85798
85799}).call(this,require('_process'))
85800},{"_process":265,"assert":68,"util":397}],403:[function(require,module,exports){
85801var indexOf = function (xs, item) {
85802 if (xs.indexOf) return xs.indexOf(item);
85803 else for (var i = 0; i < xs.length; i++) {
85804 if (xs[i] === item) return i;
85805 }
85806 return -1;
85807};
85808var Object_keys = function (obj) {
85809 if (Object.keys) return Object.keys(obj)
85810 else {
85811 var res = [];
85812 for (var key in obj) res.push(key)
85813 return res;
85814 }
85815};
85816
85817var forEach = function (xs, fn) {
85818 if (xs.forEach) return xs.forEach(fn)
85819 else for (var i = 0; i < xs.length; i++) {
85820 fn(xs[i], i, xs);
85821 }
85822};
85823
85824var defineProp = (function() {
85825 try {
85826 Object.defineProperty({}, '_', {});
85827 return function(obj, name, value) {
85828 Object.defineProperty(obj, name, {
85829 writable: true,
85830 enumerable: false,
85831 configurable: true,
85832 value: value
85833 })
85834 };
85835 } catch(e) {
85836 return function(obj, name, value) {
85837 obj[name] = value;
85838 };
85839 }
85840}());
85841
85842var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
85843'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
85844'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
85845'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
85846'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
85847
85848function Context() {}
85849Context.prototype = {};
85850
85851var Script = exports.Script = function NodeScript (code) {
85852 if (!(this instanceof Script)) return new Script(code);
85853 this.code = code;
85854};
85855
85856Script.prototype.runInContext = function (context) {
85857 if (!(context instanceof Context)) {
85858 throw new TypeError("needs a 'context' argument.");
85859 }
85860
85861 var iframe = document.createElement('iframe');
85862 if (!iframe.style) iframe.style = {};
85863 iframe.style.display = 'none';
85864
85865 document.body.appendChild(iframe);
85866
85867 var win = iframe.contentWindow;
85868 var wEval = win.eval, wExecScript = win.execScript;
85869
85870 if (!wEval && wExecScript) {
85871 // win.eval() magically appears when this is called in IE:
85872 wExecScript.call(win, 'null');
85873 wEval = win.eval;
85874 }
85875
85876 forEach(Object_keys(context), function (key) {
85877 win[key] = context[key];
85878 });
85879 forEach(globals, function (key) {
85880 if (context[key]) {
85881 win[key] = context[key];
85882 }
85883 });
85884
85885 var winKeys = Object_keys(win);
85886
85887 var res = wEval.call(win, this.code);
85888
85889 forEach(Object_keys(win), function (key) {
85890 // Avoid copying circular objects like `top` and `window` by only
85891 // updating existing context properties or new properties in the `win`
85892 // that was only introduced after the eval.
85893 if (key in context || indexOf(winKeys, key) === -1) {
85894 context[key] = win[key];
85895 }
85896 });
85897
85898 forEach(globals, function (key) {
85899 if (!(key in context)) {
85900 defineProp(context, key, win[key]);
85901 }
85902 });
85903
85904 document.body.removeChild(iframe);
85905
85906 return res;
85907};
85908
85909Script.prototype.runInThisContext = function () {
85910 return eval(this.code); // maybe...
85911};
85912
85913Script.prototype.runInNewContext = function (context) {
85914 var ctx = Script.createContext(context);
85915 var res = this.runInContext(ctx);
85916
85917 if (context) {
85918 forEach(Object_keys(ctx), function (key) {
85919 context[key] = ctx[key];
85920 });
85921 }
85922
85923 return res;
85924};
85925
85926forEach(Object_keys(Script.prototype), function (name) {
85927 exports[name] = Script[name] = function (code) {
85928 var s = Script(code);
85929 return s[name].apply(s, [].slice.call(arguments, 1));
85930 };
85931});
85932
85933exports.isContext = function (context) {
85934 return context instanceof Context;
85935};
85936
85937exports.createScript = function (code) {
85938 return exports.Script(code);
85939};
85940
85941exports.createContext = Script.createContext = function (context) {
85942 var copy = new Context();
85943 if(typeof context === 'object') {
85944 forEach(Object_keys(context), function (key) {
85945 copy[key] = context[key];
85946 });
85947 }
85948 return copy;
85949};
85950
85951},{}],404:[function(require,module,exports){
85952/*jshint strict:true node:true es5:true onevar:true laxcomma:true laxbreak:true*/
85953(function () {
85954 "use strict";
85955
85956 // "FIFO" isn't easy to convert to camelCase and back reliably
85957 var isFnodeTypes = [
85958 "isFile", "isDirectory", "isSymbolicLink", "isBlockDevice", "isCharacterDevice", "isFIFO", "isSocket"
85959 ],
85960 fnodeTypes = [
85961 "file", "directory", "symbolicLink", "blockDevice", "characterDevice", "FIFO", "socket"
85962 ],
85963 fnodeTypesPlural = [
85964 "files", "directories", "symbolicLinks", "blockDevices", "characterDevices", "FIFOs", "sockets"
85965 ];
85966
85967
85968 //
85969 function createNodeGroups() {
85970 var nodeGroups = {};
85971 fnodeTypesPlural.concat("nodes", "errors").forEach(function (fnodeTypePlural) {
85972 nodeGroups[fnodeTypePlural] = [];
85973 });
85974 return nodeGroups;
85975 }
85976
85977
85978 // Determine each file node's type
85979 //
85980 function sortFnodesByType(stat, fnodes) {
85981 var i, isType;
85982
85983 for (i = 0; i < isFnodeTypes.length; i += 1) {
85984 isType = isFnodeTypes[i];
85985 if (stat[isType]()) {
85986 stat.type = fnodeTypes[i];
85987 fnodes[fnodeTypesPlural[i]].push(stat);
85988 return;
85989 }
85990 }
85991 }
85992
85993
85994 // Get the current number of listeners (which may change)
85995 // Emit events to each listener
85996 // Wait for all listeners to `next()` before continueing
85997 // (in theory this may avoid disk thrashing)
85998 function emitSingleEvents(emitter, path, stats, next, self) {
85999 var num = 1 + emitter.listeners(stats.type).length + emitter.listeners("node").length;
86000
86001 function nextWhenReady(flag) {
86002 if (flag) {
86003 stats.flag = flag;
86004 }
86005 num -= 1;
86006 if (0 === num) { next.call(self); }
86007 }
86008
86009 emitter.emit(stats.type, path, stats, nextWhenReady);
86010 emitter.emit("node", path, stats, nextWhenReady);
86011 nextWhenReady();
86012 }
86013
86014
86015 // Since the risk for disk thrashing among anything
86016 // other than files is relatively low, all types are
86017 // emitted at once, but all must complete before advancing
86018 function emitPluralEvents(emitter, path, nodes, next, self) {
86019 var num = 1;
86020
86021 function nextWhenReady() {
86022 num -= 1;
86023 if (0 === num) { next.call(self); }
86024 }
86025
86026 fnodeTypesPlural.concat(["nodes", "errors"]).forEach(function (fnodeType) {
86027 if (0 === nodes[fnodeType].length) { return; }
86028 num += emitter.listeners(fnodeType).length;
86029 emitter.emit(fnodeType, path, nodes[fnodeType], nextWhenReady);
86030 });
86031 nextWhenReady();
86032 }
86033
86034 module.exports = {
86035 emitNodeType: emitSingleEvents,
86036 emitNodeTypeGroups: emitPluralEvents,
86037 isFnodeTypes: isFnodeTypes,
86038 fnodeTypes: fnodeTypes,
86039 fnodeTypesPlural: fnodeTypesPlural,
86040 sortFnodesByType: sortFnodesByType,
86041 createNodeGroups: createNodeGroups
86042 };
86043}());
86044
86045},{}],405:[function(require,module,exports){
86046// Adapted from work by jorge@jorgechamorro.com on 2010-11-25
86047(function () {
86048 "use strict";
86049
86050 function noop() {}
86051
86052 var fs = require('fs')
86053 , forEachAsync = require('foreachasync').forEachAsync
86054 , EventEmitter = require('events').EventEmitter
86055 , TypeEmitter = require('./node-type-emitter')
86056 , util = require('util')
86057 , path = require('path')
86058 ;
86059
86060 function appendToDirs(stat) {
86061 /*jshint validthis:true*/
86062 if(stat.flag && stat.flag === NO_DESCEND) { return; }
86063 this.push(stat.name);
86064 }
86065
86066 function wFilesHandlerWrapper(items) {
86067 /*jshint validthis:true*/
86068 this._wFilesHandler(noop, items);
86069 }
86070
86071 function Walker(pathname, options, sync) {
86072 EventEmitter.call(this);
86073
86074 var me = this
86075 ;
86076
86077 options = options || {};
86078 me._wStat = options.followLinks && 'stat' || 'lstat';
86079 me._wStatSync = me._wStat + 'Sync';
86080 me._wsync = sync;
86081 me._wq = [];
86082 me._wqueue = [me._wq];
86083 me._wcurpath = undefined;
86084 me._wfilters = options.filters || [];
86085 me._wfirstrun = true;
86086 me._wcurpath = pathname;
86087
86088 if (me._wsync) {
86089 //console.log('_walkSync');
86090 me._wWalk = me._wWalkSync;
86091 } else {
86092 //console.log('_walkASync');
86093 me._wWalk = me._wWalkAsync;
86094 }
86095
86096 options.listeners = options.listeners || {};
86097 Object.keys(options.listeners).forEach(function (event) {
86098 var callbacks = options.listeners[event]
86099 ;
86100
86101 if ('function' === typeof callbacks) {
86102 callbacks = [callbacks];
86103 }
86104
86105 callbacks.forEach(function (callback) {
86106 me.on(event, callback);
86107 });
86108 });
86109
86110 me._wWalk();
86111 }
86112
86113 // Inherits must come before prototype additions
86114 util.inherits(Walker, EventEmitter);
86115
86116 Walker.prototype._wLstatHandler = function (err, stat) {
86117 var me = this
86118 ;
86119
86120 stat = stat || {};
86121 stat.name = me._wcurfile;
86122
86123 if (err) {
86124 stat.error = err;
86125 //me.emit('error', curpath, stat);
86126 // TODO v3.0 (don't noop the next if there are listeners)
86127 me.emit('nodeError', me._wcurpath, stat, noop);
86128 me._wfnodegroups.errors.push(stat);
86129 me._wCurFileCallback();
86130 } else {
86131 TypeEmitter.sortFnodesByType(stat, me._wfnodegroups);
86132 // NOTE: wCurFileCallback doesn't need thisness, so this is okay
86133 TypeEmitter.emitNodeType(me, me._wcurpath, stat, me._wCurFileCallback, me);
86134 }
86135 };
86136 Walker.prototype._wFilesHandler = function (cont, file) {
86137 var statPath
86138 , me = this
86139 ;
86140
86141
86142 me._wcurfile = file;
86143 me._wCurFileCallback = cont;
86144 me.emit('name', me._wcurpath, file, noop);
86145
86146 statPath = me._wcurpath + path.sep + file;
86147
86148 if (!me._wsync) {
86149 // TODO how to remove this anony?
86150 fs[me._wStat](statPath, function (err, stat) {
86151 me._wLstatHandler(err, stat);
86152 });
86153 return;
86154 }
86155
86156 try {
86157 me._wLstatHandler(null, fs[me._wStatSync](statPath));
86158 } catch(e) {
86159 me._wLstatHandler(e);
86160 }
86161 };
86162 Walker.prototype._wOnEmitDone = function () {
86163 var me = this
86164 , dirs = []
86165 ;
86166
86167 me._wfnodegroups.directories.forEach(appendToDirs, dirs);
86168 dirs.forEach(me._wJoinPath, me);
86169 me._wqueue.push(me._wq = dirs);
86170 me._wNext();
86171 };
86172 Walker.prototype._wPostFilesHandler = function () {
86173 var me = this
86174 ;
86175
86176 if (me._wfnodegroups.errors.length) {
86177 // TODO v3.0 (don't noop the next)
86178 // .errors is an array of stats with { name: name, error: error }
86179 me.emit('errors', me._wcurpath, me._wfnodegroups.errors, noop);
86180 }
86181 // XXX emitNodeTypes still needs refactor
86182 TypeEmitter.emitNodeTypeGroups(me, me._wcurpath, me._wfnodegroups, me._wOnEmitDone, me);
86183 };
86184 Walker.prototype._wReadFiles = function () {
86185 var me = this
86186 ;
86187
86188 if (!me._wcurfiles || 0 === me._wcurfiles.length) {
86189 return me._wNext();
86190 }
86191
86192 // TODO could allow user to selectively stat
86193 // and don't stat if there are no stat listeners
86194 me.emit('names', me._wcurpath, me._wcurfiles, noop);
86195
86196 if (me._wsync) {
86197 me._wcurfiles.forEach(wFilesHandlerWrapper, me);
86198 me._wPostFilesHandler();
86199 } else {
86200 forEachAsync(me._wcurfiles, me._wFilesHandler, me).then(me._wPostFilesHandler);
86201 }
86202 };
86203 Walker.prototype._wReaddirHandler = function (err, files) {
86204 var fnodeGroups = TypeEmitter.createNodeGroups()
86205 , me = this
86206 , parent
86207 , child
86208 ;
86209
86210 me._wfnodegroups = fnodeGroups;
86211 me._wcurfiles = files;
86212
86213 // no error, great
86214 if (!err) {
86215 me._wReadFiles();
86216 return;
86217 }
86218
86219 // TODO path.sep
86220 me._wcurpath = me._wcurpath.replace(/\/$/, '');
86221
86222 // error? not first run? => directory error
86223 if (!me._wfirstrun) {
86224 // TODO v3.0 (don't noop the next if there are listeners)
86225 me.emit('directoryError', me._wcurpath, { error: err }, noop);
86226 // TODO v3.0
86227 //me.emit('directoryError', me._wcurpath.replace(/^(.*)\/.*$/, '$1'), { name: me._wcurpath.replace(/^.*\/(.*)/, '$1'), error: err }, noop);
86228 me._wReadFiles();
86229 return;
86230 }
86231
86232 // error? first run? => maybe a file, maybe a true error
86233 me._wfirstrun = false;
86234
86235 // readdir failed (might be a file), try a stat on the parent
86236 parent = me._wcurpath.replace(/^(.*)\/.*$/, '$1');
86237 fs[me._wStat](parent, function (e, stat) {
86238
86239 if (stat) {
86240 // success
86241 // now try stat on this as a child of the parent directory
86242 child = me._wcurpath.replace(/^.*\/(.*)$/, '$1');
86243 me._wcurfiles = [child];
86244 me._wcurpath = parent;
86245 } else {
86246 // TODO v3.0
86247 //me.emit('directoryError', me._wcurpath.replace(/^(.*)\/.*$/, '$1'), { name: me._wcurpath.replace(/^.*\/(.*)/, '$1'), error: err }, noop);
86248 // TODO v3.0 (don't noop the next)
86249 // the original readdir error, not the parent stat error
86250 me.emit('nodeError', me._wcurpath, { error: err }, noop);
86251 }
86252
86253 me._wReadFiles();
86254 });
86255 };
86256 Walker.prototype._wFilter = function () {
86257 var me = this
86258 , exclude
86259 ;
86260
86261 // Stop directories that contain filter keywords
86262 // from continuing through the walk process
86263 exclude = me._wfilters.some(function (filter) {
86264 if (me._wcurpath.match(filter)) {
86265 return true;
86266 }
86267 });
86268
86269 return exclude;
86270 };
86271 Walker.prototype._wWalkSync = function () {
86272 //console.log('walkSync');
86273 var err
86274 , files
86275 , me = this
86276 ;
86277
86278 try {
86279 files = fs.readdirSync(me._wcurpath);
86280 } catch(e) {
86281 err = e;
86282 }
86283
86284 me._wReaddirHandler(err, files);
86285 };
86286 Walker.prototype._wWalkAsync = function () {
86287 //console.log('walkAsync');
86288 var me = this
86289 ;
86290
86291 // TODO how to remove this anony?
86292 fs.readdir(me._wcurpath, function (err, files) {
86293 me._wReaddirHandler(err, files);
86294 });
86295 };
86296 Walker.prototype._wNext = function () {
86297 var me = this
86298 ;
86299
86300 if (me._paused) {
86301 return;
86302 }
86303 if (me._wq.length) {
86304 me._wcurpath = me._wq.pop();
86305 while (me._wq.length && me._wFilter()) {
86306 me._wcurpath = me._wq.pop();
86307 }
86308 if (me._wcurpath && !me._wFilter()) {
86309 me._wWalk();
86310 } else {
86311 me._wNext();
86312 }
86313 return;
86314 }
86315 me._wqueue.length -= 1;
86316 if (me._wqueue.length) {
86317 me._wq = me._wqueue[me._wqueue.length - 1];
86318 return me._wNext();
86319 }
86320
86321 // To not break compatibility
86322 //process.nextTick(function () {
86323 me.emit('end');
86324 //});
86325 };
86326 Walker.prototype._wJoinPath = function (v, i, o) {
86327 var me = this
86328 ;
86329
86330 o[i] = [me._wcurpath, path.sep, v].join('');
86331 };
86332 Walker.prototype.pause = function () {
86333 this._paused = true;
86334 };
86335 Walker.prototype.resume = function () {
86336 this._paused = false;
86337 this._wNext();
86338 };
86339
86340 exports.walk = function (path, opts) {
86341 return new Walker(path, opts, false);
86342 };
86343
86344 exports.walkSync = function (path, opts) {
86345 return new Walker(path, opts, true);
86346 };
86347}());
86348
86349},{"./node-type-emitter":404,"events":159,"foreachasync":165,"fs":112,"path":257,"util":397}],406:[function(require,module,exports){
86350module.exports = extend
86351
86352var hasOwnProperty = Object.prototype.hasOwnProperty;
86353
86354function extend() {
86355 var target = {}
86356
86357 for (var i = 0; i < arguments.length; i++) {
86358 var source = arguments[i]
86359
86360 for (var key in source) {
86361 if (hasOwnProperty.call(source, key)) {
86362 target[key] = source[key]
86363 }
86364 }
86365 }
86366
86367 return target
86368}
86369
86370},{}],407:[function(require,module,exports){
86371module.exports={
86372 "name": "percy-client",
86373 "version": "3.4.0",
86374 "description": "JavaScript API client library for Percy (https://percy.io).",
86375 "main": "dist/main.js",
86376 "scripts": {
86377 "build": "npm run build:compile && npm run build:browserify",
86378 "build:browserify": "browserify --standalone percy-client dist/main.js -o dist/bundle.js",
86379 "build:compile": "babel src --presets babel-preset-es2015 --out-dir dist",
86380 "debug": "mocha debug --require babel-core/register",
86381 "lint": "./node_modules/eslint/bin/eslint.js .",
86382 "lint:fix": "./node_modules/eslint/bin/eslint.js . --fix",
86383 "prepublish": "npm run build",
86384 "tdd": "mocha --require babel-core/register --watch",
86385 "test": "mocha --require babel-core/register"
86386 },
86387 "lint-staged": {
86388 "*.{js,css}": [
86389 "./node_modules/eslint/bin/eslint.js --fix --color",
86390 "git add"
86391 ]
86392 },
86393 "files": [
86394 "dist/"
86395 ],
86396 "repository": {
86397 "type": "git",
86398 "url": "https://github.com/percy/percy-js.git"
86399 },
86400 "author": "Perceptual Inc.",
86401 "license": "MIT",
86402 "bugs": {
86403 "url": "https://github.com/percy/percy-js/issues"
86404 },
86405 "homepage": "https://github.com/percy/percy-js",
86406 "devDependencies": {
86407 "babel-cli": "^6.26.0",
86408 "babel-core": "^6.26.0",
86409 "babel-plugin-transform-object-assign": "^6.22.0",
86410 "babel-preset-es2015": "^6.3.13",
86411 "browserify": "^16.2.3",
86412 "eslint": "^6.0.0",
86413 "eslint-config-prettier": "^6.0.0",
86414 "eslint-plugin-prettier": "^3.0.1",
86415 "husky": "^3.0.1",
86416 "lint-staged": "^9.1.0",
86417 "mocha": "^6.0.0",
86418 "nock": "^10.0.6",
86419 "prettier": "^1.12.1",
86420 "sinon": "^7.2.3"
86421 },
86422 "dependencies": {
86423 "bluebird": "^3.5.1",
86424 "bluebird-retry": "^0.11.0",
86425 "dotenv": "^8.1.0",
86426 "es6-promise-pool": "^2.5.0",
86427 "jssha": "^2.1.0",
86428 "regenerator-runtime": "^0.13.1",
86429 "request": "^2.87.0",
86430 "request-promise": "^4.2.2",
86431 "walk": "^2.3.14"
86432 },
86433 "husky": {
86434 "hooks": {
86435 "pre-commit": "lint-staged"
86436 }
86437 }
86438}
86439
86440},{}]},{},[2])(2)
86441});