UNPKG

412 kBJavaScriptView Raw
1(function webpackUniversalModuleDefinition(root, factory) {
2 if(typeof exports === 'object' && typeof module === 'object')
3 module.exports = factory();
4 else if(typeof define === 'function' && define.amd)
5 define([], factory);
6 else if(typeof exports === 'object')
7 exports["AWS"] = factory();
8 else
9 root["AWS"] = factory();
10})(this, function() {
11return /******/ (function(modules) { // webpackBootstrap
12/******/ // The module cache
13/******/ var installedModules = {};
14
15/******/ // The require function
16/******/ function __webpack_require__(moduleId) {
17
18/******/ // Check if module is in cache
19/******/ if(installedModules[moduleId])
20/******/ return installedModules[moduleId].exports;
21
22/******/ // Create a new module (and put it into the cache)
23/******/ var module = installedModules[moduleId] = {
24/******/ exports: {},
25/******/ id: moduleId,
26/******/ loaded: false
27/******/ };
28
29/******/ // Execute the module function
30/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
31
32/******/ // Flag the module as loaded
33/******/ module.loaded = true;
34
35/******/ // Return the exports of the module
36/******/ return module.exports;
37/******/ }
38
39
40/******/ // expose the modules object (__webpack_modules__)
41/******/ __webpack_require__.m = modules;
42
43/******/ // expose the module cache
44/******/ __webpack_require__.c = installedModules;
45
46/******/ // __webpack_public_path__
47/******/ __webpack_require__.p = "";
48
49/******/ // Load entry module and return exports
50/******/ return __webpack_require__(0);
51/******/ })
52/************************************************************************/
53/******/ ([
54/* 0 */
55/***/ (function(module, exports, __webpack_require__) {
56
57 module.exports = __webpack_require__(1);
58
59
60/***/ }),
61/* 1 */
62/***/ (function(module, exports, __webpack_require__) {
63
64 /**
65 * The main AWS namespace
66 */
67 var AWS = { util: __webpack_require__(2) };
68
69 /**
70 * @api private
71 * @!macro [new] nobrowser
72 * @note This feature is not supported in the browser environment of the SDK.
73 */
74 var _hidden = {}; _hidden.toString(); // hack to parse macro
75
76 /**
77 * @api private
78 */
79 module.exports = AWS;
80
81 AWS.util.update(AWS, {
82
83 /**
84 * @constant
85 */
86 VERSION: '2.617.0',
87
88 /**
89 * @api private
90 */
91 Signers: {},
92
93 /**
94 * @api private
95 */
96 Protocol: {
97 Json: __webpack_require__(13),
98 Query: __webpack_require__(17),
99 Rest: __webpack_require__(21),
100 RestJson: __webpack_require__(22),
101 RestXml: __webpack_require__(23)
102 },
103
104 /**
105 * @api private
106 */
107 XML: {
108 Builder: __webpack_require__(24),
109 Parser: null // conditionally set based on environment
110 },
111
112 /**
113 * @api private
114 */
115 JSON: {
116 Builder: __webpack_require__(14),
117 Parser: __webpack_require__(15)
118 },
119
120 /**
121 * @api private
122 */
123 Model: {
124 Api: __webpack_require__(29),
125 Operation: __webpack_require__(30),
126 Shape: __webpack_require__(19),
127 Paginator: __webpack_require__(31),
128 ResourceWaiter: __webpack_require__(32)
129 },
130
131 /**
132 * @api private
133 */
134 apiLoader: __webpack_require__(33),
135
136 /**
137 * @api private
138 */
139 EndpointCache: __webpack_require__(34).EndpointCache
140 });
141 __webpack_require__(36);
142 __webpack_require__(37);
143 __webpack_require__(40);
144 __webpack_require__(43);
145 __webpack_require__(44);
146 __webpack_require__(49);
147 __webpack_require__(52);
148 __webpack_require__(53);
149 __webpack_require__(54);
150 __webpack_require__(62);
151
152 /**
153 * @readonly
154 * @return [AWS.SequentialExecutor] a collection of global event listeners that
155 * are attached to every sent request.
156 * @see AWS.Request AWS.Request for a list of events to listen for
157 * @example Logging the time taken to send a request
158 * AWS.events.on('send', function startSend(resp) {
159 * resp.startTime = new Date().getTime();
160 * }).on('complete', function calculateTime(resp) {
161 * var time = (new Date().getTime() - resp.startTime) / 1000;
162 * console.log('Request took ' + time + ' seconds');
163 * });
164 *
165 * new AWS.S3().listBuckets(); // prints 'Request took 0.285 seconds'
166 */
167 AWS.events = new AWS.SequentialExecutor();
168
169 //create endpoint cache lazily
170 AWS.util.memoizedProperty(AWS, 'endpointCache', function() {
171 return new AWS.EndpointCache(AWS.config.endpointCacheSize);
172 }, true);
173
174
175/***/ }),
176/* 2 */
177/***/ (function(module, exports, __webpack_require__) {
178
179 /* WEBPACK VAR INJECTION */(function(process, setImmediate) {/* eslint guard-for-in:0 */
180 var AWS;
181
182 /**
183 * A set of utility methods for use with the AWS SDK.
184 *
185 * @!attribute abort
186 * Return this value from an iterator function {each} or {arrayEach}
187 * to break out of the iteration.
188 * @example Breaking out of an iterator function
189 * AWS.util.each({a: 1, b: 2, c: 3}, function(key, value) {
190 * if (key == 'b') return AWS.util.abort;
191 * });
192 * @see each
193 * @see arrayEach
194 * @api private
195 */
196 var util = {
197 environment: 'nodejs',
198 engine: function engine() {
199 if (util.isBrowser() && typeof navigator !== 'undefined') {
200 return navigator.userAgent;
201 } else {
202 var engine = process.platform + '/' + process.version;
203 if (process.env.AWS_EXECUTION_ENV) {
204 engine += ' exec-env/' + process.env.AWS_EXECUTION_ENV;
205 }
206 return engine;
207 }
208 },
209
210 userAgent: function userAgent() {
211 var name = util.environment;
212 var agent = 'aws-sdk-' + name + '/' + __webpack_require__(1).VERSION;
213 if (name === 'nodejs') agent += ' ' + util.engine();
214 return agent;
215 },
216
217 uriEscape: function uriEscape(string) {
218 var output = encodeURIComponent(string);
219 output = output.replace(/[^A-Za-z0-9_.~\-%]+/g, escape);
220
221 // AWS percent-encodes some extra non-standard characters in a URI
222 output = output.replace(/[*]/g, function(ch) {
223 return '%' + ch.charCodeAt(0).toString(16).toUpperCase();
224 });
225
226 return output;
227 },
228
229 uriEscapePath: function uriEscapePath(string) {
230 var parts = [];
231 util.arrayEach(string.split('/'), function (part) {
232 parts.push(util.uriEscape(part));
233 });
234 return parts.join('/');
235 },
236
237 urlParse: function urlParse(url) {
238 return util.url.parse(url);
239 },
240
241 urlFormat: function urlFormat(url) {
242 return util.url.format(url);
243 },
244
245 queryStringParse: function queryStringParse(qs) {
246 return util.querystring.parse(qs);
247 },
248
249 queryParamsToString: function queryParamsToString(params) {
250 var items = [];
251 var escape = util.uriEscape;
252 var sortedKeys = Object.keys(params).sort();
253
254 util.arrayEach(sortedKeys, function(name) {
255 var value = params[name];
256 var ename = escape(name);
257 var result = ename + '=';
258 if (Array.isArray(value)) {
259 var vals = [];
260 util.arrayEach(value, function(item) { vals.push(escape(item)); });
261 result = ename + '=' + vals.sort().join('&' + ename + '=');
262 } else if (value !== undefined && value !== null) {
263 result = ename + '=' + escape(value);
264 }
265 items.push(result);
266 });
267
268 return items.join('&');
269 },
270
271 readFileSync: function readFileSync(path) {
272 if (util.isBrowser()) return null;
273 return __webpack_require__(6).readFileSync(path, 'utf-8');
274 },
275
276 base64: {
277 encode: function encode64(string) {
278 if (typeof string === 'number') {
279 throw util.error(new Error('Cannot base64 encode number ' + string));
280 }
281 if (string === null || typeof string === 'undefined') {
282 return string;
283 }
284 var buf = util.buffer.toBuffer(string);
285 return buf.toString('base64');
286 },
287
288 decode: function decode64(string) {
289 if (typeof string === 'number') {
290 throw util.error(new Error('Cannot base64 decode number ' + string));
291 }
292 if (string === null || typeof string === 'undefined') {
293 return string;
294 }
295 return util.buffer.toBuffer(string, 'base64');
296 }
297
298 },
299
300 buffer: {
301 /**
302 * Buffer constructor for Node buffer and buffer pollyfill
303 */
304 toBuffer: function(data, encoding) {
305 return (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ?
306 util.Buffer.from(data, encoding) : new util.Buffer(data, encoding);
307 },
308
309 alloc: function(size, fill, encoding) {
310 if (typeof size !== 'number') {
311 throw new Error('size passed to alloc must be a number.');
312 }
313 if (typeof util.Buffer.alloc === 'function') {
314 return util.Buffer.alloc(size, fill, encoding);
315 } else {
316 var buf = new util.Buffer(size);
317 if (fill !== undefined && typeof buf.fill === 'function') {
318 buf.fill(fill, undefined, undefined, encoding);
319 }
320 return buf;
321 }
322 },
323
324 toStream: function toStream(buffer) {
325 if (!util.Buffer.isBuffer(buffer)) buffer = util.buffer.toBuffer(buffer);
326
327 var readable = new (util.stream.Readable)();
328 var pos = 0;
329 readable._read = function(size) {
330 if (pos >= buffer.length) return readable.push(null);
331
332 var end = pos + size;
333 if (end > buffer.length) end = buffer.length;
334 readable.push(buffer.slice(pos, end));
335 pos = end;
336 };
337
338 return readable;
339 },
340
341 /**
342 * Concatenates a list of Buffer objects.
343 */
344 concat: function(buffers) {
345 var length = 0,
346 offset = 0,
347 buffer = null, i;
348
349 for (i = 0; i < buffers.length; i++) {
350 length += buffers[i].length;
351 }
352
353 buffer = util.buffer.alloc(length);
354
355 for (i = 0; i < buffers.length; i++) {
356 buffers[i].copy(buffer, offset);
357 offset += buffers[i].length;
358 }
359
360 return buffer;
361 }
362 },
363
364 string: {
365 byteLength: function byteLength(string) {
366 if (string === null || string === undefined) return 0;
367 if (typeof string === 'string') string = util.buffer.toBuffer(string);
368
369 if (typeof string.byteLength === 'number') {
370 return string.byteLength;
371 } else if (typeof string.length === 'number') {
372 return string.length;
373 } else if (typeof string.size === 'number') {
374 return string.size;
375 } else if (typeof string.path === 'string') {
376 return __webpack_require__(6).lstatSync(string.path).size;
377 } else {
378 throw util.error(new Error('Cannot determine length of ' + string),
379 { object: string });
380 }
381 },
382
383 upperFirst: function upperFirst(string) {
384 return string[0].toUpperCase() + string.substr(1);
385 },
386
387 lowerFirst: function lowerFirst(string) {
388 return string[0].toLowerCase() + string.substr(1);
389 }
390 },
391
392 ini: {
393 parse: function string(ini) {
394 var currentSection, map = {};
395 util.arrayEach(ini.split(/\r?\n/), function(line) {
396 line = line.split(/(^|\s)[;#]/)[0]; // remove comments
397 var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/);
398 if (section) {
399 currentSection = section[1];
400 } else if (currentSection) {
401 var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/);
402 if (item) {
403 map[currentSection] = map[currentSection] || {};
404 map[currentSection][item[1]] = item[2];
405 }
406 }
407 });
408
409 return map;
410 }
411 },
412
413 fn: {
414 noop: function() {},
415 callback: function (err) { if (err) throw err; },
416
417 /**
418 * Turn a synchronous function into as "async" function by making it call
419 * a callback. The underlying function is called with all but the last argument,
420 * which is treated as the callback. The callback is passed passed a first argument
421 * of null on success to mimick standard node callbacks.
422 */
423 makeAsync: function makeAsync(fn, expectedArgs) {
424 if (expectedArgs && expectedArgs <= fn.length) {
425 return fn;
426 }
427
428 return function() {
429 var args = Array.prototype.slice.call(arguments, 0);
430 var callback = args.pop();
431 var result = fn.apply(null, args);
432 callback(result);
433 };
434 }
435 },
436
437 /**
438 * Date and time utility functions.
439 */
440 date: {
441
442 /**
443 * @return [Date] the current JavaScript date object. Since all
444 * AWS services rely on this date object, you can override
445 * this function to provide a special time value to AWS service
446 * requests.
447 */
448 getDate: function getDate() {
449 if (!AWS) AWS = __webpack_require__(1);
450 if (AWS.config.systemClockOffset) { // use offset when non-zero
451 return new Date(new Date().getTime() + AWS.config.systemClockOffset);
452 } else {
453 return new Date();
454 }
455 },
456
457 /**
458 * @return [String] the date in ISO-8601 format
459 */
460 iso8601: function iso8601(date) {
461 if (date === undefined) { date = util.date.getDate(); }
462 return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
463 },
464
465 /**
466 * @return [String] the date in RFC 822 format
467 */
468 rfc822: function rfc822(date) {
469 if (date === undefined) { date = util.date.getDate(); }
470 return date.toUTCString();
471 },
472
473 /**
474 * @return [Integer] the UNIX timestamp value for the current time
475 */
476 unixTimestamp: function unixTimestamp(date) {
477 if (date === undefined) { date = util.date.getDate(); }
478 return date.getTime() / 1000;
479 },
480
481 /**
482 * @param [String,number,Date] date
483 * @return [Date]
484 */
485 from: function format(date) {
486 if (typeof date === 'number') {
487 return new Date(date * 1000); // unix timestamp
488 } else {
489 return new Date(date);
490 }
491 },
492
493 /**
494 * Given a Date or date-like value, this function formats the
495 * date into a string of the requested value.
496 * @param [String,number,Date] date
497 * @param [String] formatter Valid formats are:
498 # * 'iso8601'
499 # * 'rfc822'
500 # * 'unixTimestamp'
501 * @return [String]
502 */
503 format: function format(date, formatter) {
504 if (!formatter) formatter = 'iso8601';
505 return util.date[formatter](util.date.from(date));
506 },
507
508 parseTimestamp: function parseTimestamp(value) {
509 if (typeof value === 'number') { // unix timestamp (number)
510 return new Date(value * 1000);
511 } else if (value.match(/^\d+$/)) { // unix timestamp
512 return new Date(value * 1000);
513 } else if (value.match(/^\d{4}/)) { // iso8601
514 return new Date(value);
515 } else if (value.match(/^\w{3},/)) { // rfc822
516 return new Date(value);
517 } else {
518 throw util.error(
519 new Error('unhandled timestamp format: ' + value),
520 {code: 'TimestampParserError'});
521 }
522 }
523
524 },
525
526 crypto: {
527 crc32Table: [
528 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
529 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
530 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
531 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
532 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
533 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
534 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
535 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
536 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
537 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
538 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
539 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
540 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
541 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
542 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
543 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
544 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
545 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
546 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
547 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
548 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
549 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
550 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
551 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
552 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
553 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
554 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
555 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
556 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
557 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
558 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
559 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
560 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
561 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
562 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
563 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
564 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
565 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
566 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
567 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
568 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
569 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
570 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
571 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
572 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
573 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
574 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
575 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
576 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
577 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
578 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
579 0x2D02EF8D],
580
581 crc32: function crc32(data) {
582 var tbl = util.crypto.crc32Table;
583 var crc = 0 ^ -1;
584
585 if (typeof data === 'string') {
586 data = util.buffer.toBuffer(data);
587 }
588
589 for (var i = 0; i < data.length; i++) {
590 var code = data.readUInt8(i);
591 crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF];
592 }
593 return (crc ^ -1) >>> 0;
594 },
595
596 hmac: function hmac(key, string, digest, fn) {
597 if (!digest) digest = 'binary';
598 if (digest === 'buffer') { digest = undefined; }
599 if (!fn) fn = 'sha256';
600 if (typeof string === 'string') string = util.buffer.toBuffer(string);
601 return util.crypto.lib.createHmac(fn, key).update(string).digest(digest);
602 },
603
604 md5: function md5(data, digest, callback) {
605 return util.crypto.hash('md5', data, digest, callback);
606 },
607
608 sha256: function sha256(data, digest, callback) {
609 return util.crypto.hash('sha256', data, digest, callback);
610 },
611
612 hash: function(algorithm, data, digest, callback) {
613 var hash = util.crypto.createHash(algorithm);
614 if (!digest) { digest = 'binary'; }
615 if (digest === 'buffer') { digest = undefined; }
616 if (typeof data === 'string') data = util.buffer.toBuffer(data);
617 var sliceFn = util.arraySliceFn(data);
618 var isBuffer = util.Buffer.isBuffer(data);
619 //Identifying objects with an ArrayBuffer as buffers
620 if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true;
621
622 if (callback && typeof data === 'object' &&
623 typeof data.on === 'function' && !isBuffer) {
624 data.on('data', function(chunk) { hash.update(chunk); });
625 data.on('error', function(err) { callback(err); });
626 data.on('end', function() { callback(null, hash.digest(digest)); });
627 } else if (callback && sliceFn && !isBuffer &&
628 typeof FileReader !== 'undefined') {
629 // this might be a File/Blob
630 var index = 0, size = 1024 * 512;
631 var reader = new FileReader();
632 reader.onerror = function() {
633 callback(new Error('Failed to read data.'));
634 };
635 reader.onload = function() {
636 var buf = new util.Buffer(new Uint8Array(reader.result));
637 hash.update(buf);
638 index += buf.length;
639 reader._continueReading();
640 };
641 reader._continueReading = function() {
642 if (index >= data.size) {
643 callback(null, hash.digest(digest));
644 return;
645 }
646
647 var back = index + size;
648 if (back > data.size) back = data.size;
649 reader.readAsArrayBuffer(sliceFn.call(data, index, back));
650 };
651
652 reader._continueReading();
653 } else {
654 if (util.isBrowser() && typeof data === 'object' && !isBuffer) {
655 data = new util.Buffer(new Uint8Array(data));
656 }
657 var out = hash.update(data).digest(digest);
658 if (callback) callback(null, out);
659 return out;
660 }
661 },
662
663 toHex: function toHex(data) {
664 var out = [];
665 for (var i = 0; i < data.length; i++) {
666 out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2));
667 }
668 return out.join('');
669 },
670
671 createHash: function createHash(algorithm) {
672 return util.crypto.lib.createHash(algorithm);
673 }
674
675 },
676
677 /** @!ignore */
678
679 /* Abort constant */
680 abort: {},
681
682 each: function each(object, iterFunction) {
683 for (var key in object) {
684 if (Object.prototype.hasOwnProperty.call(object, key)) {
685 var ret = iterFunction.call(this, key, object[key]);
686 if (ret === util.abort) break;
687 }
688 }
689 },
690
691 arrayEach: function arrayEach(array, iterFunction) {
692 for (var idx in array) {
693 if (Object.prototype.hasOwnProperty.call(array, idx)) {
694 var ret = iterFunction.call(this, array[idx], parseInt(idx, 10));
695 if (ret === util.abort) break;
696 }
697 }
698 },
699
700 update: function update(obj1, obj2) {
701 util.each(obj2, function iterator(key, item) {
702 obj1[key] = item;
703 });
704 return obj1;
705 },
706
707 merge: function merge(obj1, obj2) {
708 return util.update(util.copy(obj1), obj2);
709 },
710
711 copy: function copy(object) {
712 if (object === null || object === undefined) return object;
713 var dupe = {};
714 // jshint forin:false
715 for (var key in object) {
716 dupe[key] = object[key];
717 }
718 return dupe;
719 },
720
721 isEmpty: function isEmpty(obj) {
722 for (var prop in obj) {
723 if (Object.prototype.hasOwnProperty.call(obj, prop)) {
724 return false;
725 }
726 }
727 return true;
728 },
729
730 arraySliceFn: function arraySliceFn(obj) {
731 var fn = obj.slice || obj.webkitSlice || obj.mozSlice;
732 return typeof fn === 'function' ? fn : null;
733 },
734
735 isType: function isType(obj, type) {
736 // handle cross-"frame" objects
737 if (typeof type === 'function') type = util.typeName(type);
738 return Object.prototype.toString.call(obj) === '[object ' + type + ']';
739 },
740
741 typeName: function typeName(type) {
742 if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name;
743 var str = type.toString();
744 var match = str.match(/^\s*function (.+)\(/);
745 return match ? match[1] : str;
746 },
747
748 error: function error(err, options) {
749 var originalError = null;
750 if (typeof err.message === 'string' && err.message !== '') {
751 if (typeof options === 'string' || (options && options.message)) {
752 originalError = util.copy(err);
753 originalError.message = err.message;
754 }
755 }
756 err.message = err.message || null;
757
758 if (typeof options === 'string') {
759 err.message = options;
760 } else if (typeof options === 'object' && options !== null) {
761 util.update(err, options);
762 if (options.message)
763 err.message = options.message;
764 if (options.code || options.name)
765 err.code = options.code || options.name;
766 if (options.stack)
767 err.stack = options.stack;
768 }
769
770 if (typeof Object.defineProperty === 'function') {
771 Object.defineProperty(err, 'name', {writable: true, enumerable: false});
772 Object.defineProperty(err, 'message', {enumerable: true});
773 }
774
775 err.name = String(options && options.name || err.name || err.code || 'Error');
776 err.time = new Date();
777
778 if (originalError) err.originalError = originalError;
779
780 return err;
781 },
782
783 /**
784 * @api private
785 */
786 inherit: function inherit(klass, features) {
787 var newObject = null;
788 if (features === undefined) {
789 features = klass;
790 klass = Object;
791 newObject = {};
792 } else {
793 var ctor = function ConstructorWrapper() {};
794 ctor.prototype = klass.prototype;
795 newObject = new ctor();
796 }
797
798 // constructor not supplied, create pass-through ctor
799 if (features.constructor === Object) {
800 features.constructor = function() {
801 if (klass !== Object) {
802 return klass.apply(this, arguments);
803 }
804 };
805 }
806
807 features.constructor.prototype = newObject;
808 util.update(features.constructor.prototype, features);
809 features.constructor.__super__ = klass;
810 return features.constructor;
811 },
812
813 /**
814 * @api private
815 */
816 mixin: function mixin() {
817 var klass = arguments[0];
818 for (var i = 1; i < arguments.length; i++) {
819 // jshint forin:false
820 for (var prop in arguments[i].prototype) {
821 var fn = arguments[i].prototype[prop];
822 if (prop !== 'constructor') {
823 klass.prototype[prop] = fn;
824 }
825 }
826 }
827 return klass;
828 },
829
830 /**
831 * @api private
832 */
833 hideProperties: function hideProperties(obj, props) {
834 if (typeof Object.defineProperty !== 'function') return;
835
836 util.arrayEach(props, function (key) {
837 Object.defineProperty(obj, key, {
838 enumerable: false, writable: true, configurable: true });
839 });
840 },
841
842 /**
843 * @api private
844 */
845 property: function property(obj, name, value, enumerable, isValue) {
846 var opts = {
847 configurable: true,
848 enumerable: enumerable !== undefined ? enumerable : true
849 };
850 if (typeof value === 'function' && !isValue) {
851 opts.get = value;
852 }
853 else {
854 opts.value = value; opts.writable = true;
855 }
856
857 Object.defineProperty(obj, name, opts);
858 },
859
860 /**
861 * @api private
862 */
863 memoizedProperty: function memoizedProperty(obj, name, get, enumerable) {
864 var cachedValue = null;
865
866 // build enumerable attribute for each value with lazy accessor.
867 util.property(obj, name, function() {
868 if (cachedValue === null) {
869 cachedValue = get();
870 }
871 return cachedValue;
872 }, enumerable);
873 },
874
875 /**
876 * TODO Remove in major version revision
877 * This backfill populates response data without the
878 * top-level payload name.
879 *
880 * @api private
881 */
882 hoistPayloadMember: function hoistPayloadMember(resp) {
883 var req = resp.request;
884 var operationName = req.operation;
885 var operation = req.service.api.operations[operationName];
886 var output = operation.output;
887 if (output.payload && !operation.hasEventOutput) {
888 var payloadMember = output.members[output.payload];
889 var responsePayload = resp.data[output.payload];
890 if (payloadMember.type === 'structure') {
891 util.each(responsePayload, function(key, value) {
892 util.property(resp.data, key, value, false);
893 });
894 }
895 }
896 },
897
898 /**
899 * Compute SHA-256 checksums of streams
900 *
901 * @api private
902 */
903 computeSha256: function computeSha256(body, done) {
904 if (util.isNode()) {
905 var Stream = util.stream.Stream;
906 var fs = __webpack_require__(6);
907 if (typeof Stream === 'function' && body instanceof Stream) {
908 if (typeof body.path === 'string') { // assume file object
909 var settings = {};
910 if (typeof body.start === 'number') {
911 settings.start = body.start;
912 }
913 if (typeof body.end === 'number') {
914 settings.end = body.end;
915 }
916 body = fs.createReadStream(body.path, settings);
917 } else { // TODO support other stream types
918 return done(new Error('Non-file stream objects are ' +
919 'not supported with SigV4'));
920 }
921 }
922 }
923
924 util.crypto.sha256(body, 'hex', function(err, sha) {
925 if (err) done(err);
926 else done(null, sha);
927 });
928 },
929
930 /**
931 * @api private
932 */
933 isClockSkewed: function isClockSkewed(serverTime) {
934 if (serverTime) {
935 util.property(AWS.config, 'isClockSkewed',
936 Math.abs(new Date().getTime() - serverTime) >= 300000, false);
937 return AWS.config.isClockSkewed;
938 }
939 },
940
941 applyClockOffset: function applyClockOffset(serverTime) {
942 if (serverTime)
943 AWS.config.systemClockOffset = serverTime - new Date().getTime();
944 },
945
946 /**
947 * @api private
948 */
949 extractRequestId: function extractRequestId(resp) {
950 var requestId = resp.httpResponse.headers['x-amz-request-id'] ||
951 resp.httpResponse.headers['x-amzn-requestid'];
952
953 if (!requestId && resp.data && resp.data.ResponseMetadata) {
954 requestId = resp.data.ResponseMetadata.RequestId;
955 }
956
957 if (requestId) {
958 resp.requestId = requestId;
959 }
960
961 if (resp.error) {
962 resp.error.requestId = requestId;
963 }
964 },
965
966 /**
967 * @api private
968 */
969 addPromises: function addPromises(constructors, PromiseDependency) {
970 var deletePromises = false;
971 if (PromiseDependency === undefined && AWS && AWS.config) {
972 PromiseDependency = AWS.config.getPromisesDependency();
973 }
974 if (PromiseDependency === undefined && typeof Promise !== 'undefined') {
975 PromiseDependency = Promise;
976 }
977 if (typeof PromiseDependency !== 'function') deletePromises = true;
978 if (!Array.isArray(constructors)) constructors = [constructors];
979
980 for (var ind = 0; ind < constructors.length; ind++) {
981 var constructor = constructors[ind];
982 if (deletePromises) {
983 if (constructor.deletePromisesFromClass) {
984 constructor.deletePromisesFromClass();
985 }
986 } else if (constructor.addPromisesToClass) {
987 constructor.addPromisesToClass(PromiseDependency);
988 }
989 }
990 },
991
992 /**
993 * @api private
994 * Return a function that will return a promise whose fate is decided by the
995 * callback behavior of the given method with `methodName`. The method to be
996 * promisified should conform to node.js convention of accepting a callback as
997 * last argument and calling that callback with error as the first argument
998 * and success value on the second argument.
999 */
1000 promisifyMethod: function promisifyMethod(methodName, PromiseDependency) {
1001 return function promise() {
1002 var self = this;
1003 var args = Array.prototype.slice.call(arguments);
1004 return new PromiseDependency(function(resolve, reject) {
1005 args.push(function(err, data) {
1006 if (err) {
1007 reject(err);
1008 } else {
1009 resolve(data);
1010 }
1011 });
1012 self[methodName].apply(self, args);
1013 });
1014 };
1015 },
1016
1017 /**
1018 * @api private
1019 */
1020 isDualstackAvailable: function isDualstackAvailable(service) {
1021 if (!service) return false;
1022 var metadata = __webpack_require__(7);
1023 if (typeof service !== 'string') service = service.serviceIdentifier;
1024 if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false;
1025 return !!metadata[service].dualstackAvailable;
1026 },
1027
1028 /**
1029 * @api private
1030 */
1031 calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions, err) {
1032 if (!retryDelayOptions) retryDelayOptions = {};
1033 var customBackoff = retryDelayOptions.customBackoff || null;
1034 if (typeof customBackoff === 'function') {
1035 return customBackoff(retryCount, err);
1036 }
1037 var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100;
1038 var delay = Math.random() * (Math.pow(2, retryCount) * base);
1039 return delay;
1040 },
1041
1042 /**
1043 * @api private
1044 */
1045 handleRequestWithRetries: function handleRequestWithRetries(httpRequest, options, cb) {
1046 if (!options) options = {};
1047 var http = AWS.HttpClient.getInstance();
1048 var httpOptions = options.httpOptions || {};
1049 var retryCount = 0;
1050
1051 var errCallback = function(err) {
1052 var maxRetries = options.maxRetries || 0;
1053 if (err && err.code === 'TimeoutError') err.retryable = true;
1054 var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions, err);
1055 if (err && err.retryable && retryCount < maxRetries && delay >= 0) {
1056 retryCount++;
1057 setTimeout(sendRequest, delay + (err.retryAfter || 0));
1058 } else {
1059 cb(err);
1060 }
1061 };
1062
1063 var sendRequest = function() {
1064 var data = '';
1065 http.handleRequest(httpRequest, httpOptions, function(httpResponse) {
1066 httpResponse.on('data', function(chunk) { data += chunk.toString(); });
1067 httpResponse.on('end', function() {
1068 var statusCode = httpResponse.statusCode;
1069 if (statusCode < 300) {
1070 cb(null, data);
1071 } else {
1072 var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0;
1073 var err = util.error(new Error(),
1074 {
1075 statusCode: statusCode,
1076 retryable: statusCode >= 500 || statusCode === 429
1077 }
1078 );
1079 if (retryAfter && err.retryable) err.retryAfter = retryAfter;
1080 errCallback(err);
1081 }
1082 });
1083 }, errCallback);
1084 };
1085
1086 AWS.util.defer(sendRequest);
1087 },
1088
1089 /**
1090 * @api private
1091 */
1092 uuid: {
1093 v4: function uuidV4() {
1094 return __webpack_require__(8).v4();
1095 }
1096 },
1097
1098 /**
1099 * @api private
1100 */
1101 convertPayloadToString: function convertPayloadToString(resp) {
1102 var req = resp.request;
1103 var operation = req.operation;
1104 var rules = req.service.api.operations[operation].output || {};
1105 if (rules.payload && resp.data[rules.payload]) {
1106 resp.data[rules.payload] = resp.data[rules.payload].toString();
1107 }
1108 },
1109
1110 /**
1111 * @api private
1112 */
1113 defer: function defer(callback) {
1114 if (typeof process === 'object' && typeof process.nextTick === 'function') {
1115 process.nextTick(callback);
1116 } else if (typeof setImmediate === 'function') {
1117 setImmediate(callback);
1118 } else {
1119 setTimeout(callback, 0);
1120 }
1121 },
1122
1123 /**
1124 * @api private
1125 */
1126 getRequestPayloadShape: function getRequestPayloadShape(req) {
1127 var operations = req.service.api.operations;
1128 if (!operations) return undefined;
1129 var operation = (operations || {})[req.operation];
1130 if (!operation || !operation.input || !operation.input.payload) return undefined;
1131 return operation.input.members[operation.input.payload];
1132 },
1133
1134 getProfilesFromSharedConfig: function getProfilesFromSharedConfig(iniLoader, filename) {
1135 var profiles = {};
1136 var profilesFromConfig = {};
1137 if (process.env[util.configOptInEnv]) {
1138 var profilesFromConfig = iniLoader.loadFrom({
1139 isConfig: true,
1140 filename: process.env[util.sharedConfigFileEnv]
1141 });
1142 }
1143 var profilesFromCreds = iniLoader.loadFrom({
1144 filename: filename ||
1145 (process.env[util.configOptInEnv] && process.env[util.sharedCredentialsFileEnv])
1146 });
1147 for (var i = 0, profileNames = Object.keys(profilesFromConfig); i < profileNames.length; i++) {
1148 profiles[profileNames[i]] = profilesFromConfig[profileNames[i]];
1149 }
1150 for (var i = 0, profileNames = Object.keys(profilesFromCreds); i < profileNames.length; i++) {
1151 profiles[profileNames[i]] = profilesFromCreds[profileNames[i]];
1152 }
1153 return profiles;
1154 },
1155
1156 /**
1157 * @api private
1158 */
1159 ARN: {
1160 validate: function validateARN(str) {
1161 return str && str.indexOf('arn:') === 0 && str.split(':').length >= 6;
1162 },
1163 parse: function parseARN(arn) {
1164 var matched = arn.split(':');
1165 return {
1166 partition: matched[1],
1167 service: matched[2],
1168 region: matched[3],
1169 accountId: matched[4],
1170 resource: matched.slice(5).join(':')
1171 };
1172 },
1173 build: function buildARN(arnObject) {
1174 if (
1175 arnObject.service === undefined ||
1176 arnObject.region === undefined ||
1177 arnObject.accountId === undefined ||
1178 arnObject.resource === undefined
1179 ) throw util.error(new Error('Input ARN object is invalid'));
1180 return 'arn:'+ (arnObject.partition || 'aws') + ':' + arnObject.service +
1181 ':' + arnObject.region + ':' + arnObject.accountId + ':' + arnObject.resource;
1182 }
1183 },
1184
1185 /**
1186 * @api private
1187 */
1188 defaultProfile: 'default',
1189
1190 /**
1191 * @api private
1192 */
1193 configOptInEnv: 'AWS_SDK_LOAD_CONFIG',
1194
1195 /**
1196 * @api private
1197 */
1198 sharedCredentialsFileEnv: 'AWS_SHARED_CREDENTIALS_FILE',
1199
1200 /**
1201 * @api private
1202 */
1203 sharedConfigFileEnv: 'AWS_CONFIG_FILE',
1204
1205 /**
1206 * @api private
1207 */
1208 imdsDisabledEnv: 'AWS_EC2_METADATA_DISABLED'
1209 };
1210
1211 /**
1212 * @api private
1213 */
1214 module.exports = util;
1215
1216 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(4).setImmediate))
1217
1218/***/ }),
1219/* 3 */
1220/***/ (function(module, exports) {
1221
1222 // shim for using process in browser
1223 var process = module.exports = {};
1224
1225 // cached from whatever global is present so that test runners that stub it
1226 // don't break things. But we need to wrap it in a try catch in case it is
1227 // wrapped in strict mode code which doesn't define any globals. It's inside a
1228 // function because try/catches deoptimize in certain engines.
1229
1230 var cachedSetTimeout;
1231 var cachedClearTimeout;
1232
1233 function defaultSetTimout() {
1234 throw new Error('setTimeout has not been defined');
1235 }
1236 function defaultClearTimeout () {
1237 throw new Error('clearTimeout has not been defined');
1238 }
1239 (function () {
1240 try {
1241 if (typeof setTimeout === 'function') {
1242 cachedSetTimeout = setTimeout;
1243 } else {
1244 cachedSetTimeout = defaultSetTimout;
1245 }
1246 } catch (e) {
1247 cachedSetTimeout = defaultSetTimout;
1248 }
1249 try {
1250 if (typeof clearTimeout === 'function') {
1251 cachedClearTimeout = clearTimeout;
1252 } else {
1253 cachedClearTimeout = defaultClearTimeout;
1254 }
1255 } catch (e) {
1256 cachedClearTimeout = defaultClearTimeout;
1257 }
1258 } ())
1259 function runTimeout(fun) {
1260 if (cachedSetTimeout === setTimeout) {
1261 //normal enviroments in sane situations
1262 return setTimeout(fun, 0);
1263 }
1264 // if setTimeout wasn't available but was latter defined
1265 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
1266 cachedSetTimeout = setTimeout;
1267 return setTimeout(fun, 0);
1268 }
1269 try {
1270 // when when somebody has screwed with setTimeout but no I.E. maddness
1271 return cachedSetTimeout(fun, 0);
1272 } catch(e){
1273 try {
1274 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1275 return cachedSetTimeout.call(null, fun, 0);
1276 } catch(e){
1277 // 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
1278 return cachedSetTimeout.call(this, fun, 0);
1279 }
1280 }
1281
1282
1283 }
1284 function runClearTimeout(marker) {
1285 if (cachedClearTimeout === clearTimeout) {
1286 //normal enviroments in sane situations
1287 return clearTimeout(marker);
1288 }
1289 // if clearTimeout wasn't available but was latter defined
1290 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
1291 cachedClearTimeout = clearTimeout;
1292 return clearTimeout(marker);
1293 }
1294 try {
1295 // when when somebody has screwed with setTimeout but no I.E. maddness
1296 return cachedClearTimeout(marker);
1297 } catch (e){
1298 try {
1299 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1300 return cachedClearTimeout.call(null, marker);
1301 } catch (e){
1302 // 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.
1303 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
1304 return cachedClearTimeout.call(this, marker);
1305 }
1306 }
1307
1308
1309
1310 }
1311 var queue = [];
1312 var draining = false;
1313 var currentQueue;
1314 var queueIndex = -1;
1315
1316 function cleanUpNextTick() {
1317 if (!draining || !currentQueue) {
1318 return;
1319 }
1320 draining = false;
1321 if (currentQueue.length) {
1322 queue = currentQueue.concat(queue);
1323 } else {
1324 queueIndex = -1;
1325 }
1326 if (queue.length) {
1327 drainQueue();
1328 }
1329 }
1330
1331 function drainQueue() {
1332 if (draining) {
1333 return;
1334 }
1335 var timeout = runTimeout(cleanUpNextTick);
1336 draining = true;
1337
1338 var len = queue.length;
1339 while(len) {
1340 currentQueue = queue;
1341 queue = [];
1342 while (++queueIndex < len) {
1343 if (currentQueue) {
1344 currentQueue[queueIndex].run();
1345 }
1346 }
1347 queueIndex = -1;
1348 len = queue.length;
1349 }
1350 currentQueue = null;
1351 draining = false;
1352 runClearTimeout(timeout);
1353 }
1354
1355 process.nextTick = function (fun) {
1356 var args = new Array(arguments.length - 1);
1357 if (arguments.length > 1) {
1358 for (var i = 1; i < arguments.length; i++) {
1359 args[i - 1] = arguments[i];
1360 }
1361 }
1362 queue.push(new Item(fun, args));
1363 if (queue.length === 1 && !draining) {
1364 runTimeout(drainQueue);
1365 }
1366 };
1367
1368 // v8 likes predictible objects
1369 function Item(fun, array) {
1370 this.fun = fun;
1371 this.array = array;
1372 }
1373 Item.prototype.run = function () {
1374 this.fun.apply(null, this.array);
1375 };
1376 process.title = 'browser';
1377 process.browser = true;
1378 process.env = {};
1379 process.argv = [];
1380 process.version = ''; // empty string to avoid regexp issues
1381 process.versions = {};
1382
1383 function noop() {}
1384
1385 process.on = noop;
1386 process.addListener = noop;
1387 process.once = noop;
1388 process.off = noop;
1389 process.removeListener = noop;
1390 process.removeAllListeners = noop;
1391 process.emit = noop;
1392 process.prependListener = noop;
1393 process.prependOnceListener = noop;
1394
1395 process.listeners = function (name) { return [] }
1396
1397 process.binding = function (name) {
1398 throw new Error('process.binding is not supported');
1399 };
1400
1401 process.cwd = function () { return '/' };
1402 process.chdir = function (dir) {
1403 throw new Error('process.chdir is not supported');
1404 };
1405 process.umask = function() { return 0; };
1406
1407
1408/***/ }),
1409/* 4 */
1410/***/ (function(module, exports, __webpack_require__) {
1411
1412 /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
1413 (typeof self !== "undefined" && self) ||
1414 window;
1415 var apply = Function.prototype.apply;
1416
1417 // DOM APIs, for completeness
1418
1419 exports.setTimeout = function() {
1420 return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
1421 };
1422 exports.setInterval = function() {
1423 return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
1424 };
1425 exports.clearTimeout =
1426 exports.clearInterval = function(timeout) {
1427 if (timeout) {
1428 timeout.close();
1429 }
1430 };
1431
1432 function Timeout(id, clearFn) {
1433 this._id = id;
1434 this._clearFn = clearFn;
1435 }
1436 Timeout.prototype.unref = Timeout.prototype.ref = function() {};
1437 Timeout.prototype.close = function() {
1438 this._clearFn.call(scope, this._id);
1439 };
1440
1441 // Does not start the time, just sets up the members needed.
1442 exports.enroll = function(item, msecs) {
1443 clearTimeout(item._idleTimeoutId);
1444 item._idleTimeout = msecs;
1445 };
1446
1447 exports.unenroll = function(item) {
1448 clearTimeout(item._idleTimeoutId);
1449 item._idleTimeout = -1;
1450 };
1451
1452 exports._unrefActive = exports.active = function(item) {
1453 clearTimeout(item._idleTimeoutId);
1454
1455 var msecs = item._idleTimeout;
1456 if (msecs >= 0) {
1457 item._idleTimeoutId = setTimeout(function onTimeout() {
1458 if (item._onTimeout)
1459 item._onTimeout();
1460 }, msecs);
1461 }
1462 };
1463
1464 // setimmediate attaches itself to the global object
1465 __webpack_require__(5);
1466 // On some exotic environments, it's not clear which object `setimmediate` was
1467 // able to install onto. Search each possibility in the same order as the
1468 // `setimmediate` library.
1469 exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
1470 (typeof global !== "undefined" && global.setImmediate) ||
1471 (this && this.setImmediate);
1472 exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
1473 (typeof global !== "undefined" && global.clearImmediate) ||
1474 (this && this.clearImmediate);
1475
1476 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
1477
1478/***/ }),
1479/* 5 */
1480/***/ (function(module, exports, __webpack_require__) {
1481
1482 /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
1483 "use strict";
1484
1485 if (global.setImmediate) {
1486 return;
1487 }
1488
1489 var nextHandle = 1; // Spec says greater than zero
1490 var tasksByHandle = {};
1491 var currentlyRunningATask = false;
1492 var doc = global.document;
1493 var registerImmediate;
1494
1495 function setImmediate(callback) {
1496 // Callback can either be a function or a string
1497 if (typeof callback !== "function") {
1498 callback = new Function("" + callback);
1499 }
1500 // Copy function arguments
1501 var args = new Array(arguments.length - 1);
1502 for (var i = 0; i < args.length; i++) {
1503 args[i] = arguments[i + 1];
1504 }
1505 // Store and register the task
1506 var task = { callback: callback, args: args };
1507 tasksByHandle[nextHandle] = task;
1508 registerImmediate(nextHandle);
1509 return nextHandle++;
1510 }
1511
1512 function clearImmediate(handle) {
1513 delete tasksByHandle[handle];
1514 }
1515
1516 function run(task) {
1517 var callback = task.callback;
1518 var args = task.args;
1519 switch (args.length) {
1520 case 0:
1521 callback();
1522 break;
1523 case 1:
1524 callback(args[0]);
1525 break;
1526 case 2:
1527 callback(args[0], args[1]);
1528 break;
1529 case 3:
1530 callback(args[0], args[1], args[2]);
1531 break;
1532 default:
1533 callback.apply(undefined, args);
1534 break;
1535 }
1536 }
1537
1538 function runIfPresent(handle) {
1539 // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
1540 // So if we're currently running a task, we'll need to delay this invocation.
1541 if (currentlyRunningATask) {
1542 // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
1543 // "too much recursion" error.
1544 setTimeout(runIfPresent, 0, handle);
1545 } else {
1546 var task = tasksByHandle[handle];
1547 if (task) {
1548 currentlyRunningATask = true;
1549 try {
1550 run(task);
1551 } finally {
1552 clearImmediate(handle);
1553 currentlyRunningATask = false;
1554 }
1555 }
1556 }
1557 }
1558
1559 function installNextTickImplementation() {
1560 registerImmediate = function(handle) {
1561 process.nextTick(function () { runIfPresent(handle); });
1562 };
1563 }
1564
1565 function canUsePostMessage() {
1566 // The test against `importScripts` prevents this implementation from being installed inside a web worker,
1567 // where `global.postMessage` means something completely different and can't be used for this purpose.
1568 if (global.postMessage && !global.importScripts) {
1569 var postMessageIsAsynchronous = true;
1570 var oldOnMessage = global.onmessage;
1571 global.onmessage = function() {
1572 postMessageIsAsynchronous = false;
1573 };
1574 global.postMessage("", "*");
1575 global.onmessage = oldOnMessage;
1576 return postMessageIsAsynchronous;
1577 }
1578 }
1579
1580 function installPostMessageImplementation() {
1581 // Installs an event handler on `global` for the `message` event: see
1582 // * https://developer.mozilla.org/en/DOM/window.postMessage
1583 // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
1584
1585 var messagePrefix = "setImmediate$" + Math.random() + "$";
1586 var onGlobalMessage = function(event) {
1587 if (event.source === global &&
1588 typeof event.data === "string" &&
1589 event.data.indexOf(messagePrefix) === 0) {
1590 runIfPresent(+event.data.slice(messagePrefix.length));
1591 }
1592 };
1593
1594 if (global.addEventListener) {
1595 global.addEventListener("message", onGlobalMessage, false);
1596 } else {
1597 global.attachEvent("onmessage", onGlobalMessage);
1598 }
1599
1600 registerImmediate = function(handle) {
1601 global.postMessage(messagePrefix + handle, "*");
1602 };
1603 }
1604
1605 function installMessageChannelImplementation() {
1606 var channel = new MessageChannel();
1607 channel.port1.onmessage = function(event) {
1608 var handle = event.data;
1609 runIfPresent(handle);
1610 };
1611
1612 registerImmediate = function(handle) {
1613 channel.port2.postMessage(handle);
1614 };
1615 }
1616
1617 function installReadyStateChangeImplementation() {
1618 var html = doc.documentElement;
1619 registerImmediate = function(handle) {
1620 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
1621 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
1622 var script = doc.createElement("script");
1623 script.onreadystatechange = function () {
1624 runIfPresent(handle);
1625 script.onreadystatechange = null;
1626 html.removeChild(script);
1627 script = null;
1628 };
1629 html.appendChild(script);
1630 };
1631 }
1632
1633 function installSetTimeoutImplementation() {
1634 registerImmediate = function(handle) {
1635 setTimeout(runIfPresent, 0, handle);
1636 };
1637 }
1638
1639 // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
1640 var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
1641 attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
1642
1643 // Don't get fooled by e.g. browserify environments.
1644 if ({}.toString.call(global.process) === "[object process]") {
1645 // For Node.js before 0.9
1646 installNextTickImplementation();
1647
1648 } else if (canUsePostMessage()) {
1649 // For non-IE10 modern browsers
1650 installPostMessageImplementation();
1651
1652 } else if (global.MessageChannel) {
1653 // For web workers, where supported
1654 installMessageChannelImplementation();
1655
1656 } else if (doc && "onreadystatechange" in doc.createElement("script")) {
1657 // For IE 6–8
1658 installReadyStateChangeImplementation();
1659
1660 } else {
1661 // For older browsers
1662 installSetTimeoutImplementation();
1663 }
1664
1665 attachTo.setImmediate = setImmediate;
1666 attachTo.clearImmediate = clearImmediate;
1667 }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
1668
1669 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
1670
1671/***/ }),
1672/* 6 */
1673/***/ (function(module, exports) {
1674
1675 /* (ignored) */
1676
1677/***/ }),
1678/* 7 */
1679/***/ (function(module, exports) {
1680
1681 module.exports = {"acm":{"name":"ACM","cors":true},"apigateway":{"name":"APIGateway","cors":true},"applicationautoscaling":{"prefix":"application-autoscaling","name":"ApplicationAutoScaling","cors":true},"appstream":{"name":"AppStream"},"autoscaling":{"name":"AutoScaling","cors":true},"batch":{"name":"Batch"},"budgets":{"name":"Budgets"},"clouddirectory":{"name":"CloudDirectory","versions":["2016-05-10*"]},"cloudformation":{"name":"CloudFormation","cors":true},"cloudfront":{"name":"CloudFront","versions":["2013-05-12*","2013-11-11*","2014-05-31*","2014-10-21*","2014-11-06*","2015-04-17*","2015-07-27*","2015-09-17*","2016-01-13*","2016-01-28*","2016-08-01*","2016-08-20*","2016-09-07*","2016-09-29*","2016-11-25*","2017-03-25*","2017-10-30*","2018-06-18*","2018-11-05*"],"cors":true},"cloudhsm":{"name":"CloudHSM","cors":true},"cloudsearch":{"name":"CloudSearch"},"cloudsearchdomain":{"name":"CloudSearchDomain"},"cloudtrail":{"name":"CloudTrail","cors":true},"cloudwatch":{"prefix":"monitoring","name":"CloudWatch","cors":true},"cloudwatchevents":{"prefix":"events","name":"CloudWatchEvents","versions":["2014-02-03*"],"cors":true},"cloudwatchlogs":{"prefix":"logs","name":"CloudWatchLogs","cors":true},"codebuild":{"name":"CodeBuild","cors":true},"codecommit":{"name":"CodeCommit","cors":true},"codedeploy":{"name":"CodeDeploy","cors":true},"codepipeline":{"name":"CodePipeline","cors":true},"cognitoidentity":{"prefix":"cognito-identity","name":"CognitoIdentity","cors":true},"cognitoidentityserviceprovider":{"prefix":"cognito-idp","name":"CognitoIdentityServiceProvider","cors":true},"cognitosync":{"prefix":"cognito-sync","name":"CognitoSync","cors":true},"configservice":{"prefix":"config","name":"ConfigService","cors":true},"cur":{"name":"CUR","cors":true},"datapipeline":{"name":"DataPipeline"},"devicefarm":{"name":"DeviceFarm","cors":true},"directconnect":{"name":"DirectConnect","cors":true},"directoryservice":{"prefix":"ds","name":"DirectoryService"},"discovery":{"name":"Discovery"},"dms":{"name":"DMS"},"dynamodb":{"name":"DynamoDB","cors":true},"dynamodbstreams":{"prefix":"streams.dynamodb","name":"DynamoDBStreams","cors":true},"ec2":{"name":"EC2","versions":["2013-06-15*","2013-10-15*","2014-02-01*","2014-05-01*","2014-06-15*","2014-09-01*","2014-10-01*","2015-03-01*","2015-04-15*","2015-10-01*","2016-04-01*","2016-09-15*"],"cors":true},"ecr":{"name":"ECR","cors":true},"ecs":{"name":"ECS","cors":true},"efs":{"prefix":"elasticfilesystem","name":"EFS","cors":true},"elasticache":{"name":"ElastiCache","versions":["2012-11-15*","2014-03-24*","2014-07-15*","2014-09-30*"],"cors":true},"elasticbeanstalk":{"name":"ElasticBeanstalk","cors":true},"elb":{"prefix":"elasticloadbalancing","name":"ELB","cors":true},"elbv2":{"prefix":"elasticloadbalancingv2","name":"ELBv2","cors":true},"emr":{"prefix":"elasticmapreduce","name":"EMR","cors":true},"es":{"name":"ES"},"elastictranscoder":{"name":"ElasticTranscoder","cors":true},"firehose":{"name":"Firehose","cors":true},"gamelift":{"name":"GameLift","cors":true},"glacier":{"name":"Glacier"},"health":{"name":"Health"},"iam":{"name":"IAM","cors":true},"importexport":{"name":"ImportExport"},"inspector":{"name":"Inspector","versions":["2015-08-18*"],"cors":true},"iot":{"name":"Iot","cors":true},"iotdata":{"prefix":"iot-data","name":"IotData","cors":true},"kinesis":{"name":"Kinesis","cors":true},"kinesisanalytics":{"name":"KinesisAnalytics"},"kms":{"name":"KMS","cors":true},"lambda":{"name":"Lambda","cors":true},"lexruntime":{"prefix":"runtime.lex","name":"LexRuntime","cors":true},"lightsail":{"name":"Lightsail"},"machinelearning":{"name":"MachineLearning","cors":true},"marketplacecommerceanalytics":{"name":"MarketplaceCommerceAnalytics","cors":true},"marketplacemetering":{"prefix":"meteringmarketplace","name":"MarketplaceMetering"},"mturk":{"prefix":"mturk-requester","name":"MTurk","cors":true},"mobileanalytics":{"name":"MobileAnalytics","cors":true},"opsworks":{"name":"OpsWorks","cors":true},"opsworkscm":{"name":"OpsWorksCM"},"organizations":{"name":"Organizations"},"pinpoint":{"name":"Pinpoint"},"polly":{"name":"Polly","cors":true},"rds":{"name":"RDS","versions":["2014-09-01*"],"cors":true},"redshift":{"name":"Redshift","cors":true},"rekognition":{"name":"Rekognition","cors":true},"resourcegroupstaggingapi":{"name":"ResourceGroupsTaggingAPI"},"route53":{"name":"Route53","cors":true},"route53domains":{"name":"Route53Domains","cors":true},"s3":{"name":"S3","dualstackAvailable":true,"cors":true},"s3control":{"name":"S3Control","dualstackAvailable":true,"xmlNoDefaultLists":true},"servicecatalog":{"name":"ServiceCatalog","cors":true},"ses":{"prefix":"email","name":"SES","cors":true},"shield":{"name":"Shield"},"simpledb":{"prefix":"sdb","name":"SimpleDB"},"sms":{"name":"SMS"},"snowball":{"name":"Snowball"},"sns":{"name":"SNS","cors":true},"sqs":{"name":"SQS","cors":true},"ssm":{"name":"SSM","cors":true},"storagegateway":{"name":"StorageGateway","cors":true},"stepfunctions":{"prefix":"states","name":"StepFunctions"},"sts":{"name":"STS","cors":true},"support":{"name":"Support"},"swf":{"name":"SWF"},"xray":{"name":"XRay","cors":true},"waf":{"name":"WAF","cors":true},"wafregional":{"prefix":"waf-regional","name":"WAFRegional"},"workdocs":{"name":"WorkDocs","cors":true},"workspaces":{"name":"WorkSpaces"},"codestar":{"name":"CodeStar"},"lexmodelbuildingservice":{"prefix":"lex-models","name":"LexModelBuildingService","cors":true},"marketplaceentitlementservice":{"prefix":"entitlement.marketplace","name":"MarketplaceEntitlementService"},"athena":{"name":"Athena"},"greengrass":{"name":"Greengrass"},"dax":{"name":"DAX"},"migrationhub":{"prefix":"AWSMigrationHub","name":"MigrationHub"},"cloudhsmv2":{"name":"CloudHSMV2"},"glue":{"name":"Glue"},"mobile":{"name":"Mobile"},"pricing":{"name":"Pricing","cors":true},"costexplorer":{"prefix":"ce","name":"CostExplorer","cors":true},"mediaconvert":{"name":"MediaConvert"},"medialive":{"name":"MediaLive"},"mediapackage":{"name":"MediaPackage"},"mediastore":{"name":"MediaStore"},"mediastoredata":{"prefix":"mediastore-data","name":"MediaStoreData","cors":true},"appsync":{"name":"AppSync"},"guardduty":{"name":"GuardDuty"},"mq":{"name":"MQ"},"comprehend":{"name":"Comprehend","cors":true},"iotjobsdataplane":{"prefix":"iot-jobs-data","name":"IoTJobsDataPlane"},"kinesisvideoarchivedmedia":{"prefix":"kinesis-video-archived-media","name":"KinesisVideoArchivedMedia","cors":true},"kinesisvideomedia":{"prefix":"kinesis-video-media","name":"KinesisVideoMedia","cors":true},"kinesisvideo":{"name":"KinesisVideo","cors":true},"sagemakerruntime":{"prefix":"runtime.sagemaker","name":"SageMakerRuntime"},"sagemaker":{"name":"SageMaker"},"translate":{"name":"Translate","cors":true},"resourcegroups":{"prefix":"resource-groups","name":"ResourceGroups","cors":true},"alexaforbusiness":{"name":"AlexaForBusiness"},"cloud9":{"name":"Cloud9"},"serverlessapplicationrepository":{"prefix":"serverlessrepo","name":"ServerlessApplicationRepository"},"servicediscovery":{"name":"ServiceDiscovery"},"workmail":{"name":"WorkMail"},"autoscalingplans":{"prefix":"autoscaling-plans","name":"AutoScalingPlans"},"transcribeservice":{"prefix":"transcribe","name":"TranscribeService"},"connect":{"name":"Connect","cors":true},"acmpca":{"prefix":"acm-pca","name":"ACMPCA"},"fms":{"name":"FMS"},"secretsmanager":{"name":"SecretsManager","cors":true},"iotanalytics":{"name":"IoTAnalytics","cors":true},"iot1clickdevicesservice":{"prefix":"iot1click-devices","name":"IoT1ClickDevicesService"},"iot1clickprojects":{"prefix":"iot1click-projects","name":"IoT1ClickProjects"},"pi":{"name":"PI"},"neptune":{"name":"Neptune"},"mediatailor":{"name":"MediaTailor"},"eks":{"name":"EKS"},"macie":{"name":"Macie"},"dlm":{"name":"DLM"},"signer":{"name":"Signer"},"chime":{"name":"Chime"},"pinpointemail":{"prefix":"pinpoint-email","name":"PinpointEmail"},"ram":{"name":"RAM"},"route53resolver":{"name":"Route53Resolver"},"pinpointsmsvoice":{"prefix":"sms-voice","name":"PinpointSMSVoice"},"quicksight":{"name":"QuickSight"},"rdsdataservice":{"prefix":"rds-data","name":"RDSDataService"},"amplify":{"name":"Amplify"},"datasync":{"name":"DataSync"},"robomaker":{"name":"RoboMaker"},"transfer":{"name":"Transfer"},"globalaccelerator":{"name":"GlobalAccelerator"},"comprehendmedical":{"name":"ComprehendMedical","cors":true},"kinesisanalyticsv2":{"name":"KinesisAnalyticsV2"},"mediaconnect":{"name":"MediaConnect"},"fsx":{"name":"FSx"},"securityhub":{"name":"SecurityHub"},"appmesh":{"name":"AppMesh","versions":["2018-10-01*"]},"licensemanager":{"prefix":"license-manager","name":"LicenseManager"},"kafka":{"name":"Kafka"},"apigatewaymanagementapi":{"name":"ApiGatewayManagementApi"},"apigatewayv2":{"name":"ApiGatewayV2"},"docdb":{"name":"DocDB"},"backup":{"name":"Backup"},"worklink":{"name":"WorkLink"},"textract":{"name":"Textract"},"managedblockchain":{"name":"ManagedBlockchain"},"mediapackagevod":{"prefix":"mediapackage-vod","name":"MediaPackageVod"},"groundstation":{"name":"GroundStation"},"iotthingsgraph":{"name":"IoTThingsGraph"},"iotevents":{"name":"IoTEvents"},"ioteventsdata":{"prefix":"iotevents-data","name":"IoTEventsData"},"personalize":{"name":"Personalize","cors":true},"personalizeevents":{"prefix":"personalize-events","name":"PersonalizeEvents","cors":true},"personalizeruntime":{"prefix":"personalize-runtime","name":"PersonalizeRuntime","cors":true},"applicationinsights":{"prefix":"application-insights","name":"ApplicationInsights"},"servicequotas":{"prefix":"service-quotas","name":"ServiceQuotas"},"ec2instanceconnect":{"prefix":"ec2-instance-connect","name":"EC2InstanceConnect"},"eventbridge":{"name":"EventBridge"},"lakeformation":{"name":"LakeFormation"},"forecastservice":{"prefix":"forecast","name":"ForecastService","cors":true},"forecastqueryservice":{"prefix":"forecastquery","name":"ForecastQueryService","cors":true},"qldb":{"name":"QLDB"},"qldbsession":{"prefix":"qldb-session","name":"QLDBSession"},"workmailmessageflow":{"name":"WorkMailMessageFlow"},"codestarnotifications":{"prefix":"codestar-notifications","name":"CodeStarNotifications"},"savingsplans":{"name":"SavingsPlans"},"sso":{"name":"SSO"},"ssooidc":{"prefix":"sso-oidc","name":"SSOOIDC"},"marketplacecatalog":{"prefix":"marketplace-catalog","name":"MarketplaceCatalog"},"dataexchange":{"name":"DataExchange"},"sesv2":{"name":"SESV2"},"migrationhubconfig":{"prefix":"migrationhub-config","name":"MigrationHubConfig"},"connectparticipant":{"name":"ConnectParticipant"},"appconfig":{"name":"AppConfig"},"iotsecuretunneling":{"name":"IoTSecureTunneling"},"wafv2":{"name":"WAFV2"},"elasticinference":{"prefix":"elastic-inference","name":"ElasticInference"},"imagebuilder":{"name":"Imagebuilder"},"schemas":{"name":"Schemas"},"accessanalyzer":{"name":"AccessAnalyzer"},"codegurureviewer":{"prefix":"codeguru-reviewer","name":"CodeGuruReviewer"},"codeguruprofiler":{"name":"CodeGuruProfiler"},"computeoptimizer":{"prefix":"compute-optimizer","name":"ComputeOptimizer"},"frauddetector":{"name":"FraudDetector"},"kendra":{"name":"Kendra"},"networkmanager":{"name":"NetworkManager"},"outposts":{"name":"Outposts"},"augmentedairuntime":{"prefix":"sagemaker-a2i-runtime","name":"AugmentedAIRuntime"},"ebs":{"name":"EBS"},"kinesisvideosignalingchannels":{"prefix":"kinesis-video-signaling","name":"KinesisVideoSignalingChannels","cors":true},"detective":{"name":"Detective"},"codestarconnections":{"prefix":"codestar-connections","name":"CodeStarconnections"}}
1682
1683/***/ }),
1684/* 8 */
1685/***/ (function(module, exports, __webpack_require__) {
1686
1687 var v1 = __webpack_require__(9);
1688 var v4 = __webpack_require__(12);
1689
1690 var uuid = v4;
1691 uuid.v1 = v1;
1692 uuid.v4 = v4;
1693
1694 module.exports = uuid;
1695
1696
1697/***/ }),
1698/* 9 */
1699/***/ (function(module, exports, __webpack_require__) {
1700
1701 var rng = __webpack_require__(10);
1702 var bytesToUuid = __webpack_require__(11);
1703
1704 // **`v1()` - Generate time-based UUID**
1705 //
1706 // Inspired by https://github.com/LiosK/UUID.js
1707 // and http://docs.python.org/library/uuid.html
1708
1709 var _nodeId;
1710 var _clockseq;
1711
1712 // Previous uuid creation time
1713 var _lastMSecs = 0;
1714 var _lastNSecs = 0;
1715
1716 // See https://github.com/broofa/node-uuid for API details
1717 function v1(options, buf, offset) {
1718 var i = buf && offset || 0;
1719 var b = buf || [];
1720
1721 options = options || {};
1722 var node = options.node || _nodeId;
1723 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
1724
1725 // node and clockseq need to be initialized to random values if they're not
1726 // specified. We do this lazily to minimize issues related to insufficient
1727 // system entropy. See #189
1728 if (node == null || clockseq == null) {
1729 var seedBytes = rng();
1730 if (node == null) {
1731 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
1732 node = _nodeId = [
1733 seedBytes[0] | 0x01,
1734 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
1735 ];
1736 }
1737 if (clockseq == null) {
1738 // Per 4.2.2, randomize (14 bit) clockseq
1739 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
1740 }
1741 }
1742
1743 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
1744 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
1745 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
1746 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
1747 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
1748
1749 // Per 4.2.1.2, use count of uuid's generated during the current clock
1750 // cycle to simulate higher resolution clock
1751 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
1752
1753 // Time since last uuid creation (in msecs)
1754 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
1755
1756 // Per 4.2.1.2, Bump clockseq on clock regression
1757 if (dt < 0 && options.clockseq === undefined) {
1758 clockseq = clockseq + 1 & 0x3fff;
1759 }
1760
1761 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
1762 // time interval
1763 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
1764 nsecs = 0;
1765 }
1766
1767 // Per 4.2.1.2 Throw error if too many uuids are requested
1768 if (nsecs >= 10000) {
1769 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
1770 }
1771
1772 _lastMSecs = msecs;
1773 _lastNSecs = nsecs;
1774 _clockseq = clockseq;
1775
1776 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
1777 msecs += 12219292800000;
1778
1779 // `time_low`
1780 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
1781 b[i++] = tl >>> 24 & 0xff;
1782 b[i++] = tl >>> 16 & 0xff;
1783 b[i++] = tl >>> 8 & 0xff;
1784 b[i++] = tl & 0xff;
1785
1786 // `time_mid`
1787 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
1788 b[i++] = tmh >>> 8 & 0xff;
1789 b[i++] = tmh & 0xff;
1790
1791 // `time_high_and_version`
1792 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
1793 b[i++] = tmh >>> 16 & 0xff;
1794
1795 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
1796 b[i++] = clockseq >>> 8 | 0x80;
1797
1798 // `clock_seq_low`
1799 b[i++] = clockseq & 0xff;
1800
1801 // `node`
1802 for (var n = 0; n < 6; ++n) {
1803 b[i + n] = node[n];
1804 }
1805
1806 return buf ? buf : bytesToUuid(b);
1807 }
1808
1809 module.exports = v1;
1810
1811
1812/***/ }),
1813/* 10 */
1814/***/ (function(module, exports) {
1815
1816 // Unique ID creation requires a high quality random # generator. In the
1817 // browser this is a little complicated due to unknown quality of Math.random()
1818 // and inconsistent support for the `crypto` API. We do the best we can via
1819 // feature-detection
1820
1821 // getRandomValues needs to be invoked in a context where "this" is a Crypto
1822 // implementation. Also, find the complete implementation of crypto on IE11.
1823 var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
1824 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
1825
1826 if (getRandomValues) {
1827 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
1828 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
1829
1830 module.exports = function whatwgRNG() {
1831 getRandomValues(rnds8);
1832 return rnds8;
1833 };
1834 } else {
1835 // Math.random()-based (RNG)
1836 //
1837 // If all else fails, use Math.random(). It's fast, but is of unspecified
1838 // quality.
1839 var rnds = new Array(16);
1840
1841 module.exports = function mathRNG() {
1842 for (var i = 0, r; i < 16; i++) {
1843 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
1844 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
1845 }
1846
1847 return rnds;
1848 };
1849 }
1850
1851
1852/***/ }),
1853/* 11 */
1854/***/ (function(module, exports) {
1855
1856 /**
1857 * Convert array of 16 byte values to UUID string format of the form:
1858 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1859 */
1860 var byteToHex = [];
1861 for (var i = 0; i < 256; ++i) {
1862 byteToHex[i] = (i + 0x100).toString(16).substr(1);
1863 }
1864
1865 function bytesToUuid(buf, offset) {
1866 var i = offset || 0;
1867 var bth = byteToHex;
1868 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
1869 return ([bth[buf[i++]], bth[buf[i++]],
1870 bth[buf[i++]], bth[buf[i++]], '-',
1871 bth[buf[i++]], bth[buf[i++]], '-',
1872 bth[buf[i++]], bth[buf[i++]], '-',
1873 bth[buf[i++]], bth[buf[i++]], '-',
1874 bth[buf[i++]], bth[buf[i++]],
1875 bth[buf[i++]], bth[buf[i++]],
1876 bth[buf[i++]], bth[buf[i++]]]).join('');
1877 }
1878
1879 module.exports = bytesToUuid;
1880
1881
1882/***/ }),
1883/* 12 */
1884/***/ (function(module, exports, __webpack_require__) {
1885
1886 var rng = __webpack_require__(10);
1887 var bytesToUuid = __webpack_require__(11);
1888
1889 function v4(options, buf, offset) {
1890 var i = buf && offset || 0;
1891
1892 if (typeof(options) == 'string') {
1893 buf = options === 'binary' ? new Array(16) : null;
1894 options = null;
1895 }
1896 options = options || {};
1897
1898 var rnds = options.random || (options.rng || rng)();
1899
1900 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1901 rnds[6] = (rnds[6] & 0x0f) | 0x40;
1902 rnds[8] = (rnds[8] & 0x3f) | 0x80;
1903
1904 // Copy bytes to buffer, if provided
1905 if (buf) {
1906 for (var ii = 0; ii < 16; ++ii) {
1907 buf[i + ii] = rnds[ii];
1908 }
1909 }
1910
1911 return buf || bytesToUuid(rnds);
1912 }
1913
1914 module.exports = v4;
1915
1916
1917/***/ }),
1918/* 13 */
1919/***/ (function(module, exports, __webpack_require__) {
1920
1921 var util = __webpack_require__(2);
1922 var JsonBuilder = __webpack_require__(14);
1923 var JsonParser = __webpack_require__(15);
1924 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
1925
1926 function buildRequest(req) {
1927 var httpRequest = req.httpRequest;
1928 var api = req.service.api;
1929 var target = api.targetPrefix + '.' + api.operations[req.operation].name;
1930 var version = api.jsonVersion || '1.0';
1931 var input = api.operations[req.operation].input;
1932 var builder = new JsonBuilder();
1933
1934 if (version === 1) version = '1.0';
1935 httpRequest.body = builder.build(req.params || {}, input);
1936 httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version;
1937 httpRequest.headers['X-Amz-Target'] = target;
1938
1939 populateHostPrefix(req);
1940 }
1941
1942 function extractError(resp) {
1943 var error = {};
1944 var httpResponse = resp.httpResponse;
1945
1946 error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError';
1947 if (typeof error.code === 'string') {
1948 error.code = error.code.split(':')[0];
1949 }
1950
1951 if (httpResponse.body.length > 0) {
1952 try {
1953 var e = JSON.parse(httpResponse.body.toString());
1954 if (e.__type || e.code) {
1955 error.code = (e.__type || e.code).split('#').pop();
1956 }
1957 if (error.code === 'RequestEntityTooLarge') {
1958 error.message = 'Request body must be less than 1 MB';
1959 } else {
1960 error.message = (e.message || e.Message || null);
1961 }
1962 } catch (e) {
1963 error.statusCode = httpResponse.statusCode;
1964 error.message = httpResponse.statusMessage;
1965 }
1966 } else {
1967 error.statusCode = httpResponse.statusCode;
1968 error.message = httpResponse.statusCode.toString();
1969 }
1970
1971 resp.error = util.error(new Error(), error);
1972 }
1973
1974 function extractData(resp) {
1975 var body = resp.httpResponse.body.toString() || '{}';
1976 if (resp.request.service.config.convertResponseTypes === false) {
1977 resp.data = JSON.parse(body);
1978 } else {
1979 var operation = resp.request.service.api.operations[resp.request.operation];
1980 var shape = operation.output || {};
1981 var parser = new JsonParser();
1982 resp.data = parser.parse(body, shape);
1983 }
1984 }
1985
1986 /**
1987 * @api private
1988 */
1989 module.exports = {
1990 buildRequest: buildRequest,
1991 extractError: extractError,
1992 extractData: extractData
1993 };
1994
1995
1996/***/ }),
1997/* 14 */
1998/***/ (function(module, exports, __webpack_require__) {
1999
2000 var util = __webpack_require__(2);
2001
2002 function JsonBuilder() { }
2003
2004 JsonBuilder.prototype.build = function(value, shape) {
2005 return JSON.stringify(translate(value, shape));
2006 };
2007
2008 function translate(value, shape) {
2009 if (!shape || value === undefined || value === null) return undefined;
2010
2011 switch (shape.type) {
2012 case 'structure': return translateStructure(value, shape);
2013 case 'map': return translateMap(value, shape);
2014 case 'list': return translateList(value, shape);
2015 default: return translateScalar(value, shape);
2016 }
2017 }
2018
2019 function translateStructure(structure, shape) {
2020 var struct = {};
2021 util.each(structure, function(name, value) {
2022 var memberShape = shape.members[name];
2023 if (memberShape) {
2024 if (memberShape.location !== 'body') return;
2025 var locationName = memberShape.isLocationName ? memberShape.name : name;
2026 var result = translate(value, memberShape);
2027 if (result !== undefined) struct[locationName] = result;
2028 }
2029 });
2030 return struct;
2031 }
2032
2033 function translateList(list, shape) {
2034 var out = [];
2035 util.arrayEach(list, function(value) {
2036 var result = translate(value, shape.member);
2037 if (result !== undefined) out.push(result);
2038 });
2039 return out;
2040 }
2041
2042 function translateMap(map, shape) {
2043 var out = {};
2044 util.each(map, function(key, value) {
2045 var result = translate(value, shape.value);
2046 if (result !== undefined) out[key] = result;
2047 });
2048 return out;
2049 }
2050
2051 function translateScalar(value, shape) {
2052 return shape.toWireFormat(value);
2053 }
2054
2055 /**
2056 * @api private
2057 */
2058 module.exports = JsonBuilder;
2059
2060
2061/***/ }),
2062/* 15 */
2063/***/ (function(module, exports, __webpack_require__) {
2064
2065 var util = __webpack_require__(2);
2066
2067 function JsonParser() { }
2068
2069 JsonParser.prototype.parse = function(value, shape) {
2070 return translate(JSON.parse(value), shape);
2071 };
2072
2073 function translate(value, shape) {
2074 if (!shape || value === undefined) return undefined;
2075
2076 switch (shape.type) {
2077 case 'structure': return translateStructure(value, shape);
2078 case 'map': return translateMap(value, shape);
2079 case 'list': return translateList(value, shape);
2080 default: return translateScalar(value, shape);
2081 }
2082 }
2083
2084 function translateStructure(structure, shape) {
2085 if (structure == null) return undefined;
2086
2087 var struct = {};
2088 var shapeMembers = shape.members;
2089 util.each(shapeMembers, function(name, memberShape) {
2090 var locationName = memberShape.isLocationName ? memberShape.name : name;
2091 if (Object.prototype.hasOwnProperty.call(structure, locationName)) {
2092 var value = structure[locationName];
2093 var result = translate(value, memberShape);
2094 if (result !== undefined) struct[name] = result;
2095 }
2096 });
2097 return struct;
2098 }
2099
2100 function translateList(list, shape) {
2101 if (list == null) return undefined;
2102
2103 var out = [];
2104 util.arrayEach(list, function(value) {
2105 var result = translate(value, shape.member);
2106 if (result === undefined) out.push(null);
2107 else out.push(result);
2108 });
2109 return out;
2110 }
2111
2112 function translateMap(map, shape) {
2113 if (map == null) return undefined;
2114
2115 var out = {};
2116 util.each(map, function(key, value) {
2117 var result = translate(value, shape.value);
2118 if (result === undefined) out[key] = null;
2119 else out[key] = result;
2120 });
2121 return out;
2122 }
2123
2124 function translateScalar(value, shape) {
2125 return shape.toType(value);
2126 }
2127
2128 /**
2129 * @api private
2130 */
2131 module.exports = JsonParser;
2132
2133
2134/***/ }),
2135/* 16 */
2136/***/ (function(module, exports, __webpack_require__) {
2137
2138 var util = __webpack_require__(2);
2139 var AWS = __webpack_require__(1);
2140
2141 /**
2142 * Prepend prefix defined by API model to endpoint that's already
2143 * constructed. This feature does not apply to operations using
2144 * endpoint discovery and can be disabled.
2145 * @api private
2146 */
2147 function populateHostPrefix(request) {
2148 var enabled = request.service.config.hostPrefixEnabled;
2149 if (!enabled) return request;
2150 var operationModel = request.service.api.operations[request.operation];
2151 //don't marshal host prefix when operation has endpoint discovery traits
2152 if (hasEndpointDiscover(request)) return request;
2153 if (operationModel.endpoint && operationModel.endpoint.hostPrefix) {
2154 var hostPrefixNotation = operationModel.endpoint.hostPrefix;
2155 var hostPrefix = expandHostPrefix(hostPrefixNotation, request.params, operationModel.input);
2156 prependEndpointPrefix(request.httpRequest.endpoint, hostPrefix);
2157 validateHostname(request.httpRequest.endpoint.hostname);
2158 }
2159 return request;
2160 }
2161
2162 /**
2163 * @api private
2164 */
2165 function hasEndpointDiscover(request) {
2166 var api = request.service.api;
2167 var operationModel = api.operations[request.operation];
2168 var isEndpointOperation = api.endpointOperation && (api.endpointOperation === util.string.lowerFirst(operationModel.name));
2169 return (operationModel.endpointDiscoveryRequired !== 'NULL' || isEndpointOperation === true);
2170 }
2171
2172 /**
2173 * @api private
2174 */
2175 function expandHostPrefix(hostPrefixNotation, params, shape) {
2176 util.each(shape.members, function(name, member) {
2177 if (member.hostLabel === true) {
2178 if (typeof params[name] !== 'string' || params[name] === '') {
2179 throw util.error(new Error(), {
2180 message: 'Parameter ' + name + ' should be a non-empty string.',
2181 code: 'InvalidParameter'
2182 });
2183 }
2184 var regex = new RegExp('\\{' + name + '\\}', 'g');
2185 hostPrefixNotation = hostPrefixNotation.replace(regex, params[name]);
2186 }
2187 });
2188 return hostPrefixNotation;
2189 }
2190
2191 /**
2192 * @api private
2193 */
2194 function prependEndpointPrefix(endpoint, prefix) {
2195 if (endpoint.host) {
2196 endpoint.host = prefix + endpoint.host;
2197 }
2198 if (endpoint.hostname) {
2199 endpoint.hostname = prefix + endpoint.hostname;
2200 }
2201 }
2202
2203 /**
2204 * @api private
2205 */
2206 function validateHostname(hostname) {
2207 var labels = hostname.split('.');
2208 //Reference: https://tools.ietf.org/html/rfc1123#section-2
2209 var hostPattern = /^[a-zA-Z0-9]{1}$|^[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]$/;
2210 util.arrayEach(labels, function(label) {
2211 if (!label.length || label.length < 1 || label.length > 63) {
2212 throw util.error(new Error(), {
2213 code: 'ValidationError',
2214 message: 'Hostname label length should be between 1 to 63 characters, inclusive.'
2215 });
2216 }
2217 if (!hostPattern.test(label)) {
2218 throw AWS.util.error(new Error(),
2219 {code: 'ValidationError', message: label + ' is not hostname compatible.'});
2220 }
2221 });
2222 }
2223
2224 module.exports = {
2225 populateHostPrefix: populateHostPrefix
2226 };
2227
2228
2229/***/ }),
2230/* 17 */
2231/***/ (function(module, exports, __webpack_require__) {
2232
2233 var AWS = __webpack_require__(1);
2234 var util = __webpack_require__(2);
2235 var QueryParamSerializer = __webpack_require__(18);
2236 var Shape = __webpack_require__(19);
2237 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2238
2239 function buildRequest(req) {
2240 var operation = req.service.api.operations[req.operation];
2241 var httpRequest = req.httpRequest;
2242 httpRequest.headers['Content-Type'] =
2243 'application/x-www-form-urlencoded; charset=utf-8';
2244 httpRequest.params = {
2245 Version: req.service.api.apiVersion,
2246 Action: operation.name
2247 };
2248
2249 // convert the request parameters into a list of query params,
2250 // e.g. Deeply.NestedParam.0.Name=value
2251 var builder = new QueryParamSerializer();
2252 builder.serialize(req.params, operation.input, function(name, value) {
2253 httpRequest.params[name] = value;
2254 });
2255 httpRequest.body = util.queryParamsToString(httpRequest.params);
2256
2257 populateHostPrefix(req);
2258 }
2259
2260 function extractError(resp) {
2261 var data, body = resp.httpResponse.body.toString();
2262 if (body.match('<UnknownOperationException')) {
2263 data = {
2264 Code: 'UnknownOperation',
2265 Message: 'Unknown operation ' + resp.request.operation
2266 };
2267 } else {
2268 try {
2269 data = new AWS.XML.Parser().parse(body);
2270 } catch (e) {
2271 data = {
2272 Code: resp.httpResponse.statusCode,
2273 Message: resp.httpResponse.statusMessage
2274 };
2275 }
2276 }
2277
2278 if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
2279 if (data.Errors) data = data.Errors;
2280 if (data.Error) data = data.Error;
2281 if (data.Code) {
2282 resp.error = util.error(new Error(), {
2283 code: data.Code,
2284 message: data.Message
2285 });
2286 } else {
2287 resp.error = util.error(new Error(), {
2288 code: resp.httpResponse.statusCode,
2289 message: null
2290 });
2291 }
2292 }
2293
2294 function extractData(resp) {
2295 var req = resp.request;
2296 var operation = req.service.api.operations[req.operation];
2297 var shape = operation.output || {};
2298 var origRules = shape;
2299
2300 if (origRules.resultWrapper) {
2301 var tmp = Shape.create({type: 'structure'});
2302 tmp.members[origRules.resultWrapper] = shape;
2303 tmp.memberNames = [origRules.resultWrapper];
2304 util.property(shape, 'name', shape.resultWrapper);
2305 shape = tmp;
2306 }
2307
2308 var parser = new AWS.XML.Parser();
2309
2310 // TODO: Refactor XML Parser to parse RequestId from response.
2311 if (shape && shape.members && !shape.members._XAMZRequestId) {
2312 var requestIdShape = Shape.create(
2313 { type: 'string' },
2314 { api: { protocol: 'query' } },
2315 'requestId'
2316 );
2317 shape.members._XAMZRequestId = requestIdShape;
2318 }
2319
2320 var data = parser.parse(resp.httpResponse.body.toString(), shape);
2321 resp.requestId = data._XAMZRequestId || data.requestId;
2322
2323 if (data._XAMZRequestId) delete data._XAMZRequestId;
2324
2325 if (origRules.resultWrapper) {
2326 if (data[origRules.resultWrapper]) {
2327 util.update(data, data[origRules.resultWrapper]);
2328 delete data[origRules.resultWrapper];
2329 }
2330 }
2331
2332 resp.data = data;
2333 }
2334
2335 /**
2336 * @api private
2337 */
2338 module.exports = {
2339 buildRequest: buildRequest,
2340 extractError: extractError,
2341 extractData: extractData
2342 };
2343
2344
2345/***/ }),
2346/* 18 */
2347/***/ (function(module, exports, __webpack_require__) {
2348
2349 var util = __webpack_require__(2);
2350
2351 function QueryParamSerializer() {
2352 }
2353
2354 QueryParamSerializer.prototype.serialize = function(params, shape, fn) {
2355 serializeStructure('', params, shape, fn);
2356 };
2357
2358 function ucfirst(shape) {
2359 if (shape.isQueryName || shape.api.protocol !== 'ec2') {
2360 return shape.name;
2361 } else {
2362 return shape.name[0].toUpperCase() + shape.name.substr(1);
2363 }
2364 }
2365
2366 function serializeStructure(prefix, struct, rules, fn) {
2367 util.each(rules.members, function(name, member) {
2368 var value = struct[name];
2369 if (value === null || value === undefined) return;
2370
2371 var memberName = ucfirst(member);
2372 memberName = prefix ? prefix + '.' + memberName : memberName;
2373 serializeMember(memberName, value, member, fn);
2374 });
2375 }
2376
2377 function serializeMap(name, map, rules, fn) {
2378 var i = 1;
2379 util.each(map, function (key, value) {
2380 var prefix = rules.flattened ? '.' : '.entry.';
2381 var position = prefix + (i++) + '.';
2382 var keyName = position + (rules.key.name || 'key');
2383 var valueName = position + (rules.value.name || 'value');
2384 serializeMember(name + keyName, key, rules.key, fn);
2385 serializeMember(name + valueName, value, rules.value, fn);
2386 });
2387 }
2388
2389 function serializeList(name, list, rules, fn) {
2390 var memberRules = rules.member || {};
2391
2392 if (list.length === 0) {
2393 fn.call(this, name, null);
2394 return;
2395 }
2396
2397 util.arrayEach(list, function (v, n) {
2398 var suffix = '.' + (n + 1);
2399 if (rules.api.protocol === 'ec2') {
2400 // Do nothing for EC2
2401 suffix = suffix + ''; // make linter happy
2402 } else if (rules.flattened) {
2403 if (memberRules.name) {
2404 var parts = name.split('.');
2405 parts.pop();
2406 parts.push(ucfirst(memberRules));
2407 name = parts.join('.');
2408 }
2409 } else {
2410 suffix = '.' + (memberRules.name ? memberRules.name : 'member') + suffix;
2411 }
2412 serializeMember(name + suffix, v, memberRules, fn);
2413 });
2414 }
2415
2416 function serializeMember(name, value, rules, fn) {
2417 if (value === null || value === undefined) return;
2418 if (rules.type === 'structure') {
2419 serializeStructure(name, value, rules, fn);
2420 } else if (rules.type === 'list') {
2421 serializeList(name, value, rules, fn);
2422 } else if (rules.type === 'map') {
2423 serializeMap(name, value, rules, fn);
2424 } else {
2425 fn(name, rules.toWireFormat(value).toString());
2426 }
2427 }
2428
2429 /**
2430 * @api private
2431 */
2432 module.exports = QueryParamSerializer;
2433
2434
2435/***/ }),
2436/* 19 */
2437/***/ (function(module, exports, __webpack_require__) {
2438
2439 var Collection = __webpack_require__(20);
2440
2441 var util = __webpack_require__(2);
2442
2443 function property(obj, name, value) {
2444 if (value !== null && value !== undefined) {
2445 util.property.apply(this, arguments);
2446 }
2447 }
2448
2449 function memoizedProperty(obj, name) {
2450 if (!obj.constructor.prototype[name]) {
2451 util.memoizedProperty.apply(this, arguments);
2452 }
2453 }
2454
2455 function Shape(shape, options, memberName) {
2456 options = options || {};
2457
2458 property(this, 'shape', shape.shape);
2459 property(this, 'api', options.api, false);
2460 property(this, 'type', shape.type);
2461 property(this, 'enum', shape.enum);
2462 property(this, 'min', shape.min);
2463 property(this, 'max', shape.max);
2464 property(this, 'pattern', shape.pattern);
2465 property(this, 'location', shape.location || this.location || 'body');
2466 property(this, 'name', this.name || shape.xmlName || shape.queryName ||
2467 shape.locationName || memberName);
2468 property(this, 'isStreaming', shape.streaming || this.isStreaming || false);
2469 property(this, 'requiresLength', shape.requiresLength, false);
2470 property(this, 'isComposite', shape.isComposite || false);
2471 property(this, 'isShape', true, false);
2472 property(this, 'isQueryName', Boolean(shape.queryName), false);
2473 property(this, 'isLocationName', Boolean(shape.locationName), false);
2474 property(this, 'isIdempotent', shape.idempotencyToken === true);
2475 property(this, 'isJsonValue', shape.jsonvalue === true);
2476 property(this, 'isSensitive', shape.sensitive === true || shape.prototype && shape.prototype.sensitive === true);
2477 property(this, 'isEventStream', Boolean(shape.eventstream), false);
2478 property(this, 'isEvent', Boolean(shape.event), false);
2479 property(this, 'isEventPayload', Boolean(shape.eventpayload), false);
2480 property(this, 'isEventHeader', Boolean(shape.eventheader), false);
2481 property(this, 'isTimestampFormatSet', Boolean(shape.timestampFormat) || shape.prototype && shape.prototype.isTimestampFormatSet === true, false);
2482 property(this, 'endpointDiscoveryId', Boolean(shape.endpointdiscoveryid), false);
2483 property(this, 'hostLabel', Boolean(shape.hostLabel), false);
2484
2485 if (options.documentation) {
2486 property(this, 'documentation', shape.documentation);
2487 property(this, 'documentationUrl', shape.documentationUrl);
2488 }
2489
2490 if (shape.xmlAttribute) {
2491 property(this, 'isXmlAttribute', shape.xmlAttribute || false);
2492 }
2493
2494 // type conversion and parsing
2495 property(this, 'defaultValue', null);
2496 this.toWireFormat = function(value) {
2497 if (value === null || value === undefined) return '';
2498 return value;
2499 };
2500 this.toType = function(value) { return value; };
2501 }
2502
2503 /**
2504 * @api private
2505 */
2506 Shape.normalizedTypes = {
2507 character: 'string',
2508 double: 'float',
2509 long: 'integer',
2510 short: 'integer',
2511 biginteger: 'integer',
2512 bigdecimal: 'float',
2513 blob: 'binary'
2514 };
2515
2516 /**
2517 * @api private
2518 */
2519 Shape.types = {
2520 'structure': StructureShape,
2521 'list': ListShape,
2522 'map': MapShape,
2523 'boolean': BooleanShape,
2524 'timestamp': TimestampShape,
2525 'float': FloatShape,
2526 'integer': IntegerShape,
2527 'string': StringShape,
2528 'base64': Base64Shape,
2529 'binary': BinaryShape
2530 };
2531
2532 Shape.resolve = function resolve(shape, options) {
2533 if (shape.shape) {
2534 var refShape = options.api.shapes[shape.shape];
2535 if (!refShape) {
2536 throw new Error('Cannot find shape reference: ' + shape.shape);
2537 }
2538
2539 return refShape;
2540 } else {
2541 return null;
2542 }
2543 };
2544
2545 Shape.create = function create(shape, options, memberName) {
2546 if (shape.isShape) return shape;
2547
2548 var refShape = Shape.resolve(shape, options);
2549 if (refShape) {
2550 var filteredKeys = Object.keys(shape);
2551 if (!options.documentation) {
2552 filteredKeys = filteredKeys.filter(function(name) {
2553 return !name.match(/documentation/);
2554 });
2555 }
2556
2557 // create an inline shape with extra members
2558 var InlineShape = function() {
2559 refShape.constructor.call(this, shape, options, memberName);
2560 };
2561 InlineShape.prototype = refShape;
2562 return new InlineShape();
2563 } else {
2564 // set type if not set
2565 if (!shape.type) {
2566 if (shape.members) shape.type = 'structure';
2567 else if (shape.member) shape.type = 'list';
2568 else if (shape.key) shape.type = 'map';
2569 else shape.type = 'string';
2570 }
2571
2572 // normalize types
2573 var origType = shape.type;
2574 if (Shape.normalizedTypes[shape.type]) {
2575 shape.type = Shape.normalizedTypes[shape.type];
2576 }
2577
2578 if (Shape.types[shape.type]) {
2579 return new Shape.types[shape.type](shape, options, memberName);
2580 } else {
2581 throw new Error('Unrecognized shape type: ' + origType);
2582 }
2583 }
2584 };
2585
2586 function CompositeShape(shape) {
2587 Shape.apply(this, arguments);
2588 property(this, 'isComposite', true);
2589
2590 if (shape.flattened) {
2591 property(this, 'flattened', shape.flattened || false);
2592 }
2593 }
2594
2595 function StructureShape(shape, options) {
2596 var self = this;
2597 var requiredMap = null, firstInit = !this.isShape;
2598
2599 CompositeShape.apply(this, arguments);
2600
2601 if (firstInit) {
2602 property(this, 'defaultValue', function() { return {}; });
2603 property(this, 'members', {});
2604 property(this, 'memberNames', []);
2605 property(this, 'required', []);
2606 property(this, 'isRequired', function() { return false; });
2607 }
2608
2609 if (shape.members) {
2610 property(this, 'members', new Collection(shape.members, options, function(name, member) {
2611 return Shape.create(member, options, name);
2612 }));
2613 memoizedProperty(this, 'memberNames', function() {
2614 return shape.xmlOrder || Object.keys(shape.members);
2615 });
2616
2617 if (shape.event) {
2618 memoizedProperty(this, 'eventPayloadMemberName', function() {
2619 var members = self.members;
2620 var memberNames = self.memberNames;
2621 // iterate over members to find ones that are event payloads
2622 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2623 if (members[memberNames[i]].isEventPayload) {
2624 return memberNames[i];
2625 }
2626 }
2627 });
2628
2629 memoizedProperty(this, 'eventHeaderMemberNames', function() {
2630 var members = self.members;
2631 var memberNames = self.memberNames;
2632 var eventHeaderMemberNames = [];
2633 // iterate over members to find ones that are event headers
2634 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2635 if (members[memberNames[i]].isEventHeader) {
2636 eventHeaderMemberNames.push(memberNames[i]);
2637 }
2638 }
2639 return eventHeaderMemberNames;
2640 });
2641 }
2642 }
2643
2644 if (shape.required) {
2645 property(this, 'required', shape.required);
2646 property(this, 'isRequired', function(name) {
2647 if (!requiredMap) {
2648 requiredMap = {};
2649 for (var i = 0; i < shape.required.length; i++) {
2650 requiredMap[shape.required[i]] = true;
2651 }
2652 }
2653
2654 return requiredMap[name];
2655 }, false, true);
2656 }
2657
2658 property(this, 'resultWrapper', shape.resultWrapper || null);
2659
2660 if (shape.payload) {
2661 property(this, 'payload', shape.payload);
2662 }
2663
2664 if (typeof shape.xmlNamespace === 'string') {
2665 property(this, 'xmlNamespaceUri', shape.xmlNamespace);
2666 } else if (typeof shape.xmlNamespace === 'object') {
2667 property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix);
2668 property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri);
2669 }
2670 }
2671
2672 function ListShape(shape, options) {
2673 var self = this, firstInit = !this.isShape;
2674 CompositeShape.apply(this, arguments);
2675
2676 if (firstInit) {
2677 property(this, 'defaultValue', function() { return []; });
2678 }
2679
2680 if (shape.member) {
2681 memoizedProperty(this, 'member', function() {
2682 return Shape.create(shape.member, options);
2683 });
2684 }
2685
2686 if (this.flattened) {
2687 var oldName = this.name;
2688 memoizedProperty(this, 'name', function() {
2689 return self.member.name || oldName;
2690 });
2691 }
2692 }
2693
2694 function MapShape(shape, options) {
2695 var firstInit = !this.isShape;
2696 CompositeShape.apply(this, arguments);
2697
2698 if (firstInit) {
2699 property(this, 'defaultValue', function() { return {}; });
2700 property(this, 'key', Shape.create({type: 'string'}, options));
2701 property(this, 'value', Shape.create({type: 'string'}, options));
2702 }
2703
2704 if (shape.key) {
2705 memoizedProperty(this, 'key', function() {
2706 return Shape.create(shape.key, options);
2707 });
2708 }
2709 if (shape.value) {
2710 memoizedProperty(this, 'value', function() {
2711 return Shape.create(shape.value, options);
2712 });
2713 }
2714 }
2715
2716 function TimestampShape(shape) {
2717 var self = this;
2718 Shape.apply(this, arguments);
2719
2720 if (shape.timestampFormat) {
2721 property(this, 'timestampFormat', shape.timestampFormat);
2722 } else if (self.isTimestampFormatSet && this.timestampFormat) {
2723 property(this, 'timestampFormat', this.timestampFormat);
2724 } else if (this.location === 'header') {
2725 property(this, 'timestampFormat', 'rfc822');
2726 } else if (this.location === 'querystring') {
2727 property(this, 'timestampFormat', 'iso8601');
2728 } else if (this.api) {
2729 switch (this.api.protocol) {
2730 case 'json':
2731 case 'rest-json':
2732 property(this, 'timestampFormat', 'unixTimestamp');
2733 break;
2734 case 'rest-xml':
2735 case 'query':
2736 case 'ec2':
2737 property(this, 'timestampFormat', 'iso8601');
2738 break;
2739 }
2740 }
2741
2742 this.toType = function(value) {
2743 if (value === null || value === undefined) return null;
2744 if (typeof value.toUTCString === 'function') return value;
2745 return typeof value === 'string' || typeof value === 'number' ?
2746 util.date.parseTimestamp(value) : null;
2747 };
2748
2749 this.toWireFormat = function(value) {
2750 return util.date.format(value, self.timestampFormat);
2751 };
2752 }
2753
2754 function StringShape() {
2755 Shape.apply(this, arguments);
2756
2757 var nullLessProtocols = ['rest-xml', 'query', 'ec2'];
2758 this.toType = function(value) {
2759 value = this.api && nullLessProtocols.indexOf(this.api.protocol) > -1 ?
2760 value || '' : value;
2761 if (this.isJsonValue) {
2762 return JSON.parse(value);
2763 }
2764
2765 return value && typeof value.toString === 'function' ?
2766 value.toString() : value;
2767 };
2768
2769 this.toWireFormat = function(value) {
2770 return this.isJsonValue ? JSON.stringify(value) : value;
2771 };
2772 }
2773
2774 function FloatShape() {
2775 Shape.apply(this, arguments);
2776
2777 this.toType = function(value) {
2778 if (value === null || value === undefined) return null;
2779 return parseFloat(value);
2780 };
2781 this.toWireFormat = this.toType;
2782 }
2783
2784 function IntegerShape() {
2785 Shape.apply(this, arguments);
2786
2787 this.toType = function(value) {
2788 if (value === null || value === undefined) return null;
2789 return parseInt(value, 10);
2790 };
2791 this.toWireFormat = this.toType;
2792 }
2793
2794 function BinaryShape() {
2795 Shape.apply(this, arguments);
2796 this.toType = function(value) {
2797 var buf = util.base64.decode(value);
2798 if (this.isSensitive && util.isNode() && typeof util.Buffer.alloc === 'function') {
2799 /* Node.js can create a Buffer that is not isolated.
2800 * i.e. buf.byteLength !== buf.buffer.byteLength
2801 * This means that the sensitive data is accessible to anyone with access to buf.buffer.
2802 * If this is the node shared Buffer, then other code within this process _could_ find this secret.
2803 * Copy sensitive data to an isolated Buffer and zero the sensitive data.
2804 * While this is safe to do here, copying this code somewhere else may produce unexpected results.
2805 */
2806 var secureBuf = util.Buffer.alloc(buf.length, buf);
2807 buf.fill(0);
2808 buf = secureBuf;
2809 }
2810 return buf;
2811 };
2812 this.toWireFormat = util.base64.encode;
2813 }
2814
2815 function Base64Shape() {
2816 BinaryShape.apply(this, arguments);
2817 }
2818
2819 function BooleanShape() {
2820 Shape.apply(this, arguments);
2821
2822 this.toType = function(value) {
2823 if (typeof value === 'boolean') return value;
2824 if (value === null || value === undefined) return null;
2825 return value === 'true';
2826 };
2827 }
2828
2829 /**
2830 * @api private
2831 */
2832 Shape.shapes = {
2833 StructureShape: StructureShape,
2834 ListShape: ListShape,
2835 MapShape: MapShape,
2836 StringShape: StringShape,
2837 BooleanShape: BooleanShape,
2838 Base64Shape: Base64Shape
2839 };
2840
2841 /**
2842 * @api private
2843 */
2844 module.exports = Shape;
2845
2846
2847/***/ }),
2848/* 20 */
2849/***/ (function(module, exports, __webpack_require__) {
2850
2851 var memoizedProperty = __webpack_require__(2).memoizedProperty;
2852
2853 function memoize(name, value, factory, nameTr) {
2854 memoizedProperty(this, nameTr(name), function() {
2855 return factory(name, value);
2856 });
2857 }
2858
2859 function Collection(iterable, options, factory, nameTr, callback) {
2860 nameTr = nameTr || String;
2861 var self = this;
2862
2863 for (var id in iterable) {
2864 if (Object.prototype.hasOwnProperty.call(iterable, id)) {
2865 memoize.call(self, id, iterable[id], factory, nameTr);
2866 if (callback) callback(id, iterable[id]);
2867 }
2868 }
2869 }
2870
2871 /**
2872 * @api private
2873 */
2874 module.exports = Collection;
2875
2876
2877/***/ }),
2878/* 21 */
2879/***/ (function(module, exports, __webpack_require__) {
2880
2881 var util = __webpack_require__(2);
2882 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2883
2884 function populateMethod(req) {
2885 req.httpRequest.method = req.service.api.operations[req.operation].httpMethod;
2886 }
2887
2888 function generateURI(endpointPath, operationPath, input, params) {
2889 var uri = [endpointPath, operationPath].join('/');
2890 uri = uri.replace(/\/+/g, '/');
2891
2892 var queryString = {}, queryStringSet = false;
2893 util.each(input.members, function (name, member) {
2894 var paramValue = params[name];
2895 if (paramValue === null || paramValue === undefined) return;
2896 if (member.location === 'uri') {
2897 var regex = new RegExp('\\{' + member.name + '(\\+)?\\}');
2898 uri = uri.replace(regex, function(_, plus) {
2899 var fn = plus ? util.uriEscapePath : util.uriEscape;
2900 return fn(String(paramValue));
2901 });
2902 } else if (member.location === 'querystring') {
2903 queryStringSet = true;
2904
2905 if (member.type === 'list') {
2906 queryString[member.name] = paramValue.map(function(val) {
2907 return util.uriEscape(member.member.toWireFormat(val).toString());
2908 });
2909 } else if (member.type === 'map') {
2910 util.each(paramValue, function(key, value) {
2911 if (Array.isArray(value)) {
2912 queryString[key] = value.map(function(val) {
2913 return util.uriEscape(String(val));
2914 });
2915 } else {
2916 queryString[key] = util.uriEscape(String(value));
2917 }
2918 });
2919 } else {
2920 queryString[member.name] = util.uriEscape(member.toWireFormat(paramValue).toString());
2921 }
2922 }
2923 });
2924
2925 if (queryStringSet) {
2926 uri += (uri.indexOf('?') >= 0 ? '&' : '?');
2927 var parts = [];
2928 util.arrayEach(Object.keys(queryString).sort(), function(key) {
2929 if (!Array.isArray(queryString[key])) {
2930 queryString[key] = [queryString[key]];
2931 }
2932 for (var i = 0; i < queryString[key].length; i++) {
2933 parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]);
2934 }
2935 });
2936 uri += parts.join('&');
2937 }
2938
2939 return uri;
2940 }
2941
2942 function populateURI(req) {
2943 var operation = req.service.api.operations[req.operation];
2944 var input = operation.input;
2945
2946 var uri = generateURI(req.httpRequest.endpoint.path, operation.httpPath, input, req.params);
2947 req.httpRequest.path = uri;
2948 }
2949
2950 function populateHeaders(req) {
2951 var operation = req.service.api.operations[req.operation];
2952 util.each(operation.input.members, function (name, member) {
2953 var value = req.params[name];
2954 if (value === null || value === undefined) return;
2955
2956 if (member.location === 'headers' && member.type === 'map') {
2957 util.each(value, function(key, memberValue) {
2958 req.httpRequest.headers[member.name + key] = memberValue;
2959 });
2960 } else if (member.location === 'header') {
2961 value = member.toWireFormat(value).toString();
2962 if (member.isJsonValue) {
2963 value = util.base64.encode(value);
2964 }
2965 req.httpRequest.headers[member.name] = value;
2966 }
2967 });
2968 }
2969
2970 function buildRequest(req) {
2971 populateMethod(req);
2972 populateURI(req);
2973 populateHeaders(req);
2974 populateHostPrefix(req);
2975 }
2976
2977 function extractError() {
2978 }
2979
2980 function extractData(resp) {
2981 var req = resp.request;
2982 var data = {};
2983 var r = resp.httpResponse;
2984 var operation = req.service.api.operations[req.operation];
2985 var output = operation.output;
2986
2987 // normalize headers names to lower-cased keys for matching
2988 var headers = {};
2989 util.each(r.headers, function (k, v) {
2990 headers[k.toLowerCase()] = v;
2991 });
2992
2993 util.each(output.members, function(name, member) {
2994 var header = (member.name || name).toLowerCase();
2995 if (member.location === 'headers' && member.type === 'map') {
2996 data[name] = {};
2997 var location = member.isLocationName ? member.name : '';
2998 var pattern = new RegExp('^' + location + '(.+)', 'i');
2999 util.each(r.headers, function (k, v) {
3000 var result = k.match(pattern);
3001 if (result !== null) {
3002 data[name][result[1]] = v;
3003 }
3004 });
3005 } else if (member.location === 'header') {
3006 if (headers[header] !== undefined) {
3007 var value = member.isJsonValue ?
3008 util.base64.decode(headers[header]) :
3009 headers[header];
3010 data[name] = member.toType(value);
3011 }
3012 } else if (member.location === 'statusCode') {
3013 data[name] = parseInt(r.statusCode, 10);
3014 }
3015 });
3016
3017 resp.data = data;
3018 }
3019
3020 /**
3021 * @api private
3022 */
3023 module.exports = {
3024 buildRequest: buildRequest,
3025 extractError: extractError,
3026 extractData: extractData,
3027 generateURI: generateURI
3028 };
3029
3030
3031/***/ }),
3032/* 22 */
3033/***/ (function(module, exports, __webpack_require__) {
3034
3035 var util = __webpack_require__(2);
3036 var Rest = __webpack_require__(21);
3037 var Json = __webpack_require__(13);
3038 var JsonBuilder = __webpack_require__(14);
3039 var JsonParser = __webpack_require__(15);
3040
3041 function populateBody(req) {
3042 var builder = new JsonBuilder();
3043 var input = req.service.api.operations[req.operation].input;
3044
3045 if (input.payload) {
3046 var params = {};
3047 var payloadShape = input.members[input.payload];
3048 params = req.params[input.payload];
3049 if (params === undefined) return;
3050
3051 if (payloadShape.type === 'structure') {
3052 req.httpRequest.body = builder.build(params, payloadShape);
3053 applyContentTypeHeader(req);
3054 } else { // non-JSON payload
3055 req.httpRequest.body = params;
3056 if (payloadShape.type === 'binary' || payloadShape.isStreaming) {
3057 applyContentTypeHeader(req, true);
3058 }
3059 }
3060 } else {
3061 var body = builder.build(req.params, input);
3062 if (body !== '{}' || req.httpRequest.method !== 'GET') { //don't send empty body for GET method
3063 req.httpRequest.body = body;
3064 }
3065 applyContentTypeHeader(req);
3066 }
3067 }
3068
3069 function applyContentTypeHeader(req, isBinary) {
3070 var operation = req.service.api.operations[req.operation];
3071 var input = operation.input;
3072
3073 if (!req.httpRequest.headers['Content-Type']) {
3074 var type = isBinary ? 'binary/octet-stream' : 'application/json';
3075 req.httpRequest.headers['Content-Type'] = type;
3076 }
3077 }
3078
3079 function buildRequest(req) {
3080 Rest.buildRequest(req);
3081
3082 // never send body payload on HEAD/DELETE
3083 if (['HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) {
3084 populateBody(req);
3085 }
3086 }
3087
3088 function extractError(resp) {
3089 Json.extractError(resp);
3090 }
3091
3092 function extractData(resp) {
3093 Rest.extractData(resp);
3094
3095 var req = resp.request;
3096 var operation = req.service.api.operations[req.operation];
3097 var rules = req.service.api.operations[req.operation].output || {};
3098 var parser;
3099 var hasEventOutput = operation.hasEventOutput;
3100
3101 if (rules.payload) {
3102 var payloadMember = rules.members[rules.payload];
3103 var body = resp.httpResponse.body;
3104 if (payloadMember.isEventStream) {
3105 parser = new JsonParser();
3106 resp.data[payload] = util.createEventStream(
3107 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : body,
3108 parser,
3109 payloadMember
3110 );
3111 } else if (payloadMember.type === 'structure' || payloadMember.type === 'list') {
3112 var parser = new JsonParser();
3113 resp.data[rules.payload] = parser.parse(body, payloadMember);
3114 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3115 resp.data[rules.payload] = body;
3116 } else {
3117 resp.data[rules.payload] = payloadMember.toType(body);
3118 }
3119 } else {
3120 var data = resp.data;
3121 Json.extractData(resp);
3122 resp.data = util.merge(data, resp.data);
3123 }
3124 }
3125
3126 /**
3127 * @api private
3128 */
3129 module.exports = {
3130 buildRequest: buildRequest,
3131 extractError: extractError,
3132 extractData: extractData
3133 };
3134
3135
3136/***/ }),
3137/* 23 */
3138/***/ (function(module, exports, __webpack_require__) {
3139
3140 var AWS = __webpack_require__(1);
3141 var util = __webpack_require__(2);
3142 var Rest = __webpack_require__(21);
3143
3144 function populateBody(req) {
3145 var input = req.service.api.operations[req.operation].input;
3146 var builder = new AWS.XML.Builder();
3147 var params = req.params;
3148
3149 var payload = input.payload;
3150 if (payload) {
3151 var payloadMember = input.members[payload];
3152 params = params[payload];
3153 if (params === undefined) return;
3154
3155 if (payloadMember.type === 'structure') {
3156 var rootElement = payloadMember.name;
3157 req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true);
3158 } else { // non-xml payload
3159 req.httpRequest.body = params;
3160 }
3161 } else {
3162 req.httpRequest.body = builder.toXML(params, input, input.name ||
3163 input.shape || util.string.upperFirst(req.operation) + 'Request');
3164 }
3165 }
3166
3167 function buildRequest(req) {
3168 Rest.buildRequest(req);
3169
3170 // never send body payload on GET/HEAD
3171 if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) {
3172 populateBody(req);
3173 }
3174 }
3175
3176 function extractError(resp) {
3177 Rest.extractError(resp);
3178
3179 var data;
3180 try {
3181 data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString());
3182 } catch (e) {
3183 data = {
3184 Code: resp.httpResponse.statusCode,
3185 Message: resp.httpResponse.statusMessage
3186 };
3187 }
3188
3189 if (data.Errors) data = data.Errors;
3190 if (data.Error) data = data.Error;
3191 if (data.Code) {
3192 resp.error = util.error(new Error(), {
3193 code: data.Code,
3194 message: data.Message
3195 });
3196 } else {
3197 resp.error = util.error(new Error(), {
3198 code: resp.httpResponse.statusCode,
3199 message: null
3200 });
3201 }
3202 }
3203
3204 function extractData(resp) {
3205 Rest.extractData(resp);
3206
3207 var parser;
3208 var req = resp.request;
3209 var body = resp.httpResponse.body;
3210 var operation = req.service.api.operations[req.operation];
3211 var output = operation.output;
3212
3213 var hasEventOutput = operation.hasEventOutput;
3214
3215 var payload = output.payload;
3216 if (payload) {
3217 var payloadMember = output.members[payload];
3218 if (payloadMember.isEventStream) {
3219 parser = new AWS.XML.Parser();
3220 resp.data[payload] = util.createEventStream(
3221 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : resp.httpResponse.body,
3222 parser,
3223 payloadMember
3224 );
3225 } else if (payloadMember.type === 'structure') {
3226 parser = new AWS.XML.Parser();
3227 resp.data[payload] = parser.parse(body.toString(), payloadMember);
3228 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3229 resp.data[payload] = body;
3230 } else {
3231 resp.data[payload] = payloadMember.toType(body);
3232 }
3233 } else if (body.length > 0) {
3234 parser = new AWS.XML.Parser();
3235 var data = parser.parse(body.toString(), output);
3236 util.update(resp.data, data);
3237 }
3238 }
3239
3240 /**
3241 * @api private
3242 */
3243 module.exports = {
3244 buildRequest: buildRequest,
3245 extractError: extractError,
3246 extractData: extractData
3247 };
3248
3249
3250/***/ }),
3251/* 24 */
3252/***/ (function(module, exports, __webpack_require__) {
3253
3254 var util = __webpack_require__(2);
3255 var XmlNode = __webpack_require__(25).XmlNode;
3256 var XmlText = __webpack_require__(27).XmlText;
3257
3258 function XmlBuilder() { }
3259
3260 XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) {
3261 var xml = new XmlNode(rootElement);
3262 applyNamespaces(xml, shape, true);
3263 serialize(xml, params, shape);
3264 return xml.children.length > 0 || noEmpty ? xml.toString() : '';
3265 };
3266
3267 function serialize(xml, value, shape) {
3268 switch (shape.type) {
3269 case 'structure': return serializeStructure(xml, value, shape);
3270 case 'map': return serializeMap(xml, value, shape);
3271 case 'list': return serializeList(xml, value, shape);
3272 default: return serializeScalar(xml, value, shape);
3273 }
3274 }
3275
3276 function serializeStructure(xml, params, shape) {
3277 util.arrayEach(shape.memberNames, function(memberName) {
3278 var memberShape = shape.members[memberName];
3279 if (memberShape.location !== 'body') return;
3280
3281 var value = params[memberName];
3282 var name = memberShape.name;
3283 if (value !== undefined && value !== null) {
3284 if (memberShape.isXmlAttribute) {
3285 xml.addAttribute(name, value);
3286 } else if (memberShape.flattened) {
3287 serialize(xml, value, memberShape);
3288 } else {
3289 var element = new XmlNode(name);
3290 xml.addChildNode(element);
3291 applyNamespaces(element, memberShape);
3292 serialize(element, value, memberShape);
3293 }
3294 }
3295 });
3296 }
3297
3298 function serializeMap(xml, map, shape) {
3299 var xmlKey = shape.key.name || 'key';
3300 var xmlValue = shape.value.name || 'value';
3301
3302 util.each(map, function(key, value) {
3303 var entry = new XmlNode(shape.flattened ? shape.name : 'entry');
3304 xml.addChildNode(entry);
3305
3306 var entryKey = new XmlNode(xmlKey);
3307 var entryValue = new XmlNode(xmlValue);
3308 entry.addChildNode(entryKey);
3309 entry.addChildNode(entryValue);
3310
3311 serialize(entryKey, key, shape.key);
3312 serialize(entryValue, value, shape.value);
3313 });
3314 }
3315
3316 function serializeList(xml, list, shape) {
3317 if (shape.flattened) {
3318 util.arrayEach(list, function(value) {
3319 var name = shape.member.name || shape.name;
3320 var element = new XmlNode(name);
3321 xml.addChildNode(element);
3322 serialize(element, value, shape.member);
3323 });
3324 } else {
3325 util.arrayEach(list, function(value) {
3326 var name = shape.member.name || 'member';
3327 var element = new XmlNode(name);
3328 xml.addChildNode(element);
3329 serialize(element, value, shape.member);
3330 });
3331 }
3332 }
3333
3334 function serializeScalar(xml, value, shape) {
3335 xml.addChildNode(
3336 new XmlText(shape.toWireFormat(value))
3337 );
3338 }
3339
3340 function applyNamespaces(xml, shape, isRoot) {
3341 var uri, prefix = 'xmlns';
3342 if (shape.xmlNamespaceUri) {
3343 uri = shape.xmlNamespaceUri;
3344 if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix;
3345 } else if (isRoot && shape.api.xmlNamespaceUri) {
3346 uri = shape.api.xmlNamespaceUri;
3347 }
3348
3349 if (uri) xml.addAttribute(prefix, uri);
3350 }
3351
3352 /**
3353 * @api private
3354 */
3355 module.exports = XmlBuilder;
3356
3357
3358/***/ }),
3359/* 25 */
3360/***/ (function(module, exports, __webpack_require__) {
3361
3362 var escapeAttribute = __webpack_require__(26).escapeAttribute;
3363
3364 /**
3365 * Represents an XML node.
3366 * @api private
3367 */
3368 function XmlNode(name, children) {
3369 if (children === void 0) { children = []; }
3370 this.name = name;
3371 this.children = children;
3372 this.attributes = {};
3373 }
3374 XmlNode.prototype.addAttribute = function (name, value) {
3375 this.attributes[name] = value;
3376 return this;
3377 };
3378 XmlNode.prototype.addChildNode = function (child) {
3379 this.children.push(child);
3380 return this;
3381 };
3382 XmlNode.prototype.removeAttribute = function (name) {
3383 delete this.attributes[name];
3384 return this;
3385 };
3386 XmlNode.prototype.toString = function () {
3387 var hasChildren = Boolean(this.children.length);
3388 var xmlText = '<' + this.name;
3389 // add attributes
3390 var attributes = this.attributes;
3391 for (var i = 0, attributeNames = Object.keys(attributes); i < attributeNames.length; i++) {
3392 var attributeName = attributeNames[i];
3393 var attribute = attributes[attributeName];
3394 if (typeof attribute !== 'undefined' && attribute !== null) {
3395 xmlText += ' ' + attributeName + '=\"' + escapeAttribute('' + attribute) + '\"';
3396 }
3397 }
3398 return xmlText += !hasChildren ? '/>' : '>' + this.children.map(function (c) { return c.toString(); }).join('') + '</' + this.name + '>';
3399 };
3400
3401 /**
3402 * @api private
3403 */
3404 module.exports = {
3405 XmlNode: XmlNode
3406 };
3407
3408
3409/***/ }),
3410/* 26 */
3411/***/ (function(module, exports) {
3412
3413 /**
3414 * Escapes characters that can not be in an XML attribute.
3415 */
3416 function escapeAttribute(value) {
3417 return value.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
3418 }
3419
3420 /**
3421 * @api private
3422 */
3423 module.exports = {
3424 escapeAttribute: escapeAttribute
3425 };
3426
3427
3428/***/ }),
3429/* 27 */
3430/***/ (function(module, exports, __webpack_require__) {
3431
3432 var escapeElement = __webpack_require__(28).escapeElement;
3433
3434 /**
3435 * Represents an XML text value.
3436 * @api private
3437 */
3438 function XmlText(value) {
3439 this.value = value;
3440 }
3441
3442 XmlText.prototype.toString = function () {
3443 return escapeElement('' + this.value);
3444 };
3445
3446 /**
3447 * @api private
3448 */
3449 module.exports = {
3450 XmlText: XmlText
3451 };
3452
3453
3454/***/ }),
3455/* 28 */
3456/***/ (function(module, exports) {
3457
3458 /**
3459 * Escapes characters that can not be in an XML element.
3460 */
3461 function escapeElement(value) {
3462 return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3463 }
3464
3465 /**
3466 * @api private
3467 */
3468 module.exports = {
3469 escapeElement: escapeElement
3470 };
3471
3472
3473/***/ }),
3474/* 29 */
3475/***/ (function(module, exports, __webpack_require__) {
3476
3477 var Collection = __webpack_require__(20);
3478 var Operation = __webpack_require__(30);
3479 var Shape = __webpack_require__(19);
3480 var Paginator = __webpack_require__(31);
3481 var ResourceWaiter = __webpack_require__(32);
3482 var metadata = __webpack_require__(7);
3483
3484 var util = __webpack_require__(2);
3485 var property = util.property;
3486 var memoizedProperty = util.memoizedProperty;
3487
3488 function Api(api, options) {
3489 var self = this;
3490 api = api || {};
3491 options = options || {};
3492 options.api = this;
3493
3494 api.metadata = api.metadata || {};
3495
3496 var serviceIdentifier = options.serviceIdentifier;
3497 delete options.serviceIdentifier;
3498
3499 property(this, 'isApi', true, false);
3500 property(this, 'apiVersion', api.metadata.apiVersion);
3501 property(this, 'endpointPrefix', api.metadata.endpointPrefix);
3502 property(this, 'signingName', api.metadata.signingName);
3503 property(this, 'globalEndpoint', api.metadata.globalEndpoint);
3504 property(this, 'signatureVersion', api.metadata.signatureVersion);
3505 property(this, 'jsonVersion', api.metadata.jsonVersion);
3506 property(this, 'targetPrefix', api.metadata.targetPrefix);
3507 property(this, 'protocol', api.metadata.protocol);
3508 property(this, 'timestampFormat', api.metadata.timestampFormat);
3509 property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace);
3510 property(this, 'abbreviation', api.metadata.serviceAbbreviation);
3511 property(this, 'fullName', api.metadata.serviceFullName);
3512 property(this, 'serviceId', api.metadata.serviceId);
3513 if (serviceIdentifier) {
3514 property(this, 'xmlNoDefaultLists', metadata[serviceIdentifier].xmlNoDefaultLists, false);
3515 }
3516
3517 memoizedProperty(this, 'className', function() {
3518 var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName;
3519 if (!name) return null;
3520
3521 name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, '');
3522 if (name === 'ElasticLoadBalancing') name = 'ELB';
3523 return name;
3524 });
3525
3526 function addEndpointOperation(name, operation) {
3527 if (operation.endpointoperation === true) {
3528 property(self, 'endpointOperation', util.string.lowerFirst(name));
3529 }
3530 }
3531
3532 property(this, 'operations', new Collection(api.operations, options, function(name, operation) {
3533 return new Operation(name, operation, options);
3534 }, util.string.lowerFirst, addEndpointOperation));
3535
3536 property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) {
3537 return Shape.create(shape, options);
3538 }));
3539
3540 property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) {
3541 return new Paginator(name, paginator, options);
3542 }));
3543
3544 property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) {
3545 return new ResourceWaiter(name, waiter, options);
3546 }, util.string.lowerFirst));
3547
3548 if (options.documentation) {
3549 property(this, 'documentation', api.documentation);
3550 property(this, 'documentationUrl', api.documentationUrl);
3551 }
3552 }
3553
3554 /**
3555 * @api private
3556 */
3557 module.exports = Api;
3558
3559
3560/***/ }),
3561/* 30 */
3562/***/ (function(module, exports, __webpack_require__) {
3563
3564 var Shape = __webpack_require__(19);
3565
3566 var util = __webpack_require__(2);
3567 var property = util.property;
3568 var memoizedProperty = util.memoizedProperty;
3569
3570 function Operation(name, operation, options) {
3571 var self = this;
3572 options = options || {};
3573
3574 property(this, 'name', operation.name || name);
3575 property(this, 'api', options.api, false);
3576
3577 operation.http = operation.http || {};
3578 property(this, 'endpoint', operation.endpoint);
3579 property(this, 'httpMethod', operation.http.method || 'POST');
3580 property(this, 'httpPath', operation.http.requestUri || '/');
3581 property(this, 'authtype', operation.authtype || '');
3582 property(
3583 this,
3584 'endpointDiscoveryRequired',
3585 operation.endpointdiscovery ?
3586 (operation.endpointdiscovery.required ? 'REQUIRED' : 'OPTIONAL') :
3587 'NULL'
3588 );
3589
3590 memoizedProperty(this, 'input', function() {
3591 if (!operation.input) {
3592 return new Shape.create({type: 'structure'}, options);
3593 }
3594 return Shape.create(operation.input, options);
3595 });
3596
3597 memoizedProperty(this, 'output', function() {
3598 if (!operation.output) {
3599 return new Shape.create({type: 'structure'}, options);
3600 }
3601 return Shape.create(operation.output, options);
3602 });
3603
3604 memoizedProperty(this, 'errors', function() {
3605 var list = [];
3606 if (!operation.errors) return null;
3607
3608 for (var i = 0; i < operation.errors.length; i++) {
3609 list.push(Shape.create(operation.errors[i], options));
3610 }
3611
3612 return list;
3613 });
3614
3615 memoizedProperty(this, 'paginator', function() {
3616 return options.api.paginators[name];
3617 });
3618
3619 if (options.documentation) {
3620 property(this, 'documentation', operation.documentation);
3621 property(this, 'documentationUrl', operation.documentationUrl);
3622 }
3623
3624 // idempotentMembers only tracks top-level input shapes
3625 memoizedProperty(this, 'idempotentMembers', function() {
3626 var idempotentMembers = [];
3627 var input = self.input;
3628 var members = input.members;
3629 if (!input.members) {
3630 return idempotentMembers;
3631 }
3632 for (var name in members) {
3633 if (!members.hasOwnProperty(name)) {
3634 continue;
3635 }
3636 if (members[name].isIdempotent === true) {
3637 idempotentMembers.push(name);
3638 }
3639 }
3640 return idempotentMembers;
3641 });
3642
3643 memoizedProperty(this, 'hasEventOutput', function() {
3644 var output = self.output;
3645 return hasEventStream(output);
3646 });
3647 }
3648
3649 function hasEventStream(topLevelShape) {
3650 var members = topLevelShape.members;
3651 var payload = topLevelShape.payload;
3652
3653 if (!topLevelShape.members) {
3654 return false;
3655 }
3656
3657 if (payload) {
3658 var payloadMember = members[payload];
3659 return payloadMember.isEventStream;
3660 }
3661
3662 // check if any member is an event stream
3663 for (var name in members) {
3664 if (!members.hasOwnProperty(name)) {
3665 if (members[name].isEventStream === true) {
3666 return true;
3667 }
3668 }
3669 }
3670 return false;
3671 }
3672
3673 /**
3674 * @api private
3675 */
3676 module.exports = Operation;
3677
3678
3679/***/ }),
3680/* 31 */
3681/***/ (function(module, exports, __webpack_require__) {
3682
3683 var property = __webpack_require__(2).property;
3684
3685 function Paginator(name, paginator) {
3686 property(this, 'inputToken', paginator.input_token);
3687 property(this, 'limitKey', paginator.limit_key);
3688 property(this, 'moreResults', paginator.more_results);
3689 property(this, 'outputToken', paginator.output_token);
3690 property(this, 'resultKey', paginator.result_key);
3691 }
3692
3693 /**
3694 * @api private
3695 */
3696 module.exports = Paginator;
3697
3698
3699/***/ }),
3700/* 32 */
3701/***/ (function(module, exports, __webpack_require__) {
3702
3703 var util = __webpack_require__(2);
3704 var property = util.property;
3705
3706 function ResourceWaiter(name, waiter, options) {
3707 options = options || {};
3708 property(this, 'name', name);
3709 property(this, 'api', options.api, false);
3710
3711 if (waiter.operation) {
3712 property(this, 'operation', util.string.lowerFirst(waiter.operation));
3713 }
3714
3715 var self = this;
3716 var keys = [
3717 'type',
3718 'description',
3719 'delay',
3720 'maxAttempts',
3721 'acceptors'
3722 ];
3723
3724 keys.forEach(function(key) {
3725 var value = waiter[key];
3726 if (value) {
3727 property(self, key, value);
3728 }
3729 });
3730 }
3731
3732 /**
3733 * @api private
3734 */
3735 module.exports = ResourceWaiter;
3736
3737
3738/***/ }),
3739/* 33 */
3740/***/ (function(module, exports) {
3741
3742 function apiLoader(svc, version) {
3743 if (!apiLoader.services.hasOwnProperty(svc)) {
3744 throw new Error('InvalidService: Failed to load api for ' + svc);
3745 }
3746 return apiLoader.services[svc][version];
3747 }
3748
3749 /**
3750 * @api private
3751 *
3752 * This member of AWS.apiLoader is private, but changing it will necessitate a
3753 * change to ../scripts/services-table-generator.ts
3754 */
3755 apiLoader.services = {};
3756
3757 /**
3758 * @api private
3759 */
3760 module.exports = apiLoader;
3761
3762
3763/***/ }),
3764/* 34 */
3765/***/ (function(module, exports, __webpack_require__) {
3766
3767 "use strict";
3768 Object.defineProperty(exports, "__esModule", { value: true });
3769 var LRU_1 = __webpack_require__(35);
3770 var CACHE_SIZE = 1000;
3771 /**
3772 * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache]
3773 */
3774 var EndpointCache = /** @class */ (function () {
3775 function EndpointCache(maxSize) {
3776 if (maxSize === void 0) { maxSize = CACHE_SIZE; }
3777 this.maxSize = maxSize;
3778 this.cache = new LRU_1.LRUCache(maxSize);
3779 }
3780 ;
3781 Object.defineProperty(EndpointCache.prototype, "size", {
3782 get: function () {
3783 return this.cache.length;
3784 },
3785 enumerable: true,
3786 configurable: true
3787 });
3788 EndpointCache.prototype.put = function (key, value) {
3789 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3790 var endpointRecord = this.populateValue(value);
3791 this.cache.put(keyString, endpointRecord);
3792 };
3793 EndpointCache.prototype.get = function (key) {
3794 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3795 var now = Date.now();
3796 var records = this.cache.get(keyString);
3797 if (records) {
3798 for (var i = 0; i < records.length; i++) {
3799 var record = records[i];
3800 if (record.Expire < now) {
3801 this.cache.remove(keyString);
3802 return undefined;
3803 }
3804 }
3805 }
3806 return records;
3807 };
3808 EndpointCache.getKeyString = function (key) {
3809 var identifiers = [];
3810 var identifierNames = Object.keys(key).sort();
3811 for (var i = 0; i < identifierNames.length; i++) {
3812 var identifierName = identifierNames[i];
3813 if (key[identifierName] === undefined)
3814 continue;
3815 identifiers.push(key[identifierName]);
3816 }
3817 return identifiers.join(' ');
3818 };
3819 EndpointCache.prototype.populateValue = function (endpoints) {
3820 var now = Date.now();
3821 return endpoints.map(function (endpoint) { return ({
3822 Address: endpoint.Address || '',
3823 Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000
3824 }); });
3825 };
3826 EndpointCache.prototype.empty = function () {
3827 this.cache.empty();
3828 };
3829 EndpointCache.prototype.remove = function (key) {
3830 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3831 this.cache.remove(keyString);
3832 };
3833 return EndpointCache;
3834 }());
3835 exports.EndpointCache = EndpointCache;
3836
3837/***/ }),
3838/* 35 */
3839/***/ (function(module, exports) {
3840
3841 "use strict";
3842 Object.defineProperty(exports, "__esModule", { value: true });
3843 var LinkedListNode = /** @class */ (function () {
3844 function LinkedListNode(key, value) {
3845 this.key = key;
3846 this.value = value;
3847 }
3848 return LinkedListNode;
3849 }());
3850 var LRUCache = /** @class */ (function () {
3851 function LRUCache(size) {
3852 this.nodeMap = {};
3853 this.size = 0;
3854 if (typeof size !== 'number' || size < 1) {
3855 throw new Error('Cache size can only be positive number');
3856 }
3857 this.sizeLimit = size;
3858 }
3859 Object.defineProperty(LRUCache.prototype, "length", {
3860 get: function () {
3861 return this.size;
3862 },
3863 enumerable: true,
3864 configurable: true
3865 });
3866 LRUCache.prototype.prependToList = function (node) {
3867 if (!this.headerNode) {
3868 this.tailNode = node;
3869 }
3870 else {
3871 this.headerNode.prev = node;
3872 node.next = this.headerNode;
3873 }
3874 this.headerNode = node;
3875 this.size++;
3876 };
3877 LRUCache.prototype.removeFromTail = function () {
3878 if (!this.tailNode) {
3879 return undefined;
3880 }
3881 var node = this.tailNode;
3882 var prevNode = node.prev;
3883 if (prevNode) {
3884 prevNode.next = undefined;
3885 }
3886 node.prev = undefined;
3887 this.tailNode = prevNode;
3888 this.size--;
3889 return node;
3890 };
3891 LRUCache.prototype.detachFromList = function (node) {
3892 if (this.headerNode === node) {
3893 this.headerNode = node.next;
3894 }
3895 if (this.tailNode === node) {
3896 this.tailNode = node.prev;
3897 }
3898 if (node.prev) {
3899 node.prev.next = node.next;
3900 }
3901 if (node.next) {
3902 node.next.prev = node.prev;
3903 }
3904 node.next = undefined;
3905 node.prev = undefined;
3906 this.size--;
3907 };
3908 LRUCache.prototype.get = function (key) {
3909 if (this.nodeMap[key]) {
3910 var node = this.nodeMap[key];
3911 this.detachFromList(node);
3912 this.prependToList(node);
3913 return node.value;
3914 }
3915 };
3916 LRUCache.prototype.remove = function (key) {
3917 if (this.nodeMap[key]) {
3918 var node = this.nodeMap[key];
3919 this.detachFromList(node);
3920 delete this.nodeMap[key];
3921 }
3922 };
3923 LRUCache.prototype.put = function (key, value) {
3924 if (this.nodeMap[key]) {
3925 this.remove(key);
3926 }
3927 else if (this.size === this.sizeLimit) {
3928 var tailNode = this.removeFromTail();
3929 var key_1 = tailNode.key;
3930 delete this.nodeMap[key_1];
3931 }
3932 var newNode = new LinkedListNode(key, value);
3933 this.nodeMap[key] = newNode;
3934 this.prependToList(newNode);
3935 };
3936 LRUCache.prototype.empty = function () {
3937 var keys = Object.keys(this.nodeMap);
3938 for (var i = 0; i < keys.length; i++) {
3939 var key = keys[i];
3940 var node = this.nodeMap[key];
3941 this.detachFromList(node);
3942 delete this.nodeMap[key];
3943 }
3944 };
3945 return LRUCache;
3946 }());
3947 exports.LRUCache = LRUCache;
3948
3949/***/ }),
3950/* 36 */
3951/***/ (function(module, exports, __webpack_require__) {
3952
3953 var AWS = __webpack_require__(1);
3954
3955 /**
3956 * @api private
3957 * @!method on(eventName, callback)
3958 * Registers an event listener callback for the event given by `eventName`.
3959 * Parameters passed to the callback function depend on the individual event
3960 * being triggered. See the event documentation for those parameters.
3961 *
3962 * @param eventName [String] the event name to register the listener for
3963 * @param callback [Function] the listener callback function
3964 * @param toHead [Boolean] attach the listener callback to the head of callback array if set to true.
3965 * Default to be false.
3966 * @return [AWS.SequentialExecutor] the same object for chaining
3967 */
3968 AWS.SequentialExecutor = AWS.util.inherit({
3969
3970 constructor: function SequentialExecutor() {
3971 this._events = {};
3972 },
3973
3974 /**
3975 * @api private
3976 */
3977 listeners: function listeners(eventName) {
3978 return this._events[eventName] ? this._events[eventName].slice(0) : [];
3979 },
3980
3981 on: function on(eventName, listener, toHead) {
3982 if (this._events[eventName]) {
3983 toHead ?
3984 this._events[eventName].unshift(listener) :
3985 this._events[eventName].push(listener);
3986 } else {
3987 this._events[eventName] = [listener];
3988 }
3989 return this;
3990 },
3991
3992 onAsync: function onAsync(eventName, listener, toHead) {
3993 listener._isAsync = true;
3994 return this.on(eventName, listener, toHead);
3995 },
3996
3997 removeListener: function removeListener(eventName, listener) {
3998 var listeners = this._events[eventName];
3999 if (listeners) {
4000 var length = listeners.length;
4001 var position = -1;
4002 for (var i = 0; i < length; ++i) {
4003 if (listeners[i] === listener) {
4004 position = i;
4005 }
4006 }
4007 if (position > -1) {
4008 listeners.splice(position, 1);
4009 }
4010 }
4011 return this;
4012 },
4013
4014 removeAllListeners: function removeAllListeners(eventName) {
4015 if (eventName) {
4016 delete this._events[eventName];
4017 } else {
4018 this._events = {};
4019 }
4020 return this;
4021 },
4022
4023 /**
4024 * @api private
4025 */
4026 emit: function emit(eventName, eventArgs, doneCallback) {
4027 if (!doneCallback) doneCallback = function() { };
4028 var listeners = this.listeners(eventName);
4029 var count = listeners.length;
4030 this.callListeners(listeners, eventArgs, doneCallback);
4031 return count > 0;
4032 },
4033
4034 /**
4035 * @api private
4036 */
4037 callListeners: function callListeners(listeners, args, doneCallback, prevError) {
4038 var self = this;
4039 var error = prevError || null;
4040
4041 function callNextListener(err) {
4042 if (err) {
4043 error = AWS.util.error(error || new Error(), err);
4044 if (self._haltHandlersOnError) {
4045 return doneCallback.call(self, error);
4046 }
4047 }
4048 self.callListeners(listeners, args, doneCallback, error);
4049 }
4050
4051 while (listeners.length > 0) {
4052 var listener = listeners.shift();
4053 if (listener._isAsync) { // asynchronous listener
4054 listener.apply(self, args.concat([callNextListener]));
4055 return; // stop here, callNextListener will continue
4056 } else { // synchronous listener
4057 try {
4058 listener.apply(self, args);
4059 } catch (err) {
4060 error = AWS.util.error(error || new Error(), err);
4061 }
4062 if (error && self._haltHandlersOnError) {
4063 doneCallback.call(self, error);
4064 return;
4065 }
4066 }
4067 }
4068 doneCallback.call(self, error);
4069 },
4070
4071 /**
4072 * Adds or copies a set of listeners from another list of
4073 * listeners or SequentialExecutor object.
4074 *
4075 * @param listeners [map<String,Array<Function>>, AWS.SequentialExecutor]
4076 * a list of events and callbacks, or an event emitter object
4077 * containing listeners to add to this emitter object.
4078 * @return [AWS.SequentialExecutor] the emitter object, for chaining.
4079 * @example Adding listeners from a map of listeners
4080 * emitter.addListeners({
4081 * event1: [function() { ... }, function() { ... }],
4082 * event2: [function() { ... }]
4083 * });
4084 * emitter.emit('event1'); // emitter has event1
4085 * emitter.emit('event2'); // emitter has event2
4086 * @example Adding listeners from another emitter object
4087 * var emitter1 = new AWS.SequentialExecutor();
4088 * emitter1.on('event1', function() { ... });
4089 * emitter1.on('event2', function() { ... });
4090 * var emitter2 = new AWS.SequentialExecutor();
4091 * emitter2.addListeners(emitter1);
4092 * emitter2.emit('event1'); // emitter2 has event1
4093 * emitter2.emit('event2'); // emitter2 has event2
4094 */
4095 addListeners: function addListeners(listeners) {
4096 var self = this;
4097
4098 // extract listeners if parameter is an SequentialExecutor object
4099 if (listeners._events) listeners = listeners._events;
4100
4101 AWS.util.each(listeners, function(event, callbacks) {
4102 if (typeof callbacks === 'function') callbacks = [callbacks];
4103 AWS.util.arrayEach(callbacks, function(callback) {
4104 self.on(event, callback);
4105 });
4106 });
4107
4108 return self;
4109 },
4110
4111 /**
4112 * Registers an event with {on} and saves the callback handle function
4113 * as a property on the emitter object using a given `name`.
4114 *
4115 * @param name [String] the property name to set on this object containing
4116 * the callback function handle so that the listener can be removed in
4117 * the future.
4118 * @param (see on)
4119 * @return (see on)
4120 * @example Adding a named listener DATA_CALLBACK
4121 * var listener = function() { doSomething(); };
4122 * emitter.addNamedListener('DATA_CALLBACK', 'data', listener);
4123 *
4124 * // the following prints: true
4125 * console.log(emitter.DATA_CALLBACK == listener);
4126 */
4127 addNamedListener: function addNamedListener(name, eventName, callback, toHead) {
4128 this[name] = callback;
4129 this.addListener(eventName, callback, toHead);
4130 return this;
4131 },
4132
4133 /**
4134 * @api private
4135 */
4136 addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback, toHead) {
4137 callback._isAsync = true;
4138 return this.addNamedListener(name, eventName, callback, toHead);
4139 },
4140
4141 /**
4142 * Helper method to add a set of named listeners using
4143 * {addNamedListener}. The callback contains a parameter
4144 * with a handle to the `addNamedListener` method.
4145 *
4146 * @callback callback function(add)
4147 * The callback function is called immediately in order to provide
4148 * the `add` function to the block. This simplifies the addition of
4149 * a large group of named listeners.
4150 * @param add [Function] the {addNamedListener} function to call
4151 * when registering listeners.
4152 * @example Adding a set of named listeners
4153 * emitter.addNamedListeners(function(add) {
4154 * add('DATA_CALLBACK', 'data', function() { ... });
4155 * add('OTHER', 'otherEvent', function() { ... });
4156 * add('LAST', 'lastEvent', function() { ... });
4157 * });
4158 *
4159 * // these properties are now set:
4160 * emitter.DATA_CALLBACK;
4161 * emitter.OTHER;
4162 * emitter.LAST;
4163 */
4164 addNamedListeners: function addNamedListeners(callback) {
4165 var self = this;
4166 callback(
4167 function() {
4168 self.addNamedListener.apply(self, arguments);
4169 },
4170 function() {
4171 self.addNamedAsyncListener.apply(self, arguments);
4172 }
4173 );
4174 return this;
4175 }
4176 });
4177
4178 /**
4179 * {on} is the prefered method.
4180 * @api private
4181 */
4182 AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on;
4183
4184 /**
4185 * @api private
4186 */
4187 module.exports = AWS.SequentialExecutor;
4188
4189
4190/***/ }),
4191/* 37 */
4192/***/ (function(module, exports, __webpack_require__) {
4193
4194 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
4195 var Api = __webpack_require__(29);
4196 var regionConfig = __webpack_require__(38);
4197
4198 var inherit = AWS.util.inherit;
4199 var clientCount = 0;
4200
4201 /**
4202 * The service class representing an AWS service.
4203 *
4204 * @class_abstract This class is an abstract class.
4205 *
4206 * @!attribute apiVersions
4207 * @return [Array<String>] the list of API versions supported by this service.
4208 * @readonly
4209 */
4210 AWS.Service = inherit({
4211 /**
4212 * Create a new service object with a configuration object
4213 *
4214 * @param config [map] a map of configuration options
4215 */
4216 constructor: function Service(config) {
4217 if (!this.loadServiceClass) {
4218 throw AWS.util.error(new Error(),
4219 'Service must be constructed with `new\' operator');
4220 }
4221 var ServiceClass = this.loadServiceClass(config || {});
4222 if (ServiceClass) {
4223 var originalConfig = AWS.util.copy(config);
4224 var svc = new ServiceClass(config);
4225 Object.defineProperty(svc, '_originalConfig', {
4226 get: function() { return originalConfig; },
4227 enumerable: false,
4228 configurable: true
4229 });
4230 svc._clientId = ++clientCount;
4231 return svc;
4232 }
4233 this.initialize(config);
4234 },
4235
4236 /**
4237 * @api private
4238 */
4239 initialize: function initialize(config) {
4240 var svcConfig = AWS.config[this.serviceIdentifier];
4241 this.config = new AWS.Config(AWS.config);
4242 if (svcConfig) this.config.update(svcConfig, true);
4243 if (config) this.config.update(config, true);
4244
4245 this.validateService();
4246 if (!this.config.endpoint) regionConfig.configureEndpoint(this);
4247
4248 this.config.endpoint = this.endpointFromTemplate(this.config.endpoint);
4249 this.setEndpoint(this.config.endpoint);
4250 //enable attaching listeners to service client
4251 AWS.SequentialExecutor.call(this);
4252 AWS.Service.addDefaultMonitoringListeners(this);
4253 if ((this.config.clientSideMonitoring || AWS.Service._clientSideMonitoring) && this.publisher) {
4254 var publisher = this.publisher;
4255 this.addNamedListener('PUBLISH_API_CALL', 'apiCall', function PUBLISH_API_CALL(event) {
4256 process.nextTick(function() {publisher.eventHandler(event);});
4257 });
4258 this.addNamedListener('PUBLISH_API_ATTEMPT', 'apiCallAttempt', function PUBLISH_API_ATTEMPT(event) {
4259 process.nextTick(function() {publisher.eventHandler(event);});
4260 });
4261 }
4262 },
4263
4264 /**
4265 * @api private
4266 */
4267 validateService: function validateService() {
4268 },
4269
4270 /**
4271 * @api private
4272 */
4273 loadServiceClass: function loadServiceClass(serviceConfig) {
4274 var config = serviceConfig;
4275 if (!AWS.util.isEmpty(this.api)) {
4276 return null;
4277 } else if (config.apiConfig) {
4278 return AWS.Service.defineServiceApi(this.constructor, config.apiConfig);
4279 } else if (!this.constructor.services) {
4280 return null;
4281 } else {
4282 config = new AWS.Config(AWS.config);
4283 config.update(serviceConfig, true);
4284 var version = config.apiVersions[this.constructor.serviceIdentifier];
4285 version = version || config.apiVersion;
4286 return this.getLatestServiceClass(version);
4287 }
4288 },
4289
4290 /**
4291 * @api private
4292 */
4293 getLatestServiceClass: function getLatestServiceClass(version) {
4294 version = this.getLatestServiceVersion(version);
4295 if (this.constructor.services[version] === null) {
4296 AWS.Service.defineServiceApi(this.constructor, version);
4297 }
4298
4299 return this.constructor.services[version];
4300 },
4301
4302 /**
4303 * @api private
4304 */
4305 getLatestServiceVersion: function getLatestServiceVersion(version) {
4306 if (!this.constructor.services || this.constructor.services.length === 0) {
4307 throw new Error('No services defined on ' +
4308 this.constructor.serviceIdentifier);
4309 }
4310
4311 if (!version) {
4312 version = 'latest';
4313 } else if (AWS.util.isType(version, Date)) {
4314 version = AWS.util.date.iso8601(version).split('T')[0];
4315 }
4316
4317 if (Object.hasOwnProperty(this.constructor.services, version)) {
4318 return version;
4319 }
4320
4321 var keys = Object.keys(this.constructor.services).sort();
4322 var selectedVersion = null;
4323 for (var i = keys.length - 1; i >= 0; i--) {
4324 // versions that end in "*" are not available on disk and can be
4325 // skipped, so do not choose these as selectedVersions
4326 if (keys[i][keys[i].length - 1] !== '*') {
4327 selectedVersion = keys[i];
4328 }
4329 if (keys[i].substr(0, 10) <= version) {
4330 return selectedVersion;
4331 }
4332 }
4333
4334 throw new Error('Could not find ' + this.constructor.serviceIdentifier +
4335 ' API to satisfy version constraint `' + version + '\'');
4336 },
4337
4338 /**
4339 * @api private
4340 */
4341 api: {},
4342
4343 /**
4344 * @api private
4345 */
4346 defaultRetryCount: 3,
4347
4348 /**
4349 * @api private
4350 */
4351 customizeRequests: function customizeRequests(callback) {
4352 if (!callback) {
4353 this.customRequestHandler = null;
4354 } else if (typeof callback === 'function') {
4355 this.customRequestHandler = callback;
4356 } else {
4357 throw new Error('Invalid callback type \'' + typeof callback + '\' provided in customizeRequests');
4358 }
4359 },
4360
4361 /**
4362 * Calls an operation on a service with the given input parameters.
4363 *
4364 * @param operation [String] the name of the operation to call on the service.
4365 * @param params [map] a map of input options for the operation
4366 * @callback callback function(err, data)
4367 * If a callback is supplied, it is called when a response is returned
4368 * from the service.
4369 * @param err [Error] the error object returned from the request.
4370 * Set to `null` if the request is successful.
4371 * @param data [Object] the de-serialized data returned from
4372 * the request. Set to `null` if a request error occurs.
4373 */
4374 makeRequest: function makeRequest(operation, params, callback) {
4375 if (typeof params === 'function') {
4376 callback = params;
4377 params = null;
4378 }
4379
4380 params = params || {};
4381 if (this.config.params) { // copy only toplevel bound params
4382 var rules = this.api.operations[operation];
4383 if (rules) {
4384 params = AWS.util.copy(params);
4385 AWS.util.each(this.config.params, function(key, value) {
4386 if (rules.input.members[key]) {
4387 if (params[key] === undefined || params[key] === null) {
4388 params[key] = value;
4389 }
4390 }
4391 });
4392 }
4393 }
4394
4395 var request = new AWS.Request(this, operation, params);
4396 this.addAllRequestListeners(request);
4397 this.attachMonitoringEmitter(request);
4398 if (callback) request.send(callback);
4399 return request;
4400 },
4401
4402 /**
4403 * Calls an operation on a service with the given input parameters, without
4404 * any authentication data. This method is useful for "public" API operations.
4405 *
4406 * @param operation [String] the name of the operation to call on the service.
4407 * @param params [map] a map of input options for the operation
4408 * @callback callback function(err, data)
4409 * If a callback is supplied, it is called when a response is returned
4410 * from the service.
4411 * @param err [Error] the error object returned from the request.
4412 * Set to `null` if the request is successful.
4413 * @param data [Object] the de-serialized data returned from
4414 * the request. Set to `null` if a request error occurs.
4415 */
4416 makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) {
4417 if (typeof params === 'function') {
4418 callback = params;
4419 params = {};
4420 }
4421
4422 var request = this.makeRequest(operation, params).toUnauthenticated();
4423 return callback ? request.send(callback) : request;
4424 },
4425
4426 /**
4427 * Waits for a given state
4428 *
4429 * @param state [String] the state on the service to wait for
4430 * @param params [map] a map of parameters to pass with each request
4431 * @option params $waiter [map] a map of configuration options for the waiter
4432 * @option params $waiter.delay [Number] The number of seconds to wait between
4433 * requests
4434 * @option params $waiter.maxAttempts [Number] The maximum number of requests
4435 * to send while waiting
4436 * @callback callback function(err, data)
4437 * If a callback is supplied, it is called when a response is returned
4438 * from the service.
4439 * @param err [Error] the error object returned from the request.
4440 * Set to `null` if the request is successful.
4441 * @param data [Object] the de-serialized data returned from
4442 * the request. Set to `null` if a request error occurs.
4443 */
4444 waitFor: function waitFor(state, params, callback) {
4445 var waiter = new AWS.ResourceWaiter(this, state);
4446 return waiter.wait(params, callback);
4447 },
4448
4449 /**
4450 * @api private
4451 */
4452 addAllRequestListeners: function addAllRequestListeners(request) {
4453 var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(),
4454 AWS.EventListeners.CorePost];
4455 for (var i = 0; i < list.length; i++) {
4456 if (list[i]) request.addListeners(list[i]);
4457 }
4458
4459 // disable parameter validation
4460 if (!this.config.paramValidation) {
4461 request.removeListener('validate',
4462 AWS.EventListeners.Core.VALIDATE_PARAMETERS);
4463 }
4464
4465 if (this.config.logger) { // add logging events
4466 request.addListeners(AWS.EventListeners.Logger);
4467 }
4468
4469 this.setupRequestListeners(request);
4470 // call prototype's customRequestHandler
4471 if (typeof this.constructor.prototype.customRequestHandler === 'function') {
4472 this.constructor.prototype.customRequestHandler(request);
4473 }
4474 // call instance's customRequestHandler
4475 if (Object.prototype.hasOwnProperty.call(this, 'customRequestHandler') && typeof this.customRequestHandler === 'function') {
4476 this.customRequestHandler(request);
4477 }
4478 },
4479
4480 /**
4481 * Event recording metrics for a whole API call.
4482 * @returns {object} a subset of api call metrics
4483 * @api private
4484 */
4485 apiCallEvent: function apiCallEvent(request) {
4486 var api = request.service.api.operations[request.operation];
4487 var monitoringEvent = {
4488 Type: 'ApiCall',
4489 Api: api ? api.name : request.operation,
4490 Version: 1,
4491 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4492 Region: request.httpRequest.region,
4493 MaxRetriesExceeded: 0,
4494 UserAgent: request.httpRequest.getUserAgent(),
4495 };
4496 var response = request.response;
4497 if (response.httpResponse.statusCode) {
4498 monitoringEvent.FinalHttpStatusCode = response.httpResponse.statusCode;
4499 }
4500 if (response.error) {
4501 var error = response.error;
4502 var statusCode = response.httpResponse.statusCode;
4503 if (statusCode > 299) {
4504 if (error.code) monitoringEvent.FinalAwsException = error.code;
4505 if (error.message) monitoringEvent.FinalAwsExceptionMessage = error.message;
4506 } else {
4507 if (error.code || error.name) monitoringEvent.FinalSdkException = error.code || error.name;
4508 if (error.message) monitoringEvent.FinalSdkExceptionMessage = error.message;
4509 }
4510 }
4511 return monitoringEvent;
4512 },
4513
4514 /**
4515 * Event recording metrics for an API call attempt.
4516 * @returns {object} a subset of api call attempt metrics
4517 * @api private
4518 */
4519 apiAttemptEvent: function apiAttemptEvent(request) {
4520 var api = request.service.api.operations[request.operation];
4521 var monitoringEvent = {
4522 Type: 'ApiCallAttempt',
4523 Api: api ? api.name : request.operation,
4524 Version: 1,
4525 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4526 Fqdn: request.httpRequest.endpoint.hostname,
4527 UserAgent: request.httpRequest.getUserAgent(),
4528 };
4529 var response = request.response;
4530 if (response.httpResponse.statusCode) {
4531 monitoringEvent.HttpStatusCode = response.httpResponse.statusCode;
4532 }
4533 if (
4534 !request._unAuthenticated &&
4535 request.service.config.credentials &&
4536 request.service.config.credentials.accessKeyId
4537 ) {
4538 monitoringEvent.AccessKey = request.service.config.credentials.accessKeyId;
4539 }
4540 if (!response.httpResponse.headers) return monitoringEvent;
4541 if (request.httpRequest.headers['x-amz-security-token']) {
4542 monitoringEvent.SessionToken = request.httpRequest.headers['x-amz-security-token'];
4543 }
4544 if (response.httpResponse.headers['x-amzn-requestid']) {
4545 monitoringEvent.XAmznRequestId = response.httpResponse.headers['x-amzn-requestid'];
4546 }
4547 if (response.httpResponse.headers['x-amz-request-id']) {
4548 monitoringEvent.XAmzRequestId = response.httpResponse.headers['x-amz-request-id'];
4549 }
4550 if (response.httpResponse.headers['x-amz-id-2']) {
4551 monitoringEvent.XAmzId2 = response.httpResponse.headers['x-amz-id-2'];
4552 }
4553 return monitoringEvent;
4554 },
4555
4556 /**
4557 * Add metrics of failed request.
4558 * @api private
4559 */
4560 attemptFailEvent: function attemptFailEvent(request) {
4561 var monitoringEvent = this.apiAttemptEvent(request);
4562 var response = request.response;
4563 var error = response.error;
4564 if (response.httpResponse.statusCode > 299 ) {
4565 if (error.code) monitoringEvent.AwsException = error.code;
4566 if (error.message) monitoringEvent.AwsExceptionMessage = error.message;
4567 } else {
4568 if (error.code || error.name) monitoringEvent.SdkException = error.code || error.name;
4569 if (error.message) monitoringEvent.SdkExceptionMessage = error.message;
4570 }
4571 return monitoringEvent;
4572 },
4573
4574 /**
4575 * Attach listeners to request object to fetch metrics of each request
4576 * and emit data object through \'ApiCall\' and \'ApiCallAttempt\' events.
4577 * @api private
4578 */
4579 attachMonitoringEmitter: function attachMonitoringEmitter(request) {
4580 var attemptTimestamp; //timestamp marking the beginning of a request attempt
4581 var attemptStartRealTime; //Start time of request attempt. Used to calculating attemptLatency
4582 var attemptLatency; //latency from request sent out to http response reaching SDK
4583 var callStartRealTime; //Start time of API call. Used to calculating API call latency
4584 var attemptCount = 0; //request.retryCount is not reliable here
4585 var region; //region cache region for each attempt since it can be updated in plase (e.g. s3)
4586 var callTimestamp; //timestamp when the request is created
4587 var self = this;
4588 var addToHead = true;
4589
4590 request.on('validate', function () {
4591 callStartRealTime = AWS.util.realClock.now();
4592 callTimestamp = Date.now();
4593 }, addToHead);
4594 request.on('sign', function () {
4595 attemptStartRealTime = AWS.util.realClock.now();
4596 attemptTimestamp = Date.now();
4597 region = request.httpRequest.region;
4598 attemptCount++;
4599 }, addToHead);
4600 request.on('validateResponse', function() {
4601 attemptLatency = Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4602 });
4603 request.addNamedListener('API_CALL_ATTEMPT', 'success', function API_CALL_ATTEMPT() {
4604 var apiAttemptEvent = self.apiAttemptEvent(request);
4605 apiAttemptEvent.Timestamp = attemptTimestamp;
4606 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4607 apiAttemptEvent.Region = region;
4608 self.emit('apiCallAttempt', [apiAttemptEvent]);
4609 });
4610 request.addNamedListener('API_CALL_ATTEMPT_RETRY', 'retry', function API_CALL_ATTEMPT_RETRY() {
4611 var apiAttemptEvent = self.attemptFailEvent(request);
4612 apiAttemptEvent.Timestamp = attemptTimestamp;
4613 //attemptLatency may not be available if fail before response
4614 attemptLatency = attemptLatency ||
4615 Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4616 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4617 apiAttemptEvent.Region = region;
4618 self.emit('apiCallAttempt', [apiAttemptEvent]);
4619 });
4620 request.addNamedListener('API_CALL', 'complete', function API_CALL() {
4621 var apiCallEvent = self.apiCallEvent(request);
4622 apiCallEvent.AttemptCount = attemptCount;
4623 if (apiCallEvent.AttemptCount <= 0) return;
4624 apiCallEvent.Timestamp = callTimestamp;
4625 var latency = Math.round(AWS.util.realClock.now() - callStartRealTime);
4626 apiCallEvent.Latency = latency >= 0 ? latency : 0;
4627 var response = request.response;
4628 if (
4629 typeof response.retryCount === 'number' &&
4630 typeof response.maxRetries === 'number' &&
4631 (response.retryCount >= response.maxRetries)
4632 ) {
4633 apiCallEvent.MaxRetriesExceeded = 1;
4634 }
4635 self.emit('apiCall', [apiCallEvent]);
4636 });
4637 },
4638
4639 /**
4640 * Override this method to setup any custom request listeners for each
4641 * new request to the service.
4642 *
4643 * @method_abstract This is an abstract method.
4644 */
4645 setupRequestListeners: function setupRequestListeners(request) {
4646 },
4647
4648 /**
4649 * Gets the signer class for a given request
4650 * @api private
4651 */
4652 getSignerClass: function getSignerClass(request) {
4653 var version;
4654 // get operation authtype if present
4655 var operation = null;
4656 var authtype = '';
4657 if (request) {
4658 var operations = request.service.api.operations || {};
4659 operation = operations[request.operation] || null;
4660 authtype = operation ? operation.authtype : '';
4661 }
4662 if (this.config.signatureVersion) {
4663 version = this.config.signatureVersion;
4664 } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') {
4665 version = 'v4';
4666 } else {
4667 version = this.api.signatureVersion;
4668 }
4669 return AWS.Signers.RequestSigner.getVersion(version);
4670 },
4671
4672 /**
4673 * @api private
4674 */
4675 serviceInterface: function serviceInterface() {
4676 switch (this.api.protocol) {
4677 case 'ec2': return AWS.EventListeners.Query;
4678 case 'query': return AWS.EventListeners.Query;
4679 case 'json': return AWS.EventListeners.Json;
4680 case 'rest-json': return AWS.EventListeners.RestJson;
4681 case 'rest-xml': return AWS.EventListeners.RestXml;
4682 }
4683 if (this.api.protocol) {
4684 throw new Error('Invalid service `protocol\' ' +
4685 this.api.protocol + ' in API config');
4686 }
4687 },
4688
4689 /**
4690 * @api private
4691 */
4692 successfulResponse: function successfulResponse(resp) {
4693 return resp.httpResponse.statusCode < 300;
4694 },
4695
4696 /**
4697 * How many times a failed request should be retried before giving up.
4698 * the defaultRetryCount can be overriden by service classes.
4699 *
4700 * @api private
4701 */
4702 numRetries: function numRetries() {
4703 if (this.config.maxRetries !== undefined) {
4704 return this.config.maxRetries;
4705 } else {
4706 return this.defaultRetryCount;
4707 }
4708 },
4709
4710 /**
4711 * @api private
4712 */
4713 retryDelays: function retryDelays(retryCount, err) {
4714 return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions, err);
4715 },
4716
4717 /**
4718 * @api private
4719 */
4720 retryableError: function retryableError(error) {
4721 if (this.timeoutError(error)) return true;
4722 if (this.networkingError(error)) return true;
4723 if (this.expiredCredentialsError(error)) return true;
4724 if (this.throttledError(error)) return true;
4725 if (error.statusCode >= 500) return true;
4726 return false;
4727 },
4728
4729 /**
4730 * @api private
4731 */
4732 networkingError: function networkingError(error) {
4733 return error.code === 'NetworkingError';
4734 },
4735
4736 /**
4737 * @api private
4738 */
4739 timeoutError: function timeoutError(error) {
4740 return error.code === 'TimeoutError';
4741 },
4742
4743 /**
4744 * @api private
4745 */
4746 expiredCredentialsError: function expiredCredentialsError(error) {
4747 // TODO : this only handles *one* of the expired credential codes
4748 return (error.code === 'ExpiredTokenException');
4749 },
4750
4751 /**
4752 * @api private
4753 */
4754 clockSkewError: function clockSkewError(error) {
4755 switch (error.code) {
4756 case 'RequestTimeTooSkewed':
4757 case 'RequestExpired':
4758 case 'InvalidSignatureException':
4759 case 'SignatureDoesNotMatch':
4760 case 'AuthFailure':
4761 case 'RequestInTheFuture':
4762 return true;
4763 default: return false;
4764 }
4765 },
4766
4767 /**
4768 * @api private
4769 */
4770 getSkewCorrectedDate: function getSkewCorrectedDate() {
4771 return new Date(Date.now() + this.config.systemClockOffset);
4772 },
4773
4774 /**
4775 * @api private
4776 */
4777 applyClockOffset: function applyClockOffset(newServerTime) {
4778 if (newServerTime) {
4779 this.config.systemClockOffset = newServerTime - Date.now();
4780 }
4781 },
4782
4783 /**
4784 * @api private
4785 */
4786 isClockSkewed: function isClockSkewed(newServerTime) {
4787 if (newServerTime) {
4788 return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 300000;
4789 }
4790 },
4791
4792 /**
4793 * @api private
4794 */
4795 throttledError: function throttledError(error) {
4796 // this logic varies between services
4797 if (error.statusCode === 429) return true;
4798 switch (error.code) {
4799 case 'ProvisionedThroughputExceededException':
4800 case 'Throttling':
4801 case 'ThrottlingException':
4802 case 'RequestLimitExceeded':
4803 case 'RequestThrottled':
4804 case 'RequestThrottledException':
4805 case 'TooManyRequestsException':
4806 case 'TransactionInProgressException': //dynamodb
4807 return true;
4808 default:
4809 return false;
4810 }
4811 },
4812
4813 /**
4814 * @api private
4815 */
4816 endpointFromTemplate: function endpointFromTemplate(endpoint) {
4817 if (typeof endpoint !== 'string') return endpoint;
4818
4819 var e = endpoint;
4820 e = e.replace(/\{service\}/g, this.api.endpointPrefix);
4821 e = e.replace(/\{region\}/g, this.config.region);
4822 e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http');
4823 return e;
4824 },
4825
4826 /**
4827 * @api private
4828 */
4829 setEndpoint: function setEndpoint(endpoint) {
4830 this.endpoint = new AWS.Endpoint(endpoint, this.config);
4831 },
4832
4833 /**
4834 * @api private
4835 */
4836 paginationConfig: function paginationConfig(operation, throwException) {
4837 var paginator = this.api.operations[operation].paginator;
4838 if (!paginator) {
4839 if (throwException) {
4840 var e = new Error();
4841 throw AWS.util.error(e, 'No pagination configuration for ' + operation);
4842 }
4843 return null;
4844 }
4845
4846 return paginator;
4847 }
4848 });
4849
4850 AWS.util.update(AWS.Service, {
4851
4852 /**
4853 * Adds one method for each operation described in the api configuration
4854 *
4855 * @api private
4856 */
4857 defineMethods: function defineMethods(svc) {
4858 AWS.util.each(svc.prototype.api.operations, function iterator(method) {
4859 if (svc.prototype[method]) return;
4860 var operation = svc.prototype.api.operations[method];
4861 if (operation.authtype === 'none') {
4862 svc.prototype[method] = function (params, callback) {
4863 return this.makeUnauthenticatedRequest(method, params, callback);
4864 };
4865 } else {
4866 svc.prototype[method] = function (params, callback) {
4867 return this.makeRequest(method, params, callback);
4868 };
4869 }
4870 });
4871 },
4872
4873 /**
4874 * Defines a new Service class using a service identifier and list of versions
4875 * including an optional set of features (functions) to apply to the class
4876 * prototype.
4877 *
4878 * @param serviceIdentifier [String] the identifier for the service
4879 * @param versions [Array<String>] a list of versions that work with this
4880 * service
4881 * @param features [Object] an object to attach to the prototype
4882 * @return [Class<Service>] the service class defined by this function.
4883 */
4884 defineService: function defineService(serviceIdentifier, versions, features) {
4885 AWS.Service._serviceMap[serviceIdentifier] = true;
4886 if (!Array.isArray(versions)) {
4887 features = versions;
4888 versions = [];
4889 }
4890
4891 var svc = inherit(AWS.Service, features || {});
4892
4893 if (typeof serviceIdentifier === 'string') {
4894 AWS.Service.addVersions(svc, versions);
4895
4896 var identifier = svc.serviceIdentifier || serviceIdentifier;
4897 svc.serviceIdentifier = identifier;
4898 } else { // defineService called with an API
4899 svc.prototype.api = serviceIdentifier;
4900 AWS.Service.defineMethods(svc);
4901 }
4902 AWS.SequentialExecutor.call(this.prototype);
4903 //util.clientSideMonitoring is only available in node
4904 if (!this.prototype.publisher && AWS.util.clientSideMonitoring) {
4905 var Publisher = AWS.util.clientSideMonitoring.Publisher;
4906 var configProvider = AWS.util.clientSideMonitoring.configProvider;
4907 var publisherConfig = configProvider();
4908 this.prototype.publisher = new Publisher(publisherConfig);
4909 if (publisherConfig.enabled) {
4910 //if csm is enabled in environment, SDK should send all metrics
4911 AWS.Service._clientSideMonitoring = true;
4912 }
4913 }
4914 AWS.SequentialExecutor.call(svc.prototype);
4915 AWS.Service.addDefaultMonitoringListeners(svc.prototype);
4916 return svc;
4917 },
4918
4919 /**
4920 * @api private
4921 */
4922 addVersions: function addVersions(svc, versions) {
4923 if (!Array.isArray(versions)) versions = [versions];
4924
4925 svc.services = svc.services || {};
4926 for (var i = 0; i < versions.length; i++) {
4927 if (svc.services[versions[i]] === undefined) {
4928 svc.services[versions[i]] = null;
4929 }
4930 }
4931
4932 svc.apiVersions = Object.keys(svc.services).sort();
4933 },
4934
4935 /**
4936 * @api private
4937 */
4938 defineServiceApi: function defineServiceApi(superclass, version, apiConfig) {
4939 var svc = inherit(superclass, {
4940 serviceIdentifier: superclass.serviceIdentifier
4941 });
4942
4943 function setApi(api) {
4944 if (api.isApi) {
4945 svc.prototype.api = api;
4946 } else {
4947 svc.prototype.api = new Api(api, {
4948 serviceIdentifier: superclass.serviceIdentifier
4949 });
4950 }
4951 }
4952
4953 if (typeof version === 'string') {
4954 if (apiConfig) {
4955 setApi(apiConfig);
4956 } else {
4957 try {
4958 setApi(AWS.apiLoader(superclass.serviceIdentifier, version));
4959 } catch (err) {
4960 throw AWS.util.error(err, {
4961 message: 'Could not find API configuration ' +
4962 superclass.serviceIdentifier + '-' + version
4963 });
4964 }
4965 }
4966 if (!Object.prototype.hasOwnProperty.call(superclass.services, version)) {
4967 superclass.apiVersions = superclass.apiVersions.concat(version).sort();
4968 }
4969 superclass.services[version] = svc;
4970 } else {
4971 setApi(version);
4972 }
4973
4974 AWS.Service.defineMethods(svc);
4975 return svc;
4976 },
4977
4978 /**
4979 * @api private
4980 */
4981 hasService: function(identifier) {
4982 return Object.prototype.hasOwnProperty.call(AWS.Service._serviceMap, identifier);
4983 },
4984
4985 /**
4986 * @param attachOn attach default monitoring listeners to object
4987 *
4988 * Each monitoring event should be emitted from service client to service constructor prototype and then
4989 * to global service prototype like bubbling up. These default monitoring events listener will transfer
4990 * the monitoring events to the upper layer.
4991 * @api private
4992 */
4993 addDefaultMonitoringListeners: function addDefaultMonitoringListeners(attachOn) {
4994 attachOn.addNamedListener('MONITOR_EVENTS_BUBBLE', 'apiCallAttempt', function EVENTS_BUBBLE(event) {
4995 var baseClass = Object.getPrototypeOf(attachOn);
4996 if (baseClass._events) baseClass.emit('apiCallAttempt', [event]);
4997 });
4998 attachOn.addNamedListener('CALL_EVENTS_BUBBLE', 'apiCall', function CALL_EVENTS_BUBBLE(event) {
4999 var baseClass = Object.getPrototypeOf(attachOn);
5000 if (baseClass._events) baseClass.emit('apiCall', [event]);
5001 });
5002 },
5003
5004 /**
5005 * @api private
5006 */
5007 _serviceMap: {}
5008 });
5009
5010 AWS.util.mixin(AWS.Service, AWS.SequentialExecutor);
5011
5012 /**
5013 * @api private
5014 */
5015 module.exports = AWS.Service;
5016
5017 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
5018
5019/***/ }),
5020/* 38 */
5021/***/ (function(module, exports, __webpack_require__) {
5022
5023 var util = __webpack_require__(2);
5024 var regionConfig = __webpack_require__(39);
5025
5026 function generateRegionPrefix(region) {
5027 if (!region) return null;
5028
5029 var parts = region.split('-');
5030 if (parts.length < 3) return null;
5031 return parts.slice(0, parts.length - 2).join('-') + '-*';
5032 }
5033
5034 function derivedKeys(service) {
5035 var region = service.config.region;
5036 var regionPrefix = generateRegionPrefix(region);
5037 var endpointPrefix = service.api.endpointPrefix;
5038
5039 return [
5040 [region, endpointPrefix],
5041 [regionPrefix, endpointPrefix],
5042 [region, '*'],
5043 [regionPrefix, '*'],
5044 ['*', endpointPrefix],
5045 ['*', '*']
5046 ].map(function(item) {
5047 return item[0] && item[1] ? item.join('/') : null;
5048 });
5049 }
5050
5051 function applyConfig(service, config) {
5052 util.each(config, function(key, value) {
5053 if (key === 'globalEndpoint') return;
5054 if (service.config[key] === undefined || service.config[key] === null) {
5055 service.config[key] = value;
5056 }
5057 });
5058 }
5059
5060 function configureEndpoint(service) {
5061 var keys = derivedKeys(service);
5062 for (var i = 0; i < keys.length; i++) {
5063 var key = keys[i];
5064 if (!key) continue;
5065
5066 if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) {
5067 var config = regionConfig.rules[key];
5068 if (typeof config === 'string') {
5069 config = regionConfig.patterns[config];
5070 }
5071
5072 // set dualstack endpoint
5073 if (service.config.useDualstack && util.isDualstackAvailable(service)) {
5074 config = util.copy(config);
5075 config.endpoint = '{service}.dualstack.{region}.amazonaws.com';
5076 }
5077
5078 // set global endpoint
5079 service.isGlobalEndpoint = !!config.globalEndpoint;
5080
5081 // signature version
5082 if (!config.signatureVersion) config.signatureVersion = 'v4';
5083
5084 // merge config
5085 applyConfig(service, config);
5086 return;
5087 }
5088 }
5089 }
5090
5091 function getEndpointSuffix(region) {
5092 var regionRegexes = {
5093 '^(us|eu|ap|sa|ca|me)\\-\\w+\\-\\d+$': 'amazonaws.com',
5094 '^cn\\-\\w+\\-\\d+$': 'amazonaws.com.cn',
5095 '^us\\-gov\\-\\w+\\-\\d+$': 'amazonaws.com',
5096 '^us\\-iso\\-\\w+\\-\\d+$': 'c2s.ic.gov',
5097 '^us\\-isob\\-\\w+\\-\\d+$': 'sc2s.sgov.gov'
5098 };
5099 var defaultSuffix = 'amazonaws.com';
5100 var regexes = Object.keys(regionRegexes);
5101 for (var i = 0; i < regexes.length; i++) {
5102 var regionPattern = RegExp(regexes[i]);
5103 var dnsSuffix = regionRegexes[regexes[i]];
5104 if (regionPattern.test(region)) return dnsSuffix;
5105 }
5106 return defaultSuffix;
5107 }
5108
5109 /**
5110 * @api private
5111 */
5112 module.exports = {
5113 configureEndpoint: configureEndpoint,
5114 getEndpointSuffix: getEndpointSuffix
5115 };
5116
5117
5118/***/ }),
5119/* 39 */
5120/***/ (function(module, exports) {
5121
5122 module.exports = {"rules":{"*/*":{"endpoint":"{service}.{region}.amazonaws.com"},"cn-*/*":{"endpoint":"{service}.{region}.amazonaws.com.cn"},"us-iso-*/*":{"endpoint":"{service}.{region}.c2s.ic.gov"},"us-isob-*/*":{"endpoint":"{service}.{region}.sc2s.sgov.gov"},"*/budgets":"globalSSL","*/cloudfront":"globalSSL","*/iam":"globalSSL","*/sts":"globalSSL","*/importexport":{"endpoint":"{service}.amazonaws.com","signatureVersion":"v2","globalEndpoint":true},"*/route53":{"endpoint":"https://{service}.amazonaws.com","signatureVersion":"v3https","globalEndpoint":true},"*/waf":"globalSSL","us-gov-*/iam":"globalGovCloud","us-gov-*/sts":{"endpoint":"{service}.{region}.amazonaws.com"},"us-gov-west-1/s3":"s3signature","us-west-1/s3":"s3signature","us-west-2/s3":"s3signature","eu-west-1/s3":"s3signature","ap-southeast-1/s3":"s3signature","ap-southeast-2/s3":"s3signature","ap-northeast-1/s3":"s3signature","sa-east-1/s3":"s3signature","us-east-1/s3":{"endpoint":"{service}.amazonaws.com","signatureVersion":"s3"},"us-east-1/sdb":{"endpoint":"{service}.amazonaws.com","signatureVersion":"v2"},"*/sdb":{"endpoint":"{service}.{region}.amazonaws.com","signatureVersion":"v2"}},"patterns":{"globalSSL":{"endpoint":"https://{service}.amazonaws.com","globalEndpoint":true},"globalGovCloud":{"endpoint":"{service}.us-gov.amazonaws.com"},"s3signature":{"endpoint":"{service}.{region}.amazonaws.com","signatureVersion":"s3"}}}
5123
5124/***/ }),
5125/* 40 */
5126/***/ (function(module, exports, __webpack_require__) {
5127
5128 var AWS = __webpack_require__(1);
5129 __webpack_require__(41);
5130 __webpack_require__(42);
5131 var PromisesDependency;
5132
5133 /**
5134 * The main configuration class used by all service objects to set
5135 * the region, credentials, and other options for requests.
5136 *
5137 * By default, credentials and region settings are left unconfigured.
5138 * This should be configured by the application before using any
5139 * AWS service APIs.
5140 *
5141 * In order to set global configuration options, properties should
5142 * be assigned to the global {AWS.config} object.
5143 *
5144 * @see AWS.config
5145 *
5146 * @!group General Configuration Options
5147 *
5148 * @!attribute credentials
5149 * @return [AWS.Credentials] the AWS credentials to sign requests with.
5150 *
5151 * @!attribute region
5152 * @example Set the global region setting to us-west-2
5153 * AWS.config.update({region: 'us-west-2'});
5154 * @return [AWS.Credentials] The region to send service requests to.
5155 * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
5156 * A list of available endpoints for each AWS service
5157 *
5158 * @!attribute maxRetries
5159 * @return [Integer] the maximum amount of retries to perform for a
5160 * service request. By default this value is calculated by the specific
5161 * service object that the request is being made to.
5162 *
5163 * @!attribute maxRedirects
5164 * @return [Integer] the maximum amount of redirects to follow for a
5165 * service request. Defaults to 10.
5166 *
5167 * @!attribute paramValidation
5168 * @return [Boolean|map] whether input parameters should be validated against
5169 * the operation description before sending the request. Defaults to true.
5170 * Pass a map to enable any of the following specific validation features:
5171 *
5172 * * **min** [Boolean] &mdash; Validates that a value meets the min
5173 * constraint. This is enabled by default when paramValidation is set
5174 * to `true`.
5175 * * **max** [Boolean] &mdash; Validates that a value meets the max
5176 * constraint.
5177 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5178 * regular expression.
5179 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5180 * of the allowable enum values.
5181 *
5182 * @!attribute computeChecksums
5183 * @return [Boolean] whether to compute checksums for payload bodies when
5184 * the service accepts it (currently supported in S3 only).
5185 *
5186 * @!attribute convertResponseTypes
5187 * @return [Boolean] whether types are converted when parsing response data.
5188 * Currently only supported for JSON based services. Turning this off may
5189 * improve performance on large response payloads. Defaults to `true`.
5190 *
5191 * @!attribute correctClockSkew
5192 * @return [Boolean] whether to apply a clock skew correction and retry
5193 * requests that fail because of an skewed client clock. Defaults to
5194 * `false`.
5195 *
5196 * @!attribute sslEnabled
5197 * @return [Boolean] whether SSL is enabled for requests
5198 *
5199 * @!attribute s3ForcePathStyle
5200 * @return [Boolean] whether to force path style URLs for S3 objects
5201 *
5202 * @!attribute s3BucketEndpoint
5203 * @note Setting this configuration option requires an `endpoint` to be
5204 * provided explicitly to the service constructor.
5205 * @return [Boolean] whether the provided endpoint addresses an individual
5206 * bucket (false if it addresses the root API endpoint).
5207 *
5208 * @!attribute s3DisableBodySigning
5209 * @return [Boolean] whether to disable S3 body signing when using signature version `v4`.
5210 * Body signing can only be disabled when using https. Defaults to `true`.
5211 *
5212 * @!attribute s3UsEast1RegionalEndpoint
5213 * @return ['legacy'|'regional'] when region is set to 'us-east-1', whether to send s3
5214 * request to global endpoints or 'us-east-1' regional endpoints. This config is only
5215 * applicable to S3 client;
5216 * Defaults to 'legacy'
5217 * @!attribute s3UseArnRegion
5218 * @return [Boolean] whether to override the request region with the region inferred
5219 * from requested resource's ARN. Only available for S3 buckets
5220 * Defaults to `true`
5221 *
5222 * @!attribute useAccelerateEndpoint
5223 * @note This configuration option is only compatible with S3 while accessing
5224 * dns-compatible buckets.
5225 * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service.
5226 * Defaults to `false`.
5227 *
5228 * @!attribute retryDelayOptions
5229 * @example Set the base retry delay for all services to 300 ms
5230 * AWS.config.update({retryDelayOptions: {base: 300}});
5231 * // Delays with maxRetries = 3: 300, 600, 1200
5232 * @example Set a custom backoff function to provide delay values on retries
5233 * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount, err) {
5234 * // returns delay in ms
5235 * }}});
5236 * @return [map] A set of options to configure the retry delay on retryable errors.
5237 * Currently supported options are:
5238 *
5239 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5240 * exponential backoff for operation retries. Defaults to 100 ms for all services except
5241 * DynamoDB, where it defaults to 50ms.
5242 *
5243 * * **customBackoff ** [function] &mdash; A custom function that accepts a
5244 * retry count and error and returns the amount of time to delay in
5245 * milliseconds. If the result is a non-zero negative value, no further
5246 * retry attempts will be made. The `base` option will be ignored if this
5247 * option is supplied.
5248 *
5249 * @!attribute httpOptions
5250 * @return [map] A set of options to pass to the low-level HTTP request.
5251 * Currently supported options are:
5252 *
5253 * * **proxy** [String] &mdash; the URL to proxy requests through
5254 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5255 * HTTP requests with. Used for connection pooling. Note that for
5256 * SSL connections, a special Agent object is used in order to enable
5257 * peer certificate verification. This feature is only supported in the
5258 * Node.js environment.
5259 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5260 * failing to establish a connection with the server after
5261 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5262 * connection has been established.
5263 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5264 * milliseconds of inactivity on the socket. Defaults to two minutes
5265 * (120000)
5266 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5267 * HTTP requests. Used in the browser environment only. Set to false to
5268 * send requests synchronously. Defaults to true (async on).
5269 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5270 * property of an XMLHttpRequest object. Used in the browser environment
5271 * only. Defaults to false.
5272 * @!attribute logger
5273 * @return [#write,#log] an object that responds to .write() (like a stream)
5274 * or .log() (like the console object) in order to log information about
5275 * requests
5276 *
5277 * @!attribute systemClockOffset
5278 * @return [Number] an offset value in milliseconds to apply to all signing
5279 * times. Use this to compensate for clock skew when your system may be
5280 * out of sync with the service time. Note that this configuration option
5281 * can only be applied to the global `AWS.config` object and cannot be
5282 * overridden in service-specific configuration. Defaults to 0 milliseconds.
5283 *
5284 * @!attribute signatureVersion
5285 * @return [String] the signature version to sign requests with (overriding
5286 * the API configuration). Possible values are: 'v2', 'v3', 'v4'.
5287 *
5288 * @!attribute signatureCache
5289 * @return [Boolean] whether the signature to sign requests with (overriding
5290 * the API configuration) is cached. Only applies to the signature version 'v4'.
5291 * Defaults to `true`.
5292 *
5293 * @!attribute endpointDiscoveryEnabled
5294 * @return [Boolean] whether to enable endpoint discovery for operations that
5295 * allow optionally using an endpoint returned by the service.
5296 * Defaults to 'false'
5297 *
5298 * @!attribute endpointCacheSize
5299 * @return [Number] the size of the global cache storing endpoints from endpoint
5300 * discovery operations. Once endpoint cache is created, updating this setting
5301 * cannot change existing cache size.
5302 * Defaults to 1000
5303 *
5304 * @!attribute hostPrefixEnabled
5305 * @return [Boolean] whether to marshal request parameters to the prefix of
5306 * hostname. Defaults to `true`.
5307 *
5308 * @!attribute stsRegionalEndpoints
5309 * @return ['legacy'|'regional'] whether to send sts request to global endpoints or
5310 * regional endpoints.
5311 * Defaults to 'legacy'
5312 */
5313 AWS.Config = AWS.util.inherit({
5314 /**
5315 * @!endgroup
5316 */
5317
5318 /**
5319 * Creates a new configuration object. This is the object that passes
5320 * option data along to service requests, including credentials, security,
5321 * region information, and some service specific settings.
5322 *
5323 * @example Creating a new configuration object with credentials and region
5324 * var config = new AWS.Config({
5325 * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
5326 * });
5327 * @option options accessKeyId [String] your AWS access key ID.
5328 * @option options secretAccessKey [String] your AWS secret access key.
5329 * @option options sessionToken [AWS.Credentials] the optional AWS
5330 * session token to sign requests with.
5331 * @option options credentials [AWS.Credentials] the AWS credentials
5332 * to sign requests with. You can either specify this object, or
5333 * specify the accessKeyId and secretAccessKey options directly.
5334 * @option options credentialProvider [AWS.CredentialProviderChain] the
5335 * provider chain used to resolve credentials if no static `credentials`
5336 * property is set.
5337 * @option options region [String] the region to send service requests to.
5338 * See {region} for more information.
5339 * @option options maxRetries [Integer] the maximum amount of retries to
5340 * attempt with a request. See {maxRetries} for more information.
5341 * @option options maxRedirects [Integer] the maximum amount of redirects to
5342 * follow with a request. See {maxRedirects} for more information.
5343 * @option options sslEnabled [Boolean] whether to enable SSL for
5344 * requests.
5345 * @option options paramValidation [Boolean|map] whether input parameters
5346 * should be validated against the operation description before sending
5347 * the request. Defaults to true. Pass a map to enable any of the
5348 * following specific validation features:
5349 *
5350 * * **min** [Boolean] &mdash; Validates that a value meets the min
5351 * constraint. This is enabled by default when paramValidation is set
5352 * to `true`.
5353 * * **max** [Boolean] &mdash; Validates that a value meets the max
5354 * constraint.
5355 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5356 * regular expression.
5357 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5358 * of the allowable enum values.
5359 * @option options computeChecksums [Boolean] whether to compute checksums
5360 * for payload bodies when the service accepts it (currently supported
5361 * in S3 only)
5362 * @option options convertResponseTypes [Boolean] whether types are converted
5363 * when parsing response data. Currently only supported for JSON based
5364 * services. Turning this off may improve performance on large response
5365 * payloads. Defaults to `true`.
5366 * @option options correctClockSkew [Boolean] whether to apply a clock skew
5367 * correction and retry requests that fail because of an skewed client
5368 * clock. Defaults to `false`.
5369 * @option options s3ForcePathStyle [Boolean] whether to force path
5370 * style URLs for S3 objects.
5371 * @option options s3BucketEndpoint [Boolean] whether the provided endpoint
5372 * addresses an individual bucket (false if it addresses the root API
5373 * endpoint). Note that setting this configuration option requires an
5374 * `endpoint` to be provided explicitly to the service constructor.
5375 * @option options s3DisableBodySigning [Boolean] whether S3 body signing
5376 * should be disabled when using signature version `v4`. Body signing
5377 * can only be disabled when using https. Defaults to `true`.
5378 * @option options s3UsEast1RegionalEndpoint ['legacy'|'regional'] when region
5379 * is set to 'us-east-1', whether to send s3 request to global endpoints or
5380 * 'us-east-1' regional endpoints. This config is only applicable to S3 client.
5381 * Defaults to `legacy`
5382 * @option options s3UseArnRegion [Boolean] whether to override the request region
5383 * with the region inferred from requested resource's ARN. Only available for S3 buckets
5384 * Defaults to `true`
5385 *
5386 * @option options retryDelayOptions [map] A set of options to configure
5387 * the retry delay on retryable errors. Currently supported options are:
5388 *
5389 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5390 * exponential backoff for operation retries. Defaults to 100 ms for all
5391 * services except DynamoDB, where it defaults to 50ms.
5392 * * **customBackoff ** [function] &mdash; A custom function that accepts a
5393 * retry count and error and returns the amount of time to delay in
5394 * milliseconds. If the result is a non-zero negative value, no further
5395 * retry attempts will be made. The `base` option will be ignored if this
5396 * option is supplied.
5397 * @option options httpOptions [map] A set of options to pass to the low-level
5398 * HTTP request. Currently supported options are:
5399 *
5400 * * **proxy** [String] &mdash; the URL to proxy requests through
5401 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5402 * HTTP requests with. Used for connection pooling. Defaults to the global
5403 * agent (`http.globalAgent`) for non-SSL connections. Note that for
5404 * SSL connections, a special Agent object is used in order to enable
5405 * peer certificate verification. This feature is only available in the
5406 * Node.js environment.
5407 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5408 * failing to establish a connection with the server after
5409 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5410 * connection has been established.
5411 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5412 * milliseconds of inactivity on the socket. Defaults to two minutes
5413 * (120000).
5414 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5415 * HTTP requests. Used in the browser environment only. Set to false to
5416 * send requests synchronously. Defaults to true (async on).
5417 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5418 * property of an XMLHttpRequest object. Used in the browser environment
5419 * only. Defaults to false.
5420 * @option options apiVersion [String, Date] a String in YYYY-MM-DD format
5421 * (or a date) that represents the latest possible API version that can be
5422 * used in all services (unless overridden by `apiVersions`). Specify
5423 * 'latest' to use the latest possible version.
5424 * @option options apiVersions [map<String, String|Date>] a map of service
5425 * identifiers (the lowercase service class name) with the API version to
5426 * use when instantiating a service. Specify 'latest' for each individual
5427 * that can use the latest available version.
5428 * @option options logger [#write,#log] an object that responds to .write()
5429 * (like a stream) or .log() (like the console object) in order to log
5430 * information about requests
5431 * @option options systemClockOffset [Number] an offset value in milliseconds
5432 * to apply to all signing times. Use this to compensate for clock skew
5433 * when your system may be out of sync with the service time. Note that
5434 * this configuration option can only be applied to the global `AWS.config`
5435 * object and cannot be overridden in service-specific configuration.
5436 * Defaults to 0 milliseconds.
5437 * @option options signatureVersion [String] the signature version to sign
5438 * requests with (overriding the API configuration). Possible values are:
5439 * 'v2', 'v3', 'v4'.
5440 * @option options signatureCache [Boolean] whether the signature to sign
5441 * requests with (overriding the API configuration) is cached. Only applies
5442 * to the signature version 'v4'. Defaults to `true`.
5443 * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32
5444 * checksum of HTTP response bodies returned by DynamoDB. Default: `true`.
5445 * @option options useAccelerateEndpoint [Boolean] Whether to use the
5446 * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`.
5447 * @option options clientSideMonitoring [Boolean] whether to collect and
5448 * publish this client's performance metrics of all its API requests.
5449 * @option options endpointDiscoveryEnabled [Boolean] whether to enable endpoint
5450 * discovery for operations that allow optionally using an endpoint returned by
5451 * the service.
5452 * Defaults to 'false'
5453 * @option options endpointCacheSize [Number] the size of the global cache storing
5454 * endpoints from endpoint discovery operations. Once endpoint cache is created,
5455 * updating this setting cannot change existing cache size.
5456 * Defaults to 1000
5457 * @option options hostPrefixEnabled [Boolean] whether to marshal request
5458 * parameters to the prefix of hostname.
5459 * Defaults to `true`.
5460 * @option options stsRegionalEndpoints ['legacy'|'regional'] whether to send sts request
5461 * to global endpoints or regional endpoints.
5462 * Defaults to 'legacy'.
5463 */
5464 constructor: function Config(options) {
5465 if (options === undefined) options = {};
5466 options = this.extractCredentials(options);
5467
5468 AWS.util.each.call(this, this.keys, function (key, value) {
5469 this.set(key, options[key], value);
5470 });
5471 },
5472
5473 /**
5474 * @!group Managing Credentials
5475 */
5476
5477 /**
5478 * Loads credentials from the configuration object. This is used internally
5479 * by the SDK to ensure that refreshable {Credentials} objects are properly
5480 * refreshed and loaded when sending a request. If you want to ensure that
5481 * your credentials are loaded prior to a request, you can use this method
5482 * directly to provide accurate credential data stored in the object.
5483 *
5484 * @note If you configure the SDK with static or environment credentials,
5485 * the credential data should already be present in {credentials} attribute.
5486 * This method is primarily necessary to load credentials from asynchronous
5487 * sources, or sources that can refresh credentials periodically.
5488 * @example Getting your access key
5489 * AWS.config.getCredentials(function(err) {
5490 * if (err) console.log(err.stack); // credentials not loaded
5491 * else console.log("Access Key:", AWS.config.credentials.accessKeyId);
5492 * })
5493 * @callback callback function(err)
5494 * Called when the {credentials} have been properly set on the configuration
5495 * object.
5496 *
5497 * @param err [Error] if this is set, credentials were not successfully
5498 * loaded and this error provides information why.
5499 * @see credentials
5500 * @see Credentials
5501 */
5502 getCredentials: function getCredentials(callback) {
5503 var self = this;
5504
5505 function finish(err) {
5506 callback(err, err ? null : self.credentials);
5507 }
5508
5509 function credError(msg, err) {
5510 return new AWS.util.error(err || new Error(), {
5511 code: 'CredentialsError',
5512 message: msg,
5513 name: 'CredentialsError'
5514 });
5515 }
5516
5517 function getAsyncCredentials() {
5518 self.credentials.get(function(err) {
5519 if (err) {
5520 var msg = 'Could not load credentials from ' +
5521 self.credentials.constructor.name;
5522 err = credError(msg, err);
5523 }
5524 finish(err);
5525 });
5526 }
5527
5528 function getStaticCredentials() {
5529 var err = null;
5530 if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
5531 err = credError('Missing credentials');
5532 }
5533 finish(err);
5534 }
5535
5536 if (self.credentials) {
5537 if (typeof self.credentials.get === 'function') {
5538 getAsyncCredentials();
5539 } else { // static credentials
5540 getStaticCredentials();
5541 }
5542 } else if (self.credentialProvider) {
5543 self.credentialProvider.resolve(function(err, creds) {
5544 if (err) {
5545 err = credError('Could not load credentials from any providers', err);
5546 }
5547 self.credentials = creds;
5548 finish(err);
5549 });
5550 } else {
5551 finish(credError('No credentials to load'));
5552 }
5553 },
5554
5555 /**
5556 * @!group Loading and Setting Configuration Options
5557 */
5558
5559 /**
5560 * @overload update(options, allowUnknownKeys = false)
5561 * Updates the current configuration object with new options.
5562 *
5563 * @example Update maxRetries property of a configuration object
5564 * config.update({maxRetries: 10});
5565 * @param [Object] options a map of option keys and values.
5566 * @param [Boolean] allowUnknownKeys whether unknown keys can be set on
5567 * the configuration object. Defaults to `false`.
5568 * @see constructor
5569 */
5570 update: function update(options, allowUnknownKeys) {
5571 allowUnknownKeys = allowUnknownKeys || false;
5572 options = this.extractCredentials(options);
5573 AWS.util.each.call(this, options, function (key, value) {
5574 if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) ||
5575 AWS.Service.hasService(key)) {
5576 this.set(key, value);
5577 }
5578 });
5579 },
5580
5581 /**
5582 * Loads configuration data from a JSON file into this config object.
5583 * @note Loading configuration will reset all existing configuration
5584 * on the object.
5585 * @!macro nobrowser
5586 * @param path [String] the path relative to your process's current
5587 * working directory to load configuration from.
5588 * @return [AWS.Config] the same configuration object
5589 */
5590 loadFromPath: function loadFromPath(path) {
5591 this.clear();
5592
5593 var options = JSON.parse(AWS.util.readFileSync(path));
5594 var fileSystemCreds = new AWS.FileSystemCredentials(path);
5595 var chain = new AWS.CredentialProviderChain();
5596 chain.providers.unshift(fileSystemCreds);
5597 chain.resolve(function (err, creds) {
5598 if (err) throw err;
5599 else options.credentials = creds;
5600 });
5601
5602 this.constructor(options);
5603
5604 return this;
5605 },
5606
5607 /**
5608 * Clears configuration data on this object
5609 *
5610 * @api private
5611 */
5612 clear: function clear() {
5613 /*jshint forin:false */
5614 AWS.util.each.call(this, this.keys, function (key) {
5615 delete this[key];
5616 });
5617
5618 // reset credential provider
5619 this.set('credentials', undefined);
5620 this.set('credentialProvider', undefined);
5621 },
5622
5623 /**
5624 * Sets a property on the configuration object, allowing for a
5625 * default value
5626 * @api private
5627 */
5628 set: function set(property, value, defaultValue) {
5629 if (value === undefined) {
5630 if (defaultValue === undefined) {
5631 defaultValue = this.keys[property];
5632 }
5633 if (typeof defaultValue === 'function') {
5634 this[property] = defaultValue.call(this);
5635 } else {
5636 this[property] = defaultValue;
5637 }
5638 } else if (property === 'httpOptions' && this[property]) {
5639 // deep merge httpOptions
5640 this[property] = AWS.util.merge(this[property], value);
5641 } else {
5642 this[property] = value;
5643 }
5644 },
5645
5646 /**
5647 * All of the keys with their default values.
5648 *
5649 * @constant
5650 * @api private
5651 */
5652 keys: {
5653 credentials: null,
5654 credentialProvider: null,
5655 region: null,
5656 logger: null,
5657 apiVersions: {},
5658 apiVersion: null,
5659 endpoint: undefined,
5660 httpOptions: {
5661 timeout: 120000
5662 },
5663 maxRetries: undefined,
5664 maxRedirects: 10,
5665 paramValidation: true,
5666 sslEnabled: true,
5667 s3ForcePathStyle: false,
5668 s3BucketEndpoint: false,
5669 s3DisableBodySigning: true,
5670 s3UsEast1RegionalEndpoint: 'legacy',
5671 s3UseArnRegion: undefined,
5672 computeChecksums: true,
5673 convertResponseTypes: true,
5674 correctClockSkew: false,
5675 customUserAgent: null,
5676 dynamoDbCrc32: true,
5677 systemClockOffset: 0,
5678 signatureVersion: null,
5679 signatureCache: true,
5680 retryDelayOptions: {},
5681 useAccelerateEndpoint: false,
5682 clientSideMonitoring: false,
5683 endpointDiscoveryEnabled: false,
5684 endpointCacheSize: 1000,
5685 hostPrefixEnabled: true,
5686 stsRegionalEndpoints: 'legacy'
5687 },
5688
5689 /**
5690 * Extracts accessKeyId, secretAccessKey and sessionToken
5691 * from a configuration hash.
5692 *
5693 * @api private
5694 */
5695 extractCredentials: function extractCredentials(options) {
5696 if (options.accessKeyId && options.secretAccessKey) {
5697 options = AWS.util.copy(options);
5698 options.credentials = new AWS.Credentials(options);
5699 }
5700 return options;
5701 },
5702
5703 /**
5704 * Sets the promise dependency the SDK will use wherever Promises are returned.
5705 * Passing `null` will force the SDK to use native Promises if they are available.
5706 * If native Promises are not available, passing `null` will have no effect.
5707 * @param [Constructor] dep A reference to a Promise constructor
5708 */
5709 setPromisesDependency: function setPromisesDependency(dep) {
5710 PromisesDependency = dep;
5711 // if null was passed in, we should try to use native promises
5712 if (dep === null && typeof Promise === 'function') {
5713 PromisesDependency = Promise;
5714 }
5715 var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain];
5716 if (AWS.S3) {
5717 constructors.push(AWS.S3);
5718 if (AWS.S3.ManagedUpload) {
5719 constructors.push(AWS.S3.ManagedUpload);
5720 }
5721 }
5722 AWS.util.addPromises(constructors, PromisesDependency);
5723 },
5724
5725 /**
5726 * Gets the promise dependency set by `AWS.config.setPromisesDependency`.
5727 */
5728 getPromisesDependency: function getPromisesDependency() {
5729 return PromisesDependency;
5730 }
5731 });
5732
5733 /**
5734 * @return [AWS.Config] The global configuration object singleton instance
5735 * @readonly
5736 * @see AWS.Config
5737 */
5738 AWS.config = new AWS.Config();
5739
5740
5741/***/ }),
5742/* 41 */
5743/***/ (function(module, exports, __webpack_require__) {
5744
5745 var AWS = __webpack_require__(1);
5746
5747 /**
5748 * Represents your AWS security credentials, specifically the
5749 * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}.
5750 * Creating a `Credentials` object allows you to pass around your
5751 * security information to configuration and service objects.
5752 *
5753 * Note that this class typically does not need to be constructed manually,
5754 * as the {AWS.Config} and {AWS.Service} classes both accept simple
5755 * options hashes with the three keys. These structures will be converted
5756 * into Credentials objects automatically.
5757 *
5758 * ## Expiring and Refreshing Credentials
5759 *
5760 * Occasionally credentials can expire in the middle of a long-running
5761 * application. In this case, the SDK will automatically attempt to
5762 * refresh the credentials from the storage location if the Credentials
5763 * class implements the {refresh} method.
5764 *
5765 * If you are implementing a credential storage location, you
5766 * will want to create a subclass of the `Credentials` class and
5767 * override the {refresh} method. This method allows credentials to be
5768 * retrieved from the backing store, be it a file system, database, or
5769 * some network storage. The method should reset the credential attributes
5770 * on the object.
5771 *
5772 * @!attribute expired
5773 * @return [Boolean] whether the credentials have been expired and
5774 * require a refresh. Used in conjunction with {expireTime}.
5775 * @!attribute expireTime
5776 * @return [Date] a time when credentials should be considered expired. Used
5777 * in conjunction with {expired}.
5778 * @!attribute accessKeyId
5779 * @return [String] the AWS access key ID
5780 * @!attribute secretAccessKey
5781 * @return [String] the AWS secret access key
5782 * @!attribute sessionToken
5783 * @return [String] an optional AWS session token
5784 */
5785 AWS.Credentials = AWS.util.inherit({
5786 /**
5787 * A credentials object can be created using positional arguments or an options
5788 * hash.
5789 *
5790 * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
5791 * Creates a Credentials object with a given set of credential information
5792 * as positional arguments.
5793 * @param accessKeyId [String] the AWS access key ID
5794 * @param secretAccessKey [String] the AWS secret access key
5795 * @param sessionToken [String] the optional AWS session token
5796 * @example Create a credentials object with AWS credentials
5797 * var creds = new AWS.Credentials('akid', 'secret', 'session');
5798 * @overload AWS.Credentials(options)
5799 * Creates a Credentials object with a given set of credential information
5800 * as an options hash.
5801 * @option options accessKeyId [String] the AWS access key ID
5802 * @option options secretAccessKey [String] the AWS secret access key
5803 * @option options sessionToken [String] the optional AWS session token
5804 * @example Create a credentials object with AWS credentials
5805 * var creds = new AWS.Credentials({
5806 * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
5807 * });
5808 */
5809 constructor: function Credentials() {
5810 // hide secretAccessKey from being displayed with util.inspect
5811 AWS.util.hideProperties(this, ['secretAccessKey']);
5812
5813 this.expired = false;
5814 this.expireTime = null;
5815 this.refreshCallbacks = [];
5816 if (arguments.length === 1 && typeof arguments[0] === 'object') {
5817 var creds = arguments[0].credentials || arguments[0];
5818 this.accessKeyId = creds.accessKeyId;
5819 this.secretAccessKey = creds.secretAccessKey;
5820 this.sessionToken = creds.sessionToken;
5821 } else {
5822 this.accessKeyId = arguments[0];
5823 this.secretAccessKey = arguments[1];
5824 this.sessionToken = arguments[2];
5825 }
5826 },
5827
5828 /**
5829 * @return [Integer] the number of seconds before {expireTime} during which
5830 * the credentials will be considered expired.
5831 */
5832 expiryWindow: 15,
5833
5834 /**
5835 * @return [Boolean] whether the credentials object should call {refresh}
5836 * @note Subclasses should override this method to provide custom refresh
5837 * logic.
5838 */
5839 needsRefresh: function needsRefresh() {
5840 var currentTime = AWS.util.date.getDate().getTime();
5841 var adjustedTime = new Date(currentTime + this.expiryWindow * 1000);
5842
5843 if (this.expireTime && adjustedTime > this.expireTime) {
5844 return true;
5845 } else {
5846 return this.expired || !this.accessKeyId || !this.secretAccessKey;
5847 }
5848 },
5849
5850 /**
5851 * Gets the existing credentials, refreshing them if they are not yet loaded
5852 * or have expired. Users should call this method before using {refresh},
5853 * as this will not attempt to reload credentials when they are already
5854 * loaded into the object.
5855 *
5856 * @callback callback function(err)
5857 * When this callback is called with no error, it means either credentials
5858 * do not need to be refreshed or refreshed credentials information has
5859 * been loaded into the object (as the `accessKeyId`, `secretAccessKey`,
5860 * and `sessionToken` properties).
5861 * @param err [Error] if an error occurred, this value will be filled
5862 */
5863 get: function get(callback) {
5864 var self = this;
5865 if (this.needsRefresh()) {
5866 this.refresh(function(err) {
5867 if (!err) self.expired = false; // reset expired flag
5868 if (callback) callback(err);
5869 });
5870 } else if (callback) {
5871 callback();
5872 }
5873 },
5874
5875 /**
5876 * @!method getPromise()
5877 * Returns a 'thenable' promise.
5878 * Gets the existing credentials, refreshing them if they are not yet loaded
5879 * or have expired. Users should call this method before using {refresh},
5880 * as this will not attempt to reload credentials when they are already
5881 * loaded into the object.
5882 *
5883 * Two callbacks can be provided to the `then` method on the returned promise.
5884 * The first callback will be called if the promise is fulfilled, and the second
5885 * callback will be called if the promise is rejected.
5886 * @callback fulfilledCallback function()
5887 * Called if the promise is fulfilled. When this callback is called, it
5888 * means either credentials do not need to be refreshed or refreshed
5889 * credentials information has been loaded into the object (as the
5890 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5891 * @callback rejectedCallback function(err)
5892 * Called if the promise is rejected.
5893 * @param err [Error] if an error occurred, this value will be filled
5894 * @return [Promise] A promise that represents the state of the `get` call.
5895 * @example Calling the `getPromise` method.
5896 * var promise = credProvider.getPromise();
5897 * promise.then(function() { ... }, function(err) { ... });
5898 */
5899
5900 /**
5901 * @!method refreshPromise()
5902 * Returns a 'thenable' promise.
5903 * Refreshes the credentials. Users should call {get} before attempting
5904 * to forcibly refresh credentials.
5905 *
5906 * Two callbacks can be provided to the `then` method on the returned promise.
5907 * The first callback will be called if the promise is fulfilled, and the second
5908 * callback will be called if the promise is rejected.
5909 * @callback fulfilledCallback function()
5910 * Called if the promise is fulfilled. When this callback is called, it
5911 * means refreshed credentials information has been loaded into the object
5912 * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5913 * @callback rejectedCallback function(err)
5914 * Called if the promise is rejected.
5915 * @param err [Error] if an error occurred, this value will be filled
5916 * @return [Promise] A promise that represents the state of the `refresh` call.
5917 * @example Calling the `refreshPromise` method.
5918 * var promise = credProvider.refreshPromise();
5919 * promise.then(function() { ... }, function(err) { ... });
5920 */
5921
5922 /**
5923 * Refreshes the credentials. Users should call {get} before attempting
5924 * to forcibly refresh credentials.
5925 *
5926 * @callback callback function(err)
5927 * When this callback is called with no error, it means refreshed
5928 * credentials information has been loaded into the object (as the
5929 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5930 * @param err [Error] if an error occurred, this value will be filled
5931 * @note Subclasses should override this class to reset the
5932 * {accessKeyId}, {secretAccessKey} and optional {sessionToken}
5933 * on the credentials object and then call the callback with
5934 * any error information.
5935 * @see get
5936 */
5937 refresh: function refresh(callback) {
5938 this.expired = false;
5939 callback();
5940 },
5941
5942 /**
5943 * @api private
5944 * @param callback
5945 */
5946 coalesceRefresh: function coalesceRefresh(callback, sync) {
5947 var self = this;
5948 if (self.refreshCallbacks.push(callback) === 1) {
5949 self.load(function onLoad(err) {
5950 AWS.util.arrayEach(self.refreshCallbacks, function(callback) {
5951 if (sync) {
5952 callback(err);
5953 } else {
5954 // callback could throw, so defer to ensure all callbacks are notified
5955 AWS.util.defer(function () {
5956 callback(err);
5957 });
5958 }
5959 });
5960 self.refreshCallbacks.length = 0;
5961 });
5962 }
5963 },
5964
5965 /**
5966 * @api private
5967 * @param callback
5968 */
5969 load: function load(callback) {
5970 callback();
5971 }
5972 });
5973
5974 /**
5975 * @api private
5976 */
5977 AWS.Credentials.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
5978 this.prototype.getPromise = AWS.util.promisifyMethod('get', PromiseDependency);
5979 this.prototype.refreshPromise = AWS.util.promisifyMethod('refresh', PromiseDependency);
5980 };
5981
5982 /**
5983 * @api private
5984 */
5985 AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() {
5986 delete this.prototype.getPromise;
5987 delete this.prototype.refreshPromise;
5988 };
5989
5990 AWS.util.addPromises(AWS.Credentials);
5991
5992
5993/***/ }),
5994/* 42 */
5995/***/ (function(module, exports, __webpack_require__) {
5996
5997 var AWS = __webpack_require__(1);
5998
5999 /**
6000 * Creates a credential provider chain that searches for AWS credentials
6001 * in a list of credential providers specified by the {providers} property.
6002 *
6003 * By default, the chain will use the {defaultProviders} to resolve credentials.
6004 * These providers will look in the environment using the
6005 * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes.
6006 *
6007 * ## Setting Providers
6008 *
6009 * Each provider in the {providers} list should be a function that returns
6010 * a {AWS.Credentials} object, or a hardcoded credentials object. The function
6011 * form allows for delayed execution of the credential construction.
6012 *
6013 * ## Resolving Credentials from a Chain
6014 *
6015 * Call {resolve} to return the first valid credential object that can be
6016 * loaded by the provider chain.
6017 *
6018 * For example, to resolve a chain with a custom provider that checks a file
6019 * on disk after the set of {defaultProviders}:
6020 *
6021 * ```javascript
6022 * var diskProvider = new AWS.FileSystemCredentials('./creds.json');
6023 * var chain = new AWS.CredentialProviderChain();
6024 * chain.providers.push(diskProvider);
6025 * chain.resolve();
6026 * ```
6027 *
6028 * The above code will return the `diskProvider` object if the
6029 * file contains credentials and the `defaultProviders` do not contain
6030 * any credential settings.
6031 *
6032 * @!attribute providers
6033 * @return [Array<AWS.Credentials, Function>]
6034 * a list of credentials objects or functions that return credentials
6035 * objects. If the provider is a function, the function will be
6036 * executed lazily when the provider needs to be checked for valid
6037 * credentials. By default, this object will be set to the
6038 * {defaultProviders}.
6039 * @see defaultProviders
6040 */
6041 AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, {
6042
6043 /**
6044 * Creates a new CredentialProviderChain with a default set of providers
6045 * specified by {defaultProviders}.
6046 */
6047 constructor: function CredentialProviderChain(providers) {
6048 if (providers) {
6049 this.providers = providers;
6050 } else {
6051 this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
6052 }
6053 this.resolveCallbacks = [];
6054 },
6055
6056 /**
6057 * @!method resolvePromise()
6058 * Returns a 'thenable' promise.
6059 * Resolves the provider chain by searching for the first set of
6060 * credentials in {providers}.
6061 *
6062 * Two callbacks can be provided to the `then` method on the returned promise.
6063 * The first callback will be called if the promise is fulfilled, and the second
6064 * callback will be called if the promise is rejected.
6065 * @callback fulfilledCallback function(credentials)
6066 * Called if the promise is fulfilled and the provider resolves the chain
6067 * to a credentials object
6068 * @param credentials [AWS.Credentials] the credentials object resolved
6069 * by the provider chain.
6070 * @callback rejectedCallback function(error)
6071 * Called if the promise is rejected.
6072 * @param err [Error] the error object returned if no credentials are found.
6073 * @return [Promise] A promise that represents the state of the `resolve` method call.
6074 * @example Calling the `resolvePromise` method.
6075 * var promise = chain.resolvePromise();
6076 * promise.then(function(credentials) { ... }, function(err) { ... });
6077 */
6078
6079 /**
6080 * Resolves the provider chain by searching for the first set of
6081 * credentials in {providers}.
6082 *
6083 * @callback callback function(err, credentials)
6084 * Called when the provider resolves the chain to a credentials object
6085 * or null if no credentials can be found.
6086 *
6087 * @param err [Error] the error object returned if no credentials are
6088 * found.
6089 * @param credentials [AWS.Credentials] the credentials object resolved
6090 * by the provider chain.
6091 * @return [AWS.CredentialProviderChain] the provider, for chaining.
6092 */
6093 resolve: function resolve(callback) {
6094 var self = this;
6095 if (self.providers.length === 0) {
6096 callback(new Error('No providers'));
6097 return self;
6098 }
6099
6100 if (self.resolveCallbacks.push(callback) === 1) {
6101 var index = 0;
6102 var providers = self.providers.slice(0);
6103
6104 function resolveNext(err, creds) {
6105 if ((!err && creds) || index === providers.length) {
6106 AWS.util.arrayEach(self.resolveCallbacks, function (callback) {
6107 callback(err, creds);
6108 });
6109 self.resolveCallbacks.length = 0;
6110 return;
6111 }
6112
6113 var provider = providers[index++];
6114 if (typeof provider === 'function') {
6115 creds = provider.call();
6116 } else {
6117 creds = provider;
6118 }
6119
6120 if (creds.get) {
6121 creds.get(function (getErr) {
6122 resolveNext(getErr, getErr ? null : creds);
6123 });
6124 } else {
6125 resolveNext(null, creds);
6126 }
6127 }
6128
6129 resolveNext();
6130 }
6131
6132 return self;
6133 }
6134 });
6135
6136 /**
6137 * The default set of providers used by a vanilla CredentialProviderChain.
6138 *
6139 * In the browser:
6140 *
6141 * ```javascript
6142 * AWS.CredentialProviderChain.defaultProviders = []
6143 * ```
6144 *
6145 * In Node.js:
6146 *
6147 * ```javascript
6148 * AWS.CredentialProviderChain.defaultProviders = [
6149 * function () { return new AWS.EnvironmentCredentials('AWS'); },
6150 * function () { return new AWS.EnvironmentCredentials('AMAZON'); },
6151 * function () { return new AWS.SharedIniFileCredentials(); },
6152 * function () { return new AWS.ECSCredentials(); },
6153 * function () { return new AWS.ProcessCredentials(); },
6154 * function () { return new AWS.TokenFileWebIdentityCredentials(); },
6155 * function () { return new AWS.EC2MetadataCredentials() }
6156 * ]
6157 * ```
6158 */
6159 AWS.CredentialProviderChain.defaultProviders = [];
6160
6161 /**
6162 * @api private
6163 */
6164 AWS.CredentialProviderChain.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
6165 this.prototype.resolvePromise = AWS.util.promisifyMethod('resolve', PromiseDependency);
6166 };
6167
6168 /**
6169 * @api private
6170 */
6171 AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFromClass() {
6172 delete this.prototype.resolvePromise;
6173 };
6174
6175 AWS.util.addPromises(AWS.CredentialProviderChain);
6176
6177
6178/***/ }),
6179/* 43 */
6180/***/ (function(module, exports, __webpack_require__) {
6181
6182 var AWS = __webpack_require__(1);
6183 var inherit = AWS.util.inherit;
6184
6185 /**
6186 * The endpoint that a service will talk to, for example,
6187 * `'https://ec2.ap-southeast-1.amazonaws.com'`. If
6188 * you need to override an endpoint for a service, you can
6189 * set the endpoint on a service by passing the endpoint
6190 * object with the `endpoint` option key:
6191 *
6192 * ```javascript
6193 * var ep = new AWS.Endpoint('awsproxy.example.com');
6194 * var s3 = new AWS.S3({endpoint: ep});
6195 * s3.service.endpoint.hostname == 'awsproxy.example.com'
6196 * ```
6197 *
6198 * Note that if you do not specify a protocol, the protocol will
6199 * be selected based on your current {AWS.config} configuration.
6200 *
6201 * @!attribute protocol
6202 * @return [String] the protocol (http or https) of the endpoint
6203 * URL
6204 * @!attribute hostname
6205 * @return [String] the host portion of the endpoint, e.g.,
6206 * example.com
6207 * @!attribute host
6208 * @return [String] the host portion of the endpoint including
6209 * the port, e.g., example.com:80
6210 * @!attribute port
6211 * @return [Integer] the port of the endpoint
6212 * @!attribute href
6213 * @return [String] the full URL of the endpoint
6214 */
6215 AWS.Endpoint = inherit({
6216
6217 /**
6218 * @overload Endpoint(endpoint)
6219 * Constructs a new endpoint given an endpoint URL. If the
6220 * URL omits a protocol (http or https), the default protocol
6221 * set in the global {AWS.config} will be used.
6222 * @param endpoint [String] the URL to construct an endpoint from
6223 */
6224 constructor: function Endpoint(endpoint, config) {
6225 AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']);
6226
6227 if (typeof endpoint === 'undefined' || endpoint === null) {
6228 throw new Error('Invalid endpoint: ' + endpoint);
6229 } else if (typeof endpoint !== 'string') {
6230 return AWS.util.copy(endpoint);
6231 }
6232
6233 if (!endpoint.match(/^http/)) {
6234 var useSSL = config && config.sslEnabled !== undefined ?
6235 config.sslEnabled : AWS.config.sslEnabled;
6236 endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
6237 }
6238
6239 AWS.util.update(this, AWS.util.urlParse(endpoint));
6240
6241 // Ensure the port property is set as an integer
6242 if (this.port) {
6243 this.port = parseInt(this.port, 10);
6244 } else {
6245 this.port = this.protocol === 'https:' ? 443 : 80;
6246 }
6247 }
6248
6249 });
6250
6251 /**
6252 * The low level HTTP request object, encapsulating all HTTP header
6253 * and body data sent by a service request.
6254 *
6255 * @!attribute method
6256 * @return [String] the HTTP method of the request
6257 * @!attribute path
6258 * @return [String] the path portion of the URI, e.g.,
6259 * "/list/?start=5&num=10"
6260 * @!attribute headers
6261 * @return [map<String,String>]
6262 * a map of header keys and their respective values
6263 * @!attribute body
6264 * @return [String] the request body payload
6265 * @!attribute endpoint
6266 * @return [AWS.Endpoint] the endpoint for the request
6267 * @!attribute region
6268 * @api private
6269 * @return [String] the region, for signing purposes only.
6270 */
6271 AWS.HttpRequest = inherit({
6272
6273 /**
6274 * @api private
6275 */
6276 constructor: function HttpRequest(endpoint, region) {
6277 endpoint = new AWS.Endpoint(endpoint);
6278 this.method = 'POST';
6279 this.path = endpoint.path || '/';
6280 this.headers = {};
6281 this.body = '';
6282 this.endpoint = endpoint;
6283 this.region = region;
6284 this._userAgent = '';
6285 this.setUserAgent();
6286 },
6287
6288 /**
6289 * @api private
6290 */
6291 setUserAgent: function setUserAgent() {
6292 this._userAgent = this.headers[this.getUserAgentHeaderName()] = AWS.util.userAgent();
6293 },
6294
6295 getUserAgentHeaderName: function getUserAgentHeaderName() {
6296 var prefix = AWS.util.isBrowser() ? 'X-Amz-' : '';
6297 return prefix + 'User-Agent';
6298 },
6299
6300 /**
6301 * @api private
6302 */
6303 appendToUserAgent: function appendToUserAgent(agentPartial) {
6304 if (typeof agentPartial === 'string' && agentPartial) {
6305 this._userAgent += ' ' + agentPartial;
6306 }
6307 this.headers[this.getUserAgentHeaderName()] = this._userAgent;
6308 },
6309
6310 /**
6311 * @api private
6312 */
6313 getUserAgent: function getUserAgent() {
6314 return this._userAgent;
6315 },
6316
6317 /**
6318 * @return [String] the part of the {path} excluding the
6319 * query string
6320 */
6321 pathname: function pathname() {
6322 return this.path.split('?', 1)[0];
6323 },
6324
6325 /**
6326 * @return [String] the query string portion of the {path}
6327 */
6328 search: function search() {
6329 var query = this.path.split('?', 2)[1];
6330 if (query) {
6331 query = AWS.util.queryStringParse(query);
6332 return AWS.util.queryParamsToString(query);
6333 }
6334 return '';
6335 },
6336
6337 /**
6338 * @api private
6339 * update httpRequest endpoint with endpoint string
6340 */
6341 updateEndpoint: function updateEndpoint(endpointStr) {
6342 var newEndpoint = new AWS.Endpoint(endpointStr);
6343 this.endpoint = newEndpoint;
6344 this.path = newEndpoint.path || '/';
6345 }
6346 });
6347
6348 /**
6349 * The low level HTTP response object, encapsulating all HTTP header
6350 * and body data returned from the request.
6351 *
6352 * @!attribute statusCode
6353 * @return [Integer] the HTTP status code of the response (e.g., 200, 404)
6354 * @!attribute headers
6355 * @return [map<String,String>]
6356 * a map of response header keys and their respective values
6357 * @!attribute body
6358 * @return [String] the response body payload
6359 * @!attribute [r] streaming
6360 * @return [Boolean] whether this response is being streamed at a low-level.
6361 * Defaults to `false` (buffered reads). Do not modify this manually, use
6362 * {createUnbufferedStream} to convert the stream to unbuffered mode
6363 * instead.
6364 */
6365 AWS.HttpResponse = inherit({
6366
6367 /**
6368 * @api private
6369 */
6370 constructor: function HttpResponse() {
6371 this.statusCode = undefined;
6372 this.headers = {};
6373 this.body = undefined;
6374 this.streaming = false;
6375 this.stream = null;
6376 },
6377
6378 /**
6379 * Disables buffering on the HTTP response and returns the stream for reading.
6380 * @return [Stream, XMLHttpRequest, null] the underlying stream object.
6381 * Use this object to directly read data off of the stream.
6382 * @note This object is only available after the {AWS.Request~httpHeaders}
6383 * event has fired. This method must be called prior to
6384 * {AWS.Request~httpData}.
6385 * @example Taking control of a stream
6386 * request.on('httpHeaders', function(statusCode, headers) {
6387 * if (statusCode < 300) {
6388 * if (headers.etag === 'xyz') {
6389 * // pipe the stream, disabling buffering
6390 * var stream = this.response.httpResponse.createUnbufferedStream();
6391 * stream.pipe(process.stdout);
6392 * } else { // abort this request and set a better error message
6393 * this.abort();
6394 * this.response.error = new Error('Invalid ETag');
6395 * }
6396 * }
6397 * }).send(console.log);
6398 */
6399 createUnbufferedStream: function createUnbufferedStream() {
6400 this.streaming = true;
6401 return this.stream;
6402 }
6403 });
6404
6405
6406 AWS.HttpClient = inherit({});
6407
6408 /**
6409 * @api private
6410 */
6411 AWS.HttpClient.getInstance = function getInstance() {
6412 if (this.singleton === undefined) {
6413 this.singleton = new this();
6414 }
6415 return this.singleton;
6416 };
6417
6418
6419/***/ }),
6420/* 44 */
6421/***/ (function(module, exports, __webpack_require__) {
6422
6423 var AWS = __webpack_require__(1);
6424 var SequentialExecutor = __webpack_require__(36);
6425 var DISCOVER_ENDPOINT = __webpack_require__(45).discoverEndpoint;
6426 /**
6427 * The namespace used to register global event listeners for request building
6428 * and sending.
6429 */
6430 AWS.EventListeners = {
6431 /**
6432 * @!attribute VALIDATE_CREDENTIALS
6433 * A request listener that validates whether the request is being
6434 * sent with credentials.
6435 * Handles the {AWS.Request~validate 'validate' Request event}
6436 * @example Sending a request without validating credentials
6437 * var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS;
6438 * request.removeListener('validate', listener);
6439 * @readonly
6440 * @return [Function]
6441 * @!attribute VALIDATE_REGION
6442 * A request listener that validates whether the region is set
6443 * for a request.
6444 * Handles the {AWS.Request~validate 'validate' Request event}
6445 * @example Sending a request without validating region configuration
6446 * var listener = AWS.EventListeners.Core.VALIDATE_REGION;
6447 * request.removeListener('validate', listener);
6448 * @readonly
6449 * @return [Function]
6450 * @!attribute VALIDATE_PARAMETERS
6451 * A request listener that validates input parameters in a request.
6452 * Handles the {AWS.Request~validate 'validate' Request event}
6453 * @example Sending a request without validating parameters
6454 * var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS;
6455 * request.removeListener('validate', listener);
6456 * @example Disable parameter validation globally
6457 * AWS.EventListeners.Core.removeListener('validate',
6458 * AWS.EventListeners.Core.VALIDATE_REGION);
6459 * @readonly
6460 * @return [Function]
6461 * @!attribute SEND
6462 * A request listener that initiates the HTTP connection for a
6463 * request being sent. Handles the {AWS.Request~send 'send' Request event}
6464 * @example Replacing the HTTP handler
6465 * var listener = AWS.EventListeners.Core.SEND;
6466 * request.removeListener('send', listener);
6467 * request.on('send', function(response) {
6468 * customHandler.send(response);
6469 * });
6470 * @return [Function]
6471 * @readonly
6472 * @!attribute HTTP_DATA
6473 * A request listener that reads data from the HTTP connection in order
6474 * to build the response data.
6475 * Handles the {AWS.Request~httpData 'httpData' Request event}.
6476 * Remove this handler if you are overriding the 'httpData' event and
6477 * do not want extra data processing and buffering overhead.
6478 * @example Disabling default data processing
6479 * var listener = AWS.EventListeners.Core.HTTP_DATA;
6480 * request.removeListener('httpData', listener);
6481 * @return [Function]
6482 * @readonly
6483 */
6484 Core: {} /* doc hack */
6485 };
6486
6487 /**
6488 * @api private
6489 */
6490 function getOperationAuthtype(req) {
6491 if (!req.service.api.operations) {
6492 return '';
6493 }
6494 var operation = req.service.api.operations[req.operation];
6495 return operation ? operation.authtype : '';
6496 }
6497
6498 AWS.EventListeners = {
6499 Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) {
6500 addAsync('VALIDATE_CREDENTIALS', 'validate',
6501 function VALIDATE_CREDENTIALS(req, done) {
6502 if (!req.service.api.signatureVersion && !req.service.config.signatureVersion) return done(); // none
6503 req.service.config.getCredentials(function(err) {
6504 if (err) {
6505 req.response.error = AWS.util.error(err,
6506 {code: 'CredentialsError', message: 'Missing credentials in config'});
6507 }
6508 done();
6509 });
6510 });
6511
6512 add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
6513 if (!req.service.config.region && !req.service.isGlobalEndpoint) {
6514 req.response.error = AWS.util.error(new Error(),
6515 {code: 'ConfigError', message: 'Missing region in config'});
6516 }
6517 });
6518
6519 add('BUILD_IDEMPOTENCY_TOKENS', 'validate', function BUILD_IDEMPOTENCY_TOKENS(req) {
6520 if (!req.service.api.operations) {
6521 return;
6522 }
6523 var operation = req.service.api.operations[req.operation];
6524 if (!operation) {
6525 return;
6526 }
6527 var idempotentMembers = operation.idempotentMembers;
6528 if (!idempotentMembers.length) {
6529 return;
6530 }
6531 // creates a copy of params so user's param object isn't mutated
6532 var params = AWS.util.copy(req.params);
6533 for (var i = 0, iLen = idempotentMembers.length; i < iLen; i++) {
6534 if (!params[idempotentMembers[i]]) {
6535 // add the member
6536 params[idempotentMembers[i]] = AWS.util.uuid.v4();
6537 }
6538 }
6539 req.params = params;
6540 });
6541
6542 add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) {
6543 if (!req.service.api.operations) {
6544 return;
6545 }
6546 var rules = req.service.api.operations[req.operation].input;
6547 var validation = req.service.config.paramValidation;
6548 new AWS.ParamValidator(validation).validate(rules, req.params);
6549 });
6550
6551 addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) {
6552 req.haltHandlersOnError();
6553 if (!req.service.api.operations) {
6554 return;
6555 }
6556 var operation = req.service.api.operations[req.operation];
6557 var authtype = operation ? operation.authtype : '';
6558 if (!req.service.api.signatureVersion && !authtype && !req.service.config.signatureVersion) return done(); // none
6559 if (req.service.getSignerClass(req) === AWS.Signers.V4) {
6560 var body = req.httpRequest.body || '';
6561 if (authtype.indexOf('unsigned-body') >= 0) {
6562 req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD';
6563 return done();
6564 }
6565 AWS.util.computeSha256(body, function(err, sha) {
6566 if (err) {
6567 done(err);
6568 }
6569 else {
6570 req.httpRequest.headers['X-Amz-Content-Sha256'] = sha;
6571 done();
6572 }
6573 });
6574 } else {
6575 done();
6576 }
6577 });
6578
6579 add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) {
6580 var authtype = getOperationAuthtype(req);
6581 var payloadMember = AWS.util.getRequestPayloadShape(req);
6582 if (req.httpRequest.headers['Content-Length'] === undefined) {
6583 try {
6584 var length = AWS.util.string.byteLength(req.httpRequest.body);
6585 req.httpRequest.headers['Content-Length'] = length;
6586 } catch (err) {
6587 if (payloadMember && payloadMember.isStreaming) {
6588 if (payloadMember.requiresLength) {
6589 //streaming payload requires length(s3, glacier)
6590 throw err;
6591 } else if (authtype.indexOf('unsigned-body') >= 0) {
6592 //unbounded streaming payload(lex, mediastore)
6593 req.httpRequest.headers['Transfer-Encoding'] = 'chunked';
6594 return;
6595 } else {
6596 throw err;
6597 }
6598 }
6599 throw err;
6600 }
6601 }
6602 });
6603
6604 add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) {
6605 req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host;
6606 });
6607
6608 add('RESTART', 'restart', function RESTART() {
6609 var err = this.response.error;
6610 if (!err || !err.retryable) return;
6611
6612 this.httpRequest = new AWS.HttpRequest(
6613 this.service.endpoint,
6614 this.service.region
6615 );
6616
6617 if (this.response.retryCount < this.service.config.maxRetries) {
6618 this.response.retryCount++;
6619 } else {
6620 this.response.error = null;
6621 }
6622 });
6623
6624 var addToHead = true;
6625 addAsync('DISCOVER_ENDPOINT', 'sign', DISCOVER_ENDPOINT, addToHead);
6626
6627 addAsync('SIGN', 'sign', function SIGN(req, done) {
6628 var service = req.service;
6629 var operations = req.service.api.operations || {};
6630 var operation = operations[req.operation];
6631 var authtype = operation ? operation.authtype : '';
6632 if (!service.api.signatureVersion && !authtype && !service.config.signatureVersion) return done(); // none
6633
6634 service.config.getCredentials(function (err, credentials) {
6635 if (err) {
6636 req.response.error = err;
6637 return done();
6638 }
6639
6640 try {
6641 var date = service.getSkewCorrectedDate();
6642 var SignerClass = service.getSignerClass(req);
6643 var signer = new SignerClass(req.httpRequest,
6644 service.api.signingName || service.api.endpointPrefix,
6645 {
6646 signatureCache: service.config.signatureCache,
6647 operation: operation,
6648 signatureVersion: service.api.signatureVersion
6649 });
6650 signer.setServiceClientId(service._clientId);
6651
6652 // clear old authorization headers
6653 delete req.httpRequest.headers['Authorization'];
6654 delete req.httpRequest.headers['Date'];
6655 delete req.httpRequest.headers['X-Amz-Date'];
6656
6657 // add new authorization
6658 signer.addAuthorization(credentials, date);
6659 req.signedAt = date;
6660 } catch (e) {
6661 req.response.error = e;
6662 }
6663 done();
6664 });
6665 });
6666
6667 add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) {
6668 if (this.service.successfulResponse(resp, this)) {
6669 resp.data = {};
6670 resp.error = null;
6671 } else {
6672 resp.data = null;
6673 resp.error = AWS.util.error(new Error(),
6674 {code: 'UnknownError', message: 'An unknown error occurred.'});
6675 }
6676 });
6677
6678 addAsync('SEND', 'send', function SEND(resp, done) {
6679 resp.httpResponse._abortCallback = done;
6680 resp.error = null;
6681 resp.data = null;
6682
6683 function callback(httpResp) {
6684 resp.httpResponse.stream = httpResp;
6685 var stream = resp.request.httpRequest.stream;
6686 var service = resp.request.service;
6687 var api = service.api;
6688 var operationName = resp.request.operation;
6689 var operation = api.operations[operationName] || {};
6690
6691 httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) {
6692 resp.request.emit(
6693 'httpHeaders',
6694 [statusCode, headers, resp, statusMessage]
6695 );
6696
6697 if (!resp.httpResponse.streaming) {
6698 if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check
6699 // if we detect event streams, we're going to have to
6700 // return the stream immediately
6701 if (operation.hasEventOutput && service.successfulResponse(resp)) {
6702 // skip reading the IncomingStream
6703 resp.request.emit('httpDone');
6704 done();
6705 return;
6706 }
6707
6708 httpResp.on('readable', function onReadable() {
6709 var data = httpResp.read();
6710 if (data !== null) {
6711 resp.request.emit('httpData', [data, resp]);
6712 }
6713 });
6714 } else { // legacy streams API
6715 httpResp.on('data', function onData(data) {
6716 resp.request.emit('httpData', [data, resp]);
6717 });
6718 }
6719 }
6720 });
6721
6722 httpResp.on('end', function onEnd() {
6723 if (!stream || !stream.didCallback) {
6724 if (AWS.HttpClient.streamsApiVersion === 2 && (operation.hasEventOutput && service.successfulResponse(resp))) {
6725 // don't concatenate response chunks when streaming event stream data when response is successful
6726 return;
6727 }
6728 resp.request.emit('httpDone');
6729 done();
6730 }
6731 });
6732 }
6733
6734 function progress(httpResp) {
6735 httpResp.on('sendProgress', function onSendProgress(value) {
6736 resp.request.emit('httpUploadProgress', [value, resp]);
6737 });
6738
6739 httpResp.on('receiveProgress', function onReceiveProgress(value) {
6740 resp.request.emit('httpDownloadProgress', [value, resp]);
6741 });
6742 }
6743
6744 function error(err) {
6745 if (err.code !== 'RequestAbortedError') {
6746 var errCode = err.code === 'TimeoutError' ? err.code : 'NetworkingError';
6747 err = AWS.util.error(err, {
6748 code: errCode,
6749 region: resp.request.httpRequest.region,
6750 hostname: resp.request.httpRequest.endpoint.hostname,
6751 retryable: true
6752 });
6753 }
6754 resp.error = err;
6755 resp.request.emit('httpError', [resp.error, resp], function() {
6756 done();
6757 });
6758 }
6759
6760 function executeSend() {
6761 var http = AWS.HttpClient.getInstance();
6762 var httpOptions = resp.request.service.config.httpOptions || {};
6763 try {
6764 var stream = http.handleRequest(resp.request.httpRequest, httpOptions,
6765 callback, error);
6766 progress(stream);
6767 } catch (err) {
6768 error(err);
6769 }
6770 }
6771 var timeDiff = (resp.request.service.getSkewCorrectedDate() - this.signedAt) / 1000;
6772 if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign
6773 this.emit('sign', [this], function(err) {
6774 if (err) done(err);
6775 else executeSend();
6776 });
6777 } else {
6778 executeSend();
6779 }
6780 });
6781
6782 add('HTTP_HEADERS', 'httpHeaders',
6783 function HTTP_HEADERS(statusCode, headers, resp, statusMessage) {
6784 resp.httpResponse.statusCode = statusCode;
6785 resp.httpResponse.statusMessage = statusMessage;
6786 resp.httpResponse.headers = headers;
6787 resp.httpResponse.body = AWS.util.buffer.toBuffer('');
6788 resp.httpResponse.buffers = [];
6789 resp.httpResponse.numBytes = 0;
6790 var dateHeader = headers.date || headers.Date;
6791 var service = resp.request.service;
6792 if (dateHeader) {
6793 var serverTime = Date.parse(dateHeader);
6794 if (service.config.correctClockSkew
6795 && service.isClockSkewed(serverTime)) {
6796 service.applyClockOffset(serverTime);
6797 }
6798 }
6799 });
6800
6801 add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) {
6802 if (chunk) {
6803 if (AWS.util.isNode()) {
6804 resp.httpResponse.numBytes += chunk.length;
6805
6806 var total = resp.httpResponse.headers['content-length'];
6807 var progress = { loaded: resp.httpResponse.numBytes, total: total };
6808 resp.request.emit('httpDownloadProgress', [progress, resp]);
6809 }
6810
6811 resp.httpResponse.buffers.push(AWS.util.buffer.toBuffer(chunk));
6812 }
6813 });
6814
6815 add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) {
6816 // convert buffers array into single buffer
6817 if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) {
6818 var body = AWS.util.buffer.concat(resp.httpResponse.buffers);
6819 resp.httpResponse.body = body;
6820 }
6821 delete resp.httpResponse.numBytes;
6822 delete resp.httpResponse.buffers;
6823 });
6824
6825 add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) {
6826 if (resp.httpResponse.statusCode) {
6827 resp.error.statusCode = resp.httpResponse.statusCode;
6828 if (resp.error.retryable === undefined) {
6829 resp.error.retryable = this.service.retryableError(resp.error, this);
6830 }
6831 }
6832 });
6833
6834 add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) {
6835 if (!resp.error) return;
6836 switch (resp.error.code) {
6837 case 'RequestExpired': // EC2 only
6838 case 'ExpiredTokenException':
6839 case 'ExpiredToken':
6840 resp.error.retryable = true;
6841 resp.request.service.config.credentials.expired = true;
6842 }
6843 });
6844
6845 add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) {
6846 var err = resp.error;
6847 if (!err) return;
6848 if (typeof err.code === 'string' && typeof err.message === 'string') {
6849 if (err.code.match(/Signature/) && err.message.match(/expired/)) {
6850 resp.error.retryable = true;
6851 }
6852 }
6853 });
6854
6855 add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) {
6856 if (!resp.error) return;
6857 if (this.service.clockSkewError(resp.error)
6858 && this.service.config.correctClockSkew) {
6859 resp.error.retryable = true;
6860 }
6861 });
6862
6863 add('REDIRECT', 'retry', function REDIRECT(resp) {
6864 if (resp.error && resp.error.statusCode >= 300 &&
6865 resp.error.statusCode < 400 && resp.httpResponse.headers['location']) {
6866 this.httpRequest.endpoint =
6867 new AWS.Endpoint(resp.httpResponse.headers['location']);
6868 this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host;
6869 resp.error.redirect = true;
6870 resp.error.retryable = true;
6871 }
6872 });
6873
6874 add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) {
6875 if (resp.error) {
6876 if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6877 resp.error.retryDelay = 0;
6878 } else if (resp.retryCount < resp.maxRetries) {
6879 resp.error.retryDelay = this.service.retryDelays(resp.retryCount, resp.error) || 0;
6880 }
6881 }
6882 });
6883
6884 addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) {
6885 var delay, willRetry = false;
6886
6887 if (resp.error) {
6888 delay = resp.error.retryDelay || 0;
6889 if (resp.error.retryable && resp.retryCount < resp.maxRetries) {
6890 resp.retryCount++;
6891 willRetry = true;
6892 } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6893 resp.redirectCount++;
6894 willRetry = true;
6895 }
6896 }
6897
6898 // delay < 0 is a signal from customBackoff to skip retries
6899 if (willRetry && delay >= 0) {
6900 resp.error = null;
6901 setTimeout(done, delay);
6902 } else {
6903 done();
6904 }
6905 });
6906 }),
6907
6908 CorePost: new SequentialExecutor().addNamedListeners(function(add) {
6909 add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId);
6910 add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId);
6911
6912 add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) {
6913 if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') {
6914 var message = 'Inaccessible host: `' + err.hostname +
6915 '\'. This service may not be available in the `' + err.region +
6916 '\' region.';
6917 this.response.error = AWS.util.error(new Error(message), {
6918 code: 'UnknownEndpoint',
6919 region: err.region,
6920 hostname: err.hostname,
6921 retryable: true,
6922 originalError: err
6923 });
6924 }
6925 });
6926 }),
6927
6928 Logger: new SequentialExecutor().addNamedListeners(function(add) {
6929 add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) {
6930 var req = resp.request;
6931 var logger = req.service.config.logger;
6932 if (!logger) return;
6933 function filterSensitiveLog(inputShape, shape) {
6934 if (!shape) {
6935 return shape;
6936 }
6937 switch (inputShape.type) {
6938 case 'structure':
6939 var struct = {};
6940 AWS.util.each(shape, function(subShapeName, subShape) {
6941 if (Object.prototype.hasOwnProperty.call(inputShape.members, subShapeName)) {
6942 struct[subShapeName] = filterSensitiveLog(inputShape.members[subShapeName], subShape);
6943 } else {
6944 struct[subShapeName] = subShape;
6945 }
6946 });
6947 return struct;
6948 case 'list':
6949 var list = [];
6950 AWS.util.arrayEach(shape, function(subShape, index) {
6951 list.push(filterSensitiveLog(inputShape.member, subShape));
6952 });
6953 return list;
6954 case 'map':
6955 var map = {};
6956 AWS.util.each(shape, function(key, value) {
6957 map[key] = filterSensitiveLog(inputShape.value, value);
6958 });
6959 return map;
6960 default:
6961 if (inputShape.isSensitive) {
6962 return '***SensitiveInformation***';
6963 } else {
6964 return shape;
6965 }
6966 }
6967 }
6968
6969 function buildMessage() {
6970 var time = resp.request.service.getSkewCorrectedDate().getTime();
6971 var delta = (time - req.startTime.getTime()) / 1000;
6972 var ansi = logger.isTTY ? true : false;
6973 var status = resp.httpResponse.statusCode;
6974 var censoredParams = req.params;
6975 if (
6976 req.service.api.operations &&
6977 req.service.api.operations[req.operation] &&
6978 req.service.api.operations[req.operation].input
6979 ) {
6980 var inputShape = req.service.api.operations[req.operation].input;
6981 censoredParams = filterSensitiveLog(inputShape, req.params);
6982 }
6983 var params = __webpack_require__(46).inspect(censoredParams, true, null);
6984 var message = '';
6985 if (ansi) message += '\x1B[33m';
6986 message += '[AWS ' + req.service.serviceIdentifier + ' ' + status;
6987 message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]';
6988 if (ansi) message += '\x1B[0;1m';
6989 message += ' ' + AWS.util.string.lowerFirst(req.operation);
6990 message += '(' + params + ')';
6991 if (ansi) message += '\x1B[0m';
6992 return message;
6993 }
6994
6995 var line = buildMessage();
6996 if (typeof logger.log === 'function') {
6997 logger.log(line);
6998 } else if (typeof logger.write === 'function') {
6999 logger.write(line + '\n');
7000 }
7001 });
7002 }),
7003
7004 Json: new SequentialExecutor().addNamedListeners(function(add) {
7005 var svc = __webpack_require__(13);
7006 add('BUILD', 'build', svc.buildRequest);
7007 add('EXTRACT_DATA', 'extractData', svc.extractData);
7008 add('EXTRACT_ERROR', 'extractError', svc.extractError);
7009 }),
7010
7011 Rest: new SequentialExecutor().addNamedListeners(function(add) {
7012 var svc = __webpack_require__(21);
7013 add('BUILD', 'build', svc.buildRequest);
7014 add('EXTRACT_DATA', 'extractData', svc.extractData);
7015 add('EXTRACT_ERROR', 'extractError', svc.extractError);
7016 }),
7017
7018 RestJson: new SequentialExecutor().addNamedListeners(function(add) {
7019 var svc = __webpack_require__(22);
7020 add('BUILD', 'build', svc.buildRequest);
7021 add('EXTRACT_DATA', 'extractData', svc.extractData);
7022 add('EXTRACT_ERROR', 'extractError', svc.extractError);
7023 }),
7024
7025 RestXml: new SequentialExecutor().addNamedListeners(function(add) {
7026 var svc = __webpack_require__(23);
7027 add('BUILD', 'build', svc.buildRequest);
7028 add('EXTRACT_DATA', 'extractData', svc.extractData);
7029 add('EXTRACT_ERROR', 'extractError', svc.extractError);
7030 }),
7031
7032 Query: new SequentialExecutor().addNamedListeners(function(add) {
7033 var svc = __webpack_require__(17);
7034 add('BUILD', 'build', svc.buildRequest);
7035 add('EXTRACT_DATA', 'extractData', svc.extractData);
7036 add('EXTRACT_ERROR', 'extractError', svc.extractError);
7037 })
7038 };
7039
7040
7041/***/ }),
7042/* 45 */
7043/***/ (function(module, exports, __webpack_require__) {
7044
7045 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
7046 var util = __webpack_require__(2);
7047 var endpointDiscoveryEnabledEnvs = ['AWS_ENABLE_ENDPOINT_DISCOVERY', 'AWS_ENDPOINT_DISCOVERY_ENABLED'];
7048
7049 /**
7050 * Generate key (except resources and operation part) to index the endpoints in the cache
7051 * If input shape has endpointdiscoveryid trait then use
7052 * accessKey + operation + resources + region + service as cache key
7053 * If input shape doesn't have endpointdiscoveryid trait then use
7054 * accessKey + region + service as cache key
7055 * @return [map<String,String>] object with keys to index endpoints.
7056 * @api private
7057 */
7058 function getCacheKey(request) {
7059 var service = request.service;
7060 var api = service.api || {};
7061 var operations = api.operations;
7062 var identifiers = {};
7063 if (service.config.region) {
7064 identifiers.region = service.config.region;
7065 }
7066 if (api.serviceId) {
7067 identifiers.serviceId = api.serviceId;
7068 }
7069 if (service.config.credentials.accessKeyId) {
7070 identifiers.accessKeyId = service.config.credentials.accessKeyId;
7071 }
7072 return identifiers;
7073 }
7074
7075 /**
7076 * Recursive helper for marshallCustomIdentifiers().
7077 * Looks for required string input members that have 'endpointdiscoveryid' trait.
7078 * @api private
7079 */
7080 function marshallCustomIdentifiersHelper(result, params, shape) {
7081 if (!shape || params === undefined || params === null) return;
7082 if (shape.type === 'structure' && shape.required && shape.required.length > 0) {
7083 util.arrayEach(shape.required, function(name) {
7084 var memberShape = shape.members[name];
7085 if (memberShape.endpointDiscoveryId === true) {
7086 var locationName = memberShape.isLocationName ? memberShape.name : name;
7087 result[locationName] = String(params[name]);
7088 } else {
7089 marshallCustomIdentifiersHelper(result, params[name], memberShape);
7090 }
7091 });
7092 }
7093 }
7094
7095 /**
7096 * Get custom identifiers for cache key.
7097 * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait.
7098 * @param [object] request object
7099 * @param [object] input shape of the given operation's api
7100 * @api private
7101 */
7102 function marshallCustomIdentifiers(request, shape) {
7103 var identifiers = {};
7104 marshallCustomIdentifiersHelper(identifiers, request.params, shape);
7105 return identifiers;
7106 }
7107
7108 /**
7109 * Call endpoint discovery operation when it's optional.
7110 * When endpoint is available in cache then use the cached endpoints. If endpoints
7111 * are unavailable then use regional endpoints and call endpoint discovery operation
7112 * asynchronously. This is turned off by default.
7113 * @param [object] request object
7114 * @api private
7115 */
7116 function optionalDiscoverEndpoint(request) {
7117 var service = request.service;
7118 var api = service.api;
7119 var operationModel = api.operations ? api.operations[request.operation] : undefined;
7120 var inputShape = operationModel ? operationModel.input : undefined;
7121
7122 var identifiers = marshallCustomIdentifiers(request, inputShape);
7123 var cacheKey = getCacheKey(request);
7124 if (Object.keys(identifiers).length > 0) {
7125 cacheKey = util.update(cacheKey, identifiers);
7126 if (operationModel) cacheKey.operation = operationModel.name;
7127 }
7128 var endpoints = AWS.endpointCache.get(cacheKey);
7129 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
7130 //endpoint operation is being made but response not yet received
7131 //or endpoint operation just failed in 1 minute
7132 return;
7133 } else if (endpoints && endpoints.length > 0) {
7134 //found endpoint record from cache
7135 request.httpRequest.updateEndpoint(endpoints[0].Address);
7136 } else {
7137 //endpoint record not in cache or outdated. make discovery operation
7138 var endpointRequest = service.makeRequest(api.endpointOperation, {
7139 Operation: operationModel.name,
7140 Identifiers: identifiers,
7141 });
7142 addApiVersionHeader(endpointRequest);
7143 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
7144 endpointRequest.removeListener('retry', AWS.EventListeners.Core.RETRY_CHECK);
7145 //put in a placeholder for endpoints already requested, prevent
7146 //too much in-flight calls
7147 AWS.endpointCache.put(cacheKey, [{
7148 Address: '',
7149 CachePeriodInMinutes: 1
7150 }]);
7151 endpointRequest.send(function(err, data) {
7152 if (data && data.Endpoints) {
7153 AWS.endpointCache.put(cacheKey, data.Endpoints);
7154 } else if (err) {
7155 AWS.endpointCache.put(cacheKey, [{
7156 Address: '',
7157 CachePeriodInMinutes: 1 //not to make more endpoint operation in next 1 minute
7158 }]);
7159 }
7160 });
7161 }
7162 }
7163
7164 var requestQueue = {};
7165
7166 /**
7167 * Call endpoint discovery operation when it's required.
7168 * When endpoint is available in cache then use cached ones. If endpoints are
7169 * unavailable then SDK should call endpoint operation then use returned new
7170 * endpoint for the api call. SDK will automatically attempt to do endpoint
7171 * discovery. This is turned off by default
7172 * @param [object] request object
7173 * @api private
7174 */
7175 function requiredDiscoverEndpoint(request, done) {
7176 var service = request.service;
7177 var api = service.api;
7178 var operationModel = api.operations ? api.operations[request.operation] : undefined;
7179 var inputShape = operationModel ? operationModel.input : undefined;
7180
7181 var identifiers = marshallCustomIdentifiers(request, inputShape);
7182 var cacheKey = getCacheKey(request);
7183 if (Object.keys(identifiers).length > 0) {
7184 cacheKey = util.update(cacheKey, identifiers);
7185 if (operationModel) cacheKey.operation = operationModel.name;
7186 }
7187 var cacheKeyStr = AWS.EndpointCache.getKeyString(cacheKey);
7188 var endpoints = AWS.endpointCache.get(cacheKeyStr); //endpoint cache also accepts string keys
7189 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
7190 //endpoint operation is being made but response not yet received
7191 //push request object to a pending queue
7192 if (!requestQueue[cacheKeyStr]) requestQueue[cacheKeyStr] = [];
7193 requestQueue[cacheKeyStr].push({request: request, callback: done});
7194 return;
7195 } else if (endpoints && endpoints.length > 0) {
7196 request.httpRequest.updateEndpoint(endpoints[0].Address);
7197 done();
7198 } else {
7199 var endpointRequest = service.makeRequest(api.endpointOperation, {
7200 Operation: operationModel.name,
7201 Identifiers: identifiers,
7202 });
7203 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
7204 addApiVersionHeader(endpointRequest);
7205
7206 //put in a placeholder for endpoints already requested, prevent
7207 //too much in-flight calls
7208 AWS.endpointCache.put(cacheKeyStr, [{
7209 Address: '',
7210 CachePeriodInMinutes: 60 //long-live cache
7211 }]);
7212 endpointRequest.send(function(err, data) {
7213 if (err) {
7214 var errorParams = {
7215 code: 'EndpointDiscoveryException',
7216 message: 'Request cannot be fulfilled without specifying an endpoint',
7217 retryable: false
7218 };
7219 request.response.error = util.error(err, errorParams);
7220 AWS.endpointCache.remove(cacheKey);
7221
7222 //fail all the pending requests in batch
7223 if (requestQueue[cacheKeyStr]) {
7224 var pendingRequests = requestQueue[cacheKeyStr];
7225 util.arrayEach(pendingRequests, function(requestContext) {
7226 requestContext.request.response.error = util.error(err, errorParams);
7227 requestContext.callback();
7228 });
7229 delete requestQueue[cacheKeyStr];
7230 }
7231 } else if (data) {
7232 AWS.endpointCache.put(cacheKeyStr, data.Endpoints);
7233 request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7234
7235 //update the endpoint for all the pending requests in batch
7236 if (requestQueue[cacheKeyStr]) {
7237 var pendingRequests = requestQueue[cacheKeyStr];
7238 util.arrayEach(pendingRequests, function(requestContext) {
7239 requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7240 requestContext.callback();
7241 });
7242 delete requestQueue[cacheKeyStr];
7243 }
7244 }
7245 done();
7246 });
7247 }
7248 }
7249
7250 /**
7251 * add api version header to endpoint operation
7252 * @api private
7253 */
7254 function addApiVersionHeader(endpointRequest) {
7255 var api = endpointRequest.service.api;
7256 var apiVersion = api.apiVersion;
7257 if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) {
7258 endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion;
7259 }
7260 }
7261
7262 /**
7263 * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid
7264 * endpoint from cache.
7265 * @api private
7266 */
7267 function invalidateCachedEndpoints(response) {
7268 var error = response.error;
7269 var httpResponse = response.httpResponse;
7270 if (error &&
7271 (error.code === 'InvalidEndpointException' || httpResponse.statusCode === 421)
7272 ) {
7273 var request = response.request;
7274 var operations = request.service.api.operations || {};
7275 var inputShape = operations[request.operation] ? operations[request.operation].input : undefined;
7276 var identifiers = marshallCustomIdentifiers(request, inputShape);
7277 var cacheKey = getCacheKey(request);
7278 if (Object.keys(identifiers).length > 0) {
7279 cacheKey = util.update(cacheKey, identifiers);
7280 if (operations[request.operation]) cacheKey.operation = operations[request.operation].name;
7281 }
7282 AWS.endpointCache.remove(cacheKey);
7283 }
7284 }
7285
7286 /**
7287 * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime.
7288 * @param [object] client Service client object.
7289 * @api private
7290 */
7291 function hasCustomEndpoint(client) {
7292 //if set endpoint is set for specific client, enable endpoint discovery will raise an error.
7293 if (client._originalConfig && client._originalConfig.endpoint && client._originalConfig.endpointDiscoveryEnabled === true) {
7294 throw util.error(new Error(), {
7295 code: 'ConfigurationException',
7296 message: 'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.'
7297 });
7298 };
7299 var svcConfig = AWS.config[client.serviceIdentifier] || {};
7300 return Boolean(AWS.config.endpoint || svcConfig.endpoint || (client._originalConfig && client._originalConfig.endpoint));
7301 }
7302
7303 /**
7304 * @api private
7305 */
7306 function isFalsy(value) {
7307 return ['false', '0'].indexOf(value) >= 0;
7308 }
7309
7310 /**
7311 * If endpoint discovery should perform for this request when endpoint discovery is optional.
7312 * SDK performs config resolution in order like below:
7313 * 1. If turned on client configuration(default to off) then turn on endpoint discovery.
7314 * 2. If turned on in env AWS_ENABLE_ENDPOINT_DISCOVERY then turn on endpoint discovery.
7315 * 3. If turned on in shared ini config file with key 'endpoint_discovery_enabled', then
7316 * turn on endpoint discovery.
7317 * @param [object] request request object.
7318 * @api private
7319 */
7320 function isEndpointDiscoveryApplicable(request) {
7321 var service = request.service || {};
7322 if (service.config.endpointDiscoveryEnabled === true) return true;
7323
7324 //shared ini file is only available in Node
7325 //not to check env in browser
7326 if (util.isBrowser()) return false;
7327
7328 for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) {
7329 var env = endpointDiscoveryEnabledEnvs[i];
7330 if (Object.prototype.hasOwnProperty.call(process.env, env)) {
7331 if (process.env[env] === '' || process.env[env] === undefined) {
7332 throw util.error(new Error(), {
7333 code: 'ConfigurationException',
7334 message: 'environmental variable ' + env + ' cannot be set to nothing'
7335 });
7336 }
7337 if (!isFalsy(process.env[env])) return true;
7338 }
7339 }
7340
7341 var configFile = {};
7342 try {
7343 configFile = AWS.util.iniLoader ? AWS.util.iniLoader.loadFrom({
7344 isConfig: true,
7345 filename: process.env[AWS.util.sharedConfigFileEnv]
7346 }) : {};
7347 } catch (e) {}
7348 var sharedFileConfig = configFile[
7349 process.env.AWS_PROFILE || AWS.util.defaultProfile
7350 ] || {};
7351 if (Object.prototype.hasOwnProperty.call(sharedFileConfig, 'endpoint_discovery_enabled')) {
7352 if (sharedFileConfig.endpoint_discovery_enabled === undefined) {
7353 throw util.error(new Error(), {
7354 code: 'ConfigurationException',
7355 message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing'
7356 });
7357 }
7358 if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true;
7359 }
7360 return false;
7361 }
7362
7363 /**
7364 * attach endpoint discovery logic to request object
7365 * @param [object] request
7366 * @api private
7367 */
7368 function discoverEndpoint(request, done) {
7369 var service = request.service || {};
7370 if (hasCustomEndpoint(service) || request.isPresigned()) return done();
7371
7372 if (!isEndpointDiscoveryApplicable(request)) return done();
7373
7374 request.httpRequest.appendToUserAgent('endpoint-discovery');
7375
7376 var operations = service.api.operations || {};
7377 var operationModel = operations[request.operation];
7378 var isEndpointDiscoveryRequired = operationModel ? operationModel.endpointDiscoveryRequired : 'NULL';
7379 switch (isEndpointDiscoveryRequired) {
7380 case 'OPTIONAL':
7381 optionalDiscoverEndpoint(request);
7382 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7383 done();
7384 break;
7385 case 'REQUIRED':
7386 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7387 requiredDiscoverEndpoint(request, done);
7388 break;
7389 case 'NULL':
7390 default:
7391 done();
7392 break;
7393 }
7394 }
7395
7396 module.exports = {
7397 discoverEndpoint: discoverEndpoint,
7398 requiredDiscoverEndpoint: requiredDiscoverEndpoint,
7399 optionalDiscoverEndpoint: optionalDiscoverEndpoint,
7400 marshallCustomIdentifiers: marshallCustomIdentifiers,
7401 getCacheKey: getCacheKey,
7402 invalidateCachedEndpoint: invalidateCachedEndpoints,
7403 };
7404
7405 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
7406
7407/***/ }),
7408/* 46 */
7409/***/ (function(module, exports, __webpack_require__) {
7410
7411 /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
7412 //
7413 // Permission is hereby granted, free of charge, to any person obtaining a
7414 // copy of this software and associated documentation files (the
7415 // "Software"), to deal in the Software without restriction, including
7416 // without limitation the rights to use, copy, modify, merge, publish,
7417 // distribute, sublicense, and/or sell copies of the Software, and to permit
7418 // persons to whom the Software is furnished to do so, subject to the
7419 // following conditions:
7420 //
7421 // The above copyright notice and this permission notice shall be included
7422 // in all copies or substantial portions of the Software.
7423 //
7424 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7425 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7426 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7427 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7428 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7429 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7430 // USE OR OTHER DEALINGS IN THE SOFTWARE.
7431
7432 var formatRegExp = /%[sdj%]/g;
7433 exports.format = function(f) {
7434 if (!isString(f)) {
7435 var objects = [];
7436 for (var i = 0; i < arguments.length; i++) {
7437 objects.push(inspect(arguments[i]));
7438 }
7439 return objects.join(' ');
7440 }
7441
7442 var i = 1;
7443 var args = arguments;
7444 var len = args.length;
7445 var str = String(f).replace(formatRegExp, function(x) {
7446 if (x === '%%') return '%';
7447 if (i >= len) return x;
7448 switch (x) {
7449 case '%s': return String(args[i++]);
7450 case '%d': return Number(args[i++]);
7451 case '%j':
7452 try {
7453 return JSON.stringify(args[i++]);
7454 } catch (_) {
7455 return '[Circular]';
7456 }
7457 default:
7458 return x;
7459 }
7460 });
7461 for (var x = args[i]; i < len; x = args[++i]) {
7462 if (isNull(x) || !isObject(x)) {
7463 str += ' ' + x;
7464 } else {
7465 str += ' ' + inspect(x);
7466 }
7467 }
7468 return str;
7469 };
7470
7471
7472 // Mark that a method should not be used.
7473 // Returns a modified function which warns once by default.
7474 // If --no-deprecation is set, then it is a no-op.
7475 exports.deprecate = function(fn, msg) {
7476 // Allow for deprecating things in the process of starting up.
7477 if (isUndefined(global.process)) {
7478 return function() {
7479 return exports.deprecate(fn, msg).apply(this, arguments);
7480 };
7481 }
7482
7483 if (process.noDeprecation === true) {
7484 return fn;
7485 }
7486
7487 var warned = false;
7488 function deprecated() {
7489 if (!warned) {
7490 if (process.throwDeprecation) {
7491 throw new Error(msg);
7492 } else if (process.traceDeprecation) {
7493 console.trace(msg);
7494 } else {
7495 console.error(msg);
7496 }
7497 warned = true;
7498 }
7499 return fn.apply(this, arguments);
7500 }
7501
7502 return deprecated;
7503 };
7504
7505
7506 var debugs = {};
7507 var debugEnviron;
7508 exports.debuglog = function(set) {
7509 if (isUndefined(debugEnviron))
7510 debugEnviron = process.env.NODE_DEBUG || '';
7511 set = set.toUpperCase();
7512 if (!debugs[set]) {
7513 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
7514 var pid = process.pid;
7515 debugs[set] = function() {
7516 var msg = exports.format.apply(exports, arguments);
7517 console.error('%s %d: %s', set, pid, msg);
7518 };
7519 } else {
7520 debugs[set] = function() {};
7521 }
7522 }
7523 return debugs[set];
7524 };
7525
7526
7527 /**
7528 * Echos the value of a value. Trys to print the value out
7529 * in the best way possible given the different types.
7530 *
7531 * @param {Object} obj The object to print out.
7532 * @param {Object} opts Optional options object that alters the output.
7533 */
7534 /* legacy: obj, showHidden, depth, colors*/
7535 function inspect(obj, opts) {
7536 // default options
7537 var ctx = {
7538 seen: [],
7539 stylize: stylizeNoColor
7540 };
7541 // legacy...
7542 if (arguments.length >= 3) ctx.depth = arguments[2];
7543 if (arguments.length >= 4) ctx.colors = arguments[3];
7544 if (isBoolean(opts)) {
7545 // legacy...
7546 ctx.showHidden = opts;
7547 } else if (opts) {
7548 // got an "options" object
7549 exports._extend(ctx, opts);
7550 }
7551 // set default options
7552 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
7553 if (isUndefined(ctx.depth)) ctx.depth = 2;
7554 if (isUndefined(ctx.colors)) ctx.colors = false;
7555 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
7556 if (ctx.colors) ctx.stylize = stylizeWithColor;
7557 return formatValue(ctx, obj, ctx.depth);
7558 }
7559 exports.inspect = inspect;
7560
7561
7562 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
7563 inspect.colors = {
7564 'bold' : [1, 22],
7565 'italic' : [3, 23],
7566 'underline' : [4, 24],
7567 'inverse' : [7, 27],
7568 'white' : [37, 39],
7569 'grey' : [90, 39],
7570 'black' : [30, 39],
7571 'blue' : [34, 39],
7572 'cyan' : [36, 39],
7573 'green' : [32, 39],
7574 'magenta' : [35, 39],
7575 'red' : [31, 39],
7576 'yellow' : [33, 39]
7577 };
7578
7579 // Don't use 'blue' not visible on cmd.exe
7580 inspect.styles = {
7581 'special': 'cyan',
7582 'number': 'yellow',
7583 'boolean': 'yellow',
7584 'undefined': 'grey',
7585 'null': 'bold',
7586 'string': 'green',
7587 'date': 'magenta',
7588 // "name": intentionally not styling
7589 'regexp': 'red'
7590 };
7591
7592
7593 function stylizeWithColor(str, styleType) {
7594 var style = inspect.styles[styleType];
7595
7596 if (style) {
7597 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
7598 '\u001b[' + inspect.colors[style][1] + 'm';
7599 } else {
7600 return str;
7601 }
7602 }
7603
7604
7605 function stylizeNoColor(str, styleType) {
7606 return str;
7607 }
7608
7609
7610 function arrayToHash(array) {
7611 var hash = {};
7612
7613 array.forEach(function(val, idx) {
7614 hash[val] = true;
7615 });
7616
7617 return hash;
7618 }
7619
7620
7621 function formatValue(ctx, value, recurseTimes) {
7622 // Provide a hook for user-specified inspect functions.
7623 // Check that value is an object with an inspect function on it
7624 if (ctx.customInspect &&
7625 value &&
7626 isFunction(value.inspect) &&
7627 // Filter out the util module, it's inspect function is special
7628 value.inspect !== exports.inspect &&
7629 // Also filter out any prototype objects using the circular check.
7630 !(value.constructor && value.constructor.prototype === value)) {
7631 var ret = value.inspect(recurseTimes, ctx);
7632 if (!isString(ret)) {
7633 ret = formatValue(ctx, ret, recurseTimes);
7634 }
7635 return ret;
7636 }
7637
7638 // Primitive types cannot have properties
7639 var primitive = formatPrimitive(ctx, value);
7640 if (primitive) {
7641 return primitive;
7642 }
7643
7644 // Look up the keys of the object.
7645 var keys = Object.keys(value);
7646 var visibleKeys = arrayToHash(keys);
7647
7648 if (ctx.showHidden) {
7649 keys = Object.getOwnPropertyNames(value);
7650 }
7651
7652 // IE doesn't make error fields non-enumerable
7653 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
7654 if (isError(value)
7655 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
7656 return formatError(value);
7657 }
7658
7659 // Some type of object without properties can be shortcutted.
7660 if (keys.length === 0) {
7661 if (isFunction(value)) {
7662 var name = value.name ? ': ' + value.name : '';
7663 return ctx.stylize('[Function' + name + ']', 'special');
7664 }
7665 if (isRegExp(value)) {
7666 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7667 }
7668 if (isDate(value)) {
7669 return ctx.stylize(Date.prototype.toString.call(value), 'date');
7670 }
7671 if (isError(value)) {
7672 return formatError(value);
7673 }
7674 }
7675
7676 var base = '', array = false, braces = ['{', '}'];
7677
7678 // Make Array say that they are Array
7679 if (isArray(value)) {
7680 array = true;
7681 braces = ['[', ']'];
7682 }
7683
7684 // Make functions say that they are functions
7685 if (isFunction(value)) {
7686 var n = value.name ? ': ' + value.name : '';
7687 base = ' [Function' + n + ']';
7688 }
7689
7690 // Make RegExps say that they are RegExps
7691 if (isRegExp(value)) {
7692 base = ' ' + RegExp.prototype.toString.call(value);
7693 }
7694
7695 // Make dates with properties first say the date
7696 if (isDate(value)) {
7697 base = ' ' + Date.prototype.toUTCString.call(value);
7698 }
7699
7700 // Make error with message first say the error
7701 if (isError(value)) {
7702 base = ' ' + formatError(value);
7703 }
7704
7705 if (keys.length === 0 && (!array || value.length == 0)) {
7706 return braces[0] + base + braces[1];
7707 }
7708
7709 if (recurseTimes < 0) {
7710 if (isRegExp(value)) {
7711 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7712 } else {
7713 return ctx.stylize('[Object]', 'special');
7714 }
7715 }
7716
7717 ctx.seen.push(value);
7718
7719 var output;
7720 if (array) {
7721 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
7722 } else {
7723 output = keys.map(function(key) {
7724 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
7725 });
7726 }
7727
7728 ctx.seen.pop();
7729
7730 return reduceToSingleString(output, base, braces);
7731 }
7732
7733
7734 function formatPrimitive(ctx, value) {
7735 if (isUndefined(value))
7736 return ctx.stylize('undefined', 'undefined');
7737 if (isString(value)) {
7738 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
7739 .replace(/'/g, "\\'")
7740 .replace(/\\"/g, '"') + '\'';
7741 return ctx.stylize(simple, 'string');
7742 }
7743 if (isNumber(value))
7744 return ctx.stylize('' + value, 'number');
7745 if (isBoolean(value))
7746 return ctx.stylize('' + value, 'boolean');
7747 // For some reason typeof null is "object", so special case here.
7748 if (isNull(value))
7749 return ctx.stylize('null', 'null');
7750 }
7751
7752
7753 function formatError(value) {
7754 return '[' + Error.prototype.toString.call(value) + ']';
7755 }
7756
7757
7758 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
7759 var output = [];
7760 for (var i = 0, l = value.length; i < l; ++i) {
7761 if (hasOwnProperty(value, String(i))) {
7762 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7763 String(i), true));
7764 } else {
7765 output.push('');
7766 }
7767 }
7768 keys.forEach(function(key) {
7769 if (!key.match(/^\d+$/)) {
7770 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7771 key, true));
7772 }
7773 });
7774 return output;
7775 }
7776
7777
7778 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
7779 var name, str, desc;
7780 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
7781 if (desc.get) {
7782 if (desc.set) {
7783 str = ctx.stylize('[Getter/Setter]', 'special');
7784 } else {
7785 str = ctx.stylize('[Getter]', 'special');
7786 }
7787 } else {
7788 if (desc.set) {
7789 str = ctx.stylize('[Setter]', 'special');
7790 }
7791 }
7792 if (!hasOwnProperty(visibleKeys, key)) {
7793 name = '[' + key + ']';
7794 }
7795 if (!str) {
7796 if (ctx.seen.indexOf(desc.value) < 0) {
7797 if (isNull(recurseTimes)) {
7798 str = formatValue(ctx, desc.value, null);
7799 } else {
7800 str = formatValue(ctx, desc.value, recurseTimes - 1);
7801 }
7802 if (str.indexOf('\n') > -1) {
7803 if (array) {
7804 str = str.split('\n').map(function(line) {
7805 return ' ' + line;
7806 }).join('\n').substr(2);
7807 } else {
7808 str = '\n' + str.split('\n').map(function(line) {
7809 return ' ' + line;
7810 }).join('\n');
7811 }
7812 }
7813 } else {
7814 str = ctx.stylize('[Circular]', 'special');
7815 }
7816 }
7817 if (isUndefined(name)) {
7818 if (array && key.match(/^\d+$/)) {
7819 return str;
7820 }
7821 name = JSON.stringify('' + key);
7822 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
7823 name = name.substr(1, name.length - 2);
7824 name = ctx.stylize(name, 'name');
7825 } else {
7826 name = name.replace(/'/g, "\\'")
7827 .replace(/\\"/g, '"')
7828 .replace(/(^"|"$)/g, "'");
7829 name = ctx.stylize(name, 'string');
7830 }
7831 }
7832
7833 return name + ': ' + str;
7834 }
7835
7836
7837 function reduceToSingleString(output, base, braces) {
7838 var numLinesEst = 0;
7839 var length = output.reduce(function(prev, cur) {
7840 numLinesEst++;
7841 if (cur.indexOf('\n') >= 0) numLinesEst++;
7842 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
7843 }, 0);
7844
7845 if (length > 60) {
7846 return braces[0] +
7847 (base === '' ? '' : base + '\n ') +
7848 ' ' +
7849 output.join(',\n ') +
7850 ' ' +
7851 braces[1];
7852 }
7853
7854 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
7855 }
7856
7857
7858 // NOTE: These type checking functions intentionally don't use `instanceof`
7859 // because it is fragile and can be easily faked with `Object.create()`.
7860 function isArray(ar) {
7861 return Array.isArray(ar);
7862 }
7863 exports.isArray = isArray;
7864
7865 function isBoolean(arg) {
7866 return typeof arg === 'boolean';
7867 }
7868 exports.isBoolean = isBoolean;
7869
7870 function isNull(arg) {
7871 return arg === null;
7872 }
7873 exports.isNull = isNull;
7874
7875 function isNullOrUndefined(arg) {
7876 return arg == null;
7877 }
7878 exports.isNullOrUndefined = isNullOrUndefined;
7879
7880 function isNumber(arg) {
7881 return typeof arg === 'number';
7882 }
7883 exports.isNumber = isNumber;
7884
7885 function isString(arg) {
7886 return typeof arg === 'string';
7887 }
7888 exports.isString = isString;
7889
7890 function isSymbol(arg) {
7891 return typeof arg === 'symbol';
7892 }
7893 exports.isSymbol = isSymbol;
7894
7895 function isUndefined(arg) {
7896 return arg === void 0;
7897 }
7898 exports.isUndefined = isUndefined;
7899
7900 function isRegExp(re) {
7901 return isObject(re) && objectToString(re) === '[object RegExp]';
7902 }
7903 exports.isRegExp = isRegExp;
7904
7905 function isObject(arg) {
7906 return typeof arg === 'object' && arg !== null;
7907 }
7908 exports.isObject = isObject;
7909
7910 function isDate(d) {
7911 return isObject(d) && objectToString(d) === '[object Date]';
7912 }
7913 exports.isDate = isDate;
7914
7915 function isError(e) {
7916 return isObject(e) &&
7917 (objectToString(e) === '[object Error]' || e instanceof Error);
7918 }
7919 exports.isError = isError;
7920
7921 function isFunction(arg) {
7922 return typeof arg === 'function';
7923 }
7924 exports.isFunction = isFunction;
7925
7926 function isPrimitive(arg) {
7927 return arg === null ||
7928 typeof arg === 'boolean' ||
7929 typeof arg === 'number' ||
7930 typeof arg === 'string' ||
7931 typeof arg === 'symbol' || // ES6 symbol
7932 typeof arg === 'undefined';
7933 }
7934 exports.isPrimitive = isPrimitive;
7935
7936 exports.isBuffer = __webpack_require__(47);
7937
7938 function objectToString(o) {
7939 return Object.prototype.toString.call(o);
7940 }
7941
7942
7943 function pad(n) {
7944 return n < 10 ? '0' + n.toString(10) : n.toString(10);
7945 }
7946
7947
7948 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
7949 'Oct', 'Nov', 'Dec'];
7950
7951 // 26 Feb 16:19:34
7952 function timestamp() {
7953 var d = new Date();
7954 var time = [pad(d.getHours()),
7955 pad(d.getMinutes()),
7956 pad(d.getSeconds())].join(':');
7957 return [d.getDate(), months[d.getMonth()], time].join(' ');
7958 }
7959
7960
7961 // log is just a thin wrapper to console.log that prepends a timestamp
7962 exports.log = function() {
7963 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
7964 };
7965
7966
7967 /**
7968 * Inherit the prototype methods from one constructor into another.
7969 *
7970 * The Function.prototype.inherits from lang.js rewritten as a standalone
7971 * function (not on Function.prototype). NOTE: If this file is to be loaded
7972 * during bootstrapping this function needs to be rewritten using some native
7973 * functions as prototype setup using normal JavaScript does not work as
7974 * expected during bootstrapping (see mirror.js in r114903).
7975 *
7976 * @param {function} ctor Constructor function which needs to inherit the
7977 * prototype.
7978 * @param {function} superCtor Constructor function to inherit prototype from.
7979 */
7980 exports.inherits = __webpack_require__(48);
7981
7982 exports._extend = function(origin, add) {
7983 // Don't do anything if add isn't an object
7984 if (!add || !isObject(add)) return origin;
7985
7986 var keys = Object.keys(add);
7987 var i = keys.length;
7988 while (i--) {
7989 origin[keys[i]] = add[keys[i]];
7990 }
7991 return origin;
7992 };
7993
7994 function hasOwnProperty(obj, prop) {
7995 return Object.prototype.hasOwnProperty.call(obj, prop);
7996 }
7997
7998 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
7999
8000/***/ }),
8001/* 47 */
8002/***/ (function(module, exports) {
8003
8004 module.exports = function isBuffer(arg) {
8005 return arg && typeof arg === 'object'
8006 && typeof arg.copy === 'function'
8007 && typeof arg.fill === 'function'
8008 && typeof arg.readUInt8 === 'function';
8009 }
8010
8011/***/ }),
8012/* 48 */
8013/***/ (function(module, exports) {
8014
8015 if (typeof Object.create === 'function') {
8016 // implementation from standard node.js 'util' module
8017 module.exports = function inherits(ctor, superCtor) {
8018 ctor.super_ = superCtor
8019 ctor.prototype = Object.create(superCtor.prototype, {
8020 constructor: {
8021 value: ctor,
8022 enumerable: false,
8023 writable: true,
8024 configurable: true
8025 }
8026 });
8027 };
8028 } else {
8029 // old school shim for old browsers
8030 module.exports = function inherits(ctor, superCtor) {
8031 ctor.super_ = superCtor
8032 var TempCtor = function () {}
8033 TempCtor.prototype = superCtor.prototype
8034 ctor.prototype = new TempCtor()
8035 ctor.prototype.constructor = ctor
8036 }
8037 }
8038
8039
8040/***/ }),
8041/* 49 */
8042/***/ (function(module, exports, __webpack_require__) {
8043
8044 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
8045 var AcceptorStateMachine = __webpack_require__(50);
8046 var inherit = AWS.util.inherit;
8047 var domain = AWS.util.domain;
8048 var jmespath = __webpack_require__(51);
8049
8050 /**
8051 * @api private
8052 */
8053 var hardErrorStates = {success: 1, error: 1, complete: 1};
8054
8055 function isTerminalState(machine) {
8056 return Object.prototype.hasOwnProperty.call(hardErrorStates, machine._asm.currentState);
8057 }
8058
8059 var fsm = new AcceptorStateMachine();
8060 fsm.setupStates = function() {
8061 var transition = function(_, done) {
8062 var self = this;
8063 self._haltHandlersOnError = false;
8064
8065 self.emit(self._asm.currentState, function(err) {
8066 if (err) {
8067 if (isTerminalState(self)) {
8068 if (domain && self.domain instanceof domain.Domain) {
8069 err.domainEmitter = self;
8070 err.domain = self.domain;
8071 err.domainThrown = false;
8072 self.domain.emit('error', err);
8073 } else {
8074 throw err;
8075 }
8076 } else {
8077 self.response.error = err;
8078 done(err);
8079 }
8080 } else {
8081 done(self.response.error);
8082 }
8083 });
8084
8085 };
8086
8087 this.addState('validate', 'build', 'error', transition);
8088 this.addState('build', 'afterBuild', 'restart', transition);
8089 this.addState('afterBuild', 'sign', 'restart', transition);
8090 this.addState('sign', 'send', 'retry', transition);
8091 this.addState('retry', 'afterRetry', 'afterRetry', transition);
8092 this.addState('afterRetry', 'sign', 'error', transition);
8093 this.addState('send', 'validateResponse', 'retry', transition);
8094 this.addState('validateResponse', 'extractData', 'extractError', transition);
8095 this.addState('extractError', 'extractData', 'retry', transition);
8096 this.addState('extractData', 'success', 'retry', transition);
8097 this.addState('restart', 'build', 'error', transition);
8098 this.addState('success', 'complete', 'complete', transition);
8099 this.addState('error', 'complete', 'complete', transition);
8100 this.addState('complete', null, null, transition);
8101 };
8102 fsm.setupStates();
8103
8104 /**
8105 * ## Asynchronous Requests
8106 *
8107 * All requests made through the SDK are asynchronous and use a
8108 * callback interface. Each service method that kicks off a request
8109 * returns an `AWS.Request` object that you can use to register
8110 * callbacks.
8111 *
8112 * For example, the following service method returns the request
8113 * object as "request", which can be used to register callbacks:
8114 *
8115 * ```javascript
8116 * // request is an AWS.Request object
8117 * var request = ec2.describeInstances();
8118 *
8119 * // register callbacks on request to retrieve response data
8120 * request.on('success', function(response) {
8121 * console.log(response.data);
8122 * });
8123 * ```
8124 *
8125 * When a request is ready to be sent, the {send} method should
8126 * be called:
8127 *
8128 * ```javascript
8129 * request.send();
8130 * ```
8131 *
8132 * Since registered callbacks may or may not be idempotent, requests should only
8133 * be sent once. To perform the same operation multiple times, you will need to
8134 * create multiple request objects, each with its own registered callbacks.
8135 *
8136 * ## Removing Default Listeners for Events
8137 *
8138 * Request objects are built with default listeners for the various events,
8139 * depending on the service type. In some cases, you may want to remove
8140 * some built-in listeners to customize behaviour. Doing this requires
8141 * access to the built-in listener functions, which are exposed through
8142 * the {AWS.EventListeners.Core} namespace. For instance, you may
8143 * want to customize the HTTP handler used when sending a request. In this
8144 * case, you can remove the built-in listener associated with the 'send'
8145 * event, the {AWS.EventListeners.Core.SEND} listener and add your own.
8146 *
8147 * ## Multiple Callbacks and Chaining
8148 *
8149 * You can register multiple callbacks on any request object. The
8150 * callbacks can be registered for different events, or all for the
8151 * same event. In addition, you can chain callback registration, for
8152 * example:
8153 *
8154 * ```javascript
8155 * request.
8156 * on('success', function(response) {
8157 * console.log("Success!");
8158 * }).
8159 * on('error', function(error, response) {
8160 * console.log("Error!");
8161 * }).
8162 * on('complete', function(response) {
8163 * console.log("Always!");
8164 * }).
8165 * send();
8166 * ```
8167 *
8168 * The above example will print either "Success! Always!", or "Error! Always!",
8169 * depending on whether the request succeeded or not.
8170 *
8171 * @!attribute httpRequest
8172 * @readonly
8173 * @!group HTTP Properties
8174 * @return [AWS.HttpRequest] the raw HTTP request object
8175 * containing request headers and body information
8176 * sent by the service.
8177 *
8178 * @!attribute startTime
8179 * @readonly
8180 * @!group Operation Properties
8181 * @return [Date] the time that the request started
8182 *
8183 * @!group Request Building Events
8184 *
8185 * @!event validate(request)
8186 * Triggered when a request is being validated. Listeners
8187 * should throw an error if the request should not be sent.
8188 * @param request [Request] the request object being sent
8189 * @see AWS.EventListeners.Core.VALIDATE_CREDENTIALS
8190 * @see AWS.EventListeners.Core.VALIDATE_REGION
8191 * @example Ensuring that a certain parameter is set before sending a request
8192 * var req = s3.putObject(params);
8193 * req.on('validate', function() {
8194 * if (!req.params.Body.match(/^Hello\s/)) {
8195 * throw new Error('Body must start with "Hello "');
8196 * }
8197 * });
8198 * req.send(function(err, data) { ... });
8199 *
8200 * @!event build(request)
8201 * Triggered when the request payload is being built. Listeners
8202 * should fill the necessary information to send the request
8203 * over HTTP.
8204 * @param (see AWS.Request~validate)
8205 * @example Add a custom HTTP header to a request
8206 * var req = s3.putObject(params);
8207 * req.on('build', function() {
8208 * req.httpRequest.headers['Custom-Header'] = 'value';
8209 * });
8210 * req.send(function(err, data) { ... });
8211 *
8212 * @!event sign(request)
8213 * Triggered when the request is being signed. Listeners should
8214 * add the correct authentication headers and/or adjust the body,
8215 * depending on the authentication mechanism being used.
8216 * @param (see AWS.Request~validate)
8217 *
8218 * @!group Request Sending Events
8219 *
8220 * @!event send(response)
8221 * Triggered when the request is ready to be sent. Listeners
8222 * should call the underlying transport layer to initiate
8223 * the sending of the request.
8224 * @param response [Response] the response object
8225 * @context [Request] the request object that was sent
8226 * @see AWS.EventListeners.Core.SEND
8227 *
8228 * @!event retry(response)
8229 * Triggered when a request failed and might need to be retried or redirected.
8230 * If the response is retryable, the listener should set the
8231 * `response.error.retryable` property to `true`, and optionally set
8232 * `response.error.retryDelay` to the millisecond delay for the next attempt.
8233 * In the case of a redirect, `response.error.redirect` should be set to
8234 * `true` with `retryDelay` set to an optional delay on the next request.
8235 *
8236 * If a listener decides that a request should not be retried,
8237 * it should set both `retryable` and `redirect` to false.
8238 *
8239 * Note that a retryable error will be retried at most
8240 * {AWS.Config.maxRetries} times (based on the service object's config).
8241 * Similarly, a request that is redirected will only redirect at most
8242 * {AWS.Config.maxRedirects} times.
8243 *
8244 * @param (see AWS.Request~send)
8245 * @context (see AWS.Request~send)
8246 * @example Adding a custom retry for a 404 response
8247 * request.on('retry', function(response) {
8248 * // this resource is not yet available, wait 10 seconds to get it again
8249 * if (response.httpResponse.statusCode === 404 && response.error) {
8250 * response.error.retryable = true; // retry this error
8251 * response.error.retryDelay = 10000; // wait 10 seconds
8252 * }
8253 * });
8254 *
8255 * @!group Data Parsing Events
8256 *
8257 * @!event extractError(response)
8258 * Triggered on all non-2xx requests so that listeners can extract
8259 * error details from the response body. Listeners to this event
8260 * should set the `response.error` property.
8261 * @param (see AWS.Request~send)
8262 * @context (see AWS.Request~send)
8263 *
8264 * @!event extractData(response)
8265 * Triggered in successful requests to allow listeners to
8266 * de-serialize the response body into `response.data`.
8267 * @param (see AWS.Request~send)
8268 * @context (see AWS.Request~send)
8269 *
8270 * @!group Completion Events
8271 *
8272 * @!event success(response)
8273 * Triggered when the request completed successfully.
8274 * `response.data` will contain the response data and
8275 * `response.error` will be null.
8276 * @param (see AWS.Request~send)
8277 * @context (see AWS.Request~send)
8278 *
8279 * @!event error(error, response)
8280 * Triggered when an error occurs at any point during the
8281 * request. `response.error` will contain details about the error
8282 * that occurred. `response.data` will be null.
8283 * @param error [Error] the error object containing details about
8284 * the error that occurred.
8285 * @param (see AWS.Request~send)
8286 * @context (see AWS.Request~send)
8287 *
8288 * @!event complete(response)
8289 * Triggered whenever a request cycle completes. `response.error`
8290 * should be checked, since the request may have failed.
8291 * @param (see AWS.Request~send)
8292 * @context (see AWS.Request~send)
8293 *
8294 * @!group HTTP Events
8295 *
8296 * @!event httpHeaders(statusCode, headers, response, statusMessage)
8297 * Triggered when headers are sent by the remote server
8298 * @param statusCode [Integer] the HTTP response code
8299 * @param headers [map<String,String>] the response headers
8300 * @param (see AWS.Request~send)
8301 * @param statusMessage [String] A status message corresponding to the HTTP
8302 * response code
8303 * @context (see AWS.Request~send)
8304 *
8305 * @!event httpData(chunk, response)
8306 * Triggered when data is sent by the remote server
8307 * @param chunk [Buffer] the buffer data containing the next data chunk
8308 * from the server
8309 * @param (see AWS.Request~send)
8310 * @context (see AWS.Request~send)
8311 * @see AWS.EventListeners.Core.HTTP_DATA
8312 *
8313 * @!event httpUploadProgress(progress, response)
8314 * Triggered when the HTTP request has uploaded more data
8315 * @param progress [map] An object containing the `loaded` and `total` bytes
8316 * of the request.
8317 * @param (see AWS.Request~send)
8318 * @context (see AWS.Request~send)
8319 * @note This event will not be emitted in Node.js 0.8.x.
8320 *
8321 * @!event httpDownloadProgress(progress, response)
8322 * Triggered when the HTTP request has downloaded more data
8323 * @param progress [map] An object containing the `loaded` and `total` bytes
8324 * of the request.
8325 * @param (see AWS.Request~send)
8326 * @context (see AWS.Request~send)
8327 * @note This event will not be emitted in Node.js 0.8.x.
8328 *
8329 * @!event httpError(error, response)
8330 * Triggered when the HTTP request failed
8331 * @param error [Error] the error object that was thrown
8332 * @param (see AWS.Request~send)
8333 * @context (see AWS.Request~send)
8334 *
8335 * @!event httpDone(response)
8336 * Triggered when the server is finished sending data
8337 * @param (see AWS.Request~send)
8338 * @context (see AWS.Request~send)
8339 *
8340 * @see AWS.Response
8341 */
8342 AWS.Request = inherit({
8343
8344 /**
8345 * Creates a request for an operation on a given service with
8346 * a set of input parameters.
8347 *
8348 * @param service [AWS.Service] the service to perform the operation on
8349 * @param operation [String] the operation to perform on the service
8350 * @param params [Object] parameters to send to the operation.
8351 * See the operation's documentation for the format of the
8352 * parameters.
8353 */
8354 constructor: function Request(service, operation, params) {
8355 var endpoint = service.endpoint;
8356 var region = service.config.region;
8357 var customUserAgent = service.config.customUserAgent;
8358
8359 // global endpoints sign as us-east-1
8360 if (service.isGlobalEndpoint) region = 'us-east-1';
8361
8362 this.domain = domain && domain.active;
8363 this.service = service;
8364 this.operation = operation;
8365 this.params = params || {};
8366 this.httpRequest = new AWS.HttpRequest(endpoint, region);
8367 this.httpRequest.appendToUserAgent(customUserAgent);
8368 this.startTime = service.getSkewCorrectedDate();
8369
8370 this.response = new AWS.Response(this);
8371 this._asm = new AcceptorStateMachine(fsm.states, 'validate');
8372 this._haltHandlersOnError = false;
8373
8374 AWS.SequentialExecutor.call(this);
8375 this.emit = this.emitEvent;
8376 },
8377
8378 /**
8379 * @!group Sending a Request
8380 */
8381
8382 /**
8383 * @overload send(callback = null)
8384 * Sends the request object.
8385 *
8386 * @callback callback function(err, data)
8387 * If a callback is supplied, it is called when a response is returned
8388 * from the service.
8389 * @context [AWS.Request] the request object being sent.
8390 * @param err [Error] the error object returned from the request.
8391 * Set to `null` if the request is successful.
8392 * @param data [Object] the de-serialized data returned from
8393 * the request. Set to `null` if a request error occurs.
8394 * @example Sending a request with a callback
8395 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8396 * request.send(function(err, data) { console.log(err, data); });
8397 * @example Sending a request with no callback (using event handlers)
8398 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8399 * request.on('complete', function(response) { ... }); // register a callback
8400 * request.send();
8401 */
8402 send: function send(callback) {
8403 if (callback) {
8404 // append to user agent
8405 this.httpRequest.appendToUserAgent('callback');
8406 this.on('complete', function (resp) {
8407 callback.call(resp, resp.error, resp.data);
8408 });
8409 }
8410 this.runTo();
8411
8412 return this.response;
8413 },
8414
8415 /**
8416 * @!method promise()
8417 * Sends the request and returns a 'thenable' promise.
8418 *
8419 * Two callbacks can be provided to the `then` method on the returned promise.
8420 * The first callback will be called if the promise is fulfilled, and the second
8421 * callback will be called if the promise is rejected.
8422 * @callback fulfilledCallback function(data)
8423 * Called if the promise is fulfilled.
8424 * @param data [Object] the de-serialized data returned from the request.
8425 * @callback rejectedCallback function(error)
8426 * Called if the promise is rejected.
8427 * @param error [Error] the error object returned from the request.
8428 * @return [Promise] A promise that represents the state of the request.
8429 * @example Sending a request using promises.
8430 * var request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8431 * var result = request.promise();
8432 * result.then(function(data) { ... }, function(error) { ... });
8433 */
8434
8435 /**
8436 * @api private
8437 */
8438 build: function build(callback) {
8439 return this.runTo('send', callback);
8440 },
8441
8442 /**
8443 * @api private
8444 */
8445 runTo: function runTo(state, done) {
8446 this._asm.runTo(state, done, this);
8447 return this;
8448 },
8449
8450 /**
8451 * Aborts a request, emitting the error and complete events.
8452 *
8453 * @!macro nobrowser
8454 * @example Aborting a request after sending
8455 * var params = {
8456 * Bucket: 'bucket', Key: 'key',
8457 * Body: Buffer.alloc(1024 * 1024 * 5) // 5MB payload
8458 * };
8459 * var request = s3.putObject(params);
8460 * request.send(function (err, data) {
8461 * if (err) console.log("Error:", err.code, err.message);
8462 * else console.log(data);
8463 * });
8464 *
8465 * // abort request in 1 second
8466 * setTimeout(request.abort.bind(request), 1000);
8467 *
8468 * // prints "Error: RequestAbortedError Request aborted by user"
8469 * @return [AWS.Request] the same request object, for chaining.
8470 * @since v1.4.0
8471 */
8472 abort: function abort() {
8473 this.removeAllListeners('validateResponse');
8474 this.removeAllListeners('extractError');
8475 this.on('validateResponse', function addAbortedError(resp) {
8476 resp.error = AWS.util.error(new Error('Request aborted by user'), {
8477 code: 'RequestAbortedError', retryable: false
8478 });
8479 });
8480
8481 if (this.httpRequest.stream && !this.httpRequest.stream.didCallback) { // abort HTTP stream
8482 this.httpRequest.stream.abort();
8483 if (this.httpRequest._abortCallback) {
8484 this.httpRequest._abortCallback();
8485 } else {
8486 this.removeAllListeners('send'); // haven't sent yet, so let's not
8487 }
8488 }
8489
8490 return this;
8491 },
8492
8493 /**
8494 * Iterates over each page of results given a pageable request, calling
8495 * the provided callback with each page of data. After all pages have been
8496 * retrieved, the callback is called with `null` data.
8497 *
8498 * @note This operation can generate multiple requests to a service.
8499 * @example Iterating over multiple pages of objects in an S3 bucket
8500 * var pages = 1;
8501 * s3.listObjects().eachPage(function(err, data) {
8502 * if (err) return;
8503 * console.log("Page", pages++);
8504 * console.log(data);
8505 * });
8506 * @example Iterating over multiple pages with an asynchronous callback
8507 * s3.listObjects(params).eachPage(function(err, data, done) {
8508 * doSomethingAsyncAndOrExpensive(function() {
8509 * // The next page of results isn't fetched until done is called
8510 * done();
8511 * });
8512 * });
8513 * @callback callback function(err, data, [doneCallback])
8514 * Called with each page of resulting data from the request. If the
8515 * optional `doneCallback` is provided in the function, it must be called
8516 * when the callback is complete.
8517 *
8518 * @param err [Error] an error object, if an error occurred.
8519 * @param data [Object] a single page of response data. If there is no
8520 * more data, this object will be `null`.
8521 * @param doneCallback [Function] an optional done callback. If this
8522 * argument is defined in the function declaration, it should be called
8523 * when the next page is ready to be retrieved. This is useful for
8524 * controlling serial pagination across asynchronous operations.
8525 * @return [Boolean] if the callback returns `false`, pagination will
8526 * stop.
8527 *
8528 * @see AWS.Request.eachItem
8529 * @see AWS.Response.nextPage
8530 * @since v1.4.0
8531 */
8532 eachPage: function eachPage(callback) {
8533 // Make all callbacks async-ish
8534 callback = AWS.util.fn.makeAsync(callback, 3);
8535
8536 function wrappedCallback(response) {
8537 callback.call(response, response.error, response.data, function (result) {
8538 if (result === false) return;
8539
8540 if (response.hasNextPage()) {
8541 response.nextPage().on('complete', wrappedCallback).send();
8542 } else {
8543 callback.call(response, null, null, AWS.util.fn.noop);
8544 }
8545 });
8546 }
8547
8548 this.on('complete', wrappedCallback).send();
8549 },
8550
8551 /**
8552 * Enumerates over individual items of a request, paging the responses if
8553 * necessary.
8554 *
8555 * @api experimental
8556 * @since v1.4.0
8557 */
8558 eachItem: function eachItem(callback) {
8559 var self = this;
8560 function wrappedCallback(err, data) {
8561 if (err) return callback(err, null);
8562 if (data === null) return callback(null, null);
8563
8564 var config = self.service.paginationConfig(self.operation);
8565 var resultKey = config.resultKey;
8566 if (Array.isArray(resultKey)) resultKey = resultKey[0];
8567 var items = jmespath.search(data, resultKey);
8568 var continueIteration = true;
8569 AWS.util.arrayEach(items, function(item) {
8570 continueIteration = callback(null, item);
8571 if (continueIteration === false) {
8572 return AWS.util.abort;
8573 }
8574 });
8575 return continueIteration;
8576 }
8577
8578 this.eachPage(wrappedCallback);
8579 },
8580
8581 /**
8582 * @return [Boolean] whether the operation can return multiple pages of
8583 * response data.
8584 * @see AWS.Response.eachPage
8585 * @since v1.4.0
8586 */
8587 isPageable: function isPageable() {
8588 return this.service.paginationConfig(this.operation) ? true : false;
8589 },
8590
8591 /**
8592 * Sends the request and converts the request object into a readable stream
8593 * that can be read from or piped into a writable stream.
8594 *
8595 * @note The data read from a readable stream contains only
8596 * the raw HTTP body contents.
8597 * @example Manually reading from a stream
8598 * request.createReadStream().on('data', function(data) {
8599 * console.log("Got data:", data.toString());
8600 * });
8601 * @example Piping a request body into a file
8602 * var out = fs.createWriteStream('/path/to/outfile.jpg');
8603 * s3.service.getObject(params).createReadStream().pipe(out);
8604 * @return [Stream] the readable stream object that can be piped
8605 * or read from (by registering 'data' event listeners).
8606 * @!macro nobrowser
8607 */
8608 createReadStream: function createReadStream() {
8609 var streams = AWS.util.stream;
8610 var req = this;
8611 var stream = null;
8612
8613 if (AWS.HttpClient.streamsApiVersion === 2) {
8614 stream = new streams.PassThrough();
8615 process.nextTick(function() { req.send(); });
8616 } else {
8617 stream = new streams.Stream();
8618 stream.readable = true;
8619
8620 stream.sent = false;
8621 stream.on('newListener', function(event) {
8622 if (!stream.sent && event === 'data') {
8623 stream.sent = true;
8624 process.nextTick(function() { req.send(); });
8625 }
8626 });
8627 }
8628
8629 this.on('error', function(err) {
8630 stream.emit('error', err);
8631 });
8632
8633 this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
8634 if (statusCode < 300) {
8635 req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
8636 req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
8637 req.on('httpError', function streamHttpError(error) {
8638 resp.error = error;
8639 resp.error.retryable = false;
8640 });
8641
8642 var shouldCheckContentLength = false;
8643 var expectedLen;
8644 if (req.httpRequest.method !== 'HEAD') {
8645 expectedLen = parseInt(headers['content-length'], 10);
8646 }
8647 if (expectedLen !== undefined && !isNaN(expectedLen) && expectedLen >= 0) {
8648 shouldCheckContentLength = true;
8649 var receivedLen = 0;
8650 }
8651
8652 var checkContentLengthAndEmit = function checkContentLengthAndEmit() {
8653 if (shouldCheckContentLength && receivedLen !== expectedLen) {
8654 stream.emit('error', AWS.util.error(
8655 new Error('Stream content length mismatch. Received ' +
8656 receivedLen + ' of ' + expectedLen + ' bytes.'),
8657 { code: 'StreamContentLengthMismatch' }
8658 ));
8659 } else if (AWS.HttpClient.streamsApiVersion === 2) {
8660 stream.end();
8661 } else {
8662 stream.emit('end');
8663 }
8664 };
8665
8666 var httpStream = resp.httpResponse.createUnbufferedStream();
8667
8668 if (AWS.HttpClient.streamsApiVersion === 2) {
8669 if (shouldCheckContentLength) {
8670 var lengthAccumulator = new streams.PassThrough();
8671 lengthAccumulator._write = function(chunk) {
8672 if (chunk && chunk.length) {
8673 receivedLen += chunk.length;
8674 }
8675 return streams.PassThrough.prototype._write.apply(this, arguments);
8676 };
8677
8678 lengthAccumulator.on('end', checkContentLengthAndEmit);
8679 stream.on('error', function(err) {
8680 shouldCheckContentLength = false;
8681 httpStream.unpipe(lengthAccumulator);
8682 lengthAccumulator.emit('end');
8683 lengthAccumulator.end();
8684 });
8685 httpStream.pipe(lengthAccumulator).pipe(stream, { end: false });
8686 } else {
8687 httpStream.pipe(stream);
8688 }
8689 } else {
8690
8691 if (shouldCheckContentLength) {
8692 httpStream.on('data', function(arg) {
8693 if (arg && arg.length) {
8694 receivedLen += arg.length;
8695 }
8696 });
8697 }
8698
8699 httpStream.on('data', function(arg) {
8700 stream.emit('data', arg);
8701 });
8702 httpStream.on('end', checkContentLengthAndEmit);
8703 }
8704
8705 httpStream.on('error', function(err) {
8706 shouldCheckContentLength = false;
8707 stream.emit('error', err);
8708 });
8709 }
8710 });
8711
8712 return stream;
8713 },
8714
8715 /**
8716 * @param [Array,Response] args This should be the response object,
8717 * or an array of args to send to the event.
8718 * @api private
8719 */
8720 emitEvent: function emit(eventName, args, done) {
8721 if (typeof args === 'function') { done = args; args = null; }
8722 if (!done) done = function() { };
8723 if (!args) args = this.eventParameters(eventName, this.response);
8724
8725 var origEmit = AWS.SequentialExecutor.prototype.emit;
8726 origEmit.call(this, eventName, args, function (err) {
8727 if (err) this.response.error = err;
8728 done.call(this, err);
8729 });
8730 },
8731
8732 /**
8733 * @api private
8734 */
8735 eventParameters: function eventParameters(eventName) {
8736 switch (eventName) {
8737 case 'restart':
8738 case 'validate':
8739 case 'sign':
8740 case 'build':
8741 case 'afterValidate':
8742 case 'afterBuild':
8743 return [this];
8744 case 'error':
8745 return [this.response.error, this.response];
8746 default:
8747 return [this.response];
8748 }
8749 },
8750
8751 /**
8752 * @api private
8753 */
8754 presign: function presign(expires, callback) {
8755 if (!callback && typeof expires === 'function') {
8756 callback = expires;
8757 expires = null;
8758 }
8759 return new AWS.Signers.Presign().sign(this.toGet(), expires, callback);
8760 },
8761
8762 /**
8763 * @api private
8764 */
8765 isPresigned: function isPresigned() {
8766 return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires');
8767 },
8768
8769 /**
8770 * @api private
8771 */
8772 toUnauthenticated: function toUnauthenticated() {
8773 this._unAuthenticated = true;
8774 this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS);
8775 this.removeListener('sign', AWS.EventListeners.Core.SIGN);
8776 return this;
8777 },
8778
8779 /**
8780 * @api private
8781 */
8782 toGet: function toGet() {
8783 if (this.service.api.protocol === 'query' ||
8784 this.service.api.protocol === 'ec2') {
8785 this.removeListener('build', this.buildAsGet);
8786 this.addListener('build', this.buildAsGet);
8787 }
8788 return this;
8789 },
8790
8791 /**
8792 * @api private
8793 */
8794 buildAsGet: function buildAsGet(request) {
8795 request.httpRequest.method = 'GET';
8796 request.httpRequest.path = request.service.endpoint.path +
8797 '?' + request.httpRequest.body;
8798 request.httpRequest.body = '';
8799
8800 // don't need these headers on a GET request
8801 delete request.httpRequest.headers['Content-Length'];
8802 delete request.httpRequest.headers['Content-Type'];
8803 },
8804
8805 /**
8806 * @api private
8807 */
8808 haltHandlersOnError: function haltHandlersOnError() {
8809 this._haltHandlersOnError = true;
8810 }
8811 });
8812
8813 /**
8814 * @api private
8815 */
8816 AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
8817 this.prototype.promise = function promise() {
8818 var self = this;
8819 // append to user agent
8820 this.httpRequest.appendToUserAgent('promise');
8821 return new PromiseDependency(function(resolve, reject) {
8822 self.on('complete', function(resp) {
8823 if (resp.error) {
8824 reject(resp.error);
8825 } else {
8826 // define $response property so that it is not enumberable
8827 // this prevents circular reference errors when stringifying the JSON object
8828 resolve(Object.defineProperty(
8829 resp.data || {},
8830 '$response',
8831 {value: resp}
8832 ));
8833 }
8834 });
8835 self.runTo();
8836 });
8837 };
8838 };
8839
8840 /**
8841 * @api private
8842 */
8843 AWS.Request.deletePromisesFromClass = function deletePromisesFromClass() {
8844 delete this.prototype.promise;
8845 };
8846
8847 AWS.util.addPromises(AWS.Request);
8848
8849 AWS.util.mixin(AWS.Request, AWS.SequentialExecutor);
8850
8851 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
8852
8853/***/ }),
8854/* 50 */
8855/***/ (function(module, exports) {
8856
8857 function AcceptorStateMachine(states, state) {
8858 this.currentState = state || null;
8859 this.states = states || {};
8860 }
8861
8862 AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) {
8863 if (typeof finalState === 'function') {
8864 inputError = bindObject; bindObject = done;
8865 done = finalState; finalState = null;
8866 }
8867
8868 var self = this;
8869 var state = self.states[self.currentState];
8870 state.fn.call(bindObject || self, inputError, function(err) {
8871 if (err) {
8872 if (state.fail) self.currentState = state.fail;
8873 else return done ? done.call(bindObject, err) : null;
8874 } else {
8875 if (state.accept) self.currentState = state.accept;
8876 else return done ? done.call(bindObject) : null;
8877 }
8878 if (self.currentState === finalState) {
8879 return done ? done.call(bindObject, err) : null;
8880 }
8881
8882 self.runTo(finalState, done, bindObject, err);
8883 });
8884 };
8885
8886 AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) {
8887 if (typeof acceptState === 'function') {
8888 fn = acceptState; acceptState = null; failState = null;
8889 } else if (typeof failState === 'function') {
8890 fn = failState; failState = null;
8891 }
8892
8893 if (!this.currentState) this.currentState = name;
8894 this.states[name] = { accept: acceptState, fail: failState, fn: fn };
8895 return this;
8896 };
8897
8898 /**
8899 * @api private
8900 */
8901 module.exports = AcceptorStateMachine;
8902
8903
8904/***/ }),
8905/* 51 */
8906/***/ (function(module, exports, __webpack_require__) {
8907
8908 (function(exports) {
8909 "use strict";
8910
8911 function isArray(obj) {
8912 if (obj !== null) {
8913 return Object.prototype.toString.call(obj) === "[object Array]";
8914 } else {
8915 return false;
8916 }
8917 }
8918
8919 function isObject(obj) {
8920 if (obj !== null) {
8921 return Object.prototype.toString.call(obj) === "[object Object]";
8922 } else {
8923 return false;
8924 }
8925 }
8926
8927 function strictDeepEqual(first, second) {
8928 // Check the scalar case first.
8929 if (first === second) {
8930 return true;
8931 }
8932
8933 // Check if they are the same type.
8934 var firstType = Object.prototype.toString.call(first);
8935 if (firstType !== Object.prototype.toString.call(second)) {
8936 return false;
8937 }
8938 // We know that first and second have the same type so we can just check the
8939 // first type from now on.
8940 if (isArray(first) === true) {
8941 // Short circuit if they're not the same length;
8942 if (first.length !== second.length) {
8943 return false;
8944 }
8945 for (var i = 0; i < first.length; i++) {
8946 if (strictDeepEqual(first[i], second[i]) === false) {
8947 return false;
8948 }
8949 }
8950 return true;
8951 }
8952 if (isObject(first) === true) {
8953 // An object is equal if it has the same key/value pairs.
8954 var keysSeen = {};
8955 for (var key in first) {
8956 if (hasOwnProperty.call(first, key)) {
8957 if (strictDeepEqual(first[key], second[key]) === false) {
8958 return false;
8959 }
8960 keysSeen[key] = true;
8961 }
8962 }
8963 // Now check that there aren't any keys in second that weren't
8964 // in first.
8965 for (var key2 in second) {
8966 if (hasOwnProperty.call(second, key2)) {
8967 if (keysSeen[key2] !== true) {
8968 return false;
8969 }
8970 }
8971 }
8972 return true;
8973 }
8974 return false;
8975 }
8976
8977 function isFalse(obj) {
8978 // From the spec:
8979 // A false value corresponds to the following values:
8980 // Empty list
8981 // Empty object
8982 // Empty string
8983 // False boolean
8984 // null value
8985
8986 // First check the scalar values.
8987 if (obj === "" || obj === false || obj === null) {
8988 return true;
8989 } else if (isArray(obj) && obj.length === 0) {
8990 // Check for an empty array.
8991 return true;
8992 } else if (isObject(obj)) {
8993 // Check for an empty object.
8994 for (var key in obj) {
8995 // If there are any keys, then
8996 // the object is not empty so the object
8997 // is not false.
8998 if (obj.hasOwnProperty(key)) {
8999 return false;
9000 }
9001 }
9002 return true;
9003 } else {
9004 return false;
9005 }
9006 }
9007
9008 function objValues(obj) {
9009 var keys = Object.keys(obj);
9010 var values = [];
9011 for (var i = 0; i < keys.length; i++) {
9012 values.push(obj[keys[i]]);
9013 }
9014 return values;
9015 }
9016
9017 function merge(a, b) {
9018 var merged = {};
9019 for (var key in a) {
9020 merged[key] = a[key];
9021 }
9022 for (var key2 in b) {
9023 merged[key2] = b[key2];
9024 }
9025 return merged;
9026 }
9027
9028 var trimLeft;
9029 if (typeof String.prototype.trimLeft === "function") {
9030 trimLeft = function(str) {
9031 return str.trimLeft();
9032 };
9033 } else {
9034 trimLeft = function(str) {
9035 return str.match(/^\s*(.*)/)[1];
9036 };
9037 }
9038
9039 // Type constants used to define functions.
9040 var TYPE_NUMBER = 0;
9041 var TYPE_ANY = 1;
9042 var TYPE_STRING = 2;
9043 var TYPE_ARRAY = 3;
9044 var TYPE_OBJECT = 4;
9045 var TYPE_BOOLEAN = 5;
9046 var TYPE_EXPREF = 6;
9047 var TYPE_NULL = 7;
9048 var TYPE_ARRAY_NUMBER = 8;
9049 var TYPE_ARRAY_STRING = 9;
9050
9051 var TOK_EOF = "EOF";
9052 var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier";
9053 var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier";
9054 var TOK_RBRACKET = "Rbracket";
9055 var TOK_RPAREN = "Rparen";
9056 var TOK_COMMA = "Comma";
9057 var TOK_COLON = "Colon";
9058 var TOK_RBRACE = "Rbrace";
9059 var TOK_NUMBER = "Number";
9060 var TOK_CURRENT = "Current";
9061 var TOK_EXPREF = "Expref";
9062 var TOK_PIPE = "Pipe";
9063 var TOK_OR = "Or";
9064 var TOK_AND = "And";
9065 var TOK_EQ = "EQ";
9066 var TOK_GT = "GT";
9067 var TOK_LT = "LT";
9068 var TOK_GTE = "GTE";
9069 var TOK_LTE = "LTE";
9070 var TOK_NE = "NE";
9071 var TOK_FLATTEN = "Flatten";
9072 var TOK_STAR = "Star";
9073 var TOK_FILTER = "Filter";
9074 var TOK_DOT = "Dot";
9075 var TOK_NOT = "Not";
9076 var TOK_LBRACE = "Lbrace";
9077 var TOK_LBRACKET = "Lbracket";
9078 var TOK_LPAREN= "Lparen";
9079 var TOK_LITERAL= "Literal";
9080
9081 // The "&", "[", "<", ">" tokens
9082 // are not in basicToken because
9083 // there are two token variants
9084 // ("&&", "[?", "<=", ">="). This is specially handled
9085 // below.
9086
9087 var basicTokens = {
9088 ".": TOK_DOT,
9089 "*": TOK_STAR,
9090 ",": TOK_COMMA,
9091 ":": TOK_COLON,
9092 "{": TOK_LBRACE,
9093 "}": TOK_RBRACE,
9094 "]": TOK_RBRACKET,
9095 "(": TOK_LPAREN,
9096 ")": TOK_RPAREN,
9097 "@": TOK_CURRENT
9098 };
9099
9100 var operatorStartToken = {
9101 "<": true,
9102 ">": true,
9103 "=": true,
9104 "!": true
9105 };
9106
9107 var skipChars = {
9108 " ": true,
9109 "\t": true,
9110 "\n": true
9111 };
9112
9113
9114 function isAlpha(ch) {
9115 return (ch >= "a" && ch <= "z") ||
9116 (ch >= "A" && ch <= "Z") ||
9117 ch === "_";
9118 }
9119
9120 function isNum(ch) {
9121 return (ch >= "0" && ch <= "9") ||
9122 ch === "-";
9123 }
9124 function isAlphaNum(ch) {
9125 return (ch >= "a" && ch <= "z") ||
9126 (ch >= "A" && ch <= "Z") ||
9127 (ch >= "0" && ch <= "9") ||
9128 ch === "_";
9129 }
9130
9131 function Lexer() {
9132 }
9133 Lexer.prototype = {
9134 tokenize: function(stream) {
9135 var tokens = [];
9136 this._current = 0;
9137 var start;
9138 var identifier;
9139 var token;
9140 while (this._current < stream.length) {
9141 if (isAlpha(stream[this._current])) {
9142 start = this._current;
9143 identifier = this._consumeUnquotedIdentifier(stream);
9144 tokens.push({type: TOK_UNQUOTEDIDENTIFIER,
9145 value: identifier,
9146 start: start});
9147 } else if (basicTokens[stream[this._current]] !== undefined) {
9148 tokens.push({type: basicTokens[stream[this._current]],
9149 value: stream[this._current],
9150 start: this._current});
9151 this._current++;
9152 } else if (isNum(stream[this._current])) {
9153 token = this._consumeNumber(stream);
9154 tokens.push(token);
9155 } else if (stream[this._current] === "[") {
9156 // No need to increment this._current. This happens
9157 // in _consumeLBracket
9158 token = this._consumeLBracket(stream);
9159 tokens.push(token);
9160 } else if (stream[this._current] === "\"") {
9161 start = this._current;
9162 identifier = this._consumeQuotedIdentifier(stream);
9163 tokens.push({type: TOK_QUOTEDIDENTIFIER,
9164 value: identifier,
9165 start: start});
9166 } else if (stream[this._current] === "'") {
9167 start = this._current;
9168 identifier = this._consumeRawStringLiteral(stream);
9169 tokens.push({type: TOK_LITERAL,
9170 value: identifier,
9171 start: start});
9172 } else if (stream[this._current] === "`") {
9173 start = this._current;
9174 var literal = this._consumeLiteral(stream);
9175 tokens.push({type: TOK_LITERAL,
9176 value: literal,
9177 start: start});
9178 } else if (operatorStartToken[stream[this._current]] !== undefined) {
9179 tokens.push(this._consumeOperator(stream));
9180 } else if (skipChars[stream[this._current]] !== undefined) {
9181 // Ignore whitespace.
9182 this._current++;
9183 } else if (stream[this._current] === "&") {
9184 start = this._current;
9185 this._current++;
9186 if (stream[this._current] === "&") {
9187 this._current++;
9188 tokens.push({type: TOK_AND, value: "&&", start: start});
9189 } else {
9190 tokens.push({type: TOK_EXPREF, value: "&", start: start});
9191 }
9192 } else if (stream[this._current] === "|") {
9193 start = this._current;
9194 this._current++;
9195 if (stream[this._current] === "|") {
9196 this._current++;
9197 tokens.push({type: TOK_OR, value: "||", start: start});
9198 } else {
9199 tokens.push({type: TOK_PIPE, value: "|", start: start});
9200 }
9201 } else {
9202 var error = new Error("Unknown character:" + stream[this._current]);
9203 error.name = "LexerError";
9204 throw error;
9205 }
9206 }
9207 return tokens;
9208 },
9209
9210 _consumeUnquotedIdentifier: function(stream) {
9211 var start = this._current;
9212 this._current++;
9213 while (this._current < stream.length && isAlphaNum(stream[this._current])) {
9214 this._current++;
9215 }
9216 return stream.slice(start, this._current);
9217 },
9218
9219 _consumeQuotedIdentifier: function(stream) {
9220 var start = this._current;
9221 this._current++;
9222 var maxLength = stream.length;
9223 while (stream[this._current] !== "\"" && this._current < maxLength) {
9224 // You can escape a double quote and you can escape an escape.
9225 var current = this._current;
9226 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9227 stream[current + 1] === "\"")) {
9228 current += 2;
9229 } else {
9230 current++;
9231 }
9232 this._current = current;
9233 }
9234 this._current++;
9235 return JSON.parse(stream.slice(start, this._current));
9236 },
9237
9238 _consumeRawStringLiteral: function(stream) {
9239 var start = this._current;
9240 this._current++;
9241 var maxLength = stream.length;
9242 while (stream[this._current] !== "'" && this._current < maxLength) {
9243 // You can escape a single quote and you can escape an escape.
9244 var current = this._current;
9245 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9246 stream[current + 1] === "'")) {
9247 current += 2;
9248 } else {
9249 current++;
9250 }
9251 this._current = current;
9252 }
9253 this._current++;
9254 var literal = stream.slice(start + 1, this._current - 1);
9255 return literal.replace("\\'", "'");
9256 },
9257
9258 _consumeNumber: function(stream) {
9259 var start = this._current;
9260 this._current++;
9261 var maxLength = stream.length;
9262 while (isNum(stream[this._current]) && this._current < maxLength) {
9263 this._current++;
9264 }
9265 var value = parseInt(stream.slice(start, this._current));
9266 return {type: TOK_NUMBER, value: value, start: start};
9267 },
9268
9269 _consumeLBracket: function(stream) {
9270 var start = this._current;
9271 this._current++;
9272 if (stream[this._current] === "?") {
9273 this._current++;
9274 return {type: TOK_FILTER, value: "[?", start: start};
9275 } else if (stream[this._current] === "]") {
9276 this._current++;
9277 return {type: TOK_FLATTEN, value: "[]", start: start};
9278 } else {
9279 return {type: TOK_LBRACKET, value: "[", start: start};
9280 }
9281 },
9282
9283 _consumeOperator: function(stream) {
9284 var start = this._current;
9285 var startingChar = stream[start];
9286 this._current++;
9287 if (startingChar === "!") {
9288 if (stream[this._current] === "=") {
9289 this._current++;
9290 return {type: TOK_NE, value: "!=", start: start};
9291 } else {
9292 return {type: TOK_NOT, value: "!", start: start};
9293 }
9294 } else if (startingChar === "<") {
9295 if (stream[this._current] === "=") {
9296 this._current++;
9297 return {type: TOK_LTE, value: "<=", start: start};
9298 } else {
9299 return {type: TOK_LT, value: "<", start: start};
9300 }
9301 } else if (startingChar === ">") {
9302 if (stream[this._current] === "=") {
9303 this._current++;
9304 return {type: TOK_GTE, value: ">=", start: start};
9305 } else {
9306 return {type: TOK_GT, value: ">", start: start};
9307 }
9308 } else if (startingChar === "=") {
9309 if (stream[this._current] === "=") {
9310 this._current++;
9311 return {type: TOK_EQ, value: "==", start: start};
9312 }
9313 }
9314 },
9315
9316 _consumeLiteral: function(stream) {
9317 this._current++;
9318 var start = this._current;
9319 var maxLength = stream.length;
9320 var literal;
9321 while(stream[this._current] !== "`" && this._current < maxLength) {
9322 // You can escape a literal char or you can escape the escape.
9323 var current = this._current;
9324 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9325 stream[current + 1] === "`")) {
9326 current += 2;
9327 } else {
9328 current++;
9329 }
9330 this._current = current;
9331 }
9332 var literalString = trimLeft(stream.slice(start, this._current));
9333 literalString = literalString.replace("\\`", "`");
9334 if (this._looksLikeJSON(literalString)) {
9335 literal = JSON.parse(literalString);
9336 } else {
9337 // Try to JSON parse it as "<literal>"
9338 literal = JSON.parse("\"" + literalString + "\"");
9339 }
9340 // +1 gets us to the ending "`", +1 to move on to the next char.
9341 this._current++;
9342 return literal;
9343 },
9344
9345 _looksLikeJSON: function(literalString) {
9346 var startingChars = "[{\"";
9347 var jsonLiterals = ["true", "false", "null"];
9348 var numberLooking = "-0123456789";
9349
9350 if (literalString === "") {
9351 return false;
9352 } else if (startingChars.indexOf(literalString[0]) >= 0) {
9353 return true;
9354 } else if (jsonLiterals.indexOf(literalString) >= 0) {
9355 return true;
9356 } else if (numberLooking.indexOf(literalString[0]) >= 0) {
9357 try {
9358 JSON.parse(literalString);
9359 return true;
9360 } catch (ex) {
9361 return false;
9362 }
9363 } else {
9364 return false;
9365 }
9366 }
9367 };
9368
9369 var bindingPower = {};
9370 bindingPower[TOK_EOF] = 0;
9371 bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0;
9372 bindingPower[TOK_QUOTEDIDENTIFIER] = 0;
9373 bindingPower[TOK_RBRACKET] = 0;
9374 bindingPower[TOK_RPAREN] = 0;
9375 bindingPower[TOK_COMMA] = 0;
9376 bindingPower[TOK_RBRACE] = 0;
9377 bindingPower[TOK_NUMBER] = 0;
9378 bindingPower[TOK_CURRENT] = 0;
9379 bindingPower[TOK_EXPREF] = 0;
9380 bindingPower[TOK_PIPE] = 1;
9381 bindingPower[TOK_OR] = 2;
9382 bindingPower[TOK_AND] = 3;
9383 bindingPower[TOK_EQ] = 5;
9384 bindingPower[TOK_GT] = 5;
9385 bindingPower[TOK_LT] = 5;
9386 bindingPower[TOK_GTE] = 5;
9387 bindingPower[TOK_LTE] = 5;
9388 bindingPower[TOK_NE] = 5;
9389 bindingPower[TOK_FLATTEN] = 9;
9390 bindingPower[TOK_STAR] = 20;
9391 bindingPower[TOK_FILTER] = 21;
9392 bindingPower[TOK_DOT] = 40;
9393 bindingPower[TOK_NOT] = 45;
9394 bindingPower[TOK_LBRACE] = 50;
9395 bindingPower[TOK_LBRACKET] = 55;
9396 bindingPower[TOK_LPAREN] = 60;
9397
9398 function Parser() {
9399 }
9400
9401 Parser.prototype = {
9402 parse: function(expression) {
9403 this._loadTokens(expression);
9404 this.index = 0;
9405 var ast = this.expression(0);
9406 if (this._lookahead(0) !== TOK_EOF) {
9407 var t = this._lookaheadToken(0);
9408 var error = new Error(
9409 "Unexpected token type: " + t.type + ", value: " + t.value);
9410 error.name = "ParserError";
9411 throw error;
9412 }
9413 return ast;
9414 },
9415
9416 _loadTokens: function(expression) {
9417 var lexer = new Lexer();
9418 var tokens = lexer.tokenize(expression);
9419 tokens.push({type: TOK_EOF, value: "", start: expression.length});
9420 this.tokens = tokens;
9421 },
9422
9423 expression: function(rbp) {
9424 var leftToken = this._lookaheadToken(0);
9425 this._advance();
9426 var left = this.nud(leftToken);
9427 var currentToken = this._lookahead(0);
9428 while (rbp < bindingPower[currentToken]) {
9429 this._advance();
9430 left = this.led(currentToken, left);
9431 currentToken = this._lookahead(0);
9432 }
9433 return left;
9434 },
9435
9436 _lookahead: function(number) {
9437 return this.tokens[this.index + number].type;
9438 },
9439
9440 _lookaheadToken: function(number) {
9441 return this.tokens[this.index + number];
9442 },
9443
9444 _advance: function() {
9445 this.index++;
9446 },
9447
9448 nud: function(token) {
9449 var left;
9450 var right;
9451 var expression;
9452 switch (token.type) {
9453 case TOK_LITERAL:
9454 return {type: "Literal", value: token.value};
9455 case TOK_UNQUOTEDIDENTIFIER:
9456 return {type: "Field", name: token.value};
9457 case TOK_QUOTEDIDENTIFIER:
9458 var node = {type: "Field", name: token.value};
9459 if (this._lookahead(0) === TOK_LPAREN) {
9460 throw new Error("Quoted identifier not allowed for function names.");
9461 } else {
9462 return node;
9463 }
9464 break;
9465 case TOK_NOT:
9466 right = this.expression(bindingPower.Not);
9467 return {type: "NotExpression", children: [right]};
9468 case TOK_STAR:
9469 left = {type: "Identity"};
9470 right = null;
9471 if (this._lookahead(0) === TOK_RBRACKET) {
9472 // This can happen in a multiselect,
9473 // [a, b, *]
9474 right = {type: "Identity"};
9475 } else {
9476 right = this._parseProjectionRHS(bindingPower.Star);
9477 }
9478 return {type: "ValueProjection", children: [left, right]};
9479 case TOK_FILTER:
9480 return this.led(token.type, {type: "Identity"});
9481 case TOK_LBRACE:
9482 return this._parseMultiselectHash();
9483 case TOK_FLATTEN:
9484 left = {type: TOK_FLATTEN, children: [{type: "Identity"}]};
9485 right = this._parseProjectionRHS(bindingPower.Flatten);
9486 return {type: "Projection", children: [left, right]};
9487 case TOK_LBRACKET:
9488 if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) {
9489 right = this._parseIndexExpression();
9490 return this._projectIfSlice({type: "Identity"}, right);
9491 } else if (this._lookahead(0) === TOK_STAR &&
9492 this._lookahead(1) === TOK_RBRACKET) {
9493 this._advance();
9494 this._advance();
9495 right = this._parseProjectionRHS(bindingPower.Star);
9496 return {type: "Projection",
9497 children: [{type: "Identity"}, right]};
9498 } else {
9499 return this._parseMultiselectList();
9500 }
9501 break;
9502 case TOK_CURRENT:
9503 return {type: TOK_CURRENT};
9504 case TOK_EXPREF:
9505 expression = this.expression(bindingPower.Expref);
9506 return {type: "ExpressionReference", children: [expression]};
9507 case TOK_LPAREN:
9508 var args = [];
9509 while (this._lookahead(0) !== TOK_RPAREN) {
9510 if (this._lookahead(0) === TOK_CURRENT) {
9511 expression = {type: TOK_CURRENT};
9512 this._advance();
9513 } else {
9514 expression = this.expression(0);
9515 }
9516 args.push(expression);
9517 }
9518 this._match(TOK_RPAREN);
9519 return args[0];
9520 default:
9521 this._errorToken(token);
9522 }
9523 },
9524
9525 led: function(tokenName, left) {
9526 var right;
9527 switch(tokenName) {
9528 case TOK_DOT:
9529 var rbp = bindingPower.Dot;
9530 if (this._lookahead(0) !== TOK_STAR) {
9531 right = this._parseDotRHS(rbp);
9532 return {type: "Subexpression", children: [left, right]};
9533 } else {
9534 // Creating a projection.
9535 this._advance();
9536 right = this._parseProjectionRHS(rbp);
9537 return {type: "ValueProjection", children: [left, right]};
9538 }
9539 break;
9540 case TOK_PIPE:
9541 right = this.expression(bindingPower.Pipe);
9542 return {type: TOK_PIPE, children: [left, right]};
9543 case TOK_OR:
9544 right = this.expression(bindingPower.Or);
9545 return {type: "OrExpression", children: [left, right]};
9546 case TOK_AND:
9547 right = this.expression(bindingPower.And);
9548 return {type: "AndExpression", children: [left, right]};
9549 case TOK_LPAREN:
9550 var name = left.name;
9551 var args = [];
9552 var expression, node;
9553 while (this._lookahead(0) !== TOK_RPAREN) {
9554 if (this._lookahead(0) === TOK_CURRENT) {
9555 expression = {type: TOK_CURRENT};
9556 this._advance();
9557 } else {
9558 expression = this.expression(0);
9559 }
9560 if (this._lookahead(0) === TOK_COMMA) {
9561 this._match(TOK_COMMA);
9562 }
9563 args.push(expression);
9564 }
9565 this._match(TOK_RPAREN);
9566 node = {type: "Function", name: name, children: args};
9567 return node;
9568 case TOK_FILTER:
9569 var condition = this.expression(0);
9570 this._match(TOK_RBRACKET);
9571 if (this._lookahead(0) === TOK_FLATTEN) {
9572 right = {type: "Identity"};
9573 } else {
9574 right = this._parseProjectionRHS(bindingPower.Filter);
9575 }
9576 return {type: "FilterProjection", children: [left, right, condition]};
9577 case TOK_FLATTEN:
9578 var leftNode = {type: TOK_FLATTEN, children: [left]};
9579 var rightNode = this._parseProjectionRHS(bindingPower.Flatten);
9580 return {type: "Projection", children: [leftNode, rightNode]};
9581 case TOK_EQ:
9582 case TOK_NE:
9583 case TOK_GT:
9584 case TOK_GTE:
9585 case TOK_LT:
9586 case TOK_LTE:
9587 return this._parseComparator(left, tokenName);
9588 case TOK_LBRACKET:
9589 var token = this._lookaheadToken(0);
9590 if (token.type === TOK_NUMBER || token.type === TOK_COLON) {
9591 right = this._parseIndexExpression();
9592 return this._projectIfSlice(left, right);
9593 } else {
9594 this._match(TOK_STAR);
9595 this._match(TOK_RBRACKET);
9596 right = this._parseProjectionRHS(bindingPower.Star);
9597 return {type: "Projection", children: [left, right]};
9598 }
9599 break;
9600 default:
9601 this._errorToken(this._lookaheadToken(0));
9602 }
9603 },
9604
9605 _match: function(tokenType) {
9606 if (this._lookahead(0) === tokenType) {
9607 this._advance();
9608 } else {
9609 var t = this._lookaheadToken(0);
9610 var error = new Error("Expected " + tokenType + ", got: " + t.type);
9611 error.name = "ParserError";
9612 throw error;
9613 }
9614 },
9615
9616 _errorToken: function(token) {
9617 var error = new Error("Invalid token (" +
9618 token.type + "): \"" +
9619 token.value + "\"");
9620 error.name = "ParserError";
9621 throw error;
9622 },
9623
9624
9625 _parseIndexExpression: function() {
9626 if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) {
9627 return this._parseSliceExpression();
9628 } else {
9629 var node = {
9630 type: "Index",
9631 value: this._lookaheadToken(0).value};
9632 this._advance();
9633 this._match(TOK_RBRACKET);
9634 return node;
9635 }
9636 },
9637
9638 _projectIfSlice: function(left, right) {
9639 var indexExpr = {type: "IndexExpression", children: [left, right]};
9640 if (right.type === "Slice") {
9641 return {
9642 type: "Projection",
9643 children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)]
9644 };
9645 } else {
9646 return indexExpr;
9647 }
9648 },
9649
9650 _parseSliceExpression: function() {
9651 // [start:end:step] where each part is optional, as well as the last
9652 // colon.
9653 var parts = [null, null, null];
9654 var index = 0;
9655 var currentToken = this._lookahead(0);
9656 while (currentToken !== TOK_RBRACKET && index < 3) {
9657 if (currentToken === TOK_COLON) {
9658 index++;
9659 this._advance();
9660 } else if (currentToken === TOK_NUMBER) {
9661 parts[index] = this._lookaheadToken(0).value;
9662 this._advance();
9663 } else {
9664 var t = this._lookahead(0);
9665 var error = new Error("Syntax error, unexpected token: " +
9666 t.value + "(" + t.type + ")");
9667 error.name = "Parsererror";
9668 throw error;
9669 }
9670 currentToken = this._lookahead(0);
9671 }
9672 this._match(TOK_RBRACKET);
9673 return {
9674 type: "Slice",
9675 children: parts
9676 };
9677 },
9678
9679 _parseComparator: function(left, comparator) {
9680 var right = this.expression(bindingPower[comparator]);
9681 return {type: "Comparator", name: comparator, children: [left, right]};
9682 },
9683
9684 _parseDotRHS: function(rbp) {
9685 var lookahead = this._lookahead(0);
9686 var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];
9687 if (exprTokens.indexOf(lookahead) >= 0) {
9688 return this.expression(rbp);
9689 } else if (lookahead === TOK_LBRACKET) {
9690 this._match(TOK_LBRACKET);
9691 return this._parseMultiselectList();
9692 } else if (lookahead === TOK_LBRACE) {
9693 this._match(TOK_LBRACE);
9694 return this._parseMultiselectHash();
9695 }
9696 },
9697
9698 _parseProjectionRHS: function(rbp) {
9699 var right;
9700 if (bindingPower[this._lookahead(0)] < 10) {
9701 right = {type: "Identity"};
9702 } else if (this._lookahead(0) === TOK_LBRACKET) {
9703 right = this.expression(rbp);
9704 } else if (this._lookahead(0) === TOK_FILTER) {
9705 right = this.expression(rbp);
9706 } else if (this._lookahead(0) === TOK_DOT) {
9707 this._match(TOK_DOT);
9708 right = this._parseDotRHS(rbp);
9709 } else {
9710 var t = this._lookaheadToken(0);
9711 var error = new Error("Sytanx error, unexpected token: " +
9712 t.value + "(" + t.type + ")");
9713 error.name = "ParserError";
9714 throw error;
9715 }
9716 return right;
9717 },
9718
9719 _parseMultiselectList: function() {
9720 var expressions = [];
9721 while (this._lookahead(0) !== TOK_RBRACKET) {
9722 var expression = this.expression(0);
9723 expressions.push(expression);
9724 if (this._lookahead(0) === TOK_COMMA) {
9725 this._match(TOK_COMMA);
9726 if (this._lookahead(0) === TOK_RBRACKET) {
9727 throw new Error("Unexpected token Rbracket");
9728 }
9729 }
9730 }
9731 this._match(TOK_RBRACKET);
9732 return {type: "MultiSelectList", children: expressions};
9733 },
9734
9735 _parseMultiselectHash: function() {
9736 var pairs = [];
9737 var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER];
9738 var keyToken, keyName, value, node;
9739 for (;;) {
9740 keyToken = this._lookaheadToken(0);
9741 if (identifierTypes.indexOf(keyToken.type) < 0) {
9742 throw new Error("Expecting an identifier token, got: " +
9743 keyToken.type);
9744 }
9745 keyName = keyToken.value;
9746 this._advance();
9747 this._match(TOK_COLON);
9748 value = this.expression(0);
9749 node = {type: "KeyValuePair", name: keyName, value: value};
9750 pairs.push(node);
9751 if (this._lookahead(0) === TOK_COMMA) {
9752 this._match(TOK_COMMA);
9753 } else if (this._lookahead(0) === TOK_RBRACE) {
9754 this._match(TOK_RBRACE);
9755 break;
9756 }
9757 }
9758 return {type: "MultiSelectHash", children: pairs};
9759 }
9760 };
9761
9762
9763 function TreeInterpreter(runtime) {
9764 this.runtime = runtime;
9765 }
9766
9767 TreeInterpreter.prototype = {
9768 search: function(node, value) {
9769 return this.visit(node, value);
9770 },
9771
9772 visit: function(node, value) {
9773 var matched, current, result, first, second, field, left, right, collected, i;
9774 switch (node.type) {
9775 case "Field":
9776 if (value === null ) {
9777 return null;
9778 } else if (isObject(value)) {
9779 field = value[node.name];
9780 if (field === undefined) {
9781 return null;
9782 } else {
9783 return field;
9784 }
9785 } else {
9786 return null;
9787 }
9788 break;
9789 case "Subexpression":
9790 result = this.visit(node.children[0], value);
9791 for (i = 1; i < node.children.length; i++) {
9792 result = this.visit(node.children[1], result);
9793 if (result === null) {
9794 return null;
9795 }
9796 }
9797 return result;
9798 case "IndexExpression":
9799 left = this.visit(node.children[0], value);
9800 right = this.visit(node.children[1], left);
9801 return right;
9802 case "Index":
9803 if (!isArray(value)) {
9804 return null;
9805 }
9806 var index = node.value;
9807 if (index < 0) {
9808 index = value.length + index;
9809 }
9810 result = value[index];
9811 if (result === undefined) {
9812 result = null;
9813 }
9814 return result;
9815 case "Slice":
9816 if (!isArray(value)) {
9817 return null;
9818 }
9819 var sliceParams = node.children.slice(0);
9820 var computed = this.computeSliceParams(value.length, sliceParams);
9821 var start = computed[0];
9822 var stop = computed[1];
9823 var step = computed[2];
9824 result = [];
9825 if (step > 0) {
9826 for (i = start; i < stop; i += step) {
9827 result.push(value[i]);
9828 }
9829 } else {
9830 for (i = start; i > stop; i += step) {
9831 result.push(value[i]);
9832 }
9833 }
9834 return result;
9835 case "Projection":
9836 // Evaluate left child.
9837 var base = this.visit(node.children[0], value);
9838 if (!isArray(base)) {
9839 return null;
9840 }
9841 collected = [];
9842 for (i = 0; i < base.length; i++) {
9843 current = this.visit(node.children[1], base[i]);
9844 if (current !== null) {
9845 collected.push(current);
9846 }
9847 }
9848 return collected;
9849 case "ValueProjection":
9850 // Evaluate left child.
9851 base = this.visit(node.children[0], value);
9852 if (!isObject(base)) {
9853 return null;
9854 }
9855 collected = [];
9856 var values = objValues(base);
9857 for (i = 0; i < values.length; i++) {
9858 current = this.visit(node.children[1], values[i]);
9859 if (current !== null) {
9860 collected.push(current);
9861 }
9862 }
9863 return collected;
9864 case "FilterProjection":
9865 base = this.visit(node.children[0], value);
9866 if (!isArray(base)) {
9867 return null;
9868 }
9869 var filtered = [];
9870 var finalResults = [];
9871 for (i = 0; i < base.length; i++) {
9872 matched = this.visit(node.children[2], base[i]);
9873 if (!isFalse(matched)) {
9874 filtered.push(base[i]);
9875 }
9876 }
9877 for (var j = 0; j < filtered.length; j++) {
9878 current = this.visit(node.children[1], filtered[j]);
9879 if (current !== null) {
9880 finalResults.push(current);
9881 }
9882 }
9883 return finalResults;
9884 case "Comparator":
9885 first = this.visit(node.children[0], value);
9886 second = this.visit(node.children[1], value);
9887 switch(node.name) {
9888 case TOK_EQ:
9889 result = strictDeepEqual(first, second);
9890 break;
9891 case TOK_NE:
9892 result = !strictDeepEqual(first, second);
9893 break;
9894 case TOK_GT:
9895 result = first > second;
9896 break;
9897 case TOK_GTE:
9898 result = first >= second;
9899 break;
9900 case TOK_LT:
9901 result = first < second;
9902 break;
9903 case TOK_LTE:
9904 result = first <= second;
9905 break;
9906 default:
9907 throw new Error("Unknown comparator: " + node.name);
9908 }
9909 return result;
9910 case TOK_FLATTEN:
9911 var original = this.visit(node.children[0], value);
9912 if (!isArray(original)) {
9913 return null;
9914 }
9915 var merged = [];
9916 for (i = 0; i < original.length; i++) {
9917 current = original[i];
9918 if (isArray(current)) {
9919 merged.push.apply(merged, current);
9920 } else {
9921 merged.push(current);
9922 }
9923 }
9924 return merged;
9925 case "Identity":
9926 return value;
9927 case "MultiSelectList":
9928 if (value === null) {
9929 return null;
9930 }
9931 collected = [];
9932 for (i = 0; i < node.children.length; i++) {
9933 collected.push(this.visit(node.children[i], value));
9934 }
9935 return collected;
9936 case "MultiSelectHash":
9937 if (value === null) {
9938 return null;
9939 }
9940 collected = {};
9941 var child;
9942 for (i = 0; i < node.children.length; i++) {
9943 child = node.children[i];
9944 collected[child.name] = this.visit(child.value, value);
9945 }
9946 return collected;
9947 case "OrExpression":
9948 matched = this.visit(node.children[0], value);
9949 if (isFalse(matched)) {
9950 matched = this.visit(node.children[1], value);
9951 }
9952 return matched;
9953 case "AndExpression":
9954 first = this.visit(node.children[0], value);
9955
9956 if (isFalse(first) === true) {
9957 return first;
9958 }
9959 return this.visit(node.children[1], value);
9960 case "NotExpression":
9961 first = this.visit(node.children[0], value);
9962 return isFalse(first);
9963 case "Literal":
9964 return node.value;
9965 case TOK_PIPE:
9966 left = this.visit(node.children[0], value);
9967 return this.visit(node.children[1], left);
9968 case TOK_CURRENT:
9969 return value;
9970 case "Function":
9971 var resolvedArgs = [];
9972 for (i = 0; i < node.children.length; i++) {
9973 resolvedArgs.push(this.visit(node.children[i], value));
9974 }
9975 return this.runtime.callFunction(node.name, resolvedArgs);
9976 case "ExpressionReference":
9977 var refNode = node.children[0];
9978 // Tag the node with a specific attribute so the type
9979 // checker verify the type.
9980 refNode.jmespathType = TOK_EXPREF;
9981 return refNode;
9982 default:
9983 throw new Error("Unknown node type: " + node.type);
9984 }
9985 },
9986
9987 computeSliceParams: function(arrayLength, sliceParams) {
9988 var start = sliceParams[0];
9989 var stop = sliceParams[1];
9990 var step = sliceParams[2];
9991 var computed = [null, null, null];
9992 if (step === null) {
9993 step = 1;
9994 } else if (step === 0) {
9995 var error = new Error("Invalid slice, step cannot be 0");
9996 error.name = "RuntimeError";
9997 throw error;
9998 }
9999 var stepValueNegative = step < 0 ? true : false;
10000
10001 if (start === null) {
10002 start = stepValueNegative ? arrayLength - 1 : 0;
10003 } else {
10004 start = this.capSliceRange(arrayLength, start, step);
10005 }
10006
10007 if (stop === null) {
10008 stop = stepValueNegative ? -1 : arrayLength;
10009 } else {
10010 stop = this.capSliceRange(arrayLength, stop, step);
10011 }
10012 computed[0] = start;
10013 computed[1] = stop;
10014 computed[2] = step;
10015 return computed;
10016 },
10017
10018 capSliceRange: function(arrayLength, actualValue, step) {
10019 if (actualValue < 0) {
10020 actualValue += arrayLength;
10021 if (actualValue < 0) {
10022 actualValue = step < 0 ? -1 : 0;
10023 }
10024 } else if (actualValue >= arrayLength) {
10025 actualValue = step < 0 ? arrayLength - 1 : arrayLength;
10026 }
10027 return actualValue;
10028 }
10029
10030 };
10031
10032 function Runtime(interpreter) {
10033 this._interpreter = interpreter;
10034 this.functionTable = {
10035 // name: [function, <signature>]
10036 // The <signature> can be:
10037 //
10038 // {
10039 // args: [[type1, type2], [type1, type2]],
10040 // variadic: true|false
10041 // }
10042 //
10043 // Each arg in the arg list is a list of valid types
10044 // (if the function is overloaded and supports multiple
10045 // types. If the type is "any" then no type checking
10046 // occurs on the argument. Variadic is optional
10047 // and if not provided is assumed to be false.
10048 abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]},
10049 avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
10050 ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]},
10051 contains: {
10052 _func: this._functionContains,
10053 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]},
10054 {types: [TYPE_ANY]}]},
10055 "ends_with": {
10056 _func: this._functionEndsWith,
10057 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
10058 floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]},
10059 length: {
10060 _func: this._functionLength,
10061 _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]},
10062 map: {
10063 _func: this._functionMap,
10064 _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]},
10065 max: {
10066 _func: this._functionMax,
10067 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
10068 "merge": {
10069 _func: this._functionMerge,
10070 _signature: [{types: [TYPE_OBJECT], variadic: true}]
10071 },
10072 "max_by": {
10073 _func: this._functionMaxBy,
10074 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
10075 },
10076 sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
10077 "starts_with": {
10078 _func: this._functionStartsWith,
10079 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
10080 min: {
10081 _func: this._functionMin,
10082 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
10083 "min_by": {
10084 _func: this._functionMinBy,
10085 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
10086 },
10087 type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]},
10088 keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]},
10089 values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]},
10090 sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]},
10091 "sort_by": {
10092 _func: this._functionSortBy,
10093 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
10094 },
10095 join: {
10096 _func: this._functionJoin,
10097 _signature: [
10098 {types: [TYPE_STRING]},
10099 {types: [TYPE_ARRAY_STRING]}
10100 ]
10101 },
10102 reverse: {
10103 _func: this._functionReverse,
10104 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]},
10105 "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]},
10106 "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]},
10107 "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]},
10108 "not_null": {
10109 _func: this._functionNotNull,
10110 _signature: [{types: [TYPE_ANY], variadic: true}]
10111 }
10112 };
10113 }
10114
10115 Runtime.prototype = {
10116 callFunction: function(name, resolvedArgs) {
10117 var functionEntry = this.functionTable[name];
10118 if (functionEntry === undefined) {
10119 throw new Error("Unknown function: " + name + "()");
10120 }
10121 this._validateArgs(name, resolvedArgs, functionEntry._signature);
10122 return functionEntry._func.call(this, resolvedArgs);
10123 },
10124
10125 _validateArgs: function(name, args, signature) {
10126 // Validating the args requires validating
10127 // the correct arity and the correct type of each arg.
10128 // If the last argument is declared as variadic, then we need
10129 // a minimum number of args to be required. Otherwise it has to
10130 // be an exact amount.
10131 var pluralized;
10132 if (signature[signature.length - 1].variadic) {
10133 if (args.length < signature.length) {
10134 pluralized = signature.length === 1 ? " argument" : " arguments";
10135 throw new Error("ArgumentError: " + name + "() " +
10136 "takes at least" + signature.length + pluralized +
10137 " but received " + args.length);
10138 }
10139 } else if (args.length !== signature.length) {
10140 pluralized = signature.length === 1 ? " argument" : " arguments";
10141 throw new Error("ArgumentError: " + name + "() " +
10142 "takes " + signature.length + pluralized +
10143 " but received " + args.length);
10144 }
10145 var currentSpec;
10146 var actualType;
10147 var typeMatched;
10148 for (var i = 0; i < signature.length; i++) {
10149 typeMatched = false;
10150 currentSpec = signature[i].types;
10151 actualType = this._getTypeName(args[i]);
10152 for (var j = 0; j < currentSpec.length; j++) {
10153 if (this._typeMatches(actualType, currentSpec[j], args[i])) {
10154 typeMatched = true;
10155 break;
10156 }
10157 }
10158 if (!typeMatched) {
10159 throw new Error("TypeError: " + name + "() " +
10160 "expected argument " + (i + 1) +
10161 " to be type " + currentSpec +
10162 " but received type " + actualType +
10163 " instead.");
10164 }
10165 }
10166 },
10167
10168 _typeMatches: function(actual, expected, argValue) {
10169 if (expected === TYPE_ANY) {
10170 return true;
10171 }
10172 if (expected === TYPE_ARRAY_STRING ||
10173 expected === TYPE_ARRAY_NUMBER ||
10174 expected === TYPE_ARRAY) {
10175 // The expected type can either just be array,
10176 // or it can require a specific subtype (array of numbers).
10177 //
10178 // The simplest case is if "array" with no subtype is specified.
10179 if (expected === TYPE_ARRAY) {
10180 return actual === TYPE_ARRAY;
10181 } else if (actual === TYPE_ARRAY) {
10182 // Otherwise we need to check subtypes.
10183 // I think this has potential to be improved.
10184 var subtype;
10185 if (expected === TYPE_ARRAY_NUMBER) {
10186 subtype = TYPE_NUMBER;
10187 } else if (expected === TYPE_ARRAY_STRING) {
10188 subtype = TYPE_STRING;
10189 }
10190 for (var i = 0; i < argValue.length; i++) {
10191 if (!this._typeMatches(
10192 this._getTypeName(argValue[i]), subtype,
10193 argValue[i])) {
10194 return false;
10195 }
10196 }
10197 return true;
10198 }
10199 } else {
10200 return actual === expected;
10201 }
10202 },
10203 _getTypeName: function(obj) {
10204 switch (Object.prototype.toString.call(obj)) {
10205 case "[object String]":
10206 return TYPE_STRING;
10207 case "[object Number]":
10208 return TYPE_NUMBER;
10209 case "[object Array]":
10210 return TYPE_ARRAY;
10211 case "[object Boolean]":
10212 return TYPE_BOOLEAN;
10213 case "[object Null]":
10214 return TYPE_NULL;
10215 case "[object Object]":
10216 // Check if it's an expref. If it has, it's been
10217 // tagged with a jmespathType attr of 'Expref';
10218 if (obj.jmespathType === TOK_EXPREF) {
10219 return TYPE_EXPREF;
10220 } else {
10221 return TYPE_OBJECT;
10222 }
10223 }
10224 },
10225
10226 _functionStartsWith: function(resolvedArgs) {
10227 return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0;
10228 },
10229
10230 _functionEndsWith: function(resolvedArgs) {
10231 var searchStr = resolvedArgs[0];
10232 var suffix = resolvedArgs[1];
10233 return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1;
10234 },
10235
10236 _functionReverse: function(resolvedArgs) {
10237 var typeName = this._getTypeName(resolvedArgs[0]);
10238 if (typeName === TYPE_STRING) {
10239 var originalStr = resolvedArgs[0];
10240 var reversedStr = "";
10241 for (var i = originalStr.length - 1; i >= 0; i--) {
10242 reversedStr += originalStr[i];
10243 }
10244 return reversedStr;
10245 } else {
10246 var reversedArray = resolvedArgs[0].slice(0);
10247 reversedArray.reverse();
10248 return reversedArray;
10249 }
10250 },
10251
10252 _functionAbs: function(resolvedArgs) {
10253 return Math.abs(resolvedArgs[0]);
10254 },
10255
10256 _functionCeil: function(resolvedArgs) {
10257 return Math.ceil(resolvedArgs[0]);
10258 },
10259
10260 _functionAvg: function(resolvedArgs) {
10261 var sum = 0;
10262 var inputArray = resolvedArgs[0];
10263 for (var i = 0; i < inputArray.length; i++) {
10264 sum += inputArray[i];
10265 }
10266 return sum / inputArray.length;
10267 },
10268
10269 _functionContains: function(resolvedArgs) {
10270 return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0;
10271 },
10272
10273 _functionFloor: function(resolvedArgs) {
10274 return Math.floor(resolvedArgs[0]);
10275 },
10276
10277 _functionLength: function(resolvedArgs) {
10278 if (!isObject(resolvedArgs[0])) {
10279 return resolvedArgs[0].length;
10280 } else {
10281 // As far as I can tell, there's no way to get the length
10282 // of an object without O(n) iteration through the object.
10283 return Object.keys(resolvedArgs[0]).length;
10284 }
10285 },
10286
10287 _functionMap: function(resolvedArgs) {
10288 var mapped = [];
10289 var interpreter = this._interpreter;
10290 var exprefNode = resolvedArgs[0];
10291 var elements = resolvedArgs[1];
10292 for (var i = 0; i < elements.length; i++) {
10293 mapped.push(interpreter.visit(exprefNode, elements[i]));
10294 }
10295 return mapped;
10296 },
10297
10298 _functionMerge: function(resolvedArgs) {
10299 var merged = {};
10300 for (var i = 0; i < resolvedArgs.length; i++) {
10301 var current = resolvedArgs[i];
10302 for (var key in current) {
10303 merged[key] = current[key];
10304 }
10305 }
10306 return merged;
10307 },
10308
10309 _functionMax: function(resolvedArgs) {
10310 if (resolvedArgs[0].length > 0) {
10311 var typeName = this._getTypeName(resolvedArgs[0][0]);
10312 if (typeName === TYPE_NUMBER) {
10313 return Math.max.apply(Math, resolvedArgs[0]);
10314 } else {
10315 var elements = resolvedArgs[0];
10316 var maxElement = elements[0];
10317 for (var i = 1; i < elements.length; i++) {
10318 if (maxElement.localeCompare(elements[i]) < 0) {
10319 maxElement = elements[i];
10320 }
10321 }
10322 return maxElement;
10323 }
10324 } else {
10325 return null;
10326 }
10327 },
10328
10329 _functionMin: function(resolvedArgs) {
10330 if (resolvedArgs[0].length > 0) {
10331 var typeName = this._getTypeName(resolvedArgs[0][0]);
10332 if (typeName === TYPE_NUMBER) {
10333 return Math.min.apply(Math, resolvedArgs[0]);
10334 } else {
10335 var elements = resolvedArgs[0];
10336 var minElement = elements[0];
10337 for (var i = 1; i < elements.length; i++) {
10338 if (elements[i].localeCompare(minElement) < 0) {
10339 minElement = elements[i];
10340 }
10341 }
10342 return minElement;
10343 }
10344 } else {
10345 return null;
10346 }
10347 },
10348
10349 _functionSum: function(resolvedArgs) {
10350 var sum = 0;
10351 var listToSum = resolvedArgs[0];
10352 for (var i = 0; i < listToSum.length; i++) {
10353 sum += listToSum[i];
10354 }
10355 return sum;
10356 },
10357
10358 _functionType: function(resolvedArgs) {
10359 switch (this._getTypeName(resolvedArgs[0])) {
10360 case TYPE_NUMBER:
10361 return "number";
10362 case TYPE_STRING:
10363 return "string";
10364 case TYPE_ARRAY:
10365 return "array";
10366 case TYPE_OBJECT:
10367 return "object";
10368 case TYPE_BOOLEAN:
10369 return "boolean";
10370 case TYPE_EXPREF:
10371 return "expref";
10372 case TYPE_NULL:
10373 return "null";
10374 }
10375 },
10376
10377 _functionKeys: function(resolvedArgs) {
10378 return Object.keys(resolvedArgs[0]);
10379 },
10380
10381 _functionValues: function(resolvedArgs) {
10382 var obj = resolvedArgs[0];
10383 var keys = Object.keys(obj);
10384 var values = [];
10385 for (var i = 0; i < keys.length; i++) {
10386 values.push(obj[keys[i]]);
10387 }
10388 return values;
10389 },
10390
10391 _functionJoin: function(resolvedArgs) {
10392 var joinChar = resolvedArgs[0];
10393 var listJoin = resolvedArgs[1];
10394 return listJoin.join(joinChar);
10395 },
10396
10397 _functionToArray: function(resolvedArgs) {
10398 if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) {
10399 return resolvedArgs[0];
10400 } else {
10401 return [resolvedArgs[0]];
10402 }
10403 },
10404
10405 _functionToString: function(resolvedArgs) {
10406 if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) {
10407 return resolvedArgs[0];
10408 } else {
10409 return JSON.stringify(resolvedArgs[0]);
10410 }
10411 },
10412
10413 _functionToNumber: function(resolvedArgs) {
10414 var typeName = this._getTypeName(resolvedArgs[0]);
10415 var convertedValue;
10416 if (typeName === TYPE_NUMBER) {
10417 return resolvedArgs[0];
10418 } else if (typeName === TYPE_STRING) {
10419 convertedValue = +resolvedArgs[0];
10420 if (!isNaN(convertedValue)) {
10421 return convertedValue;
10422 }
10423 }
10424 return null;
10425 },
10426
10427 _functionNotNull: function(resolvedArgs) {
10428 for (var i = 0; i < resolvedArgs.length; i++) {
10429 if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) {
10430 return resolvedArgs[i];
10431 }
10432 }
10433 return null;
10434 },
10435
10436 _functionSort: function(resolvedArgs) {
10437 var sortedArray = resolvedArgs[0].slice(0);
10438 sortedArray.sort();
10439 return sortedArray;
10440 },
10441
10442 _functionSortBy: function(resolvedArgs) {
10443 var sortedArray = resolvedArgs[0].slice(0);
10444 if (sortedArray.length === 0) {
10445 return sortedArray;
10446 }
10447 var interpreter = this._interpreter;
10448 var exprefNode = resolvedArgs[1];
10449 var requiredType = this._getTypeName(
10450 interpreter.visit(exprefNode, sortedArray[0]));
10451 if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) {
10452 throw new Error("TypeError");
10453 }
10454 var that = this;
10455 // In order to get a stable sort out of an unstable
10456 // sort algorithm, we decorate/sort/undecorate (DSU)
10457 // by creating a new list of [index, element] pairs.
10458 // In the cmp function, if the evaluated elements are
10459 // equal, then the index will be used as the tiebreaker.
10460 // After the decorated list has been sorted, it will be
10461 // undecorated to extract the original elements.
10462 var decorated = [];
10463 for (var i = 0; i < sortedArray.length; i++) {
10464 decorated.push([i, sortedArray[i]]);
10465 }
10466 decorated.sort(function(a, b) {
10467 var exprA = interpreter.visit(exprefNode, a[1]);
10468 var exprB = interpreter.visit(exprefNode, b[1]);
10469 if (that._getTypeName(exprA) !== requiredType) {
10470 throw new Error(
10471 "TypeError: expected " + requiredType + ", received " +
10472 that._getTypeName(exprA));
10473 } else if (that._getTypeName(exprB) !== requiredType) {
10474 throw new Error(
10475 "TypeError: expected " + requiredType + ", received " +
10476 that._getTypeName(exprB));
10477 }
10478 if (exprA > exprB) {
10479 return 1;
10480 } else if (exprA < exprB) {
10481 return -1;
10482 } else {
10483 // If they're equal compare the items by their
10484 // order to maintain relative order of equal keys
10485 // (i.e. to get a stable sort).
10486 return a[0] - b[0];
10487 }
10488 });
10489 // Undecorate: extract out the original list elements.
10490 for (var j = 0; j < decorated.length; j++) {
10491 sortedArray[j] = decorated[j][1];
10492 }
10493 return sortedArray;
10494 },
10495
10496 _functionMaxBy: function(resolvedArgs) {
10497 var exprefNode = resolvedArgs[1];
10498 var resolvedArray = resolvedArgs[0];
10499 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10500 var maxNumber = -Infinity;
10501 var maxRecord;
10502 var current;
10503 for (var i = 0; i < resolvedArray.length; i++) {
10504 current = keyFunction(resolvedArray[i]);
10505 if (current > maxNumber) {
10506 maxNumber = current;
10507 maxRecord = resolvedArray[i];
10508 }
10509 }
10510 return maxRecord;
10511 },
10512
10513 _functionMinBy: function(resolvedArgs) {
10514 var exprefNode = resolvedArgs[1];
10515 var resolvedArray = resolvedArgs[0];
10516 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10517 var minNumber = Infinity;
10518 var minRecord;
10519 var current;
10520 for (var i = 0; i < resolvedArray.length; i++) {
10521 current = keyFunction(resolvedArray[i]);
10522 if (current < minNumber) {
10523 minNumber = current;
10524 minRecord = resolvedArray[i];
10525 }
10526 }
10527 return minRecord;
10528 },
10529
10530 createKeyFunction: function(exprefNode, allowedTypes) {
10531 var that = this;
10532 var interpreter = this._interpreter;
10533 var keyFunc = function(x) {
10534 var current = interpreter.visit(exprefNode, x);
10535 if (allowedTypes.indexOf(that._getTypeName(current)) < 0) {
10536 var msg = "TypeError: expected one of " + allowedTypes +
10537 ", received " + that._getTypeName(current);
10538 throw new Error(msg);
10539 }
10540 return current;
10541 };
10542 return keyFunc;
10543 }
10544
10545 };
10546
10547 function compile(stream) {
10548 var parser = new Parser();
10549 var ast = parser.parse(stream);
10550 return ast;
10551 }
10552
10553 function tokenize(stream) {
10554 var lexer = new Lexer();
10555 return lexer.tokenize(stream);
10556 }
10557
10558 function search(data, expression) {
10559 var parser = new Parser();
10560 // This needs to be improved. Both the interpreter and runtime depend on
10561 // each other. The runtime needs the interpreter to support exprefs.
10562 // There's likely a clean way to avoid the cyclic dependency.
10563 var runtime = new Runtime();
10564 var interpreter = new TreeInterpreter(runtime);
10565 runtime._interpreter = interpreter;
10566 var node = parser.parse(expression);
10567 return interpreter.search(node, data);
10568 }
10569
10570 exports.tokenize = tokenize;
10571 exports.compile = compile;
10572 exports.search = search;
10573 exports.strictDeepEqual = strictDeepEqual;
10574 })( false ? this.jmespath = {} : exports);
10575
10576
10577/***/ }),
10578/* 52 */
10579/***/ (function(module, exports, __webpack_require__) {
10580
10581 var AWS = __webpack_require__(1);
10582 var inherit = AWS.util.inherit;
10583 var jmespath = __webpack_require__(51);
10584
10585 /**
10586 * This class encapsulates the response information
10587 * from a service request operation sent through {AWS.Request}.
10588 * The response object has two main properties for getting information
10589 * back from a request:
10590 *
10591 * ## The `data` property
10592 *
10593 * The `response.data` property contains the serialized object data
10594 * retrieved from the service request. For instance, for an
10595 * Amazon DynamoDB `listTables` method call, the response data might
10596 * look like:
10597 *
10598 * ```
10599 * > resp.data
10600 * { TableNames:
10601 * [ 'table1', 'table2', ... ] }
10602 * ```
10603 *
10604 * The `data` property can be null if an error occurs (see below).
10605 *
10606 * ## The `error` property
10607 *
10608 * In the event of a service error (or transfer error), the
10609 * `response.error` property will be filled with the given
10610 * error data in the form:
10611 *
10612 * ```
10613 * { code: 'SHORT_UNIQUE_ERROR_CODE',
10614 * message: 'Some human readable error message' }
10615 * ```
10616 *
10617 * In the case of an error, the `data` property will be `null`.
10618 * Note that if you handle events that can be in a failure state,
10619 * you should always check whether `response.error` is set
10620 * before attempting to access the `response.data` property.
10621 *
10622 * @!attribute data
10623 * @readonly
10624 * @!group Data Properties
10625 * @note Inside of a {AWS.Request~httpData} event, this
10626 * property contains a single raw packet instead of the
10627 * full de-serialized service response.
10628 * @return [Object] the de-serialized response data
10629 * from the service.
10630 *
10631 * @!attribute error
10632 * An structure containing information about a service
10633 * or networking error.
10634 * @readonly
10635 * @!group Data Properties
10636 * @note This attribute is only filled if a service or
10637 * networking error occurs.
10638 * @return [Error]
10639 * * code [String] a unique short code representing the
10640 * error that was emitted.
10641 * * message [String] a longer human readable error message
10642 * * retryable [Boolean] whether the error message is
10643 * retryable.
10644 * * statusCode [Numeric] in the case of a request that reached the service,
10645 * this value contains the response status code.
10646 * * time [Date] the date time object when the error occurred.
10647 * * hostname [String] set when a networking error occurs to easily
10648 * identify the endpoint of the request.
10649 * * region [String] set when a networking error occurs to easily
10650 * identify the region of the request.
10651 *
10652 * @!attribute requestId
10653 * @readonly
10654 * @!group Data Properties
10655 * @return [String] the unique request ID associated with the response.
10656 * Log this value when debugging requests for AWS support.
10657 *
10658 * @!attribute retryCount
10659 * @readonly
10660 * @!group Operation Properties
10661 * @return [Integer] the number of retries that were
10662 * attempted before the request was completed.
10663 *
10664 * @!attribute redirectCount
10665 * @readonly
10666 * @!group Operation Properties
10667 * @return [Integer] the number of redirects that were
10668 * followed before the request was completed.
10669 *
10670 * @!attribute httpResponse
10671 * @readonly
10672 * @!group HTTP Properties
10673 * @return [AWS.HttpResponse] the raw HTTP response object
10674 * containing the response headers and body information
10675 * from the server.
10676 *
10677 * @see AWS.Request
10678 */
10679 AWS.Response = inherit({
10680
10681 /**
10682 * @api private
10683 */
10684 constructor: function Response(request) {
10685 this.request = request;
10686 this.data = null;
10687 this.error = null;
10688 this.retryCount = 0;
10689 this.redirectCount = 0;
10690 this.httpResponse = new AWS.HttpResponse();
10691 if (request) {
10692 this.maxRetries = request.service.numRetries();
10693 this.maxRedirects = request.service.config.maxRedirects;
10694 }
10695 },
10696
10697 /**
10698 * Creates a new request for the next page of response data, calling the
10699 * callback with the page data if a callback is provided.
10700 *
10701 * @callback callback function(err, data)
10702 * Called when a page of data is returned from the next request.
10703 *
10704 * @param err [Error] an error object, if an error occurred in the request
10705 * @param data [Object] the next page of data, or null, if there are no
10706 * more pages left.
10707 * @return [AWS.Request] the request object for the next page of data
10708 * @return [null] if no callback is provided and there are no pages left
10709 * to retrieve.
10710 * @since v1.4.0
10711 */
10712 nextPage: function nextPage(callback) {
10713 var config;
10714 var service = this.request.service;
10715 var operation = this.request.operation;
10716 try {
10717 config = service.paginationConfig(operation, true);
10718 } catch (e) { this.error = e; }
10719
10720 if (!this.hasNextPage()) {
10721 if (callback) callback(this.error, null);
10722 else if (this.error) throw this.error;
10723 return null;
10724 }
10725
10726 var params = AWS.util.copy(this.request.params);
10727 if (!this.nextPageTokens) {
10728 return callback ? callback(null, null) : null;
10729 } else {
10730 var inputTokens = config.inputToken;
10731 if (typeof inputTokens === 'string') inputTokens = [inputTokens];
10732 for (var i = 0; i < inputTokens.length; i++) {
10733 params[inputTokens[i]] = this.nextPageTokens[i];
10734 }
10735 return service.makeRequest(this.request.operation, params, callback);
10736 }
10737 },
10738
10739 /**
10740 * @return [Boolean] whether more pages of data can be returned by further
10741 * requests
10742 * @since v1.4.0
10743 */
10744 hasNextPage: function hasNextPage() {
10745 this.cacheNextPageTokens();
10746 if (this.nextPageTokens) return true;
10747 if (this.nextPageTokens === undefined) return undefined;
10748 else return false;
10749 },
10750
10751 /**
10752 * @api private
10753 */
10754 cacheNextPageTokens: function cacheNextPageTokens() {
10755 if (Object.prototype.hasOwnProperty.call(this, 'nextPageTokens')) return this.nextPageTokens;
10756 this.nextPageTokens = undefined;
10757
10758 var config = this.request.service.paginationConfig(this.request.operation);
10759 if (!config) return this.nextPageTokens;
10760
10761 this.nextPageTokens = null;
10762 if (config.moreResults) {
10763 if (!jmespath.search(this.data, config.moreResults)) {
10764 return this.nextPageTokens;
10765 }
10766 }
10767
10768 var exprs = config.outputToken;
10769 if (typeof exprs === 'string') exprs = [exprs];
10770 AWS.util.arrayEach.call(this, exprs, function (expr) {
10771 var output = jmespath.search(this.data, expr);
10772 if (output) {
10773 this.nextPageTokens = this.nextPageTokens || [];
10774 this.nextPageTokens.push(output);
10775 }
10776 });
10777
10778 return this.nextPageTokens;
10779 }
10780
10781 });
10782
10783
10784/***/ }),
10785/* 53 */
10786/***/ (function(module, exports, __webpack_require__) {
10787
10788 /**
10789 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
10790 *
10791 * Licensed under the Apache License, Version 2.0 (the "License"). You
10792 * may not use this file except in compliance with the License. A copy of
10793 * the License is located at
10794 *
10795 * http://aws.amazon.com/apache2.0/
10796 *
10797 * or in the "license" file accompanying this file. This file is
10798 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
10799 * ANY KIND, either express or implied. See the License for the specific
10800 * language governing permissions and limitations under the License.
10801 */
10802
10803 var AWS = __webpack_require__(1);
10804 var inherit = AWS.util.inherit;
10805 var jmespath = __webpack_require__(51);
10806
10807 /**
10808 * @api private
10809 */
10810 function CHECK_ACCEPTORS(resp) {
10811 var waiter = resp.request._waiter;
10812 var acceptors = waiter.config.acceptors;
10813 var acceptorMatched = false;
10814 var state = 'retry';
10815
10816 acceptors.forEach(function(acceptor) {
10817 if (!acceptorMatched) {
10818 var matcher = waiter.matchers[acceptor.matcher];
10819 if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) {
10820 acceptorMatched = true;
10821 state = acceptor.state;
10822 }
10823 }
10824 });
10825
10826 if (!acceptorMatched && resp.error) state = 'failure';
10827
10828 if (state === 'success') {
10829 waiter.setSuccess(resp);
10830 } else {
10831 waiter.setError(resp, state === 'retry');
10832 }
10833 }
10834
10835 /**
10836 * @api private
10837 */
10838 AWS.ResourceWaiter = inherit({
10839 /**
10840 * Waits for a given state on a service object
10841 * @param service [Service] the service object to wait on
10842 * @param state [String] the state (defined in waiter configuration) to wait
10843 * for.
10844 * @example Create a waiter for running EC2 instances
10845 * var ec2 = new AWS.EC2;
10846 * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
10847 */
10848 constructor: function constructor(service, state) {
10849 this.service = service;
10850 this.state = state;
10851 this.loadWaiterConfig(this.state);
10852 },
10853
10854 service: null,
10855
10856 state: null,
10857
10858 config: null,
10859
10860 matchers: {
10861 path: function(resp, expected, argument) {
10862 try {
10863 var result = jmespath.search(resp.data, argument);
10864 } catch (err) {
10865 return false;
10866 }
10867
10868 return jmespath.strictDeepEqual(result,expected);
10869 },
10870
10871 pathAll: function(resp, expected, argument) {
10872 try {
10873 var results = jmespath.search(resp.data, argument);
10874 } catch (err) {
10875 return false;
10876 }
10877
10878 if (!Array.isArray(results)) results = [results];
10879 var numResults = results.length;
10880 if (!numResults) return false;
10881 for (var ind = 0 ; ind < numResults; ind++) {
10882 if (!jmespath.strictDeepEqual(results[ind], expected)) {
10883 return false;
10884 }
10885 }
10886 return true;
10887 },
10888
10889 pathAny: function(resp, expected, argument) {
10890 try {
10891 var results = jmespath.search(resp.data, argument);
10892 } catch (err) {
10893 return false;
10894 }
10895
10896 if (!Array.isArray(results)) results = [results];
10897 var numResults = results.length;
10898 for (var ind = 0 ; ind < numResults; ind++) {
10899 if (jmespath.strictDeepEqual(results[ind], expected)) {
10900 return true;
10901 }
10902 }
10903 return false;
10904 },
10905
10906 status: function(resp, expected) {
10907 var statusCode = resp.httpResponse.statusCode;
10908 return (typeof statusCode === 'number') && (statusCode === expected);
10909 },
10910
10911 error: function(resp, expected) {
10912 if (typeof expected === 'string' && resp.error) {
10913 return expected === resp.error.code;
10914 }
10915 // if expected is not string, can be boolean indicating presence of error
10916 return expected === !!resp.error;
10917 }
10918 },
10919
10920 listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) {
10921 add('RETRY_CHECK', 'retry', function(resp) {
10922 var waiter = resp.request._waiter;
10923 if (resp.error && resp.error.code === 'ResourceNotReady') {
10924 resp.error.retryDelay = (waiter.config.delay || 0) * 1000;
10925 }
10926 });
10927
10928 add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS);
10929
10930 add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS);
10931 }),
10932
10933 /**
10934 * @return [AWS.Request]
10935 */
10936 wait: function wait(params, callback) {
10937 if (typeof params === 'function') {
10938 callback = params; params = undefined;
10939 }
10940
10941 if (params && params.$waiter) {
10942 params = AWS.util.copy(params);
10943 if (typeof params.$waiter.delay === 'number') {
10944 this.config.delay = params.$waiter.delay;
10945 }
10946 if (typeof params.$waiter.maxAttempts === 'number') {
10947 this.config.maxAttempts = params.$waiter.maxAttempts;
10948 }
10949 delete params.$waiter;
10950 }
10951
10952 var request = this.service.makeRequest(this.config.operation, params);
10953 request._waiter = this;
10954 request.response.maxRetries = this.config.maxAttempts;
10955 request.addListeners(this.listeners);
10956
10957 if (callback) request.send(callback);
10958 return request;
10959 },
10960
10961 setSuccess: function setSuccess(resp) {
10962 resp.error = null;
10963 resp.data = resp.data || {};
10964 resp.request.removeAllListeners('extractData');
10965 },
10966
10967 setError: function setError(resp, retryable) {
10968 resp.data = null;
10969 resp.error = AWS.util.error(resp.error || new Error(), {
10970 code: 'ResourceNotReady',
10971 message: 'Resource is not in the state ' + this.state,
10972 retryable: retryable
10973 });
10974 },
10975
10976 /**
10977 * Loads waiter configuration from API configuration
10978 *
10979 * @api private
10980 */
10981 loadWaiterConfig: function loadWaiterConfig(state) {
10982 if (!this.service.api.waiters[state]) {
10983 throw new AWS.util.error(new Error(), {
10984 code: 'StateNotFoundError',
10985 message: 'State ' + state + ' not found.'
10986 });
10987 }
10988
10989 this.config = AWS.util.copy(this.service.api.waiters[state]);
10990 }
10991 });
10992
10993
10994/***/ }),
10995/* 54 */
10996/***/ (function(module, exports, __webpack_require__) {
10997
10998 var AWS = __webpack_require__(1);
10999
11000 var inherit = AWS.util.inherit;
11001
11002 /**
11003 * @api private
11004 */
11005 AWS.Signers.RequestSigner = inherit({
11006 constructor: function RequestSigner(request) {
11007 this.request = request;
11008 },
11009
11010 setServiceClientId: function setServiceClientId(id) {
11011 this.serviceClientId = id;
11012 },
11013
11014 getServiceClientId: function getServiceClientId() {
11015 return this.serviceClientId;
11016 }
11017 });
11018
11019 AWS.Signers.RequestSigner.getVersion = function getVersion(version) {
11020 switch (version) {
11021 case 'v2': return AWS.Signers.V2;
11022 case 'v3': return AWS.Signers.V3;
11023 case 's3v4': return AWS.Signers.V4;
11024 case 'v4': return AWS.Signers.V4;
11025 case 's3': return AWS.Signers.S3;
11026 case 'v3https': return AWS.Signers.V3Https;
11027 }
11028 throw new Error('Unknown signing version ' + version);
11029 };
11030
11031 __webpack_require__(55);
11032 __webpack_require__(56);
11033 __webpack_require__(57);
11034 __webpack_require__(58);
11035 __webpack_require__(60);
11036 __webpack_require__(61);
11037
11038
11039/***/ }),
11040/* 55 */
11041/***/ (function(module, exports, __webpack_require__) {
11042
11043 var AWS = __webpack_require__(1);
11044 var inherit = AWS.util.inherit;
11045
11046 /**
11047 * @api private
11048 */
11049 AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, {
11050 addAuthorization: function addAuthorization(credentials, date) {
11051
11052 if (!date) date = AWS.util.date.getDate();
11053
11054 var r = this.request;
11055
11056 r.params.Timestamp = AWS.util.date.iso8601(date);
11057 r.params.SignatureVersion = '2';
11058 r.params.SignatureMethod = 'HmacSHA256';
11059 r.params.AWSAccessKeyId = credentials.accessKeyId;
11060
11061 if (credentials.sessionToken) {
11062 r.params.SecurityToken = credentials.sessionToken;
11063 }
11064
11065 delete r.params.Signature; // delete old Signature for re-signing
11066 r.params.Signature = this.signature(credentials);
11067
11068 r.body = AWS.util.queryParamsToString(r.params);
11069 r.headers['Content-Length'] = r.body.length;
11070 },
11071
11072 signature: function signature(credentials) {
11073 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
11074 },
11075
11076 stringToSign: function stringToSign() {
11077 var parts = [];
11078 parts.push(this.request.method);
11079 parts.push(this.request.endpoint.host.toLowerCase());
11080 parts.push(this.request.pathname());
11081 parts.push(AWS.util.queryParamsToString(this.request.params));
11082 return parts.join('\n');
11083 }
11084
11085 });
11086
11087 /**
11088 * @api private
11089 */
11090 module.exports = AWS.Signers.V2;
11091
11092
11093/***/ }),
11094/* 56 */
11095/***/ (function(module, exports, __webpack_require__) {
11096
11097 var AWS = __webpack_require__(1);
11098 var inherit = AWS.util.inherit;
11099
11100 /**
11101 * @api private
11102 */
11103 AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, {
11104 addAuthorization: function addAuthorization(credentials, date) {
11105
11106 var datetime = AWS.util.date.rfc822(date);
11107
11108 this.request.headers['X-Amz-Date'] = datetime;
11109
11110 if (credentials.sessionToken) {
11111 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11112 }
11113
11114 this.request.headers['X-Amzn-Authorization'] =
11115 this.authorization(credentials, datetime);
11116
11117 },
11118
11119 authorization: function authorization(credentials) {
11120 return 'AWS3 ' +
11121 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
11122 'Algorithm=HmacSHA256,' +
11123 'SignedHeaders=' + this.signedHeaders() + ',' +
11124 'Signature=' + this.signature(credentials);
11125 },
11126
11127 signedHeaders: function signedHeaders() {
11128 var headers = [];
11129 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
11130 headers.push(h.toLowerCase());
11131 });
11132 return headers.sort().join(';');
11133 },
11134
11135 canonicalHeaders: function canonicalHeaders() {
11136 var headers = this.request.headers;
11137 var parts = [];
11138 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
11139 parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim());
11140 });
11141 return parts.sort().join('\n') + '\n';
11142 },
11143
11144 headersToSign: function headersToSign() {
11145 var headers = [];
11146 AWS.util.each(this.request.headers, function iterator(k) {
11147 if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) {
11148 headers.push(k);
11149 }
11150 });
11151 return headers;
11152 },
11153
11154 signature: function signature(credentials) {
11155 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
11156 },
11157
11158 stringToSign: function stringToSign() {
11159 var parts = [];
11160 parts.push(this.request.method);
11161 parts.push('/');
11162 parts.push('');
11163 parts.push(this.canonicalHeaders());
11164 parts.push(this.request.body);
11165 return AWS.util.crypto.sha256(parts.join('\n'));
11166 }
11167
11168 });
11169
11170 /**
11171 * @api private
11172 */
11173 module.exports = AWS.Signers.V3;
11174
11175
11176/***/ }),
11177/* 57 */
11178/***/ (function(module, exports, __webpack_require__) {
11179
11180 var AWS = __webpack_require__(1);
11181 var inherit = AWS.util.inherit;
11182
11183 __webpack_require__(56);
11184
11185 /**
11186 * @api private
11187 */
11188 AWS.Signers.V3Https = inherit(AWS.Signers.V3, {
11189 authorization: function authorization(credentials) {
11190 return 'AWS3-HTTPS ' +
11191 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
11192 'Algorithm=HmacSHA256,' +
11193 'Signature=' + this.signature(credentials);
11194 },
11195
11196 stringToSign: function stringToSign() {
11197 return this.request.headers['X-Amz-Date'];
11198 }
11199 });
11200
11201 /**
11202 * @api private
11203 */
11204 module.exports = AWS.Signers.V3Https;
11205
11206
11207/***/ }),
11208/* 58 */
11209/***/ (function(module, exports, __webpack_require__) {
11210
11211 var AWS = __webpack_require__(1);
11212 var v4Credentials = __webpack_require__(59);
11213 var inherit = AWS.util.inherit;
11214
11215 /**
11216 * @api private
11217 */
11218 var expiresHeader = 'presigned-expires';
11219
11220 /**
11221 * @api private
11222 */
11223 AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, {
11224 constructor: function V4(request, serviceName, options) {
11225 AWS.Signers.RequestSigner.call(this, request);
11226 this.serviceName = serviceName;
11227 options = options || {};
11228 this.signatureCache = typeof options.signatureCache === 'boolean' ? options.signatureCache : true;
11229 this.operation = options.operation;
11230 this.signatureVersion = options.signatureVersion;
11231 },
11232
11233 algorithm: 'AWS4-HMAC-SHA256',
11234
11235 addAuthorization: function addAuthorization(credentials, date) {
11236 var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '');
11237
11238 if (this.isPresigned()) {
11239 this.updateForPresigned(credentials, datetime);
11240 } else {
11241 this.addHeaders(credentials, datetime);
11242 }
11243
11244 this.request.headers['Authorization'] =
11245 this.authorization(credentials, datetime);
11246 },
11247
11248 addHeaders: function addHeaders(credentials, datetime) {
11249 this.request.headers['X-Amz-Date'] = datetime;
11250 if (credentials.sessionToken) {
11251 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11252 }
11253 },
11254
11255 updateForPresigned: function updateForPresigned(credentials, datetime) {
11256 var credString = this.credentialString(datetime);
11257 var qs = {
11258 'X-Amz-Date': datetime,
11259 'X-Amz-Algorithm': this.algorithm,
11260 'X-Amz-Credential': credentials.accessKeyId + '/' + credString,
11261 'X-Amz-Expires': this.request.headers[expiresHeader],
11262 'X-Amz-SignedHeaders': this.signedHeaders()
11263 };
11264
11265 if (credentials.sessionToken) {
11266 qs['X-Amz-Security-Token'] = credentials.sessionToken;
11267 }
11268
11269 if (this.request.headers['Content-Type']) {
11270 qs['Content-Type'] = this.request.headers['Content-Type'];
11271 }
11272 if (this.request.headers['Content-MD5']) {
11273 qs['Content-MD5'] = this.request.headers['Content-MD5'];
11274 }
11275 if (this.request.headers['Cache-Control']) {
11276 qs['Cache-Control'] = this.request.headers['Cache-Control'];
11277 }
11278
11279 // need to pull in any other X-Amz-* headers
11280 AWS.util.each.call(this, this.request.headers, function(key, value) {
11281 if (key === expiresHeader) return;
11282 if (this.isSignableHeader(key)) {
11283 var lowerKey = key.toLowerCase();
11284 // Metadata should be normalized
11285 if (lowerKey.indexOf('x-amz-meta-') === 0) {
11286 qs[lowerKey] = value;
11287 } else if (lowerKey.indexOf('x-amz-') === 0) {
11288 qs[key] = value;
11289 }
11290 }
11291 });
11292
11293 var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?';
11294 this.request.path += sep + AWS.util.queryParamsToString(qs);
11295 },
11296
11297 authorization: function authorization(credentials, datetime) {
11298 var parts = [];
11299 var credString = this.credentialString(datetime);
11300 parts.push(this.algorithm + ' Credential=' +
11301 credentials.accessKeyId + '/' + credString);
11302 parts.push('SignedHeaders=' + this.signedHeaders());
11303 parts.push('Signature=' + this.signature(credentials, datetime));
11304 return parts.join(', ');
11305 },
11306
11307 signature: function signature(credentials, datetime) {
11308 var signingKey = v4Credentials.getSigningKey(
11309 credentials,
11310 datetime.substr(0, 8),
11311 this.request.region,
11312 this.serviceName,
11313 this.signatureCache
11314 );
11315 return AWS.util.crypto.hmac(signingKey, this.stringToSign(datetime), 'hex');
11316 },
11317
11318 stringToSign: function stringToSign(datetime) {
11319 var parts = [];
11320 parts.push('AWS4-HMAC-SHA256');
11321 parts.push(datetime);
11322 parts.push(this.credentialString(datetime));
11323 parts.push(this.hexEncodedHash(this.canonicalString()));
11324 return parts.join('\n');
11325 },
11326
11327 canonicalString: function canonicalString() {
11328 var parts = [], pathname = this.request.pathname();
11329 if (this.serviceName !== 's3' && this.signatureVersion !== 's3v4') pathname = AWS.util.uriEscapePath(pathname);
11330
11331 parts.push(this.request.method);
11332 parts.push(pathname);
11333 parts.push(this.request.search());
11334 parts.push(this.canonicalHeaders() + '\n');
11335 parts.push(this.signedHeaders());
11336 parts.push(this.hexEncodedBodyHash());
11337 return parts.join('\n');
11338 },
11339
11340 canonicalHeaders: function canonicalHeaders() {
11341 var headers = [];
11342 AWS.util.each.call(this, this.request.headers, function (key, item) {
11343 headers.push([key, item]);
11344 });
11345 headers.sort(function (a, b) {
11346 return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
11347 });
11348 var parts = [];
11349 AWS.util.arrayEach.call(this, headers, function (item) {
11350 var key = item[0].toLowerCase();
11351 if (this.isSignableHeader(key)) {
11352 var value = item[1];
11353 if (typeof value === 'undefined' || value === null || typeof value.toString !== 'function') {
11354 throw AWS.util.error(new Error('Header ' + key + ' contains invalid value'), {
11355 code: 'InvalidHeader'
11356 });
11357 }
11358 parts.push(key + ':' +
11359 this.canonicalHeaderValues(value.toString()));
11360 }
11361 });
11362 return parts.join('\n');
11363 },
11364
11365 canonicalHeaderValues: function canonicalHeaderValues(values) {
11366 return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
11367 },
11368
11369 signedHeaders: function signedHeaders() {
11370 var keys = [];
11371 AWS.util.each.call(this, this.request.headers, function (key) {
11372 key = key.toLowerCase();
11373 if (this.isSignableHeader(key)) keys.push(key);
11374 });
11375 return keys.sort().join(';');
11376 },
11377
11378 credentialString: function credentialString(datetime) {
11379 return v4Credentials.createScope(
11380 datetime.substr(0, 8),
11381 this.request.region,
11382 this.serviceName
11383 );
11384 },
11385
11386 hexEncodedHash: function hash(string) {
11387 return AWS.util.crypto.sha256(string, 'hex');
11388 },
11389
11390 hexEncodedBodyHash: function hexEncodedBodyHash() {
11391 var request = this.request;
11392 if (this.isPresigned() && this.serviceName === 's3' && !request.body) {
11393 return 'UNSIGNED-PAYLOAD';
11394 } else if (request.headers['X-Amz-Content-Sha256']) {
11395 return request.headers['X-Amz-Content-Sha256'];
11396 } else {
11397 return this.hexEncodedHash(this.request.body || '');
11398 }
11399 },
11400
11401 unsignableHeaders: [
11402 'authorization',
11403 'content-type',
11404 'content-length',
11405 'user-agent',
11406 expiresHeader,
11407 'expect',
11408 'x-amzn-trace-id'
11409 ],
11410
11411 isSignableHeader: function isSignableHeader(key) {
11412 if (key.toLowerCase().indexOf('x-amz-') === 0) return true;
11413 return this.unsignableHeaders.indexOf(key) < 0;
11414 },
11415
11416 isPresigned: function isPresigned() {
11417 return this.request.headers[expiresHeader] ? true : false;
11418 }
11419
11420 });
11421
11422 /**
11423 * @api private
11424 */
11425 module.exports = AWS.Signers.V4;
11426
11427
11428/***/ }),
11429/* 59 */
11430/***/ (function(module, exports, __webpack_require__) {
11431
11432 var AWS = __webpack_require__(1);
11433
11434 /**
11435 * @api private
11436 */
11437 var cachedSecret = {};
11438
11439 /**
11440 * @api private
11441 */
11442 var cacheQueue = [];
11443
11444 /**
11445 * @api private
11446 */
11447 var maxCacheEntries = 50;
11448
11449 /**
11450 * @api private
11451 */
11452 var v4Identifier = 'aws4_request';
11453
11454 /**
11455 * @api private
11456 */
11457 module.exports = {
11458 /**
11459 * @api private
11460 *
11461 * @param date [String]
11462 * @param region [String]
11463 * @param serviceName [String]
11464 * @return [String]
11465 */
11466 createScope: function createScope(date, region, serviceName) {
11467 return [
11468 date.substr(0, 8),
11469 region,
11470 serviceName,
11471 v4Identifier
11472 ].join('/');
11473 },
11474
11475 /**
11476 * @api private
11477 *
11478 * @param credentials [Credentials]
11479 * @param date [String]
11480 * @param region [String]
11481 * @param service [String]
11482 * @param shouldCache [Boolean]
11483 * @return [String]
11484 */
11485 getSigningKey: function getSigningKey(
11486 credentials,
11487 date,
11488 region,
11489 service,
11490 shouldCache
11491 ) {
11492 var credsIdentifier = AWS.util.crypto
11493 .hmac(credentials.secretAccessKey, credentials.accessKeyId, 'base64');
11494 var cacheKey = [credsIdentifier, date, region, service].join('_');
11495 shouldCache = shouldCache !== false;
11496 if (shouldCache && (cacheKey in cachedSecret)) {
11497 return cachedSecret[cacheKey];
11498 }
11499
11500 var kDate = AWS.util.crypto.hmac(
11501 'AWS4' + credentials.secretAccessKey,
11502 date,
11503 'buffer'
11504 );
11505 var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer');
11506 var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer');
11507
11508 var signingKey = AWS.util.crypto.hmac(kService, v4Identifier, 'buffer');
11509 if (shouldCache) {
11510 cachedSecret[cacheKey] = signingKey;
11511 cacheQueue.push(cacheKey);
11512 if (cacheQueue.length > maxCacheEntries) {
11513 // remove the oldest entry (not the least recently used)
11514 delete cachedSecret[cacheQueue.shift()];
11515 }
11516 }
11517
11518 return signingKey;
11519 },
11520
11521 /**
11522 * @api private
11523 *
11524 * Empties the derived signing key cache. Made available for testing purposes
11525 * only.
11526 */
11527 emptyCache: function emptyCache() {
11528 cachedSecret = {};
11529 cacheQueue = [];
11530 }
11531 };
11532
11533
11534/***/ }),
11535/* 60 */
11536/***/ (function(module, exports, __webpack_require__) {
11537
11538 var AWS = __webpack_require__(1);
11539 var inherit = AWS.util.inherit;
11540
11541 /**
11542 * @api private
11543 */
11544 AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, {
11545 /**
11546 * When building the stringToSign, these sub resource params should be
11547 * part of the canonical resource string with their NON-decoded values
11548 */
11549 subResources: {
11550 'acl': 1,
11551 'accelerate': 1,
11552 'analytics': 1,
11553 'cors': 1,
11554 'lifecycle': 1,
11555 'delete': 1,
11556 'inventory': 1,
11557 'location': 1,
11558 'logging': 1,
11559 'metrics': 1,
11560 'notification': 1,
11561 'partNumber': 1,
11562 'policy': 1,
11563 'requestPayment': 1,
11564 'replication': 1,
11565 'restore': 1,
11566 'tagging': 1,
11567 'torrent': 1,
11568 'uploadId': 1,
11569 'uploads': 1,
11570 'versionId': 1,
11571 'versioning': 1,
11572 'versions': 1,
11573 'website': 1
11574 },
11575
11576 // when building the stringToSign, these querystring params should be
11577 // part of the canonical resource string with their NON-encoded values
11578 responseHeaders: {
11579 'response-content-type': 1,
11580 'response-content-language': 1,
11581 'response-expires': 1,
11582 'response-cache-control': 1,
11583 'response-content-disposition': 1,
11584 'response-content-encoding': 1
11585 },
11586
11587 addAuthorization: function addAuthorization(credentials, date) {
11588 if (!this.request.headers['presigned-expires']) {
11589 this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date);
11590 }
11591
11592 if (credentials.sessionToken) {
11593 // presigned URLs require this header to be lowercased
11594 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11595 }
11596
11597 var signature = this.sign(credentials.secretAccessKey, this.stringToSign());
11598 var auth = 'AWS ' + credentials.accessKeyId + ':' + signature;
11599
11600 this.request.headers['Authorization'] = auth;
11601 },
11602
11603 stringToSign: function stringToSign() {
11604 var r = this.request;
11605
11606 var parts = [];
11607 parts.push(r.method);
11608 parts.push(r.headers['Content-MD5'] || '');
11609 parts.push(r.headers['Content-Type'] || '');
11610
11611 // This is the "Date" header, but we use X-Amz-Date.
11612 // The S3 signing mechanism requires us to pass an empty
11613 // string for this Date header regardless.
11614 parts.push(r.headers['presigned-expires'] || '');
11615
11616 var headers = this.canonicalizedAmzHeaders();
11617 if (headers) parts.push(headers);
11618 parts.push(this.canonicalizedResource());
11619
11620 return parts.join('\n');
11621
11622 },
11623
11624 canonicalizedAmzHeaders: function canonicalizedAmzHeaders() {
11625
11626 var amzHeaders = [];
11627
11628 AWS.util.each(this.request.headers, function (name) {
11629 if (name.match(/^x-amz-/i))
11630 amzHeaders.push(name);
11631 });
11632
11633 amzHeaders.sort(function (a, b) {
11634 return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
11635 });
11636
11637 var parts = [];
11638 AWS.util.arrayEach.call(this, amzHeaders, function (name) {
11639 parts.push(name.toLowerCase() + ':' + String(this.request.headers[name]));
11640 });
11641
11642 return parts.join('\n');
11643
11644 },
11645
11646 canonicalizedResource: function canonicalizedResource() {
11647
11648 var r = this.request;
11649
11650 var parts = r.path.split('?');
11651 var path = parts[0];
11652 var querystring = parts[1];
11653
11654 var resource = '';
11655
11656 if (r.virtualHostedBucket)
11657 resource += '/' + r.virtualHostedBucket;
11658
11659 resource += path;
11660
11661 if (querystring) {
11662
11663 // collect a list of sub resources and query params that need to be signed
11664 var resources = [];
11665
11666 AWS.util.arrayEach.call(this, querystring.split('&'), function (param) {
11667 var name = param.split('=')[0];
11668 var value = param.split('=')[1];
11669 if (this.subResources[name] || this.responseHeaders[name]) {
11670 var subresource = { name: name };
11671 if (value !== undefined) {
11672 if (this.subResources[name]) {
11673 subresource.value = value;
11674 } else {
11675 subresource.value = decodeURIComponent(value);
11676 }
11677 }
11678 resources.push(subresource);
11679 }
11680 });
11681
11682 resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; });
11683
11684 if (resources.length) {
11685
11686 querystring = [];
11687 AWS.util.arrayEach(resources, function (res) {
11688 if (res.value === undefined) {
11689 querystring.push(res.name);
11690 } else {
11691 querystring.push(res.name + '=' + res.value);
11692 }
11693 });
11694
11695 resource += '?' + querystring.join('&');
11696 }
11697
11698 }
11699
11700 return resource;
11701
11702 },
11703
11704 sign: function sign(secret, string) {
11705 return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1');
11706 }
11707 });
11708
11709 /**
11710 * @api private
11711 */
11712 module.exports = AWS.Signers.S3;
11713
11714
11715/***/ }),
11716/* 61 */
11717/***/ (function(module, exports, __webpack_require__) {
11718
11719 var AWS = __webpack_require__(1);
11720 var inherit = AWS.util.inherit;
11721
11722 /**
11723 * @api private
11724 */
11725 var expiresHeader = 'presigned-expires';
11726
11727 /**
11728 * @api private
11729 */
11730 function signedUrlBuilder(request) {
11731 var expires = request.httpRequest.headers[expiresHeader];
11732 var signerClass = request.service.getSignerClass(request);
11733
11734 delete request.httpRequest.headers['User-Agent'];
11735 delete request.httpRequest.headers['X-Amz-User-Agent'];
11736
11737 if (signerClass === AWS.Signers.V4) {
11738 if (expires > 604800) { // one week expiry is invalid
11739 var message = 'Presigning does not support expiry time greater ' +
11740 'than a week with SigV4 signing.';
11741 throw AWS.util.error(new Error(), {
11742 code: 'InvalidExpiryTime', message: message, retryable: false
11743 });
11744 }
11745 request.httpRequest.headers[expiresHeader] = expires;
11746 } else if (signerClass === AWS.Signers.S3) {
11747 var now = request.service ? request.service.getSkewCorrectedDate() : AWS.util.date.getDate();
11748 request.httpRequest.headers[expiresHeader] = parseInt(
11749 AWS.util.date.unixTimestamp(now) + expires, 10).toString();
11750 } else {
11751 throw AWS.util.error(new Error(), {
11752 message: 'Presigning only supports S3 or SigV4 signing.',
11753 code: 'UnsupportedSigner', retryable: false
11754 });
11755 }
11756 }
11757
11758 /**
11759 * @api private
11760 */
11761 function signedUrlSigner(request) {
11762 var endpoint = request.httpRequest.endpoint;
11763 var parsedUrl = AWS.util.urlParse(request.httpRequest.path);
11764 var queryParams = {};
11765
11766 if (parsedUrl.search) {
11767 queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1));
11768 }
11769
11770 var auth = request.httpRequest.headers['Authorization'].split(' ');
11771 if (auth[0] === 'AWS') {
11772 auth = auth[1].split(':');
11773 queryParams['AWSAccessKeyId'] = auth[0];
11774 queryParams['Signature'] = auth[1];
11775
11776 AWS.util.each(request.httpRequest.headers, function (key, value) {
11777 if (key === expiresHeader) key = 'Expires';
11778 if (key.indexOf('x-amz-meta-') === 0) {
11779 // Delete existing, potentially not normalized key
11780 delete queryParams[key];
11781 key = key.toLowerCase();
11782 }
11783 queryParams[key] = value;
11784 });
11785 delete request.httpRequest.headers[expiresHeader];
11786 delete queryParams['Authorization'];
11787 delete queryParams['Host'];
11788 } else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing
11789 auth.shift();
11790 var rest = auth.join(' ');
11791 var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];
11792 queryParams['X-Amz-Signature'] = signature;
11793 delete queryParams['Expires'];
11794 }
11795
11796 // build URL
11797 endpoint.pathname = parsedUrl.pathname;
11798 endpoint.search = AWS.util.queryParamsToString(queryParams);
11799 }
11800
11801 /**
11802 * @api private
11803 */
11804 AWS.Signers.Presign = inherit({
11805 /**
11806 * @api private
11807 */
11808 sign: function sign(request, expireTime, callback) {
11809 request.httpRequest.headers[expiresHeader] = expireTime || 3600;
11810 request.on('build', signedUrlBuilder);
11811 request.on('sign', signedUrlSigner);
11812 request.removeListener('afterBuild',
11813 AWS.EventListeners.Core.SET_CONTENT_LENGTH);
11814 request.removeListener('afterBuild',
11815 AWS.EventListeners.Core.COMPUTE_SHA256);
11816
11817 request.emit('beforePresign', [request]);
11818
11819 if (callback) {
11820 request.build(function() {
11821 if (this.response.error) callback(this.response.error);
11822 else {
11823 callback(null, AWS.util.urlFormat(request.httpRequest.endpoint));
11824 }
11825 });
11826 } else {
11827 request.build();
11828 if (request.response.error) throw request.response.error;
11829 return AWS.util.urlFormat(request.httpRequest.endpoint);
11830 }
11831 }
11832 });
11833
11834 /**
11835 * @api private
11836 */
11837 module.exports = AWS.Signers.Presign;
11838
11839
11840/***/ }),
11841/* 62 */
11842/***/ (function(module, exports, __webpack_require__) {
11843
11844 var AWS = __webpack_require__(1);
11845
11846 /**
11847 * @api private
11848 */
11849 AWS.ParamValidator = AWS.util.inherit({
11850 /**
11851 * Create a new validator object.
11852 *
11853 * @param validation [Boolean|map] whether input parameters should be
11854 * validated against the operation description before sending the
11855 * request. Pass a map to enable any of the following specific
11856 * validation features:
11857 *
11858 * * **min** [Boolean] &mdash; Validates that a value meets the min
11859 * constraint. This is enabled by default when paramValidation is set
11860 * to `true`.
11861 * * **max** [Boolean] &mdash; Validates that a value meets the max
11862 * constraint.
11863 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
11864 * regular expression.
11865 * * **enum** [Boolean] &mdash; Validates that a string value matches one
11866 * of the allowable enum values.
11867 */
11868 constructor: function ParamValidator(validation) {
11869 if (validation === true || validation === undefined) {
11870 validation = {'min': true};
11871 }
11872 this.validation = validation;
11873 },
11874
11875 validate: function validate(shape, params, context) {
11876 this.errors = [];
11877 this.validateMember(shape, params || {}, context || 'params');
11878
11879 if (this.errors.length > 1) {
11880 var msg = this.errors.join('\n* ');
11881 msg = 'There were ' + this.errors.length +
11882 ' validation errors:\n* ' + msg;
11883 throw AWS.util.error(new Error(msg),
11884 {code: 'MultipleValidationErrors', errors: this.errors});
11885 } else if (this.errors.length === 1) {
11886 throw this.errors[0];
11887 } else {
11888 return true;
11889 }
11890 },
11891
11892 fail: function fail(code, message) {
11893 this.errors.push(AWS.util.error(new Error(message), {code: code}));
11894 },
11895
11896 validateStructure: function validateStructure(shape, params, context) {
11897 this.validateType(params, context, ['object'], 'structure');
11898
11899 var paramName;
11900 for (var i = 0; shape.required && i < shape.required.length; i++) {
11901 paramName = shape.required[i];
11902 var value = params[paramName];
11903 if (value === undefined || value === null) {
11904 this.fail('MissingRequiredParameter',
11905 'Missing required key \'' + paramName + '\' in ' + context);
11906 }
11907 }
11908
11909 // validate hash members
11910 for (paramName in params) {
11911 if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue;
11912
11913 var paramValue = params[paramName],
11914 memberShape = shape.members[paramName];
11915
11916 if (memberShape !== undefined) {
11917 var memberContext = [context, paramName].join('.');
11918 this.validateMember(memberShape, paramValue, memberContext);
11919 } else {
11920 this.fail('UnexpectedParameter',
11921 'Unexpected key \'' + paramName + '\' found in ' + context);
11922 }
11923 }
11924
11925 return true;
11926 },
11927
11928 validateMember: function validateMember(shape, param, context) {
11929 switch (shape.type) {
11930 case 'structure':
11931 return this.validateStructure(shape, param, context);
11932 case 'list':
11933 return this.validateList(shape, param, context);
11934 case 'map':
11935 return this.validateMap(shape, param, context);
11936 default:
11937 return this.validateScalar(shape, param, context);
11938 }
11939 },
11940
11941 validateList: function validateList(shape, params, context) {
11942 if (this.validateType(params, context, [Array])) {
11943 this.validateRange(shape, params.length, context, 'list member count');
11944 // validate array members
11945 for (var i = 0; i < params.length; i++) {
11946 this.validateMember(shape.member, params[i], context + '[' + i + ']');
11947 }
11948 }
11949 },
11950
11951 validateMap: function validateMap(shape, params, context) {
11952 if (this.validateType(params, context, ['object'], 'map')) {
11953 // Build up a count of map members to validate range traits.
11954 var mapCount = 0;
11955 for (var param in params) {
11956 if (!Object.prototype.hasOwnProperty.call(params, param)) continue;
11957 // Validate any map key trait constraints
11958 this.validateMember(shape.key, param,
11959 context + '[key=\'' + param + '\']');
11960 this.validateMember(shape.value, params[param],
11961 context + '[\'' + param + '\']');
11962 mapCount++;
11963 }
11964 this.validateRange(shape, mapCount, context, 'map member count');
11965 }
11966 },
11967
11968 validateScalar: function validateScalar(shape, value, context) {
11969 switch (shape.type) {
11970 case null:
11971 case undefined:
11972 case 'string':
11973 return this.validateString(shape, value, context);
11974 case 'base64':
11975 case 'binary':
11976 return this.validatePayload(value, context);
11977 case 'integer':
11978 case 'float':
11979 return this.validateNumber(shape, value, context);
11980 case 'boolean':
11981 return this.validateType(value, context, ['boolean']);
11982 case 'timestamp':
11983 return this.validateType(value, context, [Date,
11984 /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'],
11985 'Date object, ISO-8601 string, or a UNIX timestamp');
11986 default:
11987 return this.fail('UnkownType', 'Unhandled type ' +
11988 shape.type + ' for ' + context);
11989 }
11990 },
11991
11992 validateString: function validateString(shape, value, context) {
11993 var validTypes = ['string'];
11994 if (shape.isJsonValue) {
11995 validTypes = validTypes.concat(['number', 'object', 'boolean']);
11996 }
11997 if (value !== null && this.validateType(value, context, validTypes)) {
11998 this.validateEnum(shape, value, context);
11999 this.validateRange(shape, value.length, context, 'string length');
12000 this.validatePattern(shape, value, context);
12001 this.validateUri(shape, value, context);
12002 }
12003 },
12004
12005 validateUri: function validateUri(shape, value, context) {
12006 if (shape['location'] === 'uri') {
12007 if (value.length === 0) {
12008 this.fail('UriParameterError', 'Expected uri parameter to have length >= 1,'
12009 + ' but found "' + value +'" for ' + context);
12010 }
12011 }
12012 },
12013
12014 validatePattern: function validatePattern(shape, value, context) {
12015 if (this.validation['pattern'] && shape['pattern'] !== undefined) {
12016 if (!(new RegExp(shape['pattern'])).test(value)) {
12017 this.fail('PatternMatchError', 'Provided value "' + value + '" '
12018 + 'does not match regex pattern /' + shape['pattern'] + '/ for '
12019 + context);
12020 }
12021 }
12022 },
12023
12024 validateRange: function validateRange(shape, value, context, descriptor) {
12025 if (this.validation['min']) {
12026 if (shape['min'] !== undefined && value < shape['min']) {
12027 this.fail('MinRangeError', 'Expected ' + descriptor + ' >= '
12028 + shape['min'] + ', but found ' + value + ' for ' + context);
12029 }
12030 }
12031 if (this.validation['max']) {
12032 if (shape['max'] !== undefined && value > shape['max']) {
12033 this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= '
12034 + shape['max'] + ', but found ' + value + ' for ' + context);
12035 }
12036 }
12037 },
12038
12039 validateEnum: function validateRange(shape, value, context) {
12040 if (this.validation['enum'] && shape['enum'] !== undefined) {
12041 // Fail if the string value is not present in the enum list
12042 if (shape['enum'].indexOf(value) === -1) {
12043 this.fail('EnumError', 'Found string value of ' + value + ', but '
12044 + 'expected ' + shape['enum'].join('|') + ' for ' + context);
12045 }
12046 }
12047 },
12048
12049 validateType: function validateType(value, context, acceptedTypes, type) {
12050 // We will not log an error for null or undefined, but we will return
12051 // false so that callers know that the expected type was not strictly met.
12052 if (value === null || value === undefined) return false;
12053
12054 var foundInvalidType = false;
12055 for (var i = 0; i < acceptedTypes.length; i++) {
12056 if (typeof acceptedTypes[i] === 'string') {
12057 if (typeof value === acceptedTypes[i]) return true;
12058 } else if (acceptedTypes[i] instanceof RegExp) {
12059 if ((value || '').toString().match(acceptedTypes[i])) return true;
12060 } else {
12061 if (value instanceof acceptedTypes[i]) return true;
12062 if (AWS.util.isType(value, acceptedTypes[i])) return true;
12063 if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice();
12064 acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]);
12065 }
12066 foundInvalidType = true;
12067 }
12068
12069 var acceptedType = type;
12070 if (!acceptedType) {
12071 acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1');
12072 }
12073
12074 var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : '';
12075 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' +
12076 vowel + ' ' + acceptedType);
12077 return false;
12078 },
12079
12080 validateNumber: function validateNumber(shape, value, context) {
12081 if (value === null || value === undefined) return;
12082 if (typeof value === 'string') {
12083 var castedValue = parseFloat(value);
12084 if (castedValue.toString() === value) value = castedValue;
12085 }
12086 if (this.validateType(value, context, ['number'])) {
12087 this.validateRange(shape, value, context, 'numeric value');
12088 }
12089 },
12090
12091 validatePayload: function validatePayload(value, context) {
12092 if (value === null || value === undefined) return;
12093 if (typeof value === 'string') return;
12094 if (value && typeof value.byteLength === 'number') return; // typed arrays
12095 if (AWS.util.isNode()) { // special check for buffer/stream in Node.js
12096 var Stream = AWS.util.stream.Stream;
12097 if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return;
12098 } else {
12099 if (typeof Blob !== void 0 && value instanceof Blob) return;
12100 }
12101
12102 var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView'];
12103 if (value) {
12104 for (var i = 0; i < types.length; i++) {
12105 if (AWS.util.isType(value, types[i])) return;
12106 if (AWS.util.typeName(value.constructor) === types[i]) return;
12107 }
12108 }
12109
12110 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' +
12111 'string, Buffer, Stream, Blob, or typed array object');
12112 }
12113 });
12114
12115
12116/***/ })
12117/******/ ])
12118});
12119;
\No newline at end of file