UNPKG

401 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.428.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 = (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(string) : new util.Buffer(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 (typeof util.Buffer.from === 'function' && util.Buffer.from !== Uint8Array.from) ? util.Buffer.from(string, 'base64') : new util.Buffer(string, 'base64');
296 }
297
298 },
299
300 buffer: {
301 toStream: function toStream(buffer) {
302 if (!util.Buffer.isBuffer(buffer)) buffer = new util.Buffer(buffer);
303
304 var readable = new (util.stream.Readable)();
305 var pos = 0;
306 readable._read = function(size) {
307 if (pos >= buffer.length) return readable.push(null);
308
309 var end = pos + size;
310 if (end > buffer.length) end = buffer.length;
311 readable.push(buffer.slice(pos, end));
312 pos = end;
313 };
314
315 return readable;
316 },
317
318 /**
319 * Concatenates a list of Buffer objects.
320 */
321 concat: function(buffers) {
322 var length = 0,
323 offset = 0,
324 buffer = null, i;
325
326 for (i = 0; i < buffers.length; i++) {
327 length += buffers[i].length;
328 }
329
330 buffer = new util.Buffer(length);
331
332 for (i = 0; i < buffers.length; i++) {
333 buffers[i].copy(buffer, offset);
334 offset += buffers[i].length;
335 }
336
337 return buffer;
338 }
339 },
340
341 string: {
342 byteLength: function byteLength(string) {
343 if (string === null || string === undefined) return 0;
344 if (typeof string === 'string') string = new util.Buffer(string);
345
346 if (typeof string.byteLength === 'number') {
347 return string.byteLength;
348 } else if (typeof string.length === 'number') {
349 return string.length;
350 } else if (typeof string.size === 'number') {
351 return string.size;
352 } else if (typeof string.path === 'string') {
353 return __webpack_require__(6).lstatSync(string.path).size;
354 } else {
355 throw util.error(new Error('Cannot determine length of ' + string),
356 { object: string });
357 }
358 },
359
360 upperFirst: function upperFirst(string) {
361 return string[0].toUpperCase() + string.substr(1);
362 },
363
364 lowerFirst: function lowerFirst(string) {
365 return string[0].toLowerCase() + string.substr(1);
366 }
367 },
368
369 ini: {
370 parse: function string(ini) {
371 var currentSection, map = {};
372 util.arrayEach(ini.split(/\r?\n/), function(line) {
373 line = line.split(/(^|\s)[;#]/)[0]; // remove comments
374 var section = line.match(/^\s*\[([^\[\]]+)\]\s*$/);
375 if (section) {
376 currentSection = section[1];
377 } else if (currentSection) {
378 var item = line.match(/^\s*(.+?)\s*=\s*(.+?)\s*$/);
379 if (item) {
380 map[currentSection] = map[currentSection] || {};
381 map[currentSection][item[1]] = item[2];
382 }
383 }
384 });
385
386 return map;
387 }
388 },
389
390 fn: {
391 noop: function() {},
392 callback: function (err) { if (err) throw err; },
393
394 /**
395 * Turn a synchronous function into as "async" function by making it call
396 * a callback. The underlying function is called with all but the last argument,
397 * which is treated as the callback. The callback is passed passed a first argument
398 * of null on success to mimick standard node callbacks.
399 */
400 makeAsync: function makeAsync(fn, expectedArgs) {
401 if (expectedArgs && expectedArgs <= fn.length) {
402 return fn;
403 }
404
405 return function() {
406 var args = Array.prototype.slice.call(arguments, 0);
407 var callback = args.pop();
408 var result = fn.apply(null, args);
409 callback(result);
410 };
411 }
412 },
413
414 /**
415 * Date and time utility functions.
416 */
417 date: {
418
419 /**
420 * @return [Date] the current JavaScript date object. Since all
421 * AWS services rely on this date object, you can override
422 * this function to provide a special time value to AWS service
423 * requests.
424 */
425 getDate: function getDate() {
426 if (!AWS) AWS = __webpack_require__(1);
427 if (AWS.config.systemClockOffset) { // use offset when non-zero
428 return new Date(new Date().getTime() + AWS.config.systemClockOffset);
429 } else {
430 return new Date();
431 }
432 },
433
434 /**
435 * @return [String] the date in ISO-8601 format
436 */
437 iso8601: function iso8601(date) {
438 if (date === undefined) { date = util.date.getDate(); }
439 return date.toISOString().replace(/\.\d{3}Z$/, 'Z');
440 },
441
442 /**
443 * @return [String] the date in RFC 822 format
444 */
445 rfc822: function rfc822(date) {
446 if (date === undefined) { date = util.date.getDate(); }
447 return date.toUTCString();
448 },
449
450 /**
451 * @return [Integer] the UNIX timestamp value for the current time
452 */
453 unixTimestamp: function unixTimestamp(date) {
454 if (date === undefined) { date = util.date.getDate(); }
455 return date.getTime() / 1000;
456 },
457
458 /**
459 * @param [String,number,Date] date
460 * @return [Date]
461 */
462 from: function format(date) {
463 if (typeof date === 'number') {
464 return new Date(date * 1000); // unix timestamp
465 } else {
466 return new Date(date);
467 }
468 },
469
470 /**
471 * Given a Date or date-like value, this function formats the
472 * date into a string of the requested value.
473 * @param [String,number,Date] date
474 * @param [String] formatter Valid formats are:
475 # * 'iso8601'
476 # * 'rfc822'
477 # * 'unixTimestamp'
478 * @return [String]
479 */
480 format: function format(date, formatter) {
481 if (!formatter) formatter = 'iso8601';
482 return util.date[formatter](util.date.from(date));
483 },
484
485 parseTimestamp: function parseTimestamp(value) {
486 if (typeof value === 'number') { // unix timestamp (number)
487 return new Date(value * 1000);
488 } else if (value.match(/^\d+$/)) { // unix timestamp
489 return new Date(value * 1000);
490 } else if (value.match(/^\d{4}/)) { // iso8601
491 return new Date(value);
492 } else if (value.match(/^\w{3},/)) { // rfc822
493 return new Date(value);
494 } else {
495 throw util.error(
496 new Error('unhandled timestamp format: ' + value),
497 {code: 'TimestampParserError'});
498 }
499 }
500
501 },
502
503 crypto: {
504 crc32Table: [
505 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
506 0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
507 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
508 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
509 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
510 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
511 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
512 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
513 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
514 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
515 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
516 0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
517 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
518 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
519 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
520 0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
521 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
522 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
523 0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
524 0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
525 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
526 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
527 0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
528 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
529 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
530 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
531 0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
532 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
533 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
534 0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
535 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
536 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
537 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
538 0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
539 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
540 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
541 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
542 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
543 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
544 0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
545 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
546 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
547 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
548 0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
549 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
550 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
551 0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
552 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
553 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
554 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
555 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
556 0x2D02EF8D],
557
558 crc32: function crc32(data) {
559 var tbl = util.crypto.crc32Table;
560 var crc = 0 ^ -1;
561
562 if (typeof data === 'string') {
563 data = new util.Buffer(data);
564 }
565
566 for (var i = 0; i < data.length; i++) {
567 var code = data.readUInt8(i);
568 crc = (crc >>> 8) ^ tbl[(crc ^ code) & 0xFF];
569 }
570 return (crc ^ -1) >>> 0;
571 },
572
573 hmac: function hmac(key, string, digest, fn) {
574 if (!digest) digest = 'binary';
575 if (digest === 'buffer') { digest = undefined; }
576 if (!fn) fn = 'sha256';
577 if (typeof string === 'string') string = new util.Buffer(string);
578 return util.crypto.lib.createHmac(fn, key).update(string).digest(digest);
579 },
580
581 md5: function md5(data, digest, callback) {
582 return util.crypto.hash('md5', data, digest, callback);
583 },
584
585 sha256: function sha256(data, digest, callback) {
586 return util.crypto.hash('sha256', data, digest, callback);
587 },
588
589 hash: function(algorithm, data, digest, callback) {
590 var hash = util.crypto.createHash(algorithm);
591 if (!digest) { digest = 'binary'; }
592 if (digest === 'buffer') { digest = undefined; }
593 if (typeof data === 'string') data = new util.Buffer(data);
594 var sliceFn = util.arraySliceFn(data);
595 var isBuffer = util.Buffer.isBuffer(data);
596 //Identifying objects with an ArrayBuffer as buffers
597 if (util.isBrowser() && typeof ArrayBuffer !== 'undefined' && data && data.buffer instanceof ArrayBuffer) isBuffer = true;
598
599 if (callback && typeof data === 'object' &&
600 typeof data.on === 'function' && !isBuffer) {
601 data.on('data', function(chunk) { hash.update(chunk); });
602 data.on('error', function(err) { callback(err); });
603 data.on('end', function() { callback(null, hash.digest(digest)); });
604 } else if (callback && sliceFn && !isBuffer &&
605 typeof FileReader !== 'undefined') {
606 // this might be a File/Blob
607 var index = 0, size = 1024 * 512;
608 var reader = new FileReader();
609 reader.onerror = function() {
610 callback(new Error('Failed to read data.'));
611 };
612 reader.onload = function() {
613 var buf = new util.Buffer(new Uint8Array(reader.result));
614 hash.update(buf);
615 index += buf.length;
616 reader._continueReading();
617 };
618 reader._continueReading = function() {
619 if (index >= data.size) {
620 callback(null, hash.digest(digest));
621 return;
622 }
623
624 var back = index + size;
625 if (back > data.size) back = data.size;
626 reader.readAsArrayBuffer(sliceFn.call(data, index, back));
627 };
628
629 reader._continueReading();
630 } else {
631 if (util.isBrowser() && typeof data === 'object' && !isBuffer) {
632 data = new util.Buffer(new Uint8Array(data));
633 }
634 var out = hash.update(data).digest(digest);
635 if (callback) callback(null, out);
636 return out;
637 }
638 },
639
640 toHex: function toHex(data) {
641 var out = [];
642 for (var i = 0; i < data.length; i++) {
643 out.push(('0' + data.charCodeAt(i).toString(16)).substr(-2, 2));
644 }
645 return out.join('');
646 },
647
648 createHash: function createHash(algorithm) {
649 return util.crypto.lib.createHash(algorithm);
650 }
651
652 },
653
654 /** @!ignore */
655
656 /* Abort constant */
657 abort: {},
658
659 each: function each(object, iterFunction) {
660 for (var key in object) {
661 if (Object.prototype.hasOwnProperty.call(object, key)) {
662 var ret = iterFunction.call(this, key, object[key]);
663 if (ret === util.abort) break;
664 }
665 }
666 },
667
668 arrayEach: function arrayEach(array, iterFunction) {
669 for (var idx in array) {
670 if (Object.prototype.hasOwnProperty.call(array, idx)) {
671 var ret = iterFunction.call(this, array[idx], parseInt(idx, 10));
672 if (ret === util.abort) break;
673 }
674 }
675 },
676
677 update: function update(obj1, obj2) {
678 util.each(obj2, function iterator(key, item) {
679 obj1[key] = item;
680 });
681 return obj1;
682 },
683
684 merge: function merge(obj1, obj2) {
685 return util.update(util.copy(obj1), obj2);
686 },
687
688 copy: function copy(object) {
689 if (object === null || object === undefined) return object;
690 var dupe = {};
691 // jshint forin:false
692 for (var key in object) {
693 dupe[key] = object[key];
694 }
695 return dupe;
696 },
697
698 isEmpty: function isEmpty(obj) {
699 for (var prop in obj) {
700 if (Object.prototype.hasOwnProperty.call(obj, prop)) {
701 return false;
702 }
703 }
704 return true;
705 },
706
707 arraySliceFn: function arraySliceFn(obj) {
708 var fn = obj.slice || obj.webkitSlice || obj.mozSlice;
709 return typeof fn === 'function' ? fn : null;
710 },
711
712 isType: function isType(obj, type) {
713 // handle cross-"frame" objects
714 if (typeof type === 'function') type = util.typeName(type);
715 return Object.prototype.toString.call(obj) === '[object ' + type + ']';
716 },
717
718 typeName: function typeName(type) {
719 if (Object.prototype.hasOwnProperty.call(type, 'name')) return type.name;
720 var str = type.toString();
721 var match = str.match(/^\s*function (.+)\(/);
722 return match ? match[1] : str;
723 },
724
725 error: function error(err, options) {
726 var originalError = null;
727 if (typeof err.message === 'string' && err.message !== '') {
728 if (typeof options === 'string' || (options && options.message)) {
729 originalError = util.copy(err);
730 originalError.message = err.message;
731 }
732 }
733 err.message = err.message || null;
734
735 if (typeof options === 'string') {
736 err.message = options;
737 } else if (typeof options === 'object' && options !== null) {
738 util.update(err, options);
739 if (options.message)
740 err.message = options.message;
741 if (options.code || options.name)
742 err.code = options.code || options.name;
743 if (options.stack)
744 err.stack = options.stack;
745 }
746
747 if (typeof Object.defineProperty === 'function') {
748 Object.defineProperty(err, 'name', {writable: true, enumerable: false});
749 Object.defineProperty(err, 'message', {enumerable: true});
750 }
751
752 err.name = options && options.name || err.name || err.code || 'Error';
753 err.time = new Date();
754
755 if (originalError) err.originalError = originalError;
756
757 return err;
758 },
759
760 /**
761 * @api private
762 */
763 inherit: function inherit(klass, features) {
764 var newObject = null;
765 if (features === undefined) {
766 features = klass;
767 klass = Object;
768 newObject = {};
769 } else {
770 var ctor = function ConstructorWrapper() {};
771 ctor.prototype = klass.prototype;
772 newObject = new ctor();
773 }
774
775 // constructor not supplied, create pass-through ctor
776 if (features.constructor === Object) {
777 features.constructor = function() {
778 if (klass !== Object) {
779 return klass.apply(this, arguments);
780 }
781 };
782 }
783
784 features.constructor.prototype = newObject;
785 util.update(features.constructor.prototype, features);
786 features.constructor.__super__ = klass;
787 return features.constructor;
788 },
789
790 /**
791 * @api private
792 */
793 mixin: function mixin() {
794 var klass = arguments[0];
795 for (var i = 1; i < arguments.length; i++) {
796 // jshint forin:false
797 for (var prop in arguments[i].prototype) {
798 var fn = arguments[i].prototype[prop];
799 if (prop !== 'constructor') {
800 klass.prototype[prop] = fn;
801 }
802 }
803 }
804 return klass;
805 },
806
807 /**
808 * @api private
809 */
810 hideProperties: function hideProperties(obj, props) {
811 if (typeof Object.defineProperty !== 'function') return;
812
813 util.arrayEach(props, function (key) {
814 Object.defineProperty(obj, key, {
815 enumerable: false, writable: true, configurable: true });
816 });
817 },
818
819 /**
820 * @api private
821 */
822 property: function property(obj, name, value, enumerable, isValue) {
823 var opts = {
824 configurable: true,
825 enumerable: enumerable !== undefined ? enumerable : true
826 };
827 if (typeof value === 'function' && !isValue) {
828 opts.get = value;
829 }
830 else {
831 opts.value = value; opts.writable = true;
832 }
833
834 Object.defineProperty(obj, name, opts);
835 },
836
837 /**
838 * @api private
839 */
840 memoizedProperty: function memoizedProperty(obj, name, get, enumerable) {
841 var cachedValue = null;
842
843 // build enumerable attribute for each value with lazy accessor.
844 util.property(obj, name, function() {
845 if (cachedValue === null) {
846 cachedValue = get();
847 }
848 return cachedValue;
849 }, enumerable);
850 },
851
852 /**
853 * TODO Remove in major version revision
854 * This backfill populates response data without the
855 * top-level payload name.
856 *
857 * @api private
858 */
859 hoistPayloadMember: function hoistPayloadMember(resp) {
860 var req = resp.request;
861 var operationName = req.operation;
862 var operation = req.service.api.operations[operationName];
863 var output = operation.output;
864 if (output.payload && !operation.hasEventOutput) {
865 var payloadMember = output.members[output.payload];
866 var responsePayload = resp.data[output.payload];
867 if (payloadMember.type === 'structure') {
868 util.each(responsePayload, function(key, value) {
869 util.property(resp.data, key, value, false);
870 });
871 }
872 }
873 },
874
875 /**
876 * Compute SHA-256 checksums of streams
877 *
878 * @api private
879 */
880 computeSha256: function computeSha256(body, done) {
881 if (util.isNode()) {
882 var Stream = util.stream.Stream;
883 var fs = __webpack_require__(6);
884 if (body instanceof Stream) {
885 if (typeof body.path === 'string') { // assume file object
886 var settings = {};
887 if (typeof body.start === 'number') {
888 settings.start = body.start;
889 }
890 if (typeof body.end === 'number') {
891 settings.end = body.end;
892 }
893 body = fs.createReadStream(body.path, settings);
894 } else { // TODO support other stream types
895 return done(new Error('Non-file stream objects are ' +
896 'not supported with SigV4'));
897 }
898 }
899 }
900
901 util.crypto.sha256(body, 'hex', function(err, sha) {
902 if (err) done(err);
903 else done(null, sha);
904 });
905 },
906
907 /**
908 * @api private
909 */
910 isClockSkewed: function isClockSkewed(serverTime) {
911 if (serverTime) {
912 util.property(AWS.config, 'isClockSkewed',
913 Math.abs(new Date().getTime() - serverTime) >= 300000, false);
914 return AWS.config.isClockSkewed;
915 }
916 },
917
918 applyClockOffset: function applyClockOffset(serverTime) {
919 if (serverTime)
920 AWS.config.systemClockOffset = serverTime - new Date().getTime();
921 },
922
923 /**
924 * @api private
925 */
926 extractRequestId: function extractRequestId(resp) {
927 var requestId = resp.httpResponse.headers['x-amz-request-id'] ||
928 resp.httpResponse.headers['x-amzn-requestid'];
929
930 if (!requestId && resp.data && resp.data.ResponseMetadata) {
931 requestId = resp.data.ResponseMetadata.RequestId;
932 }
933
934 if (requestId) {
935 resp.requestId = requestId;
936 }
937
938 if (resp.error) {
939 resp.error.requestId = requestId;
940 }
941 },
942
943 /**
944 * @api private
945 */
946 addPromises: function addPromises(constructors, PromiseDependency) {
947 var deletePromises = false;
948 if (PromiseDependency === undefined && AWS && AWS.config) {
949 PromiseDependency = AWS.config.getPromisesDependency();
950 }
951 if (PromiseDependency === undefined && typeof Promise !== 'undefined') {
952 PromiseDependency = Promise;
953 }
954 if (typeof PromiseDependency !== 'function') deletePromises = true;
955 if (!Array.isArray(constructors)) constructors = [constructors];
956
957 for (var ind = 0; ind < constructors.length; ind++) {
958 var constructor = constructors[ind];
959 if (deletePromises) {
960 if (constructor.deletePromisesFromClass) {
961 constructor.deletePromisesFromClass();
962 }
963 } else if (constructor.addPromisesToClass) {
964 constructor.addPromisesToClass(PromiseDependency);
965 }
966 }
967 },
968
969 /**
970 * @api private
971 */
972 promisifyMethod: function promisifyMethod(methodName, PromiseDependency) {
973 return function promise() {
974 var self = this;
975 return new PromiseDependency(function(resolve, reject) {
976 self[methodName](function(err, data) {
977 if (err) {
978 reject(err);
979 } else {
980 resolve(data);
981 }
982 });
983 });
984 };
985 },
986
987 /**
988 * @api private
989 */
990 isDualstackAvailable: function isDualstackAvailable(service) {
991 if (!service) return false;
992 var metadata = __webpack_require__(7);
993 if (typeof service !== 'string') service = service.serviceIdentifier;
994 if (typeof service !== 'string' || !metadata.hasOwnProperty(service)) return false;
995 return !!metadata[service].dualstackAvailable;
996 },
997
998 /**
999 * @api private
1000 */
1001 calculateRetryDelay: function calculateRetryDelay(retryCount, retryDelayOptions) {
1002 if (!retryDelayOptions) retryDelayOptions = {};
1003 var customBackoff = retryDelayOptions.customBackoff || null;
1004 if (typeof customBackoff === 'function') {
1005 return customBackoff(retryCount);
1006 }
1007 var base = typeof retryDelayOptions.base === 'number' ? retryDelayOptions.base : 100;
1008 var delay = Math.random() * (Math.pow(2, retryCount) * base);
1009 return delay;
1010 },
1011
1012 /**
1013 * @api private
1014 */
1015 handleRequestWithRetries: function handleRequestWithRetries(httpRequest, options, cb) {
1016 if (!options) options = {};
1017 var http = AWS.HttpClient.getInstance();
1018 var httpOptions = options.httpOptions || {};
1019 var retryCount = 0;
1020
1021 var errCallback = function(err) {
1022 var maxRetries = options.maxRetries || 0;
1023 if (err && err.code === 'TimeoutError') err.retryable = true;
1024 if (err && err.retryable && retryCount < maxRetries) {
1025 retryCount++;
1026 var delay = util.calculateRetryDelay(retryCount, options.retryDelayOptions);
1027 setTimeout(sendRequest, delay + (err.retryAfter || 0));
1028 } else {
1029 cb(err);
1030 }
1031 };
1032
1033 var sendRequest = function() {
1034 var data = '';
1035 http.handleRequest(httpRequest, httpOptions, function(httpResponse) {
1036 httpResponse.on('data', function(chunk) { data += chunk.toString(); });
1037 httpResponse.on('end', function() {
1038 var statusCode = httpResponse.statusCode;
1039 if (statusCode < 300) {
1040 cb(null, data);
1041 } else {
1042 var retryAfter = parseInt(httpResponse.headers['retry-after'], 10) * 1000 || 0;
1043 var err = util.error(new Error(),
1044 { retryable: statusCode >= 500 || statusCode === 429 }
1045 );
1046 if (retryAfter && err.retryable) err.retryAfter = retryAfter;
1047 errCallback(err);
1048 }
1049 });
1050 }, errCallback);
1051 };
1052
1053 AWS.util.defer(sendRequest);
1054 },
1055
1056 /**
1057 * @api private
1058 */
1059 uuid: {
1060 v4: function uuidV4() {
1061 return __webpack_require__(8).v4();
1062 }
1063 },
1064
1065 /**
1066 * @api private
1067 */
1068 convertPayloadToString: function convertPayloadToString(resp) {
1069 var req = resp.request;
1070 var operation = req.operation;
1071 var rules = req.service.api.operations[operation].output || {};
1072 if (rules.payload && resp.data[rules.payload]) {
1073 resp.data[rules.payload] = resp.data[rules.payload].toString();
1074 }
1075 },
1076
1077 /**
1078 * @api private
1079 */
1080 defer: function defer(callback) {
1081 if (typeof process === 'object' && typeof process.nextTick === 'function') {
1082 process.nextTick(callback);
1083 } else if (typeof setImmediate === 'function') {
1084 setImmediate(callback);
1085 } else {
1086 setTimeout(callback, 0);
1087 }
1088 },
1089
1090 /**
1091 * @api private
1092 */
1093 defaultProfile: 'default',
1094
1095 /**
1096 * @api private
1097 */
1098 configOptInEnv: 'AWS_SDK_LOAD_CONFIG',
1099
1100 /**
1101 * @api private
1102 */
1103 sharedCredentialsFileEnv: 'AWS_SHARED_CREDENTIALS_FILE',
1104
1105 /**
1106 * @api private
1107 */
1108 sharedConfigFileEnv: 'AWS_CONFIG_FILE',
1109
1110 /**
1111 * @api private
1112 */
1113 imdsDisabledEnv: 'AWS_EC2_METADATA_DISABLED'
1114 };
1115
1116 /**
1117 * @api private
1118 */
1119 module.exports = util;
1120
1121 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(4).setImmediate))
1122
1123/***/ }),
1124/* 3 */
1125/***/ (function(module, exports) {
1126
1127 // shim for using process in browser
1128 var process = module.exports = {};
1129
1130 // cached from whatever global is present so that test runners that stub it
1131 // don't break things. But we need to wrap it in a try catch in case it is
1132 // wrapped in strict mode code which doesn't define any globals. It's inside a
1133 // function because try/catches deoptimize in certain engines.
1134
1135 var cachedSetTimeout;
1136 var cachedClearTimeout;
1137
1138 function defaultSetTimout() {
1139 throw new Error('setTimeout has not been defined');
1140 }
1141 function defaultClearTimeout () {
1142 throw new Error('clearTimeout has not been defined');
1143 }
1144 (function () {
1145 try {
1146 if (typeof setTimeout === 'function') {
1147 cachedSetTimeout = setTimeout;
1148 } else {
1149 cachedSetTimeout = defaultSetTimout;
1150 }
1151 } catch (e) {
1152 cachedSetTimeout = defaultSetTimout;
1153 }
1154 try {
1155 if (typeof clearTimeout === 'function') {
1156 cachedClearTimeout = clearTimeout;
1157 } else {
1158 cachedClearTimeout = defaultClearTimeout;
1159 }
1160 } catch (e) {
1161 cachedClearTimeout = defaultClearTimeout;
1162 }
1163 } ())
1164 function runTimeout(fun) {
1165 if (cachedSetTimeout === setTimeout) {
1166 //normal enviroments in sane situations
1167 return setTimeout(fun, 0);
1168 }
1169 // if setTimeout wasn't available but was latter defined
1170 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
1171 cachedSetTimeout = setTimeout;
1172 return setTimeout(fun, 0);
1173 }
1174 try {
1175 // when when somebody has screwed with setTimeout but no I.E. maddness
1176 return cachedSetTimeout(fun, 0);
1177 } catch(e){
1178 try {
1179 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1180 return cachedSetTimeout.call(null, fun, 0);
1181 } catch(e){
1182 // 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
1183 return cachedSetTimeout.call(this, fun, 0);
1184 }
1185 }
1186
1187
1188 }
1189 function runClearTimeout(marker) {
1190 if (cachedClearTimeout === clearTimeout) {
1191 //normal enviroments in sane situations
1192 return clearTimeout(marker);
1193 }
1194 // if clearTimeout wasn't available but was latter defined
1195 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
1196 cachedClearTimeout = clearTimeout;
1197 return clearTimeout(marker);
1198 }
1199 try {
1200 // when when somebody has screwed with setTimeout but no I.E. maddness
1201 return cachedClearTimeout(marker);
1202 } catch (e){
1203 try {
1204 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
1205 return cachedClearTimeout.call(null, marker);
1206 } catch (e){
1207 // 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.
1208 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
1209 return cachedClearTimeout.call(this, marker);
1210 }
1211 }
1212
1213
1214
1215 }
1216 var queue = [];
1217 var draining = false;
1218 var currentQueue;
1219 var queueIndex = -1;
1220
1221 function cleanUpNextTick() {
1222 if (!draining || !currentQueue) {
1223 return;
1224 }
1225 draining = false;
1226 if (currentQueue.length) {
1227 queue = currentQueue.concat(queue);
1228 } else {
1229 queueIndex = -1;
1230 }
1231 if (queue.length) {
1232 drainQueue();
1233 }
1234 }
1235
1236 function drainQueue() {
1237 if (draining) {
1238 return;
1239 }
1240 var timeout = runTimeout(cleanUpNextTick);
1241 draining = true;
1242
1243 var len = queue.length;
1244 while(len) {
1245 currentQueue = queue;
1246 queue = [];
1247 while (++queueIndex < len) {
1248 if (currentQueue) {
1249 currentQueue[queueIndex].run();
1250 }
1251 }
1252 queueIndex = -1;
1253 len = queue.length;
1254 }
1255 currentQueue = null;
1256 draining = false;
1257 runClearTimeout(timeout);
1258 }
1259
1260 process.nextTick = function (fun) {
1261 var args = new Array(arguments.length - 1);
1262 if (arguments.length > 1) {
1263 for (var i = 1; i < arguments.length; i++) {
1264 args[i - 1] = arguments[i];
1265 }
1266 }
1267 queue.push(new Item(fun, args));
1268 if (queue.length === 1 && !draining) {
1269 runTimeout(drainQueue);
1270 }
1271 };
1272
1273 // v8 likes predictible objects
1274 function Item(fun, array) {
1275 this.fun = fun;
1276 this.array = array;
1277 }
1278 Item.prototype.run = function () {
1279 this.fun.apply(null, this.array);
1280 };
1281 process.title = 'browser';
1282 process.browser = true;
1283 process.env = {};
1284 process.argv = [];
1285 process.version = ''; // empty string to avoid regexp issues
1286 process.versions = {};
1287
1288 function noop() {}
1289
1290 process.on = noop;
1291 process.addListener = noop;
1292 process.once = noop;
1293 process.off = noop;
1294 process.removeListener = noop;
1295 process.removeAllListeners = noop;
1296 process.emit = noop;
1297 process.prependListener = noop;
1298 process.prependOnceListener = noop;
1299
1300 process.listeners = function (name) { return [] }
1301
1302 process.binding = function (name) {
1303 throw new Error('process.binding is not supported');
1304 };
1305
1306 process.cwd = function () { return '/' };
1307 process.chdir = function (dir) {
1308 throw new Error('process.chdir is not supported');
1309 };
1310 process.umask = function() { return 0; };
1311
1312
1313/***/ }),
1314/* 4 */
1315/***/ (function(module, exports, __webpack_require__) {
1316
1317 /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
1318 (typeof self !== "undefined" && self) ||
1319 window;
1320 var apply = Function.prototype.apply;
1321
1322 // DOM APIs, for completeness
1323
1324 exports.setTimeout = function() {
1325 return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
1326 };
1327 exports.setInterval = function() {
1328 return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
1329 };
1330 exports.clearTimeout =
1331 exports.clearInterval = function(timeout) {
1332 if (timeout) {
1333 timeout.close();
1334 }
1335 };
1336
1337 function Timeout(id, clearFn) {
1338 this._id = id;
1339 this._clearFn = clearFn;
1340 }
1341 Timeout.prototype.unref = Timeout.prototype.ref = function() {};
1342 Timeout.prototype.close = function() {
1343 this._clearFn.call(scope, this._id);
1344 };
1345
1346 // Does not start the time, just sets up the members needed.
1347 exports.enroll = function(item, msecs) {
1348 clearTimeout(item._idleTimeoutId);
1349 item._idleTimeout = msecs;
1350 };
1351
1352 exports.unenroll = function(item) {
1353 clearTimeout(item._idleTimeoutId);
1354 item._idleTimeout = -1;
1355 };
1356
1357 exports._unrefActive = exports.active = function(item) {
1358 clearTimeout(item._idleTimeoutId);
1359
1360 var msecs = item._idleTimeout;
1361 if (msecs >= 0) {
1362 item._idleTimeoutId = setTimeout(function onTimeout() {
1363 if (item._onTimeout)
1364 item._onTimeout();
1365 }, msecs);
1366 }
1367 };
1368
1369 // setimmediate attaches itself to the global object
1370 __webpack_require__(5);
1371 // On some exotic environments, it's not clear which object `setimmediate` was
1372 // able to install onto. Search each possibility in the same order as the
1373 // `setimmediate` library.
1374 exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
1375 (typeof global !== "undefined" && global.setImmediate) ||
1376 (this && this.setImmediate);
1377 exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
1378 (typeof global !== "undefined" && global.clearImmediate) ||
1379 (this && this.clearImmediate);
1380
1381 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
1382
1383/***/ }),
1384/* 5 */
1385/***/ (function(module, exports, __webpack_require__) {
1386
1387 /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
1388 "use strict";
1389
1390 if (global.setImmediate) {
1391 return;
1392 }
1393
1394 var nextHandle = 1; // Spec says greater than zero
1395 var tasksByHandle = {};
1396 var currentlyRunningATask = false;
1397 var doc = global.document;
1398 var registerImmediate;
1399
1400 function setImmediate(callback) {
1401 // Callback can either be a function or a string
1402 if (typeof callback !== "function") {
1403 callback = new Function("" + callback);
1404 }
1405 // Copy function arguments
1406 var args = new Array(arguments.length - 1);
1407 for (var i = 0; i < args.length; i++) {
1408 args[i] = arguments[i + 1];
1409 }
1410 // Store and register the task
1411 var task = { callback: callback, args: args };
1412 tasksByHandle[nextHandle] = task;
1413 registerImmediate(nextHandle);
1414 return nextHandle++;
1415 }
1416
1417 function clearImmediate(handle) {
1418 delete tasksByHandle[handle];
1419 }
1420
1421 function run(task) {
1422 var callback = task.callback;
1423 var args = task.args;
1424 switch (args.length) {
1425 case 0:
1426 callback();
1427 break;
1428 case 1:
1429 callback(args[0]);
1430 break;
1431 case 2:
1432 callback(args[0], args[1]);
1433 break;
1434 case 3:
1435 callback(args[0], args[1], args[2]);
1436 break;
1437 default:
1438 callback.apply(undefined, args);
1439 break;
1440 }
1441 }
1442
1443 function runIfPresent(handle) {
1444 // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
1445 // So if we're currently running a task, we'll need to delay this invocation.
1446 if (currentlyRunningATask) {
1447 // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
1448 // "too much recursion" error.
1449 setTimeout(runIfPresent, 0, handle);
1450 } else {
1451 var task = tasksByHandle[handle];
1452 if (task) {
1453 currentlyRunningATask = true;
1454 try {
1455 run(task);
1456 } finally {
1457 clearImmediate(handle);
1458 currentlyRunningATask = false;
1459 }
1460 }
1461 }
1462 }
1463
1464 function installNextTickImplementation() {
1465 registerImmediate = function(handle) {
1466 process.nextTick(function () { runIfPresent(handle); });
1467 };
1468 }
1469
1470 function canUsePostMessage() {
1471 // The test against `importScripts` prevents this implementation from being installed inside a web worker,
1472 // where `global.postMessage` means something completely different and can't be used for this purpose.
1473 if (global.postMessage && !global.importScripts) {
1474 var postMessageIsAsynchronous = true;
1475 var oldOnMessage = global.onmessage;
1476 global.onmessage = function() {
1477 postMessageIsAsynchronous = false;
1478 };
1479 global.postMessage("", "*");
1480 global.onmessage = oldOnMessage;
1481 return postMessageIsAsynchronous;
1482 }
1483 }
1484
1485 function installPostMessageImplementation() {
1486 // Installs an event handler on `global` for the `message` event: see
1487 // * https://developer.mozilla.org/en/DOM/window.postMessage
1488 // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
1489
1490 var messagePrefix = "setImmediate$" + Math.random() + "$";
1491 var onGlobalMessage = function(event) {
1492 if (event.source === global &&
1493 typeof event.data === "string" &&
1494 event.data.indexOf(messagePrefix) === 0) {
1495 runIfPresent(+event.data.slice(messagePrefix.length));
1496 }
1497 };
1498
1499 if (global.addEventListener) {
1500 global.addEventListener("message", onGlobalMessage, false);
1501 } else {
1502 global.attachEvent("onmessage", onGlobalMessage);
1503 }
1504
1505 registerImmediate = function(handle) {
1506 global.postMessage(messagePrefix + handle, "*");
1507 };
1508 }
1509
1510 function installMessageChannelImplementation() {
1511 var channel = new MessageChannel();
1512 channel.port1.onmessage = function(event) {
1513 var handle = event.data;
1514 runIfPresent(handle);
1515 };
1516
1517 registerImmediate = function(handle) {
1518 channel.port2.postMessage(handle);
1519 };
1520 }
1521
1522 function installReadyStateChangeImplementation() {
1523 var html = doc.documentElement;
1524 registerImmediate = function(handle) {
1525 // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
1526 // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
1527 var script = doc.createElement("script");
1528 script.onreadystatechange = function () {
1529 runIfPresent(handle);
1530 script.onreadystatechange = null;
1531 html.removeChild(script);
1532 script = null;
1533 };
1534 html.appendChild(script);
1535 };
1536 }
1537
1538 function installSetTimeoutImplementation() {
1539 registerImmediate = function(handle) {
1540 setTimeout(runIfPresent, 0, handle);
1541 };
1542 }
1543
1544 // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
1545 var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
1546 attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
1547
1548 // Don't get fooled by e.g. browserify environments.
1549 if ({}.toString.call(global.process) === "[object process]") {
1550 // For Node.js before 0.9
1551 installNextTickImplementation();
1552
1553 } else if (canUsePostMessage()) {
1554 // For non-IE10 modern browsers
1555 installPostMessageImplementation();
1556
1557 } else if (global.MessageChannel) {
1558 // For web workers, where supported
1559 installMessageChannelImplementation();
1560
1561 } else if (doc && "onreadystatechange" in doc.createElement("script")) {
1562 // For IE 6–8
1563 installReadyStateChangeImplementation();
1564
1565 } else {
1566 // For older browsers
1567 installSetTimeoutImplementation();
1568 }
1569
1570 attachTo.setImmediate = setImmediate;
1571 attachTo.clearImmediate = clearImmediate;
1572 }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
1573
1574 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
1575
1576/***/ }),
1577/* 6 */
1578/***/ (function(module, exports) {
1579
1580 /* (ignored) */
1581
1582/***/ }),
1583/* 7 */
1584/***/ (function(module, exports) {
1585
1586 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*"],"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},"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"},"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"},"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"},"acmpca":{"prefix":"acm-pca","name":"ACMPCA"},"fms":{"name":"FMS"},"secretsmanager":{"name":"SecretsManager","cors":true},"iotanalytics":{"name":"IoTAnalytics"},"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"}}
1587
1588/***/ }),
1589/* 8 */
1590/***/ (function(module, exports, __webpack_require__) {
1591
1592 var v1 = __webpack_require__(9);
1593 var v4 = __webpack_require__(12);
1594
1595 var uuid = v4;
1596 uuid.v1 = v1;
1597 uuid.v4 = v4;
1598
1599 module.exports = uuid;
1600
1601
1602/***/ }),
1603/* 9 */
1604/***/ (function(module, exports, __webpack_require__) {
1605
1606 var rng = __webpack_require__(10);
1607 var bytesToUuid = __webpack_require__(11);
1608
1609 // **`v1()` - Generate time-based UUID**
1610 //
1611 // Inspired by https://github.com/LiosK/UUID.js
1612 // and http://docs.python.org/library/uuid.html
1613
1614 var _nodeId;
1615 var _clockseq;
1616
1617 // Previous uuid creation time
1618 var _lastMSecs = 0;
1619 var _lastNSecs = 0;
1620
1621 // See https://github.com/broofa/node-uuid for API details
1622 function v1(options, buf, offset) {
1623 var i = buf && offset || 0;
1624 var b = buf || [];
1625
1626 options = options || {};
1627 var node = options.node || _nodeId;
1628 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
1629
1630 // node and clockseq need to be initialized to random values if they're not
1631 // specified. We do this lazily to minimize issues related to insufficient
1632 // system entropy. See #189
1633 if (node == null || clockseq == null) {
1634 var seedBytes = rng();
1635 if (node == null) {
1636 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
1637 node = _nodeId = [
1638 seedBytes[0] | 0x01,
1639 seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]
1640 ];
1641 }
1642 if (clockseq == null) {
1643 // Per 4.2.2, randomize (14 bit) clockseq
1644 clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;
1645 }
1646 }
1647
1648 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
1649 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
1650 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
1651 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
1652 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
1653
1654 // Per 4.2.1.2, use count of uuid's generated during the current clock
1655 // cycle to simulate higher resolution clock
1656 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
1657
1658 // Time since last uuid creation (in msecs)
1659 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
1660
1661 // Per 4.2.1.2, Bump clockseq on clock regression
1662 if (dt < 0 && options.clockseq === undefined) {
1663 clockseq = clockseq + 1 & 0x3fff;
1664 }
1665
1666 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
1667 // time interval
1668 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
1669 nsecs = 0;
1670 }
1671
1672 // Per 4.2.1.2 Throw error if too many uuids are requested
1673 if (nsecs >= 10000) {
1674 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
1675 }
1676
1677 _lastMSecs = msecs;
1678 _lastNSecs = nsecs;
1679 _clockseq = clockseq;
1680
1681 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
1682 msecs += 12219292800000;
1683
1684 // `time_low`
1685 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
1686 b[i++] = tl >>> 24 & 0xff;
1687 b[i++] = tl >>> 16 & 0xff;
1688 b[i++] = tl >>> 8 & 0xff;
1689 b[i++] = tl & 0xff;
1690
1691 // `time_mid`
1692 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
1693 b[i++] = tmh >>> 8 & 0xff;
1694 b[i++] = tmh & 0xff;
1695
1696 // `time_high_and_version`
1697 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
1698 b[i++] = tmh >>> 16 & 0xff;
1699
1700 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
1701 b[i++] = clockseq >>> 8 | 0x80;
1702
1703 // `clock_seq_low`
1704 b[i++] = clockseq & 0xff;
1705
1706 // `node`
1707 for (var n = 0; n < 6; ++n) {
1708 b[i + n] = node[n];
1709 }
1710
1711 return buf ? buf : bytesToUuid(b);
1712 }
1713
1714 module.exports = v1;
1715
1716
1717/***/ }),
1718/* 10 */
1719/***/ (function(module, exports) {
1720
1721 // Unique ID creation requires a high quality random # generator. In the
1722 // browser this is a little complicated due to unknown quality of Math.random()
1723 // and inconsistent support for the `crypto` API. We do the best we can via
1724 // feature-detection
1725
1726 // getRandomValues needs to be invoked in a context where "this" is a Crypto
1727 // implementation. Also, find the complete implementation of crypto on IE11.
1728 var getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||
1729 (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));
1730
1731 if (getRandomValues) {
1732 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
1733 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
1734
1735 module.exports = function whatwgRNG() {
1736 getRandomValues(rnds8);
1737 return rnds8;
1738 };
1739 } else {
1740 // Math.random()-based (RNG)
1741 //
1742 // If all else fails, use Math.random(). It's fast, but is of unspecified
1743 // quality.
1744 var rnds = new Array(16);
1745
1746 module.exports = function mathRNG() {
1747 for (var i = 0, r; i < 16; i++) {
1748 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
1749 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
1750 }
1751
1752 return rnds;
1753 };
1754 }
1755
1756
1757/***/ }),
1758/* 11 */
1759/***/ (function(module, exports) {
1760
1761 /**
1762 * Convert array of 16 byte values to UUID string format of the form:
1763 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1764 */
1765 var byteToHex = [];
1766 for (var i = 0; i < 256; ++i) {
1767 byteToHex[i] = (i + 0x100).toString(16).substr(1);
1768 }
1769
1770 function bytesToUuid(buf, offset) {
1771 var i = offset || 0;
1772 var bth = byteToHex;
1773 // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4
1774 return ([bth[buf[i++]], bth[buf[i++]],
1775 bth[buf[i++]], bth[buf[i++]], '-',
1776 bth[buf[i++]], bth[buf[i++]], '-',
1777 bth[buf[i++]], bth[buf[i++]], '-',
1778 bth[buf[i++]], bth[buf[i++]], '-',
1779 bth[buf[i++]], bth[buf[i++]],
1780 bth[buf[i++]], bth[buf[i++]],
1781 bth[buf[i++]], bth[buf[i++]]]).join('');
1782 }
1783
1784 module.exports = bytesToUuid;
1785
1786
1787/***/ }),
1788/* 12 */
1789/***/ (function(module, exports, __webpack_require__) {
1790
1791 var rng = __webpack_require__(10);
1792 var bytesToUuid = __webpack_require__(11);
1793
1794 function v4(options, buf, offset) {
1795 var i = buf && offset || 0;
1796
1797 if (typeof(options) == 'string') {
1798 buf = options === 'binary' ? new Array(16) : null;
1799 options = null;
1800 }
1801 options = options || {};
1802
1803 var rnds = options.random || (options.rng || rng)();
1804
1805 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1806 rnds[6] = (rnds[6] & 0x0f) | 0x40;
1807 rnds[8] = (rnds[8] & 0x3f) | 0x80;
1808
1809 // Copy bytes to buffer, if provided
1810 if (buf) {
1811 for (var ii = 0; ii < 16; ++ii) {
1812 buf[i + ii] = rnds[ii];
1813 }
1814 }
1815
1816 return buf || bytesToUuid(rnds);
1817 }
1818
1819 module.exports = v4;
1820
1821
1822/***/ }),
1823/* 13 */
1824/***/ (function(module, exports, __webpack_require__) {
1825
1826 var util = __webpack_require__(2);
1827 var JsonBuilder = __webpack_require__(14);
1828 var JsonParser = __webpack_require__(15);
1829 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
1830
1831 function buildRequest(req) {
1832 var httpRequest = req.httpRequest;
1833 var api = req.service.api;
1834 var target = api.targetPrefix + '.' + api.operations[req.operation].name;
1835 var version = api.jsonVersion || '1.0';
1836 var input = api.operations[req.operation].input;
1837 var builder = new JsonBuilder();
1838
1839 if (version === 1) version = '1.0';
1840 httpRequest.body = builder.build(req.params || {}, input);
1841 httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version;
1842 httpRequest.headers['X-Amz-Target'] = target;
1843
1844 populateHostPrefix(req);
1845 }
1846
1847 function extractError(resp) {
1848 var error = {};
1849 var httpResponse = resp.httpResponse;
1850
1851 error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError';
1852 if (typeof error.code === 'string') {
1853 error.code = error.code.split(':')[0];
1854 }
1855
1856 if (httpResponse.body.length > 0) {
1857 try {
1858 var e = JSON.parse(httpResponse.body.toString());
1859 if (e.__type || e.code) {
1860 error.code = (e.__type || e.code).split('#').pop();
1861 }
1862 if (error.code === 'RequestEntityTooLarge') {
1863 error.message = 'Request body must be less than 1 MB';
1864 } else {
1865 error.message = (e.message || e.Message || null);
1866 }
1867 } catch (e) {
1868 error.statusCode = httpResponse.statusCode;
1869 error.message = httpResponse.statusMessage;
1870 }
1871 } else {
1872 error.statusCode = httpResponse.statusCode;
1873 error.message = httpResponse.statusCode.toString();
1874 }
1875
1876 resp.error = util.error(new Error(), error);
1877 }
1878
1879 function extractData(resp) {
1880 var body = resp.httpResponse.body.toString() || '{}';
1881 if (resp.request.service.config.convertResponseTypes === false) {
1882 resp.data = JSON.parse(body);
1883 } else {
1884 var operation = resp.request.service.api.operations[resp.request.operation];
1885 var shape = operation.output || {};
1886 var parser = new JsonParser();
1887 resp.data = parser.parse(body, shape);
1888 }
1889 }
1890
1891 /**
1892 * @api private
1893 */
1894 module.exports = {
1895 buildRequest: buildRequest,
1896 extractError: extractError,
1897 extractData: extractData
1898 };
1899
1900
1901/***/ }),
1902/* 14 */
1903/***/ (function(module, exports, __webpack_require__) {
1904
1905 var util = __webpack_require__(2);
1906
1907 function JsonBuilder() { }
1908
1909 JsonBuilder.prototype.build = function(value, shape) {
1910 return JSON.stringify(translate(value, shape));
1911 };
1912
1913 function translate(value, shape) {
1914 if (!shape || value === undefined || value === null) return undefined;
1915
1916 switch (shape.type) {
1917 case 'structure': return translateStructure(value, shape);
1918 case 'map': return translateMap(value, shape);
1919 case 'list': return translateList(value, shape);
1920 default: return translateScalar(value, shape);
1921 }
1922 }
1923
1924 function translateStructure(structure, shape) {
1925 var struct = {};
1926 util.each(structure, function(name, value) {
1927 var memberShape = shape.members[name];
1928 if (memberShape) {
1929 if (memberShape.location !== 'body') return;
1930 var locationName = memberShape.isLocationName ? memberShape.name : name;
1931 var result = translate(value, memberShape);
1932 if (result !== undefined) struct[locationName] = result;
1933 }
1934 });
1935 return struct;
1936 }
1937
1938 function translateList(list, shape) {
1939 var out = [];
1940 util.arrayEach(list, function(value) {
1941 var result = translate(value, shape.member);
1942 if (result !== undefined) out.push(result);
1943 });
1944 return out;
1945 }
1946
1947 function translateMap(map, shape) {
1948 var out = {};
1949 util.each(map, function(key, value) {
1950 var result = translate(value, shape.value);
1951 if (result !== undefined) out[key] = result;
1952 });
1953 return out;
1954 }
1955
1956 function translateScalar(value, shape) {
1957 return shape.toWireFormat(value);
1958 }
1959
1960 /**
1961 * @api private
1962 */
1963 module.exports = JsonBuilder;
1964
1965
1966/***/ }),
1967/* 15 */
1968/***/ (function(module, exports, __webpack_require__) {
1969
1970 var util = __webpack_require__(2);
1971
1972 function JsonParser() { }
1973
1974 JsonParser.prototype.parse = function(value, shape) {
1975 return translate(JSON.parse(value), shape);
1976 };
1977
1978 function translate(value, shape) {
1979 if (!shape || value === undefined) return undefined;
1980
1981 switch (shape.type) {
1982 case 'structure': return translateStructure(value, shape);
1983 case 'map': return translateMap(value, shape);
1984 case 'list': return translateList(value, shape);
1985 default: return translateScalar(value, shape);
1986 }
1987 }
1988
1989 function translateStructure(structure, shape) {
1990 if (structure == null) return undefined;
1991
1992 var struct = {};
1993 var shapeMembers = shape.members;
1994 util.each(shapeMembers, function(name, memberShape) {
1995 var locationName = memberShape.isLocationName ? memberShape.name : name;
1996 if (Object.prototype.hasOwnProperty.call(structure, locationName)) {
1997 var value = structure[locationName];
1998 var result = translate(value, memberShape);
1999 if (result !== undefined) struct[name] = result;
2000 }
2001 });
2002 return struct;
2003 }
2004
2005 function translateList(list, shape) {
2006 if (list == null) return undefined;
2007
2008 var out = [];
2009 util.arrayEach(list, function(value) {
2010 var result = translate(value, shape.member);
2011 if (result === undefined) out.push(null);
2012 else out.push(result);
2013 });
2014 return out;
2015 }
2016
2017 function translateMap(map, shape) {
2018 if (map == null) return undefined;
2019
2020 var out = {};
2021 util.each(map, function(key, value) {
2022 var result = translate(value, shape.value);
2023 if (result === undefined) out[key] = null;
2024 else out[key] = result;
2025 });
2026 return out;
2027 }
2028
2029 function translateScalar(value, shape) {
2030 return shape.toType(value);
2031 }
2032
2033 /**
2034 * @api private
2035 */
2036 module.exports = JsonParser;
2037
2038
2039/***/ }),
2040/* 16 */
2041/***/ (function(module, exports, __webpack_require__) {
2042
2043 var util = __webpack_require__(2);
2044 var AWS = __webpack_require__(1);
2045
2046 /**
2047 * Prepend prefix defined by API model to endpoint that's already
2048 * constructed. This feature does not apply to operations using
2049 * endpoint discovery and can be disabled.
2050 * @api private
2051 */
2052 function populateHostPrefix(request) {
2053 var enabled = request.service.config.hostPrefixEnabled;
2054 if (!enabled) return request;
2055 var operationModel = request.service.api.operations[request.operation];
2056 //don't marshal host prefix when operation has endpoint discovery traits
2057 if (hasEndpointDiscover(request)) return request;
2058 if (operationModel.endpoint && operationModel.endpoint.hostPrefix) {
2059 var hostPrefixNotation = operationModel.endpoint.hostPrefix;
2060 var hostPrefix = expandHostPrefix(hostPrefixNotation, request.params, operationModel.input);
2061 prependEndpointPrefix(request.httpRequest.endpoint, hostPrefix);
2062 validateHostname(request.httpRequest.endpoint.hostname);
2063 }
2064 return request;
2065 }
2066
2067 /**
2068 * @api private
2069 */
2070 function hasEndpointDiscover(request) {
2071 var api = request.service.api;
2072 var operationModel = api.operations[request.operation];
2073 var isEndpointOperation = api.endpointOperation && (api.endpointOperation === util.string.lowerFirst(operationModel.name));
2074 return (operationModel.endpointDiscoveryRequired !== 'NULL' || isEndpointOperation === true);
2075 }
2076
2077 /**
2078 * @api private
2079 */
2080 function expandHostPrefix(hostPrefixNotation, params, shape) {
2081 util.each(shape.members, function(name, member) {
2082 if (member.hostLabel === true) {
2083 if (typeof params[name] !== 'string' || params[name] === '') {
2084 throw util.error(new Error(), {
2085 message: 'Parameter ' + name + ' should be a non-empty string.',
2086 code: 'InvalidParameter'
2087 });
2088 }
2089 var regex = new RegExp('\\{' + name + '\\}', 'g');
2090 hostPrefixNotation = hostPrefixNotation.replace(regex, params[name]);
2091 }
2092 });
2093 return hostPrefixNotation;
2094 }
2095
2096 /**
2097 * @api private
2098 */
2099 function prependEndpointPrefix(endpoint, prefix) {
2100 if (endpoint.host) {
2101 endpoint.host = prefix + endpoint.host;
2102 }
2103 if (endpoint.hostname) {
2104 endpoint.hostname = prefix + endpoint.hostname;
2105 }
2106 }
2107
2108 /**
2109 * @api private
2110 */
2111 function validateHostname(hostname) {
2112 var labels = hostname.split('.');
2113 //Reference: https://tools.ietf.org/html/rfc1123#section-2
2114 var hostPattern = /^[a-zA-Z0-9]{1}$|^[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9]$/;
2115 util.arrayEach(labels, function(label) {
2116 if (!label.length || label.length < 1 || label.length > 63) {
2117 throw util.error(new Error(), {
2118 code: 'ValidationError',
2119 message: 'Hostname label length should be between 1 to 63 characters, inclusive.'
2120 });
2121 }
2122 if (!hostPattern.test(label)) {
2123 throw AWS.util.error(new Error(),
2124 {code: 'ValidationError', message: label + ' is not hostname compatible.'});
2125 }
2126 });
2127 }
2128
2129 module.exports = {
2130 populateHostPrefix: populateHostPrefix
2131 };
2132
2133
2134/***/ }),
2135/* 17 */
2136/***/ (function(module, exports, __webpack_require__) {
2137
2138 var AWS = __webpack_require__(1);
2139 var util = __webpack_require__(2);
2140 var QueryParamSerializer = __webpack_require__(18);
2141 var Shape = __webpack_require__(19);
2142 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2143
2144 function buildRequest(req) {
2145 var operation = req.service.api.operations[req.operation];
2146 var httpRequest = req.httpRequest;
2147 httpRequest.headers['Content-Type'] =
2148 'application/x-www-form-urlencoded; charset=utf-8';
2149 httpRequest.params = {
2150 Version: req.service.api.apiVersion,
2151 Action: operation.name
2152 };
2153
2154 // convert the request parameters into a list of query params,
2155 // e.g. Deeply.NestedParam.0.Name=value
2156 var builder = new QueryParamSerializer();
2157 builder.serialize(req.params, operation.input, function(name, value) {
2158 httpRequest.params[name] = value;
2159 });
2160 httpRequest.body = util.queryParamsToString(httpRequest.params);
2161
2162 populateHostPrefix(req);
2163 }
2164
2165 function extractError(resp) {
2166 var data, body = resp.httpResponse.body.toString();
2167 if (body.match('<UnknownOperationException')) {
2168 data = {
2169 Code: 'UnknownOperation',
2170 Message: 'Unknown operation ' + resp.request.operation
2171 };
2172 } else {
2173 try {
2174 data = new AWS.XML.Parser().parse(body);
2175 } catch (e) {
2176 data = {
2177 Code: resp.httpResponse.statusCode,
2178 Message: resp.httpResponse.statusMessage
2179 };
2180 }
2181 }
2182
2183 if (data.requestId && !resp.requestId) resp.requestId = data.requestId;
2184 if (data.Errors) data = data.Errors;
2185 if (data.Error) data = data.Error;
2186 if (data.Code) {
2187 resp.error = util.error(new Error(), {
2188 code: data.Code,
2189 message: data.Message
2190 });
2191 } else {
2192 resp.error = util.error(new Error(), {
2193 code: resp.httpResponse.statusCode,
2194 message: null
2195 });
2196 }
2197 }
2198
2199 function extractData(resp) {
2200 var req = resp.request;
2201 var operation = req.service.api.operations[req.operation];
2202 var shape = operation.output || {};
2203 var origRules = shape;
2204
2205 if (origRules.resultWrapper) {
2206 var tmp = Shape.create({type: 'structure'});
2207 tmp.members[origRules.resultWrapper] = shape;
2208 tmp.memberNames = [origRules.resultWrapper];
2209 util.property(shape, 'name', shape.resultWrapper);
2210 shape = tmp;
2211 }
2212
2213 var parser = new AWS.XML.Parser();
2214
2215 // TODO: Refactor XML Parser to parse RequestId from response.
2216 if (shape && shape.members && !shape.members._XAMZRequestId) {
2217 var requestIdShape = Shape.create(
2218 { type: 'string' },
2219 { api: { protocol: 'query' } },
2220 'requestId'
2221 );
2222 shape.members._XAMZRequestId = requestIdShape;
2223 }
2224
2225 var data = parser.parse(resp.httpResponse.body.toString(), shape);
2226 resp.requestId = data._XAMZRequestId || data.requestId;
2227
2228 if (data._XAMZRequestId) delete data._XAMZRequestId;
2229
2230 if (origRules.resultWrapper) {
2231 if (data[origRules.resultWrapper]) {
2232 util.update(data, data[origRules.resultWrapper]);
2233 delete data[origRules.resultWrapper];
2234 }
2235 }
2236
2237 resp.data = data;
2238 }
2239
2240 /**
2241 * @api private
2242 */
2243 module.exports = {
2244 buildRequest: buildRequest,
2245 extractError: extractError,
2246 extractData: extractData
2247 };
2248
2249
2250/***/ }),
2251/* 18 */
2252/***/ (function(module, exports, __webpack_require__) {
2253
2254 var util = __webpack_require__(2);
2255
2256 function QueryParamSerializer() {
2257 }
2258
2259 QueryParamSerializer.prototype.serialize = function(params, shape, fn) {
2260 serializeStructure('', params, shape, fn);
2261 };
2262
2263 function ucfirst(shape) {
2264 if (shape.isQueryName || shape.api.protocol !== 'ec2') {
2265 return shape.name;
2266 } else {
2267 return shape.name[0].toUpperCase() + shape.name.substr(1);
2268 }
2269 }
2270
2271 function serializeStructure(prefix, struct, rules, fn) {
2272 util.each(rules.members, function(name, member) {
2273 var value = struct[name];
2274 if (value === null || value === undefined) return;
2275
2276 var memberName = ucfirst(member);
2277 memberName = prefix ? prefix + '.' + memberName : memberName;
2278 serializeMember(memberName, value, member, fn);
2279 });
2280 }
2281
2282 function serializeMap(name, map, rules, fn) {
2283 var i = 1;
2284 util.each(map, function (key, value) {
2285 var prefix = rules.flattened ? '.' : '.entry.';
2286 var position = prefix + (i++) + '.';
2287 var keyName = position + (rules.key.name || 'key');
2288 var valueName = position + (rules.value.name || 'value');
2289 serializeMember(name + keyName, key, rules.key, fn);
2290 serializeMember(name + valueName, value, rules.value, fn);
2291 });
2292 }
2293
2294 function serializeList(name, list, rules, fn) {
2295 var memberRules = rules.member || {};
2296
2297 if (list.length === 0) {
2298 fn.call(this, name, null);
2299 return;
2300 }
2301
2302 util.arrayEach(list, function (v, n) {
2303 var suffix = '.' + (n + 1);
2304 if (rules.api.protocol === 'ec2') {
2305 // Do nothing for EC2
2306 suffix = suffix + ''; // make linter happy
2307 } else if (rules.flattened) {
2308 if (memberRules.name) {
2309 var parts = name.split('.');
2310 parts.pop();
2311 parts.push(ucfirst(memberRules));
2312 name = parts.join('.');
2313 }
2314 } else {
2315 suffix = '.' + (memberRules.name ? memberRules.name : 'member') + suffix;
2316 }
2317 serializeMember(name + suffix, v, memberRules, fn);
2318 });
2319 }
2320
2321 function serializeMember(name, value, rules, fn) {
2322 if (value === null || value === undefined) return;
2323 if (rules.type === 'structure') {
2324 serializeStructure(name, value, rules, fn);
2325 } else if (rules.type === 'list') {
2326 serializeList(name, value, rules, fn);
2327 } else if (rules.type === 'map') {
2328 serializeMap(name, value, rules, fn);
2329 } else {
2330 fn(name, rules.toWireFormat(value).toString());
2331 }
2332 }
2333
2334 /**
2335 * @api private
2336 */
2337 module.exports = QueryParamSerializer;
2338
2339
2340/***/ }),
2341/* 19 */
2342/***/ (function(module, exports, __webpack_require__) {
2343
2344 var Collection = __webpack_require__(20);
2345
2346 var util = __webpack_require__(2);
2347
2348 function property(obj, name, value) {
2349 if (value !== null && value !== undefined) {
2350 util.property.apply(this, arguments);
2351 }
2352 }
2353
2354 function memoizedProperty(obj, name) {
2355 if (!obj.constructor.prototype[name]) {
2356 util.memoizedProperty.apply(this, arguments);
2357 }
2358 }
2359
2360 function Shape(shape, options, memberName) {
2361 options = options || {};
2362
2363 property(this, 'shape', shape.shape);
2364 property(this, 'api', options.api, false);
2365 property(this, 'type', shape.type);
2366 property(this, 'enum', shape.enum);
2367 property(this, 'min', shape.min);
2368 property(this, 'max', shape.max);
2369 property(this, 'pattern', shape.pattern);
2370 property(this, 'location', shape.location || this.location || 'body');
2371 property(this, 'name', this.name || shape.xmlName || shape.queryName ||
2372 shape.locationName || memberName);
2373 property(this, 'isStreaming', shape.streaming || this.isStreaming || false);
2374 property(this, 'isComposite', shape.isComposite || false);
2375 property(this, 'isShape', true, false);
2376 property(this, 'isQueryName', Boolean(shape.queryName), false);
2377 property(this, 'isLocationName', Boolean(shape.locationName), false);
2378 property(this, 'isIdempotent', shape.idempotencyToken === true);
2379 property(this, 'isJsonValue', shape.jsonvalue === true);
2380 property(this, 'isSensitive', shape.sensitive === true || shape.prototype && shape.prototype.sensitive === true);
2381 property(this, 'isEventStream', Boolean(shape.eventstream), false);
2382 property(this, 'isEvent', Boolean(shape.event), false);
2383 property(this, 'isEventPayload', Boolean(shape.eventpayload), false);
2384 property(this, 'isEventHeader', Boolean(shape.eventheader), false);
2385 property(this, 'isTimestampFormatSet', Boolean(shape.timestampFormat) || shape.prototype && shape.prototype.isTimestampFormatSet === true, false);
2386 property(this, 'endpointDiscoveryId', Boolean(shape.endpointdiscoveryid), false);
2387 property(this, 'hostLabel', Boolean(shape.hostLabel), false);
2388
2389 if (options.documentation) {
2390 property(this, 'documentation', shape.documentation);
2391 property(this, 'documentationUrl', shape.documentationUrl);
2392 }
2393
2394 if (shape.xmlAttribute) {
2395 property(this, 'isXmlAttribute', shape.xmlAttribute || false);
2396 }
2397
2398 // type conversion and parsing
2399 property(this, 'defaultValue', null);
2400 this.toWireFormat = function(value) {
2401 if (value === null || value === undefined) return '';
2402 return value;
2403 };
2404 this.toType = function(value) { return value; };
2405 }
2406
2407 /**
2408 * @api private
2409 */
2410 Shape.normalizedTypes = {
2411 character: 'string',
2412 double: 'float',
2413 long: 'integer',
2414 short: 'integer',
2415 biginteger: 'integer',
2416 bigdecimal: 'float',
2417 blob: 'binary'
2418 };
2419
2420 /**
2421 * @api private
2422 */
2423 Shape.types = {
2424 'structure': StructureShape,
2425 'list': ListShape,
2426 'map': MapShape,
2427 'boolean': BooleanShape,
2428 'timestamp': TimestampShape,
2429 'float': FloatShape,
2430 'integer': IntegerShape,
2431 'string': StringShape,
2432 'base64': Base64Shape,
2433 'binary': BinaryShape
2434 };
2435
2436 Shape.resolve = function resolve(shape, options) {
2437 if (shape.shape) {
2438 var refShape = options.api.shapes[shape.shape];
2439 if (!refShape) {
2440 throw new Error('Cannot find shape reference: ' + shape.shape);
2441 }
2442
2443 return refShape;
2444 } else {
2445 return null;
2446 }
2447 };
2448
2449 Shape.create = function create(shape, options, memberName) {
2450 if (shape.isShape) return shape;
2451
2452 var refShape = Shape.resolve(shape, options);
2453 if (refShape) {
2454 var filteredKeys = Object.keys(shape);
2455 if (!options.documentation) {
2456 filteredKeys = filteredKeys.filter(function(name) {
2457 return !name.match(/documentation/);
2458 });
2459 }
2460
2461 // create an inline shape with extra members
2462 var InlineShape = function() {
2463 refShape.constructor.call(this, shape, options, memberName);
2464 };
2465 InlineShape.prototype = refShape;
2466 return new InlineShape();
2467 } else {
2468 // set type if not set
2469 if (!shape.type) {
2470 if (shape.members) shape.type = 'structure';
2471 else if (shape.member) shape.type = 'list';
2472 else if (shape.key) shape.type = 'map';
2473 else shape.type = 'string';
2474 }
2475
2476 // normalize types
2477 var origType = shape.type;
2478 if (Shape.normalizedTypes[shape.type]) {
2479 shape.type = Shape.normalizedTypes[shape.type];
2480 }
2481
2482 if (Shape.types[shape.type]) {
2483 return new Shape.types[shape.type](shape, options, memberName);
2484 } else {
2485 throw new Error('Unrecognized shape type: ' + origType);
2486 }
2487 }
2488 };
2489
2490 function CompositeShape(shape) {
2491 Shape.apply(this, arguments);
2492 property(this, 'isComposite', true);
2493
2494 if (shape.flattened) {
2495 property(this, 'flattened', shape.flattened || false);
2496 }
2497 }
2498
2499 function StructureShape(shape, options) {
2500 var self = this;
2501 var requiredMap = null, firstInit = !this.isShape;
2502
2503 CompositeShape.apply(this, arguments);
2504
2505 if (firstInit) {
2506 property(this, 'defaultValue', function() { return {}; });
2507 property(this, 'members', {});
2508 property(this, 'memberNames', []);
2509 property(this, 'required', []);
2510 property(this, 'isRequired', function() { return false; });
2511 }
2512
2513 if (shape.members) {
2514 property(this, 'members', new Collection(shape.members, options, function(name, member) {
2515 return Shape.create(member, options, name);
2516 }));
2517 memoizedProperty(this, 'memberNames', function() {
2518 return shape.xmlOrder || Object.keys(shape.members);
2519 });
2520
2521 if (shape.event) {
2522 memoizedProperty(this, 'eventPayloadMemberName', function() {
2523 var members = self.members;
2524 var memberNames = self.memberNames;
2525 // iterate over members to find ones that are event payloads
2526 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2527 if (members[memberNames[i]].isEventPayload) {
2528 return memberNames[i];
2529 }
2530 }
2531 });
2532
2533 memoizedProperty(this, 'eventHeaderMemberNames', function() {
2534 var members = self.members;
2535 var memberNames = self.memberNames;
2536 var eventHeaderMemberNames = [];
2537 // iterate over members to find ones that are event headers
2538 for (var i = 0, iLen = memberNames.length; i < iLen; i++) {
2539 if (members[memberNames[i]].isEventHeader) {
2540 eventHeaderMemberNames.push(memberNames[i]);
2541 }
2542 }
2543 return eventHeaderMemberNames;
2544 });
2545 }
2546 }
2547
2548 if (shape.required) {
2549 property(this, 'required', shape.required);
2550 property(this, 'isRequired', function(name) {
2551 if (!requiredMap) {
2552 requiredMap = {};
2553 for (var i = 0; i < shape.required.length; i++) {
2554 requiredMap[shape.required[i]] = true;
2555 }
2556 }
2557
2558 return requiredMap[name];
2559 }, false, true);
2560 }
2561
2562 property(this, 'resultWrapper', shape.resultWrapper || null);
2563
2564 if (shape.payload) {
2565 property(this, 'payload', shape.payload);
2566 }
2567
2568 if (typeof shape.xmlNamespace === 'string') {
2569 property(this, 'xmlNamespaceUri', shape.xmlNamespace);
2570 } else if (typeof shape.xmlNamespace === 'object') {
2571 property(this, 'xmlNamespacePrefix', shape.xmlNamespace.prefix);
2572 property(this, 'xmlNamespaceUri', shape.xmlNamespace.uri);
2573 }
2574 }
2575
2576 function ListShape(shape, options) {
2577 var self = this, firstInit = !this.isShape;
2578 CompositeShape.apply(this, arguments);
2579
2580 if (firstInit) {
2581 property(this, 'defaultValue', function() { return []; });
2582 }
2583
2584 if (shape.member) {
2585 memoizedProperty(this, 'member', function() {
2586 return Shape.create(shape.member, options);
2587 });
2588 }
2589
2590 if (this.flattened) {
2591 var oldName = this.name;
2592 memoizedProperty(this, 'name', function() {
2593 return self.member.name || oldName;
2594 });
2595 }
2596 }
2597
2598 function MapShape(shape, options) {
2599 var firstInit = !this.isShape;
2600 CompositeShape.apply(this, arguments);
2601
2602 if (firstInit) {
2603 property(this, 'defaultValue', function() { return {}; });
2604 property(this, 'key', Shape.create({type: 'string'}, options));
2605 property(this, 'value', Shape.create({type: 'string'}, options));
2606 }
2607
2608 if (shape.key) {
2609 memoizedProperty(this, 'key', function() {
2610 return Shape.create(shape.key, options);
2611 });
2612 }
2613 if (shape.value) {
2614 memoizedProperty(this, 'value', function() {
2615 return Shape.create(shape.value, options);
2616 });
2617 }
2618 }
2619
2620 function TimestampShape(shape) {
2621 var self = this;
2622 Shape.apply(this, arguments);
2623
2624 if (shape.timestampFormat) {
2625 property(this, 'timestampFormat', shape.timestampFormat);
2626 } else if (self.isTimestampFormatSet && this.timestampFormat) {
2627 property(this, 'timestampFormat', this.timestampFormat);
2628 } else if (this.location === 'header') {
2629 property(this, 'timestampFormat', 'rfc822');
2630 } else if (this.location === 'querystring') {
2631 property(this, 'timestampFormat', 'iso8601');
2632 } else if (this.api) {
2633 switch (this.api.protocol) {
2634 case 'json':
2635 case 'rest-json':
2636 property(this, 'timestampFormat', 'unixTimestamp');
2637 break;
2638 case 'rest-xml':
2639 case 'query':
2640 case 'ec2':
2641 property(this, 'timestampFormat', 'iso8601');
2642 break;
2643 }
2644 }
2645
2646 this.toType = function(value) {
2647 if (value === null || value === undefined) return null;
2648 if (typeof value.toUTCString === 'function') return value;
2649 return typeof value === 'string' || typeof value === 'number' ?
2650 util.date.parseTimestamp(value) : null;
2651 };
2652
2653 this.toWireFormat = function(value) {
2654 return util.date.format(value, self.timestampFormat);
2655 };
2656 }
2657
2658 function StringShape() {
2659 Shape.apply(this, arguments);
2660
2661 var nullLessProtocols = ['rest-xml', 'query', 'ec2'];
2662 this.toType = function(value) {
2663 value = this.api && nullLessProtocols.indexOf(this.api.protocol) > -1 ?
2664 value || '' : value;
2665 if (this.isJsonValue) {
2666 return JSON.parse(value);
2667 }
2668
2669 return value && typeof value.toString === 'function' ?
2670 value.toString() : value;
2671 };
2672
2673 this.toWireFormat = function(value) {
2674 return this.isJsonValue ? JSON.stringify(value) : value;
2675 };
2676 }
2677
2678 function FloatShape() {
2679 Shape.apply(this, arguments);
2680
2681 this.toType = function(value) {
2682 if (value === null || value === undefined) return null;
2683 return parseFloat(value);
2684 };
2685 this.toWireFormat = this.toType;
2686 }
2687
2688 function IntegerShape() {
2689 Shape.apply(this, arguments);
2690
2691 this.toType = function(value) {
2692 if (value === null || value === undefined) return null;
2693 return parseInt(value, 10);
2694 };
2695 this.toWireFormat = this.toType;
2696 }
2697
2698 function BinaryShape() {
2699 Shape.apply(this, arguments);
2700 this.toType = util.base64.decode;
2701 this.toWireFormat = util.base64.encode;
2702 }
2703
2704 function Base64Shape() {
2705 BinaryShape.apply(this, arguments);
2706 }
2707
2708 function BooleanShape() {
2709 Shape.apply(this, arguments);
2710
2711 this.toType = function(value) {
2712 if (typeof value === 'boolean') return value;
2713 if (value === null || value === undefined) return null;
2714 return value === 'true';
2715 };
2716 }
2717
2718 /**
2719 * @api private
2720 */
2721 Shape.shapes = {
2722 StructureShape: StructureShape,
2723 ListShape: ListShape,
2724 MapShape: MapShape,
2725 StringShape: StringShape,
2726 BooleanShape: BooleanShape,
2727 Base64Shape: Base64Shape
2728 };
2729
2730 /**
2731 * @api private
2732 */
2733 module.exports = Shape;
2734
2735
2736/***/ }),
2737/* 20 */
2738/***/ (function(module, exports, __webpack_require__) {
2739
2740 var memoizedProperty = __webpack_require__(2).memoizedProperty;
2741
2742 function memoize(name, value, factory, nameTr) {
2743 memoizedProperty(this, nameTr(name), function() {
2744 return factory(name, value);
2745 });
2746 }
2747
2748 function Collection(iterable, options, factory, nameTr, callback) {
2749 nameTr = nameTr || String;
2750 var self = this;
2751
2752 for (var id in iterable) {
2753 if (Object.prototype.hasOwnProperty.call(iterable, id)) {
2754 memoize.call(self, id, iterable[id], factory, nameTr);
2755 if (callback) callback(id, iterable[id]);
2756 }
2757 }
2758 }
2759
2760 /**
2761 * @api private
2762 */
2763 module.exports = Collection;
2764
2765
2766/***/ }),
2767/* 21 */
2768/***/ (function(module, exports, __webpack_require__) {
2769
2770 var util = __webpack_require__(2);
2771 var populateHostPrefix = __webpack_require__(16).populateHostPrefix;
2772
2773 function populateMethod(req) {
2774 req.httpRequest.method = req.service.api.operations[req.operation].httpMethod;
2775 }
2776
2777 function generateURI(endpointPath, operationPath, input, params) {
2778 var uri = [endpointPath, operationPath].join('/');
2779 uri = uri.replace(/\/+/g, '/');
2780
2781 var queryString = {}, queryStringSet = false;
2782 util.each(input.members, function (name, member) {
2783 var paramValue = params[name];
2784 if (paramValue === null || paramValue === undefined) return;
2785 if (member.location === 'uri') {
2786 var regex = new RegExp('\\{' + member.name + '(\\+)?\\}');
2787 uri = uri.replace(regex, function(_, plus) {
2788 var fn = plus ? util.uriEscapePath : util.uriEscape;
2789 return fn(String(paramValue));
2790 });
2791 } else if (member.location === 'querystring') {
2792 queryStringSet = true;
2793
2794 if (member.type === 'list') {
2795 queryString[member.name] = paramValue.map(function(val) {
2796 return util.uriEscape(member.member.toWireFormat(val).toString());
2797 });
2798 } else if (member.type === 'map') {
2799 util.each(paramValue, function(key, value) {
2800 if (Array.isArray(value)) {
2801 queryString[key] = value.map(function(val) {
2802 return util.uriEscape(String(val));
2803 });
2804 } else {
2805 queryString[key] = util.uriEscape(String(value));
2806 }
2807 });
2808 } else {
2809 queryString[member.name] = util.uriEscape(member.toWireFormat(paramValue).toString());
2810 }
2811 }
2812 });
2813
2814 if (queryStringSet) {
2815 uri += (uri.indexOf('?') >= 0 ? '&' : '?');
2816 var parts = [];
2817 util.arrayEach(Object.keys(queryString).sort(), function(key) {
2818 if (!Array.isArray(queryString[key])) {
2819 queryString[key] = [queryString[key]];
2820 }
2821 for (var i = 0; i < queryString[key].length; i++) {
2822 parts.push(util.uriEscape(String(key)) + '=' + queryString[key][i]);
2823 }
2824 });
2825 uri += parts.join('&');
2826 }
2827
2828 return uri;
2829 }
2830
2831 function populateURI(req) {
2832 var operation = req.service.api.operations[req.operation];
2833 var input = operation.input;
2834
2835 var uri = generateURI(req.httpRequest.endpoint.path, operation.httpPath, input, req.params);
2836 req.httpRequest.path = uri;
2837 }
2838
2839 function populateHeaders(req) {
2840 var operation = req.service.api.operations[req.operation];
2841 util.each(operation.input.members, function (name, member) {
2842 var value = req.params[name];
2843 if (value === null || value === undefined) return;
2844
2845 if (member.location === 'headers' && member.type === 'map') {
2846 util.each(value, function(key, memberValue) {
2847 req.httpRequest.headers[member.name + key] = memberValue;
2848 });
2849 } else if (member.location === 'header') {
2850 value = member.toWireFormat(value).toString();
2851 if (member.isJsonValue) {
2852 value = util.base64.encode(value);
2853 }
2854 req.httpRequest.headers[member.name] = value;
2855 }
2856 });
2857 }
2858
2859 function buildRequest(req) {
2860 populateMethod(req);
2861 populateURI(req);
2862 populateHeaders(req);
2863 populateHostPrefix(req);
2864 }
2865
2866 function extractError() {
2867 }
2868
2869 function extractData(resp) {
2870 var req = resp.request;
2871 var data = {};
2872 var r = resp.httpResponse;
2873 var operation = req.service.api.operations[req.operation];
2874 var output = operation.output;
2875
2876 // normalize headers names to lower-cased keys for matching
2877 var headers = {};
2878 util.each(r.headers, function (k, v) {
2879 headers[k.toLowerCase()] = v;
2880 });
2881
2882 util.each(output.members, function(name, member) {
2883 var header = (member.name || name).toLowerCase();
2884 if (member.location === 'headers' && member.type === 'map') {
2885 data[name] = {};
2886 var location = member.isLocationName ? member.name : '';
2887 var pattern = new RegExp('^' + location + '(.+)', 'i');
2888 util.each(r.headers, function (k, v) {
2889 var result = k.match(pattern);
2890 if (result !== null) {
2891 data[name][result[1]] = v;
2892 }
2893 });
2894 } else if (member.location === 'header') {
2895 if (headers[header] !== undefined) {
2896 var value = member.isJsonValue ?
2897 util.base64.decode(headers[header]) :
2898 headers[header];
2899 data[name] = member.toType(value);
2900 }
2901 } else if (member.location === 'statusCode') {
2902 data[name] = parseInt(r.statusCode, 10);
2903 }
2904 });
2905
2906 resp.data = data;
2907 }
2908
2909 /**
2910 * @api private
2911 */
2912 module.exports = {
2913 buildRequest: buildRequest,
2914 extractError: extractError,
2915 extractData: extractData,
2916 generateURI: generateURI
2917 };
2918
2919
2920/***/ }),
2921/* 22 */
2922/***/ (function(module, exports, __webpack_require__) {
2923
2924 var util = __webpack_require__(2);
2925 var Rest = __webpack_require__(21);
2926 var Json = __webpack_require__(13);
2927 var JsonBuilder = __webpack_require__(14);
2928 var JsonParser = __webpack_require__(15);
2929
2930 function populateBody(req) {
2931 var builder = new JsonBuilder();
2932 var input = req.service.api.operations[req.operation].input;
2933
2934 if (input.payload) {
2935 var params = {};
2936 var payloadShape = input.members[input.payload];
2937 params = req.params[input.payload];
2938 if (params === undefined) return;
2939
2940 if (payloadShape.type === 'structure') {
2941 req.httpRequest.body = builder.build(params, payloadShape);
2942 applyContentTypeHeader(req);
2943 } else { // non-JSON payload
2944 req.httpRequest.body = params;
2945 if (payloadShape.type === 'binary' || payloadShape.isStreaming) {
2946 applyContentTypeHeader(req, true);
2947 }
2948 }
2949 } else {
2950 var body = builder.build(req.params, input);
2951 if (body !== '{}' || req.httpRequest.method !== 'GET') { //don't send empty body for GET method
2952 req.httpRequest.body = body;
2953 }
2954 applyContentTypeHeader(req);
2955 }
2956 }
2957
2958 function applyContentTypeHeader(req, isBinary) {
2959 var operation = req.service.api.operations[req.operation];
2960 var input = operation.input;
2961
2962 if (!req.httpRequest.headers['Content-Type']) {
2963 var type = isBinary ? 'binary/octet-stream' : 'application/json';
2964 req.httpRequest.headers['Content-Type'] = type;
2965 }
2966 }
2967
2968 function buildRequest(req) {
2969 Rest.buildRequest(req);
2970
2971 // never send body payload on HEAD/DELETE
2972 if (['HEAD', 'DELETE'].indexOf(req.httpRequest.method) < 0) {
2973 populateBody(req);
2974 }
2975 }
2976
2977 function extractError(resp) {
2978 Json.extractError(resp);
2979 }
2980
2981 function extractData(resp) {
2982 Rest.extractData(resp);
2983
2984 var req = resp.request;
2985 var operation = req.service.api.operations[req.operation];
2986 var rules = req.service.api.operations[req.operation].output || {};
2987 var parser;
2988 var hasEventOutput = operation.hasEventOutput;
2989
2990 if (rules.payload) {
2991 var payloadMember = rules.members[rules.payload];
2992 var body = resp.httpResponse.body;
2993 if (payloadMember.isEventStream) {
2994 parser = new JsonParser();
2995 resp.data[payload] = util.createEventStream(
2996 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : body,
2997 parser,
2998 payloadMember
2999 );
3000 } else if (payloadMember.type === 'structure' || payloadMember.type === 'list') {
3001 var parser = new JsonParser();
3002 resp.data[rules.payload] = parser.parse(body, payloadMember);
3003 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3004 resp.data[rules.payload] = body;
3005 } else {
3006 resp.data[rules.payload] = payloadMember.toType(body);
3007 }
3008 } else {
3009 var data = resp.data;
3010 Json.extractData(resp);
3011 resp.data = util.merge(data, resp.data);
3012 }
3013 }
3014
3015 /**
3016 * @api private
3017 */
3018 module.exports = {
3019 buildRequest: buildRequest,
3020 extractError: extractError,
3021 extractData: extractData
3022 };
3023
3024
3025/***/ }),
3026/* 23 */
3027/***/ (function(module, exports, __webpack_require__) {
3028
3029 var AWS = __webpack_require__(1);
3030 var util = __webpack_require__(2);
3031 var Rest = __webpack_require__(21);
3032
3033 function populateBody(req) {
3034 var input = req.service.api.operations[req.operation].input;
3035 var builder = new AWS.XML.Builder();
3036 var params = req.params;
3037
3038 var payload = input.payload;
3039 if (payload) {
3040 var payloadMember = input.members[payload];
3041 params = params[payload];
3042 if (params === undefined) return;
3043
3044 if (payloadMember.type === 'structure') {
3045 var rootElement = payloadMember.name;
3046 req.httpRequest.body = builder.toXML(params, payloadMember, rootElement, true);
3047 } else { // non-xml payload
3048 req.httpRequest.body = params;
3049 }
3050 } else {
3051 req.httpRequest.body = builder.toXML(params, input, input.name ||
3052 input.shape || util.string.upperFirst(req.operation) + 'Request');
3053 }
3054 }
3055
3056 function buildRequest(req) {
3057 Rest.buildRequest(req);
3058
3059 // never send body payload on GET/HEAD
3060 if (['GET', 'HEAD'].indexOf(req.httpRequest.method) < 0) {
3061 populateBody(req);
3062 }
3063 }
3064
3065 function extractError(resp) {
3066 Rest.extractError(resp);
3067
3068 var data;
3069 try {
3070 data = new AWS.XML.Parser().parse(resp.httpResponse.body.toString());
3071 } catch (e) {
3072 data = {
3073 Code: resp.httpResponse.statusCode,
3074 Message: resp.httpResponse.statusMessage
3075 };
3076 }
3077
3078 if (data.Errors) data = data.Errors;
3079 if (data.Error) data = data.Error;
3080 if (data.Code) {
3081 resp.error = util.error(new Error(), {
3082 code: data.Code,
3083 message: data.Message
3084 });
3085 } else {
3086 resp.error = util.error(new Error(), {
3087 code: resp.httpResponse.statusCode,
3088 message: null
3089 });
3090 }
3091 }
3092
3093 function extractData(resp) {
3094 Rest.extractData(resp);
3095
3096 var parser;
3097 var req = resp.request;
3098 var body = resp.httpResponse.body;
3099 var operation = req.service.api.operations[req.operation];
3100 var output = operation.output;
3101
3102 var hasEventOutput = operation.hasEventOutput;
3103
3104 var payload = output.payload;
3105 if (payload) {
3106 var payloadMember = output.members[payload];
3107 if (payloadMember.isEventStream) {
3108 parser = new AWS.XML.Parser();
3109 resp.data[payload] = util.createEventStream(
3110 AWS.HttpClient.streamsApiVersion === 2 ? resp.httpResponse.stream : resp.httpResponse.body,
3111 parser,
3112 payloadMember
3113 );
3114 } else if (payloadMember.type === 'structure') {
3115 parser = new AWS.XML.Parser();
3116 resp.data[payload] = parser.parse(body.toString(), payloadMember);
3117 } else if (payloadMember.type === 'binary' || payloadMember.isStreaming) {
3118 resp.data[payload] = body;
3119 } else {
3120 resp.data[payload] = payloadMember.toType(body);
3121 }
3122 } else if (body.length > 0) {
3123 parser = new AWS.XML.Parser();
3124 var data = parser.parse(body.toString(), output);
3125 util.update(resp.data, data);
3126 }
3127 }
3128
3129 /**
3130 * @api private
3131 */
3132 module.exports = {
3133 buildRequest: buildRequest,
3134 extractError: extractError,
3135 extractData: extractData
3136 };
3137
3138
3139/***/ }),
3140/* 24 */
3141/***/ (function(module, exports, __webpack_require__) {
3142
3143 var util = __webpack_require__(2);
3144 var XmlNode = __webpack_require__(25).XmlNode;
3145 var XmlText = __webpack_require__(27).XmlText;
3146
3147 function XmlBuilder() { }
3148
3149 XmlBuilder.prototype.toXML = function(params, shape, rootElement, noEmpty) {
3150 var xml = new XmlNode(rootElement);
3151 applyNamespaces(xml, shape, true);
3152 serialize(xml, params, shape);
3153 return xml.children.length > 0 || noEmpty ? xml.toString() : '';
3154 };
3155
3156 function serialize(xml, value, shape) {
3157 switch (shape.type) {
3158 case 'structure': return serializeStructure(xml, value, shape);
3159 case 'map': return serializeMap(xml, value, shape);
3160 case 'list': return serializeList(xml, value, shape);
3161 default: return serializeScalar(xml, value, shape);
3162 }
3163 }
3164
3165 function serializeStructure(xml, params, shape) {
3166 util.arrayEach(shape.memberNames, function(memberName) {
3167 var memberShape = shape.members[memberName];
3168 if (memberShape.location !== 'body') return;
3169
3170 var value = params[memberName];
3171 var name = memberShape.name;
3172 if (value !== undefined && value !== null) {
3173 if (memberShape.isXmlAttribute) {
3174 xml.addAttribute(name, value);
3175 } else if (memberShape.flattened) {
3176 serialize(xml, value, memberShape);
3177 } else {
3178 var element = new XmlNode(name);
3179 xml.addChildNode(element);
3180 applyNamespaces(element, memberShape);
3181 serialize(element, value, memberShape);
3182 }
3183 }
3184 });
3185 }
3186
3187 function serializeMap(xml, map, shape) {
3188 var xmlKey = shape.key.name || 'key';
3189 var xmlValue = shape.value.name || 'value';
3190
3191 util.each(map, function(key, value) {
3192 var entry = new XmlNode(shape.flattened ? shape.name : 'entry');
3193 xml.addChildNode(entry);
3194
3195 var entryKey = new XmlNode(xmlKey);
3196 var entryValue = new XmlNode(xmlValue);
3197 entry.addChildNode(entryKey);
3198 entry.addChildNode(entryValue);
3199
3200 serialize(entryKey, key, shape.key);
3201 serialize(entryValue, value, shape.value);
3202 });
3203 }
3204
3205 function serializeList(xml, list, shape) {
3206 if (shape.flattened) {
3207 util.arrayEach(list, function(value) {
3208 var name = shape.member.name || shape.name;
3209 var element = new XmlNode(name);
3210 xml.addChildNode(element);
3211 serialize(element, value, shape.member);
3212 });
3213 } else {
3214 util.arrayEach(list, function(value) {
3215 var name = shape.member.name || 'member';
3216 var element = new XmlNode(name);
3217 xml.addChildNode(element);
3218 serialize(element, value, shape.member);
3219 });
3220 }
3221 }
3222
3223 function serializeScalar(xml, value, shape) {
3224 xml.addChildNode(
3225 new XmlText(shape.toWireFormat(value))
3226 );
3227 }
3228
3229 function applyNamespaces(xml, shape, isRoot) {
3230 var uri, prefix = 'xmlns';
3231 if (shape.xmlNamespaceUri) {
3232 uri = shape.xmlNamespaceUri;
3233 if (shape.xmlNamespacePrefix) prefix += ':' + shape.xmlNamespacePrefix;
3234 } else if (isRoot && shape.api.xmlNamespaceUri) {
3235 uri = shape.api.xmlNamespaceUri;
3236 }
3237
3238 if (uri) xml.addAttribute(prefix, uri);
3239 }
3240
3241 /**
3242 * @api private
3243 */
3244 module.exports = XmlBuilder;
3245
3246
3247/***/ }),
3248/* 25 */
3249/***/ (function(module, exports, __webpack_require__) {
3250
3251 var escapeAttribute = __webpack_require__(26).escapeAttribute;
3252
3253 /**
3254 * Represents an XML node.
3255 * @api private
3256 */
3257 function XmlNode(name, children) {
3258 if (children === void 0) { children = []; }
3259 this.name = name;
3260 this.children = children;
3261 this.attributes = {};
3262 }
3263 XmlNode.prototype.addAttribute = function (name, value) {
3264 this.attributes[name] = value;
3265 return this;
3266 };
3267 XmlNode.prototype.addChildNode = function (child) {
3268 this.children.push(child);
3269 return this;
3270 };
3271 XmlNode.prototype.removeAttribute = function (name) {
3272 delete this.attributes[name];
3273 return this;
3274 };
3275 XmlNode.prototype.toString = function () {
3276 var hasChildren = Boolean(this.children.length);
3277 var xmlText = '<' + this.name;
3278 // add attributes
3279 var attributes = this.attributes;
3280 for (var i = 0, attributeNames = Object.keys(attributes); i < attributeNames.length; i++) {
3281 var attributeName = attributeNames[i];
3282 var attribute = attributes[attributeName];
3283 if (typeof attribute !== 'undefined' && attribute !== null) {
3284 xmlText += ' ' + attributeName + '=\"' + escapeAttribute('' + attribute) + '\"';
3285 }
3286 }
3287 return xmlText += !hasChildren ? '/>' : '>' + this.children.map(function (c) { return c.toString(); }).join('') + '</' + this.name + '>';
3288 };
3289
3290 /**
3291 * @api private
3292 */
3293 module.exports = {
3294 XmlNode: XmlNode
3295 };
3296
3297
3298/***/ }),
3299/* 26 */
3300/***/ (function(module, exports) {
3301
3302 /**
3303 * Escapes characters that can not be in an XML attribute.
3304 */
3305 function escapeAttribute(value) {
3306 return value.replace(/&/g, '&amp;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
3307 }
3308
3309 /**
3310 * @api private
3311 */
3312 module.exports = {
3313 escapeAttribute: escapeAttribute
3314 };
3315
3316
3317/***/ }),
3318/* 27 */
3319/***/ (function(module, exports, __webpack_require__) {
3320
3321 var escapeElement = __webpack_require__(28).escapeElement;
3322
3323 /**
3324 * Represents an XML text value.
3325 * @api private
3326 */
3327 function XmlText(value) {
3328 this.value = value;
3329 }
3330
3331 XmlText.prototype.toString = function () {
3332 return escapeElement('' + this.value);
3333 };
3334
3335 /**
3336 * @api private
3337 */
3338 module.exports = {
3339 XmlText: XmlText
3340 };
3341
3342
3343/***/ }),
3344/* 28 */
3345/***/ (function(module, exports) {
3346
3347 /**
3348 * Escapes characters that can not be in an XML element.
3349 */
3350 function escapeElement(value) {
3351 return value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
3352 }
3353
3354 /**
3355 * @api private
3356 */
3357 module.exports = {
3358 escapeElement: escapeElement
3359 };
3360
3361
3362/***/ }),
3363/* 29 */
3364/***/ (function(module, exports, __webpack_require__) {
3365
3366 var Collection = __webpack_require__(20);
3367 var Operation = __webpack_require__(30);
3368 var Shape = __webpack_require__(19);
3369 var Paginator = __webpack_require__(31);
3370 var ResourceWaiter = __webpack_require__(32);
3371
3372 var util = __webpack_require__(2);
3373 var property = util.property;
3374 var memoizedProperty = util.memoizedProperty;
3375
3376 function Api(api, options) {
3377 var self = this;
3378 api = api || {};
3379 options = options || {};
3380 options.api = this;
3381
3382 api.metadata = api.metadata || {};
3383
3384 property(this, 'isApi', true, false);
3385 property(this, 'apiVersion', api.metadata.apiVersion);
3386 property(this, 'endpointPrefix', api.metadata.endpointPrefix);
3387 property(this, 'signingName', api.metadata.signingName);
3388 property(this, 'globalEndpoint', api.metadata.globalEndpoint);
3389 property(this, 'signatureVersion', api.metadata.signatureVersion);
3390 property(this, 'jsonVersion', api.metadata.jsonVersion);
3391 property(this, 'targetPrefix', api.metadata.targetPrefix);
3392 property(this, 'protocol', api.metadata.protocol);
3393 property(this, 'timestampFormat', api.metadata.timestampFormat);
3394 property(this, 'xmlNamespaceUri', api.metadata.xmlNamespace);
3395 property(this, 'abbreviation', api.metadata.serviceAbbreviation);
3396 property(this, 'fullName', api.metadata.serviceFullName);
3397 property(this, 'serviceId', api.metadata.serviceId);
3398
3399 memoizedProperty(this, 'className', function() {
3400 var name = api.metadata.serviceAbbreviation || api.metadata.serviceFullName;
3401 if (!name) return null;
3402
3403 name = name.replace(/^Amazon|AWS\s*|\(.*|\s+|\W+/g, '');
3404 if (name === 'ElasticLoadBalancing') name = 'ELB';
3405 return name;
3406 });
3407
3408 function addEndpointOperation(name, operation) {
3409 if (operation.endpointoperation === true) {
3410 property(self, 'endpointOperation', util.string.lowerFirst(name));
3411 }
3412 }
3413
3414 property(this, 'operations', new Collection(api.operations, options, function(name, operation) {
3415 return new Operation(name, operation, options);
3416 }, util.string.lowerFirst, addEndpointOperation));
3417
3418 property(this, 'shapes', new Collection(api.shapes, options, function(name, shape) {
3419 return Shape.create(shape, options);
3420 }));
3421
3422 property(this, 'paginators', new Collection(api.paginators, options, function(name, paginator) {
3423 return new Paginator(name, paginator, options);
3424 }));
3425
3426 property(this, 'waiters', new Collection(api.waiters, options, function(name, waiter) {
3427 return new ResourceWaiter(name, waiter, options);
3428 }, util.string.lowerFirst));
3429
3430 if (options.documentation) {
3431 property(this, 'documentation', api.documentation);
3432 property(this, 'documentationUrl', api.documentationUrl);
3433 }
3434 }
3435
3436 /**
3437 * @api private
3438 */
3439 module.exports = Api;
3440
3441
3442/***/ }),
3443/* 30 */
3444/***/ (function(module, exports, __webpack_require__) {
3445
3446 var Shape = __webpack_require__(19);
3447
3448 var util = __webpack_require__(2);
3449 var property = util.property;
3450 var memoizedProperty = util.memoizedProperty;
3451
3452 function Operation(name, operation, options) {
3453 var self = this;
3454 options = options || {};
3455
3456 property(this, 'name', operation.name || name);
3457 property(this, 'api', options.api, false);
3458
3459 operation.http = operation.http || {};
3460 property(this, 'endpoint', operation.endpoint);
3461 property(this, 'httpMethod', operation.http.method || 'POST');
3462 property(this, 'httpPath', operation.http.requestUri || '/');
3463 property(this, 'authtype', operation.authtype || '');
3464 property(
3465 this,
3466 'endpointDiscoveryRequired',
3467 operation.endpointdiscovery ?
3468 (operation.endpointdiscovery.required ? 'REQUIRED' : 'OPTIONAL') :
3469 'NULL'
3470 );
3471
3472 memoizedProperty(this, 'input', function() {
3473 if (!operation.input) {
3474 return new Shape.create({type: 'structure'}, options);
3475 }
3476 return Shape.create(operation.input, options);
3477 });
3478
3479 memoizedProperty(this, 'output', function() {
3480 if (!operation.output) {
3481 return new Shape.create({type: 'structure'}, options);
3482 }
3483 return Shape.create(operation.output, options);
3484 });
3485
3486 memoizedProperty(this, 'errors', function() {
3487 var list = [];
3488 if (!operation.errors) return null;
3489
3490 for (var i = 0; i < operation.errors.length; i++) {
3491 list.push(Shape.create(operation.errors[i], options));
3492 }
3493
3494 return list;
3495 });
3496
3497 memoizedProperty(this, 'paginator', function() {
3498 return options.api.paginators[name];
3499 });
3500
3501 if (options.documentation) {
3502 property(this, 'documentation', operation.documentation);
3503 property(this, 'documentationUrl', operation.documentationUrl);
3504 }
3505
3506 // idempotentMembers only tracks top-level input shapes
3507 memoizedProperty(this, 'idempotentMembers', function() {
3508 var idempotentMembers = [];
3509 var input = self.input;
3510 var members = input.members;
3511 if (!input.members) {
3512 return idempotentMembers;
3513 }
3514 for (var name in members) {
3515 if (!members.hasOwnProperty(name)) {
3516 continue;
3517 }
3518 if (members[name].isIdempotent === true) {
3519 idempotentMembers.push(name);
3520 }
3521 }
3522 return idempotentMembers;
3523 });
3524
3525 memoizedProperty(this, 'hasEventOutput', function() {
3526 var output = self.output;
3527 return hasEventStream(output);
3528 });
3529 }
3530
3531 function hasEventStream(topLevelShape) {
3532 var members = topLevelShape.members;
3533 var payload = topLevelShape.payload;
3534
3535 if (!topLevelShape.members) {
3536 return false;
3537 }
3538
3539 if (payload) {
3540 var payloadMember = members[payload];
3541 return payloadMember.isEventStream;
3542 }
3543
3544 // check if any member is an event stream
3545 for (var name in members) {
3546 if (!members.hasOwnProperty(name)) {
3547 if (members[name].isEventStream === true) {
3548 return true;
3549 }
3550 }
3551 }
3552 return false;
3553 }
3554
3555 /**
3556 * @api private
3557 */
3558 module.exports = Operation;
3559
3560
3561/***/ }),
3562/* 31 */
3563/***/ (function(module, exports, __webpack_require__) {
3564
3565 var property = __webpack_require__(2).property;
3566
3567 function Paginator(name, paginator) {
3568 property(this, 'inputToken', paginator.input_token);
3569 property(this, 'limitKey', paginator.limit_key);
3570 property(this, 'moreResults', paginator.more_results);
3571 property(this, 'outputToken', paginator.output_token);
3572 property(this, 'resultKey', paginator.result_key);
3573 }
3574
3575 /**
3576 * @api private
3577 */
3578 module.exports = Paginator;
3579
3580
3581/***/ }),
3582/* 32 */
3583/***/ (function(module, exports, __webpack_require__) {
3584
3585 var util = __webpack_require__(2);
3586 var property = util.property;
3587
3588 function ResourceWaiter(name, waiter, options) {
3589 options = options || {};
3590 property(this, 'name', name);
3591 property(this, 'api', options.api, false);
3592
3593 if (waiter.operation) {
3594 property(this, 'operation', util.string.lowerFirst(waiter.operation));
3595 }
3596
3597 var self = this;
3598 var keys = [
3599 'type',
3600 'description',
3601 'delay',
3602 'maxAttempts',
3603 'acceptors'
3604 ];
3605
3606 keys.forEach(function(key) {
3607 var value = waiter[key];
3608 if (value) {
3609 property(self, key, value);
3610 }
3611 });
3612 }
3613
3614 /**
3615 * @api private
3616 */
3617 module.exports = ResourceWaiter;
3618
3619
3620/***/ }),
3621/* 33 */
3622/***/ (function(module, exports) {
3623
3624 function apiLoader(svc, version) {
3625 if (!apiLoader.services.hasOwnProperty(svc)) {
3626 throw new Error('InvalidService: Failed to load api for ' + svc);
3627 }
3628 return apiLoader.services[svc][version];
3629 }
3630
3631 /**
3632 * @api private
3633 *
3634 * This member of AWS.apiLoader is private, but changing it will necessitate a
3635 * change to ../scripts/services-table-generator.ts
3636 */
3637 apiLoader.services = {};
3638
3639 /**
3640 * @api private
3641 */
3642 module.exports = apiLoader;
3643
3644
3645/***/ }),
3646/* 34 */
3647/***/ (function(module, exports, __webpack_require__) {
3648
3649 "use strict";
3650 Object.defineProperty(exports, "__esModule", { value: true });
3651 var LRU_1 = __webpack_require__(35);
3652 var CACHE_SIZE = 1000;
3653 /**
3654 * Inspired node-lru-cache[https://github.com/isaacs/node-lru-cache]
3655 */
3656 var EndpointCache = /** @class */ (function () {
3657 function EndpointCache(maxSize) {
3658 if (maxSize === void 0) { maxSize = CACHE_SIZE; }
3659 this.maxSize = maxSize;
3660 this.cache = new LRU_1.LRUCache(maxSize);
3661 }
3662 ;
3663 Object.defineProperty(EndpointCache.prototype, "size", {
3664 get: function () {
3665 return this.cache.length;
3666 },
3667 enumerable: true,
3668 configurable: true
3669 });
3670 EndpointCache.prototype.put = function (key, value) {
3671 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3672 var endpointRecord = this.populateValue(value);
3673 this.cache.put(keyString, endpointRecord);
3674 };
3675 EndpointCache.prototype.get = function (key) {
3676 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3677 var now = Date.now();
3678 var records = this.cache.get(keyString);
3679 if (records) {
3680 for (var i = 0; i < records.length; i++) {
3681 var record = records[i];
3682 if (record.Expire < now) {
3683 this.cache.remove(keyString);
3684 return undefined;
3685 }
3686 }
3687 }
3688 return records;
3689 };
3690 EndpointCache.getKeyString = function (key) {
3691 var identifiers = [];
3692 var identifierNames = Object.keys(key).sort();
3693 for (var i = 0; i < identifierNames.length; i++) {
3694 var identifierName = identifierNames[i];
3695 if (key[identifierName] === undefined)
3696 continue;
3697 identifiers.push(key[identifierName]);
3698 }
3699 return identifiers.join(' ');
3700 };
3701 EndpointCache.prototype.populateValue = function (endpoints) {
3702 var now = Date.now();
3703 return endpoints.map(function (endpoint) { return ({
3704 Address: endpoint.Address || '',
3705 Expire: now + (endpoint.CachePeriodInMinutes || 1) * 60 * 1000
3706 }); });
3707 };
3708 EndpointCache.prototype.empty = function () {
3709 this.cache.empty();
3710 };
3711 EndpointCache.prototype.remove = function (key) {
3712 var keyString = typeof key !== 'string' ? EndpointCache.getKeyString(key) : key;
3713 this.cache.remove(keyString);
3714 };
3715 return EndpointCache;
3716 }());
3717 exports.EndpointCache = EndpointCache;
3718
3719/***/ }),
3720/* 35 */
3721/***/ (function(module, exports) {
3722
3723 "use strict";
3724 Object.defineProperty(exports, "__esModule", { value: true });
3725 var LinkedListNode = /** @class */ (function () {
3726 function LinkedListNode(key, value) {
3727 this.key = key;
3728 this.value = value;
3729 }
3730 return LinkedListNode;
3731 }());
3732 var LRUCache = /** @class */ (function () {
3733 function LRUCache(size) {
3734 this.nodeMap = {};
3735 this.size = 0;
3736 if (typeof size !== 'number' || size < 1) {
3737 throw new Error('Cache size can only be positive number');
3738 }
3739 this.sizeLimit = size;
3740 }
3741 Object.defineProperty(LRUCache.prototype, "length", {
3742 get: function () {
3743 return this.size;
3744 },
3745 enumerable: true,
3746 configurable: true
3747 });
3748 LRUCache.prototype.prependToList = function (node) {
3749 if (!this.headerNode) {
3750 this.tailNode = node;
3751 }
3752 else {
3753 this.headerNode.prev = node;
3754 node.next = this.headerNode;
3755 }
3756 this.headerNode = node;
3757 this.size++;
3758 };
3759 LRUCache.prototype.removeFromTail = function () {
3760 if (!this.tailNode) {
3761 return undefined;
3762 }
3763 var node = this.tailNode;
3764 var prevNode = node.prev;
3765 if (prevNode) {
3766 prevNode.next = undefined;
3767 }
3768 node.prev = undefined;
3769 this.tailNode = prevNode;
3770 this.size--;
3771 return node;
3772 };
3773 LRUCache.prototype.detachFromList = function (node) {
3774 if (this.headerNode === node) {
3775 this.headerNode = node.next;
3776 }
3777 if (this.tailNode === node) {
3778 this.tailNode = node.prev;
3779 }
3780 if (node.prev) {
3781 node.prev.next = node.next;
3782 }
3783 if (node.next) {
3784 node.next.prev = node.prev;
3785 }
3786 node.next = undefined;
3787 node.prev = undefined;
3788 this.size--;
3789 };
3790 LRUCache.prototype.get = function (key) {
3791 if (this.nodeMap[key]) {
3792 var node = this.nodeMap[key];
3793 this.detachFromList(node);
3794 this.prependToList(node);
3795 return node.value;
3796 }
3797 };
3798 LRUCache.prototype.remove = function (key) {
3799 if (this.nodeMap[key]) {
3800 var node = this.nodeMap[key];
3801 this.detachFromList(node);
3802 delete this.nodeMap[key];
3803 }
3804 };
3805 LRUCache.prototype.put = function (key, value) {
3806 if (this.nodeMap[key]) {
3807 this.remove(key);
3808 }
3809 else if (this.size === this.sizeLimit) {
3810 var tailNode = this.removeFromTail();
3811 var key_1 = tailNode.key;
3812 delete this.nodeMap[key_1];
3813 }
3814 var newNode = new LinkedListNode(key, value);
3815 this.nodeMap[key] = newNode;
3816 this.prependToList(newNode);
3817 };
3818 LRUCache.prototype.empty = function () {
3819 var keys = Object.keys(this.nodeMap);
3820 for (var i = 0; i < keys.length; i++) {
3821 var key = keys[i];
3822 var node = this.nodeMap[key];
3823 this.detachFromList(node);
3824 delete this.nodeMap[key];
3825 }
3826 };
3827 return LRUCache;
3828 }());
3829 exports.LRUCache = LRUCache;
3830
3831/***/ }),
3832/* 36 */
3833/***/ (function(module, exports, __webpack_require__) {
3834
3835 var AWS = __webpack_require__(1);
3836
3837 /**
3838 * @api private
3839 * @!method on(eventName, callback)
3840 * Registers an event listener callback for the event given by `eventName`.
3841 * Parameters passed to the callback function depend on the individual event
3842 * being triggered. See the event documentation for those parameters.
3843 *
3844 * @param eventName [String] the event name to register the listener for
3845 * @param callback [Function] the listener callback function
3846 * @param toHead [Boolean] attach the listener callback to the head of callback array if set to true.
3847 * Default to be false.
3848 * @return [AWS.SequentialExecutor] the same object for chaining
3849 */
3850 AWS.SequentialExecutor = AWS.util.inherit({
3851
3852 constructor: function SequentialExecutor() {
3853 this._events = {};
3854 },
3855
3856 /**
3857 * @api private
3858 */
3859 listeners: function listeners(eventName) {
3860 return this._events[eventName] ? this._events[eventName].slice(0) : [];
3861 },
3862
3863 on: function on(eventName, listener, toHead) {
3864 if (this._events[eventName]) {
3865 toHead ?
3866 this._events[eventName].unshift(listener) :
3867 this._events[eventName].push(listener);
3868 } else {
3869 this._events[eventName] = [listener];
3870 }
3871 return this;
3872 },
3873
3874 onAsync: function onAsync(eventName, listener, toHead) {
3875 listener._isAsync = true;
3876 return this.on(eventName, listener, toHead);
3877 },
3878
3879 removeListener: function removeListener(eventName, listener) {
3880 var listeners = this._events[eventName];
3881 if (listeners) {
3882 var length = listeners.length;
3883 var position = -1;
3884 for (var i = 0; i < length; ++i) {
3885 if (listeners[i] === listener) {
3886 position = i;
3887 }
3888 }
3889 if (position > -1) {
3890 listeners.splice(position, 1);
3891 }
3892 }
3893 return this;
3894 },
3895
3896 removeAllListeners: function removeAllListeners(eventName) {
3897 if (eventName) {
3898 delete this._events[eventName];
3899 } else {
3900 this._events = {};
3901 }
3902 return this;
3903 },
3904
3905 /**
3906 * @api private
3907 */
3908 emit: function emit(eventName, eventArgs, doneCallback) {
3909 if (!doneCallback) doneCallback = function() { };
3910 var listeners = this.listeners(eventName);
3911 var count = listeners.length;
3912 this.callListeners(listeners, eventArgs, doneCallback);
3913 return count > 0;
3914 },
3915
3916 /**
3917 * @api private
3918 */
3919 callListeners: function callListeners(listeners, args, doneCallback, prevError) {
3920 var self = this;
3921 var error = prevError || null;
3922
3923 function callNextListener(err) {
3924 if (err) {
3925 error = AWS.util.error(error || new Error(), err);
3926 if (self._haltHandlersOnError) {
3927 return doneCallback.call(self, error);
3928 }
3929 }
3930 self.callListeners(listeners, args, doneCallback, error);
3931 }
3932
3933 while (listeners.length > 0) {
3934 var listener = listeners.shift();
3935 if (listener._isAsync) { // asynchronous listener
3936 listener.apply(self, args.concat([callNextListener]));
3937 return; // stop here, callNextListener will continue
3938 } else { // synchronous listener
3939 try {
3940 listener.apply(self, args);
3941 } catch (err) {
3942 error = AWS.util.error(error || new Error(), err);
3943 }
3944 if (error && self._haltHandlersOnError) {
3945 doneCallback.call(self, error);
3946 return;
3947 }
3948 }
3949 }
3950 doneCallback.call(self, error);
3951 },
3952
3953 /**
3954 * Adds or copies a set of listeners from another list of
3955 * listeners or SequentialExecutor object.
3956 *
3957 * @param listeners [map<String,Array<Function>>, AWS.SequentialExecutor]
3958 * a list of events and callbacks, or an event emitter object
3959 * containing listeners to add to this emitter object.
3960 * @return [AWS.SequentialExecutor] the emitter object, for chaining.
3961 * @example Adding listeners from a map of listeners
3962 * emitter.addListeners({
3963 * event1: [function() { ... }, function() { ... }],
3964 * event2: [function() { ... }]
3965 * });
3966 * emitter.emit('event1'); // emitter has event1
3967 * emitter.emit('event2'); // emitter has event2
3968 * @example Adding listeners from another emitter object
3969 * var emitter1 = new AWS.SequentialExecutor();
3970 * emitter1.on('event1', function() { ... });
3971 * emitter1.on('event2', function() { ... });
3972 * var emitter2 = new AWS.SequentialExecutor();
3973 * emitter2.addListeners(emitter1);
3974 * emitter2.emit('event1'); // emitter2 has event1
3975 * emitter2.emit('event2'); // emitter2 has event2
3976 */
3977 addListeners: function addListeners(listeners) {
3978 var self = this;
3979
3980 // extract listeners if parameter is an SequentialExecutor object
3981 if (listeners._events) listeners = listeners._events;
3982
3983 AWS.util.each(listeners, function(event, callbacks) {
3984 if (typeof callbacks === 'function') callbacks = [callbacks];
3985 AWS.util.arrayEach(callbacks, function(callback) {
3986 self.on(event, callback);
3987 });
3988 });
3989
3990 return self;
3991 },
3992
3993 /**
3994 * Registers an event with {on} and saves the callback handle function
3995 * as a property on the emitter object using a given `name`.
3996 *
3997 * @param name [String] the property name to set on this object containing
3998 * the callback function handle so that the listener can be removed in
3999 * the future.
4000 * @param (see on)
4001 * @return (see on)
4002 * @example Adding a named listener DATA_CALLBACK
4003 * var listener = function() { doSomething(); };
4004 * emitter.addNamedListener('DATA_CALLBACK', 'data', listener);
4005 *
4006 * // the following prints: true
4007 * console.log(emitter.DATA_CALLBACK == listener);
4008 */
4009 addNamedListener: function addNamedListener(name, eventName, callback, toHead) {
4010 this[name] = callback;
4011 this.addListener(eventName, callback, toHead);
4012 return this;
4013 },
4014
4015 /**
4016 * @api private
4017 */
4018 addNamedAsyncListener: function addNamedAsyncListener(name, eventName, callback, toHead) {
4019 callback._isAsync = true;
4020 return this.addNamedListener(name, eventName, callback, toHead);
4021 },
4022
4023 /**
4024 * Helper method to add a set of named listeners using
4025 * {addNamedListener}. The callback contains a parameter
4026 * with a handle to the `addNamedListener` method.
4027 *
4028 * @callback callback function(add)
4029 * The callback function is called immediately in order to provide
4030 * the `add` function to the block. This simplifies the addition of
4031 * a large group of named listeners.
4032 * @param add [Function] the {addNamedListener} function to call
4033 * when registering listeners.
4034 * @example Adding a set of named listeners
4035 * emitter.addNamedListeners(function(add) {
4036 * add('DATA_CALLBACK', 'data', function() { ... });
4037 * add('OTHER', 'otherEvent', function() { ... });
4038 * add('LAST', 'lastEvent', function() { ... });
4039 * });
4040 *
4041 * // these properties are now set:
4042 * emitter.DATA_CALLBACK;
4043 * emitter.OTHER;
4044 * emitter.LAST;
4045 */
4046 addNamedListeners: function addNamedListeners(callback) {
4047 var self = this;
4048 callback(
4049 function() {
4050 self.addNamedListener.apply(self, arguments);
4051 },
4052 function() {
4053 self.addNamedAsyncListener.apply(self, arguments);
4054 }
4055 );
4056 return this;
4057 }
4058 });
4059
4060 /**
4061 * {on} is the prefered method.
4062 * @api private
4063 */
4064 AWS.SequentialExecutor.prototype.addListener = AWS.SequentialExecutor.prototype.on;
4065
4066 /**
4067 * @api private
4068 */
4069 module.exports = AWS.SequentialExecutor;
4070
4071
4072/***/ }),
4073/* 37 */
4074/***/ (function(module, exports, __webpack_require__) {
4075
4076 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
4077 var Api = __webpack_require__(29);
4078 var regionConfig = __webpack_require__(38);
4079
4080 var inherit = AWS.util.inherit;
4081 var clientCount = 0;
4082
4083 /**
4084 * The service class representing an AWS service.
4085 *
4086 * @class_abstract This class is an abstract class.
4087 *
4088 * @!attribute apiVersions
4089 * @return [Array<String>] the list of API versions supported by this service.
4090 * @readonly
4091 */
4092 AWS.Service = inherit({
4093 /**
4094 * Create a new service object with a configuration object
4095 *
4096 * @param config [map] a map of configuration options
4097 */
4098 constructor: function Service(config) {
4099 if (!this.loadServiceClass) {
4100 throw AWS.util.error(new Error(),
4101 'Service must be constructed with `new\' operator');
4102 }
4103 var ServiceClass = this.loadServiceClass(config || {});
4104 if (ServiceClass) {
4105 var originalConfig = AWS.util.copy(config);
4106 var svc = new ServiceClass(config);
4107 Object.defineProperty(svc, '_originalConfig', {
4108 get: function() { return originalConfig; },
4109 enumerable: false,
4110 configurable: true
4111 });
4112 svc._clientId = ++clientCount;
4113 return svc;
4114 }
4115 this.initialize(config);
4116 },
4117
4118 /**
4119 * @api private
4120 */
4121 initialize: function initialize(config) {
4122 var svcConfig = AWS.config[this.serviceIdentifier];
4123 this.config = new AWS.Config(AWS.config);
4124 if (svcConfig) this.config.update(svcConfig, true);
4125 if (config) this.config.update(config, true);
4126
4127 this.validateService();
4128 if (!this.config.endpoint) regionConfig(this);
4129
4130 this.config.endpoint = this.endpointFromTemplate(this.config.endpoint);
4131 this.setEndpoint(this.config.endpoint);
4132 //enable attaching listeners to service client
4133 AWS.SequentialExecutor.call(this);
4134 AWS.Service.addDefaultMonitoringListeners(this);
4135 if ((this.config.clientSideMonitoring || AWS.Service._clientSideMonitoring) && this.publisher) {
4136 var publisher = this.publisher;
4137 this.addNamedListener('PUBLISH_API_CALL', 'apiCall', function PUBLISH_API_CALL(event) {
4138 process.nextTick(function() {publisher.eventHandler(event);});
4139 });
4140 this.addNamedListener('PUBLISH_API_ATTEMPT', 'apiCallAttempt', function PUBLISH_API_ATTEMPT(event) {
4141 process.nextTick(function() {publisher.eventHandler(event);});
4142 });
4143 }
4144 },
4145
4146 /**
4147 * @api private
4148 */
4149 validateService: function validateService() {
4150 },
4151
4152 /**
4153 * @api private
4154 */
4155 loadServiceClass: function loadServiceClass(serviceConfig) {
4156 var config = serviceConfig;
4157 if (!AWS.util.isEmpty(this.api)) {
4158 return null;
4159 } else if (config.apiConfig) {
4160 return AWS.Service.defineServiceApi(this.constructor, config.apiConfig);
4161 } else if (!this.constructor.services) {
4162 return null;
4163 } else {
4164 config = new AWS.Config(AWS.config);
4165 config.update(serviceConfig, true);
4166 var version = config.apiVersions[this.constructor.serviceIdentifier];
4167 version = version || config.apiVersion;
4168 return this.getLatestServiceClass(version);
4169 }
4170 },
4171
4172 /**
4173 * @api private
4174 */
4175 getLatestServiceClass: function getLatestServiceClass(version) {
4176 version = this.getLatestServiceVersion(version);
4177 if (this.constructor.services[version] === null) {
4178 AWS.Service.defineServiceApi(this.constructor, version);
4179 }
4180
4181 return this.constructor.services[version];
4182 },
4183
4184 /**
4185 * @api private
4186 */
4187 getLatestServiceVersion: function getLatestServiceVersion(version) {
4188 if (!this.constructor.services || this.constructor.services.length === 0) {
4189 throw new Error('No services defined on ' +
4190 this.constructor.serviceIdentifier);
4191 }
4192
4193 if (!version) {
4194 version = 'latest';
4195 } else if (AWS.util.isType(version, Date)) {
4196 version = AWS.util.date.iso8601(version).split('T')[0];
4197 }
4198
4199 if (Object.hasOwnProperty(this.constructor.services, version)) {
4200 return version;
4201 }
4202
4203 var keys = Object.keys(this.constructor.services).sort();
4204 var selectedVersion = null;
4205 for (var i = keys.length - 1; i >= 0; i--) {
4206 // versions that end in "*" are not available on disk and can be
4207 // skipped, so do not choose these as selectedVersions
4208 if (keys[i][keys[i].length - 1] !== '*') {
4209 selectedVersion = keys[i];
4210 }
4211 if (keys[i].substr(0, 10) <= version) {
4212 return selectedVersion;
4213 }
4214 }
4215
4216 throw new Error('Could not find ' + this.constructor.serviceIdentifier +
4217 ' API to satisfy version constraint `' + version + '\'');
4218 },
4219
4220 /**
4221 * @api private
4222 */
4223 api: {},
4224
4225 /**
4226 * @api private
4227 */
4228 defaultRetryCount: 3,
4229
4230 /**
4231 * @api private
4232 */
4233 customizeRequests: function customizeRequests(callback) {
4234 if (!callback) {
4235 this.customRequestHandler = null;
4236 } else if (typeof callback === 'function') {
4237 this.customRequestHandler = callback;
4238 } else {
4239 throw new Error('Invalid callback type \'' + typeof callback + '\' provided in customizeRequests');
4240 }
4241 },
4242
4243 /**
4244 * Calls an operation on a service with the given input parameters.
4245 *
4246 * @param operation [String] the name of the operation to call on the service.
4247 * @param params [map] a map of input options for the operation
4248 * @callback callback function(err, data)
4249 * If a callback is supplied, it is called when a response is returned
4250 * from the service.
4251 * @param err [Error] the error object returned from the request.
4252 * Set to `null` if the request is successful.
4253 * @param data [Object] the de-serialized data returned from
4254 * the request. Set to `null` if a request error occurs.
4255 */
4256 makeRequest: function makeRequest(operation, params, callback) {
4257 if (typeof params === 'function') {
4258 callback = params;
4259 params = null;
4260 }
4261
4262 params = params || {};
4263 if (this.config.params) { // copy only toplevel bound params
4264 var rules = this.api.operations[operation];
4265 if (rules) {
4266 params = AWS.util.copy(params);
4267 AWS.util.each(this.config.params, function(key, value) {
4268 if (rules.input.members[key]) {
4269 if (params[key] === undefined || params[key] === null) {
4270 params[key] = value;
4271 }
4272 }
4273 });
4274 }
4275 }
4276
4277 var request = new AWS.Request(this, operation, params);
4278 this.addAllRequestListeners(request);
4279 this.attachMonitoringEmitter(request);
4280 if (callback) request.send(callback);
4281 return request;
4282 },
4283
4284 /**
4285 * Calls an operation on a service with the given input parameters, without
4286 * any authentication data. This method is useful for "public" API operations.
4287 *
4288 * @param operation [String] the name of the operation to call on the service.
4289 * @param params [map] a map of input options for the operation
4290 * @callback callback function(err, data)
4291 * If a callback is supplied, it is called when a response is returned
4292 * from the service.
4293 * @param err [Error] the error object returned from the request.
4294 * Set to `null` if the request is successful.
4295 * @param data [Object] the de-serialized data returned from
4296 * the request. Set to `null` if a request error occurs.
4297 */
4298 makeUnauthenticatedRequest: function makeUnauthenticatedRequest(operation, params, callback) {
4299 if (typeof params === 'function') {
4300 callback = params;
4301 params = {};
4302 }
4303
4304 var request = this.makeRequest(operation, params).toUnauthenticated();
4305 return callback ? request.send(callback) : request;
4306 },
4307
4308 /**
4309 * Waits for a given state
4310 *
4311 * @param state [String] the state on the service to wait for
4312 * @param params [map] a map of parameters to pass with each request
4313 * @option params $waiter [map] a map of configuration options for the waiter
4314 * @option params $waiter.delay [Number] The number of seconds to wait between
4315 * requests
4316 * @option params $waiter.maxAttempts [Number] The maximum number of requests
4317 * to send while waiting
4318 * @callback callback function(err, data)
4319 * If a callback is supplied, it is called when a response is returned
4320 * from the service.
4321 * @param err [Error] the error object returned from the request.
4322 * Set to `null` if the request is successful.
4323 * @param data [Object] the de-serialized data returned from
4324 * the request. Set to `null` if a request error occurs.
4325 */
4326 waitFor: function waitFor(state, params, callback) {
4327 var waiter = new AWS.ResourceWaiter(this, state);
4328 return waiter.wait(params, callback);
4329 },
4330
4331 /**
4332 * @api private
4333 */
4334 addAllRequestListeners: function addAllRequestListeners(request) {
4335 var list = [AWS.events, AWS.EventListeners.Core, this.serviceInterface(),
4336 AWS.EventListeners.CorePost];
4337 for (var i = 0; i < list.length; i++) {
4338 if (list[i]) request.addListeners(list[i]);
4339 }
4340
4341 // disable parameter validation
4342 if (!this.config.paramValidation) {
4343 request.removeListener('validate',
4344 AWS.EventListeners.Core.VALIDATE_PARAMETERS);
4345 }
4346
4347 if (this.config.logger) { // add logging events
4348 request.addListeners(AWS.EventListeners.Logger);
4349 }
4350
4351 this.setupRequestListeners(request);
4352 // call prototype's customRequestHandler
4353 if (typeof this.constructor.prototype.customRequestHandler === 'function') {
4354 this.constructor.prototype.customRequestHandler(request);
4355 }
4356 // call instance's customRequestHandler
4357 if (Object.prototype.hasOwnProperty.call(this, 'customRequestHandler') && typeof this.customRequestHandler === 'function') {
4358 this.customRequestHandler(request);
4359 }
4360 },
4361
4362 /**
4363 * Event recording metrics for a whole API call.
4364 * @returns {object} a subset of api call metrics
4365 * @api private
4366 */
4367 apiCallEvent: function apiCallEvent(request) {
4368 var api = request.service.api.operations[request.operation];
4369 var monitoringEvent = {
4370 Type: 'ApiCall',
4371 Api: api ? api.name : request.operation,
4372 Version: 1,
4373 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4374 Region: request.httpRequest.region,
4375 MaxRetriesExceeded: 0,
4376 UserAgent: request.httpRequest.getUserAgent(),
4377 };
4378 var response = request.response;
4379 if (response.httpResponse.statusCode) {
4380 monitoringEvent.FinalHttpStatusCode = response.httpResponse.statusCode;
4381 }
4382 if (response.error) {
4383 var error = response.error;
4384 var statusCode = response.httpResponse.statusCode;
4385 if (statusCode > 299) {
4386 if (error.code) monitoringEvent.FinalAwsException = error.code;
4387 if (error.message) monitoringEvent.FinalAwsExceptionMessage = error.message;
4388 } else {
4389 if (error.code || error.name) monitoringEvent.FinalSdkException = error.code || error.name;
4390 if (error.message) monitoringEvent.FinalSdkExceptionMessage = error.message;
4391 }
4392 }
4393 return monitoringEvent;
4394 },
4395
4396 /**
4397 * Event recording metrics for an API call attempt.
4398 * @returns {object} a subset of api call attempt metrics
4399 * @api private
4400 */
4401 apiAttemptEvent: function apiAttemptEvent(request) {
4402 var api = request.service.api.operations[request.operation];
4403 var monitoringEvent = {
4404 Type: 'ApiCallAttempt',
4405 Api: api ? api.name : request.operation,
4406 Version: 1,
4407 Service: request.service.api.serviceId || request.service.api.endpointPrefix,
4408 Fqdn: request.httpRequest.endpoint.hostname,
4409 UserAgent: request.httpRequest.getUserAgent(),
4410 };
4411 var response = request.response;
4412 if (response.httpResponse.statusCode) {
4413 monitoringEvent.HttpStatusCode = response.httpResponse.statusCode;
4414 }
4415 if (
4416 !request._unAuthenticated &&
4417 request.service.config.credentials &&
4418 request.service.config.credentials.accessKeyId
4419 ) {
4420 monitoringEvent.AccessKey = request.service.config.credentials.accessKeyId;
4421 }
4422 if (!response.httpResponse.headers) return monitoringEvent;
4423 if (request.httpRequest.headers['x-amz-security-token']) {
4424 monitoringEvent.SessionToken = request.httpRequest.headers['x-amz-security-token'];
4425 }
4426 if (response.httpResponse.headers['x-amzn-requestid']) {
4427 monitoringEvent.XAmznRequestId = response.httpResponse.headers['x-amzn-requestid'];
4428 }
4429 if (response.httpResponse.headers['x-amz-request-id']) {
4430 monitoringEvent.XAmzRequestId = response.httpResponse.headers['x-amz-request-id'];
4431 }
4432 if (response.httpResponse.headers['x-amz-id-2']) {
4433 monitoringEvent.XAmzId2 = response.httpResponse.headers['x-amz-id-2'];
4434 }
4435 return monitoringEvent;
4436 },
4437
4438 /**
4439 * Add metrics of failed request.
4440 * @api private
4441 */
4442 attemptFailEvent: function attemptFailEvent(request) {
4443 var monitoringEvent = this.apiAttemptEvent(request);
4444 var response = request.response;
4445 var error = response.error;
4446 if (response.httpResponse.statusCode > 299 ) {
4447 if (error.code) monitoringEvent.AwsException = error.code;
4448 if (error.message) monitoringEvent.AwsExceptionMessage = error.message;
4449 } else {
4450 if (error.code || error.name) monitoringEvent.SdkException = error.code || error.name;
4451 if (error.message) monitoringEvent.SdkExceptionMessage = error.message;
4452 }
4453 return monitoringEvent;
4454 },
4455
4456 /**
4457 * Attach listeners to request object to fetch metrics of each request
4458 * and emit data object through \'ApiCall\' and \'ApiCallAttempt\' events.
4459 * @api private
4460 */
4461 attachMonitoringEmitter: function attachMonitoringEmitter(request) {
4462 var attemptTimestamp; //timestamp marking the beginning of a request attempt
4463 var attemptStartRealTime; //Start time of request attempt. Used to calculating attemptLatency
4464 var attemptLatency; //latency from request sent out to http response reaching SDK
4465 var callStartRealTime; //Start time of API call. Used to calculating API call latency
4466 var attemptCount = 0; //request.retryCount is not reliable here
4467 var region; //region cache region for each attempt since it can be updated in plase (e.g. s3)
4468 var callTimestamp; //timestamp when the request is created
4469 var self = this;
4470 var addToHead = true;
4471
4472 request.on('validate', function () {
4473 callStartRealTime = AWS.util.realClock.now();
4474 callTimestamp = Date.now();
4475 }, addToHead);
4476 request.on('sign', function () {
4477 attemptStartRealTime = AWS.util.realClock.now();
4478 attemptTimestamp = Date.now();
4479 region = request.httpRequest.region;
4480 attemptCount++;
4481 }, addToHead);
4482 request.on('validateResponse', function() {
4483 attemptLatency = Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4484 });
4485 request.addNamedListener('API_CALL_ATTEMPT', 'success', function API_CALL_ATTEMPT() {
4486 var apiAttemptEvent = self.apiAttemptEvent(request);
4487 apiAttemptEvent.Timestamp = attemptTimestamp;
4488 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4489 apiAttemptEvent.Region = region;
4490 self.emit('apiCallAttempt', [apiAttemptEvent]);
4491 });
4492 request.addNamedListener('API_CALL_ATTEMPT_RETRY', 'retry', function API_CALL_ATTEMPT_RETRY() {
4493 var apiAttemptEvent = self.attemptFailEvent(request);
4494 apiAttemptEvent.Timestamp = attemptTimestamp;
4495 //attemptLatency may not be available if fail before response
4496 attemptLatency = attemptLatency ||
4497 Math.round(AWS.util.realClock.now() - attemptStartRealTime);
4498 apiAttemptEvent.AttemptLatency = attemptLatency >= 0 ? attemptLatency : 0;
4499 apiAttemptEvent.Region = region;
4500 self.emit('apiCallAttempt', [apiAttemptEvent]);
4501 });
4502 request.addNamedListener('API_CALL', 'complete', function API_CALL() {
4503 var apiCallEvent = self.apiCallEvent(request);
4504 apiCallEvent.AttemptCount = attemptCount;
4505 if (apiCallEvent.AttemptCount <= 0) return;
4506 apiCallEvent.Timestamp = callTimestamp;
4507 var latency = Math.round(AWS.util.realClock.now() - callStartRealTime);
4508 apiCallEvent.Latency = latency >= 0 ? latency : 0;
4509 var response = request.response;
4510 if (
4511 typeof response.retryCount === 'number' &&
4512 typeof response.maxRetries === 'number' &&
4513 (response.retryCount >= response.maxRetries)
4514 ) {
4515 apiCallEvent.MaxRetriesExceeded = 1;
4516 }
4517 self.emit('apiCall', [apiCallEvent]);
4518 });
4519 },
4520
4521 /**
4522 * Override this method to setup any custom request listeners for each
4523 * new request to the service.
4524 *
4525 * @method_abstract This is an abstract method.
4526 */
4527 setupRequestListeners: function setupRequestListeners(request) {
4528 },
4529
4530 /**
4531 * Gets the signer class for a given request
4532 * @api private
4533 */
4534 getSignerClass: function getSignerClass(request) {
4535 var version;
4536 // get operation authtype if present
4537 var operation = null;
4538 var authtype = '';
4539 if (request) {
4540 var operations = request.service.api.operations || {};
4541 operation = operations[request.operation] || null;
4542 authtype = operation ? operation.authtype : '';
4543 }
4544 if (this.config.signatureVersion) {
4545 version = this.config.signatureVersion;
4546 } else if (authtype === 'v4' || authtype === 'v4-unsigned-body') {
4547 version = 'v4';
4548 } else {
4549 version = this.api.signatureVersion;
4550 }
4551 return AWS.Signers.RequestSigner.getVersion(version);
4552 },
4553
4554 /**
4555 * @api private
4556 */
4557 serviceInterface: function serviceInterface() {
4558 switch (this.api.protocol) {
4559 case 'ec2': return AWS.EventListeners.Query;
4560 case 'query': return AWS.EventListeners.Query;
4561 case 'json': return AWS.EventListeners.Json;
4562 case 'rest-json': return AWS.EventListeners.RestJson;
4563 case 'rest-xml': return AWS.EventListeners.RestXml;
4564 }
4565 if (this.api.protocol) {
4566 throw new Error('Invalid service `protocol\' ' +
4567 this.api.protocol + ' in API config');
4568 }
4569 },
4570
4571 /**
4572 * @api private
4573 */
4574 successfulResponse: function successfulResponse(resp) {
4575 return resp.httpResponse.statusCode < 300;
4576 },
4577
4578 /**
4579 * How many times a failed request should be retried before giving up.
4580 * the defaultRetryCount can be overriden by service classes.
4581 *
4582 * @api private
4583 */
4584 numRetries: function numRetries() {
4585 if (this.config.maxRetries !== undefined) {
4586 return this.config.maxRetries;
4587 } else {
4588 return this.defaultRetryCount;
4589 }
4590 },
4591
4592 /**
4593 * @api private
4594 */
4595 retryDelays: function retryDelays(retryCount) {
4596 return AWS.util.calculateRetryDelay(retryCount, this.config.retryDelayOptions);
4597 },
4598
4599 /**
4600 * @api private
4601 */
4602 retryableError: function retryableError(error) {
4603 if (this.timeoutError(error)) return true;
4604 if (this.networkingError(error)) return true;
4605 if (this.expiredCredentialsError(error)) return true;
4606 if (this.throttledError(error)) return true;
4607 if (error.statusCode >= 500) return true;
4608 return false;
4609 },
4610
4611 /**
4612 * @api private
4613 */
4614 networkingError: function networkingError(error) {
4615 return error.code === 'NetworkingError';
4616 },
4617
4618 /**
4619 * @api private
4620 */
4621 timeoutError: function timeoutError(error) {
4622 return error.code === 'TimeoutError';
4623 },
4624
4625 /**
4626 * @api private
4627 */
4628 expiredCredentialsError: function expiredCredentialsError(error) {
4629 // TODO : this only handles *one* of the expired credential codes
4630 return (error.code === 'ExpiredTokenException');
4631 },
4632
4633 /**
4634 * @api private
4635 */
4636 clockSkewError: function clockSkewError(error) {
4637 switch (error.code) {
4638 case 'RequestTimeTooSkewed':
4639 case 'RequestExpired':
4640 case 'InvalidSignatureException':
4641 case 'SignatureDoesNotMatch':
4642 case 'AuthFailure':
4643 case 'RequestInTheFuture':
4644 return true;
4645 default: return false;
4646 }
4647 },
4648
4649 /**
4650 * @api private
4651 */
4652 getSkewCorrectedDate: function getSkewCorrectedDate() {
4653 return new Date(Date.now() + this.config.systemClockOffset);
4654 },
4655
4656 /**
4657 * @api private
4658 */
4659 applyClockOffset: function applyClockOffset(newServerTime) {
4660 if (newServerTime) {
4661 this.config.systemClockOffset = newServerTime - Date.now();
4662 }
4663 },
4664
4665 /**
4666 * @api private
4667 */
4668 isClockSkewed: function isClockSkewed(newServerTime) {
4669 if (newServerTime) {
4670 return Math.abs(this.getSkewCorrectedDate().getTime() - newServerTime) >= 30000;
4671 }
4672 },
4673
4674 /**
4675 * @api private
4676 */
4677 throttledError: function throttledError(error) {
4678 // this logic varies between services
4679 switch (error.code) {
4680 case 'ProvisionedThroughputExceededException':
4681 case 'Throttling':
4682 case 'ThrottlingException':
4683 case 'RequestLimitExceeded':
4684 case 'RequestThrottled':
4685 case 'RequestThrottledException':
4686 case 'TooManyRequestsException':
4687 case 'TransactionInProgressException': //dynamodb
4688 return true;
4689 default:
4690 return false;
4691 }
4692 },
4693
4694 /**
4695 * @api private
4696 */
4697 endpointFromTemplate: function endpointFromTemplate(endpoint) {
4698 if (typeof endpoint !== 'string') return endpoint;
4699
4700 var e = endpoint;
4701 e = e.replace(/\{service\}/g, this.api.endpointPrefix);
4702 e = e.replace(/\{region\}/g, this.config.region);
4703 e = e.replace(/\{scheme\}/g, this.config.sslEnabled ? 'https' : 'http');
4704 return e;
4705 },
4706
4707 /**
4708 * @api private
4709 */
4710 setEndpoint: function setEndpoint(endpoint) {
4711 this.endpoint = new AWS.Endpoint(endpoint, this.config);
4712 },
4713
4714 /**
4715 * @api private
4716 */
4717 paginationConfig: function paginationConfig(operation, throwException) {
4718 var paginator = this.api.operations[operation].paginator;
4719 if (!paginator) {
4720 if (throwException) {
4721 var e = new Error();
4722 throw AWS.util.error(e, 'No pagination configuration for ' + operation);
4723 }
4724 return null;
4725 }
4726
4727 return paginator;
4728 }
4729 });
4730
4731 AWS.util.update(AWS.Service, {
4732
4733 /**
4734 * Adds one method for each operation described in the api configuration
4735 *
4736 * @api private
4737 */
4738 defineMethods: function defineMethods(svc) {
4739 AWS.util.each(svc.prototype.api.operations, function iterator(method) {
4740 if (svc.prototype[method]) return;
4741 var operation = svc.prototype.api.operations[method];
4742 if (operation.authtype === 'none') {
4743 svc.prototype[method] = function (params, callback) {
4744 return this.makeUnauthenticatedRequest(method, params, callback);
4745 };
4746 } else {
4747 svc.prototype[method] = function (params, callback) {
4748 return this.makeRequest(method, params, callback);
4749 };
4750 }
4751 });
4752 },
4753
4754 /**
4755 * Defines a new Service class using a service identifier and list of versions
4756 * including an optional set of features (functions) to apply to the class
4757 * prototype.
4758 *
4759 * @param serviceIdentifier [String] the identifier for the service
4760 * @param versions [Array<String>] a list of versions that work with this
4761 * service
4762 * @param features [Object] an object to attach to the prototype
4763 * @return [Class<Service>] the service class defined by this function.
4764 */
4765 defineService: function defineService(serviceIdentifier, versions, features) {
4766 AWS.Service._serviceMap[serviceIdentifier] = true;
4767 if (!Array.isArray(versions)) {
4768 features = versions;
4769 versions = [];
4770 }
4771
4772 var svc = inherit(AWS.Service, features || {});
4773
4774 if (typeof serviceIdentifier === 'string') {
4775 AWS.Service.addVersions(svc, versions);
4776
4777 var identifier = svc.serviceIdentifier || serviceIdentifier;
4778 svc.serviceIdentifier = identifier;
4779 } else { // defineService called with an API
4780 svc.prototype.api = serviceIdentifier;
4781 AWS.Service.defineMethods(svc);
4782 }
4783 AWS.SequentialExecutor.call(this.prototype);
4784 //util.clientSideMonitoring is only available in node
4785 if (!this.prototype.publisher && AWS.util.clientSideMonitoring) {
4786 var Publisher = AWS.util.clientSideMonitoring.Publisher;
4787 var configProvider = AWS.util.clientSideMonitoring.configProvider;
4788 var publisherConfig = configProvider();
4789 this.prototype.publisher = new Publisher(publisherConfig);
4790 if (publisherConfig.enabled) {
4791 //if csm is enabled in environment, SDK should send all metrics
4792 AWS.Service._clientSideMonitoring = true;
4793 }
4794 }
4795 AWS.SequentialExecutor.call(svc.prototype);
4796 AWS.Service.addDefaultMonitoringListeners(svc.prototype);
4797 return svc;
4798 },
4799
4800 /**
4801 * @api private
4802 */
4803 addVersions: function addVersions(svc, versions) {
4804 if (!Array.isArray(versions)) versions = [versions];
4805
4806 svc.services = svc.services || {};
4807 for (var i = 0; i < versions.length; i++) {
4808 if (svc.services[versions[i]] === undefined) {
4809 svc.services[versions[i]] = null;
4810 }
4811 }
4812
4813 svc.apiVersions = Object.keys(svc.services).sort();
4814 },
4815
4816 /**
4817 * @api private
4818 */
4819 defineServiceApi: function defineServiceApi(superclass, version, apiConfig) {
4820 var svc = inherit(superclass, {
4821 serviceIdentifier: superclass.serviceIdentifier
4822 });
4823
4824 function setApi(api) {
4825 if (api.isApi) {
4826 svc.prototype.api = api;
4827 } else {
4828 svc.prototype.api = new Api(api);
4829 }
4830 }
4831
4832 if (typeof version === 'string') {
4833 if (apiConfig) {
4834 setApi(apiConfig);
4835 } else {
4836 try {
4837 setApi(AWS.apiLoader(superclass.serviceIdentifier, version));
4838 } catch (err) {
4839 throw AWS.util.error(err, {
4840 message: 'Could not find API configuration ' +
4841 superclass.serviceIdentifier + '-' + version
4842 });
4843 }
4844 }
4845 if (!Object.prototype.hasOwnProperty.call(superclass.services, version)) {
4846 superclass.apiVersions = superclass.apiVersions.concat(version).sort();
4847 }
4848 superclass.services[version] = svc;
4849 } else {
4850 setApi(version);
4851 }
4852
4853 AWS.Service.defineMethods(svc);
4854 return svc;
4855 },
4856
4857 /**
4858 * @api private
4859 */
4860 hasService: function(identifier) {
4861 return Object.prototype.hasOwnProperty.call(AWS.Service._serviceMap, identifier);
4862 },
4863
4864 /**
4865 * @param attachOn attach default monitoring listeners to object
4866 *
4867 * Each monitoring event should be emitted from service client to service constructor prototype and then
4868 * to global service prototype like bubbling up. These default monitoring events listener will transfer
4869 * the monitoring events to the upper layer.
4870 * @api private
4871 */
4872 addDefaultMonitoringListeners: function addDefaultMonitoringListeners(attachOn) {
4873 attachOn.addNamedListener('MONITOR_EVENTS_BUBBLE', 'apiCallAttempt', function EVENTS_BUBBLE(event) {
4874 var baseClass = Object.getPrototypeOf(attachOn);
4875 if (baseClass._events) baseClass.emit('apiCallAttempt', [event]);
4876 });
4877 attachOn.addNamedListener('CALL_EVENTS_BUBBLE', 'apiCall', function CALL_EVENTS_BUBBLE(event) {
4878 var baseClass = Object.getPrototypeOf(attachOn);
4879 if (baseClass._events) baseClass.emit('apiCall', [event]);
4880 });
4881 },
4882
4883 /**
4884 * @api private
4885 */
4886 _serviceMap: {}
4887 });
4888
4889 AWS.util.mixin(AWS.Service, AWS.SequentialExecutor);
4890
4891 /**
4892 * @api private
4893 */
4894 module.exports = AWS.Service;
4895
4896 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
4897
4898/***/ }),
4899/* 38 */
4900/***/ (function(module, exports, __webpack_require__) {
4901
4902 var util = __webpack_require__(2);
4903 var regionConfig = __webpack_require__(39);
4904
4905 function generateRegionPrefix(region) {
4906 if (!region) return null;
4907
4908 var parts = region.split('-');
4909 if (parts.length < 3) return null;
4910 return parts.slice(0, parts.length - 2).join('-') + '-*';
4911 }
4912
4913 function derivedKeys(service) {
4914 var region = service.config.region;
4915 var regionPrefix = generateRegionPrefix(region);
4916 var endpointPrefix = service.api.endpointPrefix;
4917
4918 return [
4919 [region, endpointPrefix],
4920 [regionPrefix, endpointPrefix],
4921 [region, '*'],
4922 [regionPrefix, '*'],
4923 ['*', endpointPrefix],
4924 ['*', '*']
4925 ].map(function(item) {
4926 return item[0] && item[1] ? item.join('/') : null;
4927 });
4928 }
4929
4930 function applyConfig(service, config) {
4931 util.each(config, function(key, value) {
4932 if (key === 'globalEndpoint') return;
4933 if (service.config[key] === undefined || service.config[key] === null) {
4934 service.config[key] = value;
4935 }
4936 });
4937 }
4938
4939 function configureEndpoint(service) {
4940 var keys = derivedKeys(service);
4941 for (var i = 0; i < keys.length; i++) {
4942 var key = keys[i];
4943 if (!key) continue;
4944
4945 if (Object.prototype.hasOwnProperty.call(regionConfig.rules, key)) {
4946 var config = regionConfig.rules[key];
4947 if (typeof config === 'string') {
4948 config = regionConfig.patterns[config];
4949 }
4950
4951 // set dualstack endpoint
4952 if (service.config.useDualstack && util.isDualstackAvailable(service)) {
4953 config = util.copy(config);
4954 config.endpoint = '{service}.dualstack.{region}.amazonaws.com';
4955 }
4956
4957 // set global endpoint
4958 service.isGlobalEndpoint = !!config.globalEndpoint;
4959
4960 // signature version
4961 if (!config.signatureVersion) config.signatureVersion = 'v4';
4962
4963 // merge config
4964 applyConfig(service, config);
4965 return;
4966 }
4967 }
4968 }
4969
4970 /**
4971 * @api private
4972 */
4973 module.exports = configureEndpoint;
4974
4975
4976/***/ }),
4977/* 39 */
4978/***/ (function(module, exports) {
4979
4980 module.exports = {"rules":{"*/*":{"endpoint":"{service}.{region}.amazonaws.com"},"cn-*/*":{"endpoint":"{service}.{region}.amazonaws.com.cn"},"*/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"}}}
4981
4982/***/ }),
4983/* 40 */
4984/***/ (function(module, exports, __webpack_require__) {
4985
4986 var AWS = __webpack_require__(1);
4987 __webpack_require__(41);
4988 __webpack_require__(42);
4989 var PromisesDependency;
4990
4991 /**
4992 * The main configuration class used by all service objects to set
4993 * the region, credentials, and other options for requests.
4994 *
4995 * By default, credentials and region settings are left unconfigured.
4996 * This should be configured by the application before using any
4997 * AWS service APIs.
4998 *
4999 * In order to set global configuration options, properties should
5000 * be assigned to the global {AWS.config} object.
5001 *
5002 * @see AWS.config
5003 *
5004 * @!group General Configuration Options
5005 *
5006 * @!attribute credentials
5007 * @return [AWS.Credentials] the AWS credentials to sign requests with.
5008 *
5009 * @!attribute region
5010 * @example Set the global region setting to us-west-2
5011 * AWS.config.update({region: 'us-west-2'});
5012 * @return [AWS.Credentials] The region to send service requests to.
5013 * @see http://docs.amazonwebservices.com/general/latest/gr/rande.html
5014 * A list of available endpoints for each AWS service
5015 *
5016 * @!attribute maxRetries
5017 * @return [Integer] the maximum amount of retries to perform for a
5018 * service request. By default this value is calculated by the specific
5019 * service object that the request is being made to.
5020 *
5021 * @!attribute maxRedirects
5022 * @return [Integer] the maximum amount of redirects to follow for a
5023 * service request. Defaults to 10.
5024 *
5025 * @!attribute paramValidation
5026 * @return [Boolean|map] whether input parameters should be validated against
5027 * the operation description before sending the request. Defaults to true.
5028 * Pass a map to enable any of the following specific validation features:
5029 *
5030 * * **min** [Boolean] &mdash; Validates that a value meets the min
5031 * constraint. This is enabled by default when paramValidation is set
5032 * to `true`.
5033 * * **max** [Boolean] &mdash; Validates that a value meets the max
5034 * constraint.
5035 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5036 * regular expression.
5037 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5038 * of the allowable enum values.
5039 *
5040 * @!attribute computeChecksums
5041 * @return [Boolean] whether to compute checksums for payload bodies when
5042 * the service accepts it (currently supported in S3 only).
5043 *
5044 * @!attribute convertResponseTypes
5045 * @return [Boolean] whether types are converted when parsing response data.
5046 * Currently only supported for JSON based services. Turning this off may
5047 * improve performance on large response payloads. Defaults to `true`.
5048 *
5049 * @!attribute correctClockSkew
5050 * @return [Boolean] whether to apply a clock skew correction and retry
5051 * requests that fail because of an skewed client clock. Defaults to
5052 * `false`.
5053 *
5054 * @!attribute sslEnabled
5055 * @return [Boolean] whether SSL is enabled for requests
5056 *
5057 * @!attribute s3ForcePathStyle
5058 * @return [Boolean] whether to force path style URLs for S3 objects
5059 *
5060 * @!attribute s3BucketEndpoint
5061 * @note Setting this configuration option requires an `endpoint` to be
5062 * provided explicitly to the service constructor.
5063 * @return [Boolean] whether the provided endpoint addresses an individual
5064 * bucket (false if it addresses the root API endpoint).
5065 *
5066 * @!attribute s3DisableBodySigning
5067 * @return [Boolean] whether to disable S3 body signing when using signature version `v4`.
5068 * Body signing can only be disabled when using https. Defaults to `true`.
5069 *
5070 * @!attribute useAccelerateEndpoint
5071 * @note This configuration option is only compatible with S3 while accessing
5072 * dns-compatible buckets.
5073 * @return [Boolean] Whether to use the Accelerate endpoint with the S3 service.
5074 * Defaults to `false`.
5075 *
5076 * @!attribute retryDelayOptions
5077 * @example Set the base retry delay for all services to 300 ms
5078 * AWS.config.update({retryDelayOptions: {base: 300}});
5079 * // Delays with maxRetries = 3: 300, 600, 1200
5080 * @example Set a custom backoff function to provide delay values on retries
5081 * AWS.config.update({retryDelayOptions: {customBackoff: function(retryCount) {
5082 * // returns delay in ms
5083 * }}});
5084 * @return [map] A set of options to configure the retry delay on retryable errors.
5085 * Currently supported options are:
5086 *
5087 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5088 * exponential backoff for operation retries. Defaults to 100 ms for all services except
5089 * DynamoDB, where it defaults to 50ms.
5090 * * **customBackoff ** [function] &mdash; A custom function that accepts a retry count
5091 * and returns the amount of time to delay in milliseconds. The `base` option will be
5092 * ignored if this option is supplied.
5093 *
5094 * @!attribute httpOptions
5095 * @return [map] A set of options to pass to the low-level HTTP request.
5096 * Currently supported options are:
5097 *
5098 * * **proxy** [String] &mdash; the URL to proxy requests through
5099 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5100 * HTTP requests with. Used for connection pooling. Defaults to the global
5101 * agent (`http.globalAgent`) for non-SSL connections. Note that for
5102 * SSL connections, a special Agent object is used in order to enable
5103 * peer certificate verification. This feature is only supported in the
5104 * Node.js environment.
5105 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5106 * failing to establish a connection with the server after
5107 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5108 * connection has been established.
5109 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5110 * milliseconds of inactivity on the socket. Defaults to two minutes
5111 * (120000)
5112 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5113 * HTTP requests. Used in the browser environment only. Set to false to
5114 * send requests synchronously. Defaults to true (async on).
5115 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5116 * property of an XMLHttpRequest object. Used in the browser environment
5117 * only. Defaults to false.
5118 * @!attribute logger
5119 * @return [#write,#log] an object that responds to .write() (like a stream)
5120 * or .log() (like the console object) in order to log information about
5121 * requests
5122 *
5123 * @!attribute systemClockOffset
5124 * @return [Number] an offset value in milliseconds to apply to all signing
5125 * times. Use this to compensate for clock skew when your system may be
5126 * out of sync with the service time. Note that this configuration option
5127 * can only be applied to the global `AWS.config` object and cannot be
5128 * overridden in service-specific configuration. Defaults to 0 milliseconds.
5129 *
5130 * @!attribute signatureVersion
5131 * @return [String] the signature version to sign requests with (overriding
5132 * the API configuration). Possible values are: 'v2', 'v3', 'v4'.
5133 *
5134 * @!attribute signatureCache
5135 * @return [Boolean] whether the signature to sign requests with (overriding
5136 * the API configuration) is cached. Only applies to the signature version 'v4'.
5137 * Defaults to `true`.
5138 *
5139 * @!attribute endpointDiscoveryEnabled
5140 * @return [Boolean] whether to enable endpoint discovery for operations that
5141 * allow optionally using an endpoint returned by the service.
5142 * Defaults to 'false'
5143 *
5144 * @!attribute endpointCacheSize
5145 * @return [Number] the size of the global cache storing endpoints from endpoint
5146 * discovery operations. Once endpoint cache is created, updating this setting
5147 * cannot change existing cache size.
5148 * Defaults to 1000
5149 *
5150 * @!attribute hostPrefixEnabled
5151 * @return [Boolean] whether to marshal request parameters to the prefix of
5152 * hostname. Defaults to `true`.
5153 */
5154 AWS.Config = AWS.util.inherit({
5155 /**
5156 * @!endgroup
5157 */
5158
5159 /**
5160 * Creates a new configuration object. This is the object that passes
5161 * option data along to service requests, including credentials, security,
5162 * region information, and some service specific settings.
5163 *
5164 * @example Creating a new configuration object with credentials and region
5165 * var config = new AWS.Config({
5166 * accessKeyId: 'AKID', secretAccessKey: 'SECRET', region: 'us-west-2'
5167 * });
5168 * @option options accessKeyId [String] your AWS access key ID.
5169 * @option options secretAccessKey [String] your AWS secret access key.
5170 * @option options sessionToken [AWS.Credentials] the optional AWS
5171 * session token to sign requests with.
5172 * @option options credentials [AWS.Credentials] the AWS credentials
5173 * to sign requests with. You can either specify this object, or
5174 * specify the accessKeyId and secretAccessKey options directly.
5175 * @option options credentialProvider [AWS.CredentialProviderChain] the
5176 * provider chain used to resolve credentials if no static `credentials`
5177 * property is set.
5178 * @option options region [String] the region to send service requests to.
5179 * See {region} for more information.
5180 * @option options maxRetries [Integer] the maximum amount of retries to
5181 * attempt with a request. See {maxRetries} for more information.
5182 * @option options maxRedirects [Integer] the maximum amount of redirects to
5183 * follow with a request. See {maxRedirects} for more information.
5184 * @option options sslEnabled [Boolean] whether to enable SSL for
5185 * requests.
5186 * @option options paramValidation [Boolean|map] whether input parameters
5187 * should be validated against the operation description before sending
5188 * the request. Defaults to true. Pass a map to enable any of the
5189 * following specific validation features:
5190 *
5191 * * **min** [Boolean] &mdash; Validates that a value meets the min
5192 * constraint. This is enabled by default when paramValidation is set
5193 * to `true`.
5194 * * **max** [Boolean] &mdash; Validates that a value meets the max
5195 * constraint.
5196 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
5197 * regular expression.
5198 * * **enum** [Boolean] &mdash; Validates that a string value matches one
5199 * of the allowable enum values.
5200 * @option options computeChecksums [Boolean] whether to compute checksums
5201 * for payload bodies when the service accepts it (currently supported
5202 * in S3 only)
5203 * @option options convertResponseTypes [Boolean] whether types are converted
5204 * when parsing response data. Currently only supported for JSON based
5205 * services. Turning this off may improve performance on large response
5206 * payloads. Defaults to `true`.
5207 * @option options correctClockSkew [Boolean] whether to apply a clock skew
5208 * correction and retry requests that fail because of an skewed client
5209 * clock. Defaults to `false`.
5210 * @option options s3ForcePathStyle [Boolean] whether to force path
5211 * style URLs for S3 objects.
5212 * @option options s3BucketEndpoint [Boolean] whether the provided endpoint
5213 * addresses an individual bucket (false if it addresses the root API
5214 * endpoint). Note that setting this configuration option requires an
5215 * `endpoint` to be provided explicitly to the service constructor.
5216 * @option options s3DisableBodySigning [Boolean] whether S3 body signing
5217 * should be disabled when using signature version `v4`. Body signing
5218 * can only be disabled when using https. Defaults to `true`.
5219 *
5220 * @option options retryDelayOptions [map] A set of options to configure
5221 * the retry delay on retryable errors. Currently supported options are:
5222 *
5223 * * **base** [Integer] &mdash; The base number of milliseconds to use in the
5224 * exponential backoff for operation retries. Defaults to 100 ms for all
5225 * services except DynamoDB, where it defaults to 50ms.
5226 * * **customBackoff ** [function] &mdash; A custom function that accepts a retry count
5227 * and returns the amount of time to delay in milliseconds. The `base` option will be
5228 * ignored if this option is supplied.
5229 * @option options httpOptions [map] A set of options to pass to the low-level
5230 * HTTP request. Currently supported options are:
5231 *
5232 * * **proxy** [String] &mdash; the URL to proxy requests through
5233 * * **agent** [http.Agent, https.Agent] &mdash; the Agent object to perform
5234 * HTTP requests with. Used for connection pooling. Defaults to the global
5235 * agent (`http.globalAgent`) for non-SSL connections. Note that for
5236 * SSL connections, a special Agent object is used in order to enable
5237 * peer certificate verification. This feature is only available in the
5238 * Node.js environment.
5239 * * **connectTimeout** [Integer] &mdash; Sets the socket to timeout after
5240 * failing to establish a connection with the server after
5241 * `connectTimeout` milliseconds. This timeout has no effect once a socket
5242 * connection has been established.
5243 * * **timeout** [Integer] &mdash; Sets the socket to timeout after timeout
5244 * milliseconds of inactivity on the socket. Defaults to two minutes
5245 * (120000).
5246 * * **xhrAsync** [Boolean] &mdash; Whether the SDK will send asynchronous
5247 * HTTP requests. Used in the browser environment only. Set to false to
5248 * send requests synchronously. Defaults to true (async on).
5249 * * **xhrWithCredentials** [Boolean] &mdash; Sets the "withCredentials"
5250 * property of an XMLHttpRequest object. Used in the browser environment
5251 * only. Defaults to false.
5252 * @option options apiVersion [String, Date] a String in YYYY-MM-DD format
5253 * (or a date) that represents the latest possible API version that can be
5254 * used in all services (unless overridden by `apiVersions`). Specify
5255 * 'latest' to use the latest possible version.
5256 * @option options apiVersions [map<String, String|Date>] a map of service
5257 * identifiers (the lowercase service class name) with the API version to
5258 * use when instantiating a service. Specify 'latest' for each individual
5259 * that can use the latest available version.
5260 * @option options logger [#write,#log] an object that responds to .write()
5261 * (like a stream) or .log() (like the console object) in order to log
5262 * information about requests
5263 * @option options systemClockOffset [Number] an offset value in milliseconds
5264 * to apply to all signing times. Use this to compensate for clock skew
5265 * when your system may be out of sync with the service time. Note that
5266 * this configuration option can only be applied to the global `AWS.config`
5267 * object and cannot be overridden in service-specific configuration.
5268 * Defaults to 0 milliseconds.
5269 * @option options signatureVersion [String] the signature version to sign
5270 * requests with (overriding the API configuration). Possible values are:
5271 * 'v2', 'v3', 'v4'.
5272 * @option options signatureCache [Boolean] whether the signature to sign
5273 * requests with (overriding the API configuration) is cached. Only applies
5274 * to the signature version 'v4'. Defaults to `true`.
5275 * @option options dynamoDbCrc32 [Boolean] whether to validate the CRC32
5276 * checksum of HTTP response bodies returned by DynamoDB. Default: `true`.
5277 * @option options useAccelerateEndpoint [Boolean] Whether to use the
5278 * S3 Transfer Acceleration endpoint with the S3 service. Default: `false`.
5279 * @option options clientSideMonitoring [Boolean] whether to collect and
5280 * publish this client's performance metrics of all its API requests.
5281 * @option options endpointDiscoveryEnabled [Boolean] whether to enable endpoint
5282 * discovery for operations that allow optionally using an endpoint returned by
5283 * the service.
5284 * Defaults to 'false'
5285 * @option options endpointCacheSize [Number] the size of the global cache storing
5286 * endpoints from endpoint discovery operations. Once endpoint cache is created,
5287 * updating this setting cannot change existing cache size.
5288 * Defaults to 1000
5289 * @option options hostPrefixEnabled [Boolean] whether to marshal request
5290 * parameters to the prefix of hostname.
5291 * Defaults to `true`.
5292 */
5293 constructor: function Config(options) {
5294 if (options === undefined) options = {};
5295 options = this.extractCredentials(options);
5296
5297 AWS.util.each.call(this, this.keys, function (key, value) {
5298 this.set(key, options[key], value);
5299 });
5300 },
5301
5302 /**
5303 * @!group Managing Credentials
5304 */
5305
5306 /**
5307 * Loads credentials from the configuration object. This is used internally
5308 * by the SDK to ensure that refreshable {Credentials} objects are properly
5309 * refreshed and loaded when sending a request. If you want to ensure that
5310 * your credentials are loaded prior to a request, you can use this method
5311 * directly to provide accurate credential data stored in the object.
5312 *
5313 * @note If you configure the SDK with static or environment credentials,
5314 * the credential data should already be present in {credentials} attribute.
5315 * This method is primarily necessary to load credentials from asynchronous
5316 * sources, or sources that can refresh credentials periodically.
5317 * @example Getting your access key
5318 * AWS.config.getCredentials(function(err) {
5319 * if (err) console.log(err.stack); // credentials not loaded
5320 * else console.log("Access Key:", AWS.config.credentials.accessKeyId);
5321 * })
5322 * @callback callback function(err)
5323 * Called when the {credentials} have been properly set on the configuration
5324 * object.
5325 *
5326 * @param err [Error] if this is set, credentials were not successfully
5327 * loaded and this error provides information why.
5328 * @see credentials
5329 * @see Credentials
5330 */
5331 getCredentials: function getCredentials(callback) {
5332 var self = this;
5333
5334 function finish(err) {
5335 callback(err, err ? null : self.credentials);
5336 }
5337
5338 function credError(msg, err) {
5339 return new AWS.util.error(err || new Error(), {
5340 code: 'CredentialsError',
5341 message: msg,
5342 name: 'CredentialsError'
5343 });
5344 }
5345
5346 function getAsyncCredentials() {
5347 self.credentials.get(function(err) {
5348 if (err) {
5349 var msg = 'Could not load credentials from ' +
5350 self.credentials.constructor.name;
5351 err = credError(msg, err);
5352 }
5353 finish(err);
5354 });
5355 }
5356
5357 function getStaticCredentials() {
5358 var err = null;
5359 if (!self.credentials.accessKeyId || !self.credentials.secretAccessKey) {
5360 err = credError('Missing credentials');
5361 }
5362 finish(err);
5363 }
5364
5365 if (self.credentials) {
5366 if (typeof self.credentials.get === 'function') {
5367 getAsyncCredentials();
5368 } else { // static credentials
5369 getStaticCredentials();
5370 }
5371 } else if (self.credentialProvider) {
5372 self.credentialProvider.resolve(function(err, creds) {
5373 if (err) {
5374 err = credError('Could not load credentials from any providers', err);
5375 }
5376 self.credentials = creds;
5377 finish(err);
5378 });
5379 } else {
5380 finish(credError('No credentials to load'));
5381 }
5382 },
5383
5384 /**
5385 * @!group Loading and Setting Configuration Options
5386 */
5387
5388 /**
5389 * @overload update(options, allowUnknownKeys = false)
5390 * Updates the current configuration object with new options.
5391 *
5392 * @example Update maxRetries property of a configuration object
5393 * config.update({maxRetries: 10});
5394 * @param [Object] options a map of option keys and values.
5395 * @param [Boolean] allowUnknownKeys whether unknown keys can be set on
5396 * the configuration object. Defaults to `false`.
5397 * @see constructor
5398 */
5399 update: function update(options, allowUnknownKeys) {
5400 allowUnknownKeys = allowUnknownKeys || false;
5401 options = this.extractCredentials(options);
5402 AWS.util.each.call(this, options, function (key, value) {
5403 if (allowUnknownKeys || Object.prototype.hasOwnProperty.call(this.keys, key) ||
5404 AWS.Service.hasService(key)) {
5405 this.set(key, value);
5406 }
5407 });
5408 },
5409
5410 /**
5411 * Loads configuration data from a JSON file into this config object.
5412 * @note Loading configuration will reset all existing configuration
5413 * on the object.
5414 * @!macro nobrowser
5415 * @param path [String] the path relative to your process's current
5416 * working directory to load configuration from.
5417 * @return [AWS.Config] the same configuration object
5418 */
5419 loadFromPath: function loadFromPath(path) {
5420 this.clear();
5421
5422 var options = JSON.parse(AWS.util.readFileSync(path));
5423 var fileSystemCreds = new AWS.FileSystemCredentials(path);
5424 var chain = new AWS.CredentialProviderChain();
5425 chain.providers.unshift(fileSystemCreds);
5426 chain.resolve(function (err, creds) {
5427 if (err) throw err;
5428 else options.credentials = creds;
5429 });
5430
5431 this.constructor(options);
5432
5433 return this;
5434 },
5435
5436 /**
5437 * Clears configuration data on this object
5438 *
5439 * @api private
5440 */
5441 clear: function clear() {
5442 /*jshint forin:false */
5443 AWS.util.each.call(this, this.keys, function (key) {
5444 delete this[key];
5445 });
5446
5447 // reset credential provider
5448 this.set('credentials', undefined);
5449 this.set('credentialProvider', undefined);
5450 },
5451
5452 /**
5453 * Sets a property on the configuration object, allowing for a
5454 * default value
5455 * @api private
5456 */
5457 set: function set(property, value, defaultValue) {
5458 if (value === undefined) {
5459 if (defaultValue === undefined) {
5460 defaultValue = this.keys[property];
5461 }
5462 if (typeof defaultValue === 'function') {
5463 this[property] = defaultValue.call(this);
5464 } else {
5465 this[property] = defaultValue;
5466 }
5467 } else if (property === 'httpOptions' && this[property]) {
5468 // deep merge httpOptions
5469 this[property] = AWS.util.merge(this[property], value);
5470 } else {
5471 this[property] = value;
5472 }
5473 },
5474
5475 /**
5476 * All of the keys with their default values.
5477 *
5478 * @constant
5479 * @api private
5480 */
5481 keys: {
5482 credentials: null,
5483 credentialProvider: null,
5484 region: null,
5485 logger: null,
5486 apiVersions: {},
5487 apiVersion: null,
5488 endpoint: undefined,
5489 httpOptions: {
5490 timeout: 120000
5491 },
5492 maxRetries: undefined,
5493 maxRedirects: 10,
5494 paramValidation: true,
5495 sslEnabled: true,
5496 s3ForcePathStyle: false,
5497 s3BucketEndpoint: false,
5498 s3DisableBodySigning: true,
5499 computeChecksums: true,
5500 convertResponseTypes: true,
5501 correctClockSkew: false,
5502 customUserAgent: null,
5503 dynamoDbCrc32: true,
5504 systemClockOffset: 0,
5505 signatureVersion: null,
5506 signatureCache: true,
5507 retryDelayOptions: {},
5508 useAccelerateEndpoint: false,
5509 clientSideMonitoring: false,
5510 endpointDiscoveryEnabled: false,
5511 endpointCacheSize: 1000,
5512 hostPrefixEnabled: true
5513 },
5514
5515 /**
5516 * Extracts accessKeyId, secretAccessKey and sessionToken
5517 * from a configuration hash.
5518 *
5519 * @api private
5520 */
5521 extractCredentials: function extractCredentials(options) {
5522 if (options.accessKeyId && options.secretAccessKey) {
5523 options = AWS.util.copy(options);
5524 options.credentials = new AWS.Credentials(options);
5525 }
5526 return options;
5527 },
5528
5529 /**
5530 * Sets the promise dependency the SDK will use wherever Promises are returned.
5531 * Passing `null` will force the SDK to use native Promises if they are available.
5532 * If native Promises are not available, passing `null` will have no effect.
5533 * @param [Constructor] dep A reference to a Promise constructor
5534 */
5535 setPromisesDependency: function setPromisesDependency(dep) {
5536 PromisesDependency = dep;
5537 // if null was passed in, we should try to use native promises
5538 if (dep === null && typeof Promise === 'function') {
5539 PromisesDependency = Promise;
5540 }
5541 var constructors = [AWS.Request, AWS.Credentials, AWS.CredentialProviderChain];
5542 if (AWS.S3 && AWS.S3.ManagedUpload) constructors.push(AWS.S3.ManagedUpload);
5543 AWS.util.addPromises(constructors, PromisesDependency);
5544 },
5545
5546 /**
5547 * Gets the promise dependency set by `AWS.config.setPromisesDependency`.
5548 */
5549 getPromisesDependency: function getPromisesDependency() {
5550 return PromisesDependency;
5551 }
5552 });
5553
5554 /**
5555 * @return [AWS.Config] The global configuration object singleton instance
5556 * @readonly
5557 * @see AWS.Config
5558 */
5559 AWS.config = new AWS.Config();
5560
5561
5562/***/ }),
5563/* 41 */
5564/***/ (function(module, exports, __webpack_require__) {
5565
5566 var AWS = __webpack_require__(1);
5567
5568 /**
5569 * Represents your AWS security credentials, specifically the
5570 * {accessKeyId}, {secretAccessKey}, and optional {sessionToken}.
5571 * Creating a `Credentials` object allows you to pass around your
5572 * security information to configuration and service objects.
5573 *
5574 * Note that this class typically does not need to be constructed manually,
5575 * as the {AWS.Config} and {AWS.Service} classes both accept simple
5576 * options hashes with the three keys. These structures will be converted
5577 * into Credentials objects automatically.
5578 *
5579 * ## Expiring and Refreshing Credentials
5580 *
5581 * Occasionally credentials can expire in the middle of a long-running
5582 * application. In this case, the SDK will automatically attempt to
5583 * refresh the credentials from the storage location if the Credentials
5584 * class implements the {refresh} method.
5585 *
5586 * If you are implementing a credential storage location, you
5587 * will want to create a subclass of the `Credentials` class and
5588 * override the {refresh} method. This method allows credentials to be
5589 * retrieved from the backing store, be it a file system, database, or
5590 * some network storage. The method should reset the credential attributes
5591 * on the object.
5592 *
5593 * @!attribute expired
5594 * @return [Boolean] whether the credentials have been expired and
5595 * require a refresh. Used in conjunction with {expireTime}.
5596 * @!attribute expireTime
5597 * @return [Date] a time when credentials should be considered expired. Used
5598 * in conjunction with {expired}.
5599 * @!attribute accessKeyId
5600 * @return [String] the AWS access key ID
5601 * @!attribute secretAccessKey
5602 * @return [String] the AWS secret access key
5603 * @!attribute sessionToken
5604 * @return [String] an optional AWS session token
5605 */
5606 AWS.Credentials = AWS.util.inherit({
5607 /**
5608 * A credentials object can be created using positional arguments or an options
5609 * hash.
5610 *
5611 * @overload AWS.Credentials(accessKeyId, secretAccessKey, sessionToken=null)
5612 * Creates a Credentials object with a given set of credential information
5613 * as positional arguments.
5614 * @param accessKeyId [String] the AWS access key ID
5615 * @param secretAccessKey [String] the AWS secret access key
5616 * @param sessionToken [String] the optional AWS session token
5617 * @example Create a credentials object with AWS credentials
5618 * var creds = new AWS.Credentials('akid', 'secret', 'session');
5619 * @overload AWS.Credentials(options)
5620 * Creates a Credentials object with a given set of credential information
5621 * as an options hash.
5622 * @option options accessKeyId [String] the AWS access key ID
5623 * @option options secretAccessKey [String] the AWS secret access key
5624 * @option options sessionToken [String] the optional AWS session token
5625 * @example Create a credentials object with AWS credentials
5626 * var creds = new AWS.Credentials({
5627 * accessKeyId: 'akid', secretAccessKey: 'secret', sessionToken: 'session'
5628 * });
5629 */
5630 constructor: function Credentials() {
5631 // hide secretAccessKey from being displayed with util.inspect
5632 AWS.util.hideProperties(this, ['secretAccessKey']);
5633
5634 this.expired = false;
5635 this.expireTime = null;
5636 this.refreshCallbacks = [];
5637 if (arguments.length === 1 && typeof arguments[0] === 'object') {
5638 var creds = arguments[0].credentials || arguments[0];
5639 this.accessKeyId = creds.accessKeyId;
5640 this.secretAccessKey = creds.secretAccessKey;
5641 this.sessionToken = creds.sessionToken;
5642 } else {
5643 this.accessKeyId = arguments[0];
5644 this.secretAccessKey = arguments[1];
5645 this.sessionToken = arguments[2];
5646 }
5647 },
5648
5649 /**
5650 * @return [Integer] the number of seconds before {expireTime} during which
5651 * the credentials will be considered expired.
5652 */
5653 expiryWindow: 15,
5654
5655 /**
5656 * @return [Boolean] whether the credentials object should call {refresh}
5657 * @note Subclasses should override this method to provide custom refresh
5658 * logic.
5659 */
5660 needsRefresh: function needsRefresh() {
5661 var currentTime = AWS.util.date.getDate().getTime();
5662 var adjustedTime = new Date(currentTime + this.expiryWindow * 1000);
5663
5664 if (this.expireTime && adjustedTime > this.expireTime) {
5665 return true;
5666 } else {
5667 return this.expired || !this.accessKeyId || !this.secretAccessKey;
5668 }
5669 },
5670
5671 /**
5672 * Gets the existing credentials, refreshing them if they are not yet loaded
5673 * or have expired. Users should call this method before using {refresh},
5674 * as this will not attempt to reload credentials when they are already
5675 * loaded into the object.
5676 *
5677 * @callback callback function(err)
5678 * When this callback is called with no error, it means either credentials
5679 * do not need to be refreshed or refreshed credentials information has
5680 * been loaded into the object (as the `accessKeyId`, `secretAccessKey`,
5681 * and `sessionToken` properties).
5682 * @param err [Error] if an error occurred, this value will be filled
5683 */
5684 get: function get(callback) {
5685 var self = this;
5686 if (this.needsRefresh()) {
5687 this.refresh(function(err) {
5688 if (!err) self.expired = false; // reset expired flag
5689 if (callback) callback(err);
5690 });
5691 } else if (callback) {
5692 callback();
5693 }
5694 },
5695
5696 /**
5697 * @!method getPromise()
5698 * Returns a 'thenable' promise.
5699 * Gets the existing credentials, refreshing them if they are not yet loaded
5700 * or have expired. Users should call this method before using {refresh},
5701 * as this will not attempt to reload credentials when they are already
5702 * loaded into the object.
5703 *
5704 * Two callbacks can be provided to the `then` method on the returned promise.
5705 * The first callback will be called if the promise is fulfilled, and the second
5706 * callback will be called if the promise is rejected.
5707 * @callback fulfilledCallback function()
5708 * Called if the promise is fulfilled. When this callback is called, it
5709 * means either credentials do not need to be refreshed or refreshed
5710 * credentials information has been loaded into the object (as the
5711 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5712 * @callback rejectedCallback function(err)
5713 * Called if the promise is rejected.
5714 * @param err [Error] if an error occurred, this value will be filled
5715 * @return [Promise] A promise that represents the state of the `get` call.
5716 * @example Calling the `getPromise` method.
5717 * var promise = credProvider.getPromise();
5718 * promise.then(function() { ... }, function(err) { ... });
5719 */
5720
5721 /**
5722 * @!method refreshPromise()
5723 * Returns a 'thenable' promise.
5724 * Refreshes the credentials. Users should call {get} before attempting
5725 * to forcibly refresh credentials.
5726 *
5727 * Two callbacks can be provided to the `then` method on the returned promise.
5728 * The first callback will be called if the promise is fulfilled, and the second
5729 * callback will be called if the promise is rejected.
5730 * @callback fulfilledCallback function()
5731 * Called if the promise is fulfilled. When this callback is called, it
5732 * means refreshed credentials information has been loaded into the object
5733 * (as the `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5734 * @callback rejectedCallback function(err)
5735 * Called if the promise is rejected.
5736 * @param err [Error] if an error occurred, this value will be filled
5737 * @return [Promise] A promise that represents the state of the `refresh` call.
5738 * @example Calling the `refreshPromise` method.
5739 * var promise = credProvider.refreshPromise();
5740 * promise.then(function() { ... }, function(err) { ... });
5741 */
5742
5743 /**
5744 * Refreshes the credentials. Users should call {get} before attempting
5745 * to forcibly refresh credentials.
5746 *
5747 * @callback callback function(err)
5748 * When this callback is called with no error, it means refreshed
5749 * credentials information has been loaded into the object (as the
5750 * `accessKeyId`, `secretAccessKey`, and `sessionToken` properties).
5751 * @param err [Error] if an error occurred, this value will be filled
5752 * @note Subclasses should override this class to reset the
5753 * {accessKeyId}, {secretAccessKey} and optional {sessionToken}
5754 * on the credentials object and then call the callback with
5755 * any error information.
5756 * @see get
5757 */
5758 refresh: function refresh(callback) {
5759 this.expired = false;
5760 callback();
5761 },
5762
5763 /**
5764 * @api private
5765 * @param callback
5766 */
5767 coalesceRefresh: function coalesceRefresh(callback, sync) {
5768 var self = this;
5769 if (self.refreshCallbacks.push(callback) === 1) {
5770 self.load(function onLoad(err) {
5771 AWS.util.arrayEach(self.refreshCallbacks, function(callback) {
5772 if (sync) {
5773 callback(err);
5774 } else {
5775 // callback could throw, so defer to ensure all callbacks are notified
5776 AWS.util.defer(function () {
5777 callback(err);
5778 });
5779 }
5780 });
5781 self.refreshCallbacks.length = 0;
5782 });
5783 }
5784 },
5785
5786 /**
5787 * @api private
5788 * @param callback
5789 */
5790 load: function load(callback) {
5791 callback();
5792 }
5793 });
5794
5795 /**
5796 * @api private
5797 */
5798 AWS.Credentials.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
5799 this.prototype.getPromise = AWS.util.promisifyMethod('get', PromiseDependency);
5800 this.prototype.refreshPromise = AWS.util.promisifyMethod('refresh', PromiseDependency);
5801 };
5802
5803 /**
5804 * @api private
5805 */
5806 AWS.Credentials.deletePromisesFromClass = function deletePromisesFromClass() {
5807 delete this.prototype.getPromise;
5808 delete this.prototype.refreshPromise;
5809 };
5810
5811 AWS.util.addPromises(AWS.Credentials);
5812
5813
5814/***/ }),
5815/* 42 */
5816/***/ (function(module, exports, __webpack_require__) {
5817
5818 var AWS = __webpack_require__(1);
5819
5820 /**
5821 * Creates a credential provider chain that searches for AWS credentials
5822 * in a list of credential providers specified by the {providers} property.
5823 *
5824 * By default, the chain will use the {defaultProviders} to resolve credentials.
5825 * These providers will look in the environment using the
5826 * {AWS.EnvironmentCredentials} class with the 'AWS' and 'AMAZON' prefixes.
5827 *
5828 * ## Setting Providers
5829 *
5830 * Each provider in the {providers} list should be a function that returns
5831 * a {AWS.Credentials} object, or a hardcoded credentials object. The function
5832 * form allows for delayed execution of the credential construction.
5833 *
5834 * ## Resolving Credentials from a Chain
5835 *
5836 * Call {resolve} to return the first valid credential object that can be
5837 * loaded by the provider chain.
5838 *
5839 * For example, to resolve a chain with a custom provider that checks a file
5840 * on disk after the set of {defaultProviders}:
5841 *
5842 * ```javascript
5843 * var diskProvider = new AWS.FileSystemCredentials('./creds.json');
5844 * var chain = new AWS.CredentialProviderChain();
5845 * chain.providers.push(diskProvider);
5846 * chain.resolve();
5847 * ```
5848 *
5849 * The above code will return the `diskProvider` object if the
5850 * file contains credentials and the `defaultProviders` do not contain
5851 * any credential settings.
5852 *
5853 * @!attribute providers
5854 * @return [Array<AWS.Credentials, Function>]
5855 * a list of credentials objects or functions that return credentials
5856 * objects. If the provider is a function, the function will be
5857 * executed lazily when the provider needs to be checked for valid
5858 * credentials. By default, this object will be set to the
5859 * {defaultProviders}.
5860 * @see defaultProviders
5861 */
5862 AWS.CredentialProviderChain = AWS.util.inherit(AWS.Credentials, {
5863
5864 /**
5865 * Creates a new CredentialProviderChain with a default set of providers
5866 * specified by {defaultProviders}.
5867 */
5868 constructor: function CredentialProviderChain(providers) {
5869 if (providers) {
5870 this.providers = providers;
5871 } else {
5872 this.providers = AWS.CredentialProviderChain.defaultProviders.slice(0);
5873 }
5874 this.resolveCallbacks = [];
5875 },
5876
5877 /**
5878 * @!method resolvePromise()
5879 * Returns a 'thenable' promise.
5880 * Resolves the provider chain by searching for the first set of
5881 * credentials in {providers}.
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(credentials)
5887 * Called if the promise is fulfilled and the provider resolves the chain
5888 * to a credentials object
5889 * @param credentials [AWS.Credentials] the credentials object resolved
5890 * by the provider chain.
5891 * @callback rejectedCallback function(error)
5892 * Called if the promise is rejected.
5893 * @param err [Error] the error object returned if no credentials are found.
5894 * @return [Promise] A promise that represents the state of the `resolve` method call.
5895 * @example Calling the `resolvePromise` method.
5896 * var promise = chain.resolvePromise();
5897 * promise.then(function(credentials) { ... }, function(err) { ... });
5898 */
5899
5900 /**
5901 * Resolves the provider chain by searching for the first set of
5902 * credentials in {providers}.
5903 *
5904 * @callback callback function(err, credentials)
5905 * Called when the provider resolves the chain to a credentials object
5906 * or null if no credentials can be found.
5907 *
5908 * @param err [Error] the error object returned if no credentials are
5909 * found.
5910 * @param credentials [AWS.Credentials] the credentials object resolved
5911 * by the provider chain.
5912 * @return [AWS.CredentialProviderChain] the provider, for chaining.
5913 */
5914 resolve: function resolve(callback) {
5915 var self = this;
5916 if (self.providers.length === 0) {
5917 callback(new Error('No providers'));
5918 return self;
5919 }
5920
5921 if (self.resolveCallbacks.push(callback) === 1) {
5922 var index = 0;
5923 var providers = self.providers.slice(0);
5924
5925 function resolveNext(err, creds) {
5926 if ((!err && creds) || index === providers.length) {
5927 AWS.util.arrayEach(self.resolveCallbacks, function (callback) {
5928 callback(err, creds);
5929 });
5930 self.resolveCallbacks.length = 0;
5931 return;
5932 }
5933
5934 var provider = providers[index++];
5935 if (typeof provider === 'function') {
5936 creds = provider.call();
5937 } else {
5938 creds = provider;
5939 }
5940
5941 if (creds.get) {
5942 creds.get(function (getErr) {
5943 resolveNext(getErr, getErr ? null : creds);
5944 });
5945 } else {
5946 resolveNext(null, creds);
5947 }
5948 }
5949
5950 resolveNext();
5951 }
5952
5953 return self;
5954 }
5955 });
5956
5957 /**
5958 * The default set of providers used by a vanilla CredentialProviderChain.
5959 *
5960 * In the browser:
5961 *
5962 * ```javascript
5963 * AWS.CredentialProviderChain.defaultProviders = []
5964 * ```
5965 *
5966 * In Node.js:
5967 *
5968 * ```javascript
5969 * AWS.CredentialProviderChain.defaultProviders = [
5970 * function () { return new AWS.EnvironmentCredentials('AWS'); },
5971 * function () { return new AWS.EnvironmentCredentials('AMAZON'); },
5972 * function () { return new AWS.SharedIniFileCredentials(); },
5973 * function () {
5974 * // if AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set
5975 * return new AWS.ECSCredentials();
5976 * // else
5977 * return new AWS.EC2MetadataCredentials();
5978 * }
5979 * ]
5980 * ```
5981 */
5982 AWS.CredentialProviderChain.defaultProviders = [];
5983
5984 /**
5985 * @api private
5986 */
5987 AWS.CredentialProviderChain.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
5988 this.prototype.resolvePromise = AWS.util.promisifyMethod('resolve', PromiseDependency);
5989 };
5990
5991 /**
5992 * @api private
5993 */
5994 AWS.CredentialProviderChain.deletePromisesFromClass = function deletePromisesFromClass() {
5995 delete this.prototype.resolvePromise;
5996 };
5997
5998 AWS.util.addPromises(AWS.CredentialProviderChain);
5999
6000
6001/***/ }),
6002/* 43 */
6003/***/ (function(module, exports, __webpack_require__) {
6004
6005 var AWS = __webpack_require__(1);
6006 var inherit = AWS.util.inherit;
6007
6008 /**
6009 * The endpoint that a service will talk to, for example,
6010 * `'https://ec2.ap-southeast-1.amazonaws.com'`. If
6011 * you need to override an endpoint for a service, you can
6012 * set the endpoint on a service by passing the endpoint
6013 * object with the `endpoint` option key:
6014 *
6015 * ```javascript
6016 * var ep = new AWS.Endpoint('awsproxy.example.com');
6017 * var s3 = new AWS.S3({endpoint: ep});
6018 * s3.service.endpoint.hostname == 'awsproxy.example.com'
6019 * ```
6020 *
6021 * Note that if you do not specify a protocol, the protocol will
6022 * be selected based on your current {AWS.config} configuration.
6023 *
6024 * @!attribute protocol
6025 * @return [String] the protocol (http or https) of the endpoint
6026 * URL
6027 * @!attribute hostname
6028 * @return [String] the host portion of the endpoint, e.g.,
6029 * example.com
6030 * @!attribute host
6031 * @return [String] the host portion of the endpoint including
6032 * the port, e.g., example.com:80
6033 * @!attribute port
6034 * @return [Integer] the port of the endpoint
6035 * @!attribute href
6036 * @return [String] the full URL of the endpoint
6037 */
6038 AWS.Endpoint = inherit({
6039
6040 /**
6041 * @overload Endpoint(endpoint)
6042 * Constructs a new endpoint given an endpoint URL. If the
6043 * URL omits a protocol (http or https), the default protocol
6044 * set in the global {AWS.config} will be used.
6045 * @param endpoint [String] the URL to construct an endpoint from
6046 */
6047 constructor: function Endpoint(endpoint, config) {
6048 AWS.util.hideProperties(this, ['slashes', 'auth', 'hash', 'search', 'query']);
6049
6050 if (typeof endpoint === 'undefined' || endpoint === null) {
6051 throw new Error('Invalid endpoint: ' + endpoint);
6052 } else if (typeof endpoint !== 'string') {
6053 return AWS.util.copy(endpoint);
6054 }
6055
6056 if (!endpoint.match(/^http/)) {
6057 var useSSL = config && config.sslEnabled !== undefined ?
6058 config.sslEnabled : AWS.config.sslEnabled;
6059 endpoint = (useSSL ? 'https' : 'http') + '://' + endpoint;
6060 }
6061
6062 AWS.util.update(this, AWS.util.urlParse(endpoint));
6063
6064 // Ensure the port property is set as an integer
6065 if (this.port) {
6066 this.port = parseInt(this.port, 10);
6067 } else {
6068 this.port = this.protocol === 'https:' ? 443 : 80;
6069 }
6070 }
6071
6072 });
6073
6074 /**
6075 * The low level HTTP request object, encapsulating all HTTP header
6076 * and body data sent by a service request.
6077 *
6078 * @!attribute method
6079 * @return [String] the HTTP method of the request
6080 * @!attribute path
6081 * @return [String] the path portion of the URI, e.g.,
6082 * "/list/?start=5&num=10"
6083 * @!attribute headers
6084 * @return [map<String,String>]
6085 * a map of header keys and their respective values
6086 * @!attribute body
6087 * @return [String] the request body payload
6088 * @!attribute endpoint
6089 * @return [AWS.Endpoint] the endpoint for the request
6090 * @!attribute region
6091 * @api private
6092 * @return [String] the region, for signing purposes only.
6093 */
6094 AWS.HttpRequest = inherit({
6095
6096 /**
6097 * @api private
6098 */
6099 constructor: function HttpRequest(endpoint, region) {
6100 endpoint = new AWS.Endpoint(endpoint);
6101 this.method = 'POST';
6102 this.path = endpoint.path || '/';
6103 this.headers = {};
6104 this.body = '';
6105 this.endpoint = endpoint;
6106 this.region = region;
6107 this._userAgent = '';
6108 this.setUserAgent();
6109 },
6110
6111 /**
6112 * @api private
6113 */
6114 setUserAgent: function setUserAgent() {
6115 this._userAgent = this.headers[this.getUserAgentHeaderName()] = AWS.util.userAgent();
6116 },
6117
6118 getUserAgentHeaderName: function getUserAgentHeaderName() {
6119 var prefix = AWS.util.isBrowser() ? 'X-Amz-' : '';
6120 return prefix + 'User-Agent';
6121 },
6122
6123 /**
6124 * @api private
6125 */
6126 appendToUserAgent: function appendToUserAgent(agentPartial) {
6127 if (typeof agentPartial === 'string' && agentPartial) {
6128 this._userAgent += ' ' + agentPartial;
6129 }
6130 this.headers[this.getUserAgentHeaderName()] = this._userAgent;
6131 },
6132
6133 /**
6134 * @api private
6135 */
6136 getUserAgent: function getUserAgent() {
6137 return this._userAgent;
6138 },
6139
6140 /**
6141 * @return [String] the part of the {path} excluding the
6142 * query string
6143 */
6144 pathname: function pathname() {
6145 return this.path.split('?', 1)[0];
6146 },
6147
6148 /**
6149 * @return [String] the query string portion of the {path}
6150 */
6151 search: function search() {
6152 var query = this.path.split('?', 2)[1];
6153 if (query) {
6154 query = AWS.util.queryStringParse(query);
6155 return AWS.util.queryParamsToString(query);
6156 }
6157 return '';
6158 },
6159
6160 /**
6161 * @api private
6162 * update httpRequest endpoint with endpoint string
6163 */
6164 updateEndpoint: function updateEndpoint(endpointStr) {
6165 var newEndpoint = new AWS.Endpoint(endpointStr);
6166 this.endpoint = newEndpoint;
6167 this.path = newEndpoint.path || '/';
6168 }
6169 });
6170
6171 /**
6172 * The low level HTTP response object, encapsulating all HTTP header
6173 * and body data returned from the request.
6174 *
6175 * @!attribute statusCode
6176 * @return [Integer] the HTTP status code of the response (e.g., 200, 404)
6177 * @!attribute headers
6178 * @return [map<String,String>]
6179 * a map of response header keys and their respective values
6180 * @!attribute body
6181 * @return [String] the response body payload
6182 * @!attribute [r] streaming
6183 * @return [Boolean] whether this response is being streamed at a low-level.
6184 * Defaults to `false` (buffered reads). Do not modify this manually, use
6185 * {createUnbufferedStream} to convert the stream to unbuffered mode
6186 * instead.
6187 */
6188 AWS.HttpResponse = inherit({
6189
6190 /**
6191 * @api private
6192 */
6193 constructor: function HttpResponse() {
6194 this.statusCode = undefined;
6195 this.headers = {};
6196 this.body = undefined;
6197 this.streaming = false;
6198 this.stream = null;
6199 },
6200
6201 /**
6202 * Disables buffering on the HTTP response and returns the stream for reading.
6203 * @return [Stream, XMLHttpRequest, null] the underlying stream object.
6204 * Use this object to directly read data off of the stream.
6205 * @note This object is only available after the {AWS.Request~httpHeaders}
6206 * event has fired. This method must be called prior to
6207 * {AWS.Request~httpData}.
6208 * @example Taking control of a stream
6209 * request.on('httpHeaders', function(statusCode, headers) {
6210 * if (statusCode < 300) {
6211 * if (headers.etag === 'xyz') {
6212 * // pipe the stream, disabling buffering
6213 * var stream = this.response.httpResponse.createUnbufferedStream();
6214 * stream.pipe(process.stdout);
6215 * } else { // abort this request and set a better error message
6216 * this.abort();
6217 * this.response.error = new Error('Invalid ETag');
6218 * }
6219 * }
6220 * }).send(console.log);
6221 */
6222 createUnbufferedStream: function createUnbufferedStream() {
6223 this.streaming = true;
6224 return this.stream;
6225 }
6226 });
6227
6228
6229 AWS.HttpClient = inherit({});
6230
6231 /**
6232 * @api private
6233 */
6234 AWS.HttpClient.getInstance = function getInstance() {
6235 if (this.singleton === undefined) {
6236 this.singleton = new this();
6237 }
6238 return this.singleton;
6239 };
6240
6241
6242/***/ }),
6243/* 44 */
6244/***/ (function(module, exports, __webpack_require__) {
6245
6246 var AWS = __webpack_require__(1);
6247 var SequentialExecutor = __webpack_require__(36);
6248 var DISCOVER_ENDPOINT = __webpack_require__(45).discoverEndpoint;
6249 /**
6250 * The namespace used to register global event listeners for request building
6251 * and sending.
6252 */
6253 AWS.EventListeners = {
6254 /**
6255 * @!attribute VALIDATE_CREDENTIALS
6256 * A request listener that validates whether the request is being
6257 * sent with credentials.
6258 * Handles the {AWS.Request~validate 'validate' Request event}
6259 * @example Sending a request without validating credentials
6260 * var listener = AWS.EventListeners.Core.VALIDATE_CREDENTIALS;
6261 * request.removeListener('validate', listener);
6262 * @readonly
6263 * @return [Function]
6264 * @!attribute VALIDATE_REGION
6265 * A request listener that validates whether the region is set
6266 * for a request.
6267 * Handles the {AWS.Request~validate 'validate' Request event}
6268 * @example Sending a request without validating region configuration
6269 * var listener = AWS.EventListeners.Core.VALIDATE_REGION;
6270 * request.removeListener('validate', listener);
6271 * @readonly
6272 * @return [Function]
6273 * @!attribute VALIDATE_PARAMETERS
6274 * A request listener that validates input parameters in a request.
6275 * Handles the {AWS.Request~validate 'validate' Request event}
6276 * @example Sending a request without validating parameters
6277 * var listener = AWS.EventListeners.Core.VALIDATE_PARAMETERS;
6278 * request.removeListener('validate', listener);
6279 * @example Disable parameter validation globally
6280 * AWS.EventListeners.Core.removeListener('validate',
6281 * AWS.EventListeners.Core.VALIDATE_REGION);
6282 * @readonly
6283 * @return [Function]
6284 * @!attribute SEND
6285 * A request listener that initiates the HTTP connection for a
6286 * request being sent. Handles the {AWS.Request~send 'send' Request event}
6287 * @example Replacing the HTTP handler
6288 * var listener = AWS.EventListeners.Core.SEND;
6289 * request.removeListener('send', listener);
6290 * request.on('send', function(response) {
6291 * customHandler.send(response);
6292 * });
6293 * @return [Function]
6294 * @readonly
6295 * @!attribute HTTP_DATA
6296 * A request listener that reads data from the HTTP connection in order
6297 * to build the response data.
6298 * Handles the {AWS.Request~httpData 'httpData' Request event}.
6299 * Remove this handler if you are overriding the 'httpData' event and
6300 * do not want extra data processing and buffering overhead.
6301 * @example Disabling default data processing
6302 * var listener = AWS.EventListeners.Core.HTTP_DATA;
6303 * request.removeListener('httpData', listener);
6304 * @return [Function]
6305 * @readonly
6306 */
6307 Core: {} /* doc hack */
6308 };
6309
6310 /**
6311 * @api private
6312 */
6313 function getOperationAuthtype(req) {
6314 if (!req.service.api.operations) {
6315 return '';
6316 }
6317 var operation = req.service.api.operations[req.operation];
6318 return operation ? operation.authtype : '';
6319 }
6320
6321 AWS.EventListeners = {
6322 Core: new SequentialExecutor().addNamedListeners(function(add, addAsync) {
6323 addAsync('VALIDATE_CREDENTIALS', 'validate',
6324 function VALIDATE_CREDENTIALS(req, done) {
6325 if (!req.service.api.signatureVersion) return done(); // none
6326 req.service.config.getCredentials(function(err) {
6327 if (err) {
6328 req.response.error = AWS.util.error(err,
6329 {code: 'CredentialsError', message: 'Missing credentials in config'});
6330 }
6331 done();
6332 });
6333 });
6334
6335 add('VALIDATE_REGION', 'validate', function VALIDATE_REGION(req) {
6336 if (!req.service.config.region && !req.service.isGlobalEndpoint) {
6337 req.response.error = AWS.util.error(new Error(),
6338 {code: 'ConfigError', message: 'Missing region in config'});
6339 }
6340 });
6341
6342 add('BUILD_IDEMPOTENCY_TOKENS', 'validate', function BUILD_IDEMPOTENCY_TOKENS(req) {
6343 if (!req.service.api.operations) {
6344 return;
6345 }
6346 var operation = req.service.api.operations[req.operation];
6347 if (!operation) {
6348 return;
6349 }
6350 var idempotentMembers = operation.idempotentMembers;
6351 if (!idempotentMembers.length) {
6352 return;
6353 }
6354 // creates a copy of params so user's param object isn't mutated
6355 var params = AWS.util.copy(req.params);
6356 for (var i = 0, iLen = idempotentMembers.length; i < iLen; i++) {
6357 if (!params[idempotentMembers[i]]) {
6358 // add the member
6359 params[idempotentMembers[i]] = AWS.util.uuid.v4();
6360 }
6361 }
6362 req.params = params;
6363 });
6364
6365 add('VALIDATE_PARAMETERS', 'validate', function VALIDATE_PARAMETERS(req) {
6366 if (!req.service.api.operations) {
6367 return;
6368 }
6369 var rules = req.service.api.operations[req.operation].input;
6370 var validation = req.service.config.paramValidation;
6371 new AWS.ParamValidator(validation).validate(rules, req.params);
6372 });
6373
6374 addAsync('COMPUTE_SHA256', 'afterBuild', function COMPUTE_SHA256(req, done) {
6375 req.haltHandlersOnError();
6376 if (!req.service.api.operations) {
6377 return;
6378 }
6379 var operation = req.service.api.operations[req.operation];
6380 var authtype = operation ? operation.authtype : '';
6381 if (!req.service.api.signatureVersion && !authtype) return done(); // none
6382 if (req.service.getSignerClass(req) === AWS.Signers.V4) {
6383 var body = req.httpRequest.body || '';
6384 if (authtype.indexOf('unsigned-body') >= 0) {
6385 req.httpRequest.headers['X-Amz-Content-Sha256'] = 'UNSIGNED-PAYLOAD';
6386 return done();
6387 }
6388 AWS.util.computeSha256(body, function(err, sha) {
6389 if (err) {
6390 done(err);
6391 }
6392 else {
6393 req.httpRequest.headers['X-Amz-Content-Sha256'] = sha;
6394 done();
6395 }
6396 });
6397 } else {
6398 done();
6399 }
6400 });
6401
6402 add('SET_CONTENT_LENGTH', 'afterBuild', function SET_CONTENT_LENGTH(req) {
6403 var authtype = getOperationAuthtype(req);
6404 if (req.httpRequest.headers['Content-Length'] === undefined) {
6405 try {
6406 var length = AWS.util.string.byteLength(req.httpRequest.body);
6407 req.httpRequest.headers['Content-Length'] = length;
6408 } catch (err) {
6409 if (authtype.indexOf('unsigned-body') === -1) {
6410 throw err;
6411 } else {
6412 // Body isn't signed and may not need content length (lex)
6413 return;
6414 }
6415 }
6416 }
6417 });
6418
6419 add('SET_HTTP_HOST', 'afterBuild', function SET_HTTP_HOST(req) {
6420 req.httpRequest.headers['Host'] = req.httpRequest.endpoint.host;
6421 });
6422
6423 add('RESTART', 'restart', function RESTART() {
6424 var err = this.response.error;
6425 if (!err || !err.retryable) return;
6426
6427 this.httpRequest = new AWS.HttpRequest(
6428 this.service.endpoint,
6429 this.service.region
6430 );
6431
6432 if (this.response.retryCount < this.service.config.maxRetries) {
6433 this.response.retryCount++;
6434 } else {
6435 this.response.error = null;
6436 }
6437 });
6438
6439 var addToHead = true;
6440 addAsync('DISCOVER_ENDPOINT', 'sign', DISCOVER_ENDPOINT, addToHead);
6441
6442 addAsync('SIGN', 'sign', function SIGN(req, done) {
6443 var service = req.service;
6444 var operations = req.service.api.operations || {};
6445 var operation = operations[req.operation];
6446 var authtype = operation ? operation.authtype : '';
6447 if (!service.api.signatureVersion && !authtype) return done(); // none
6448
6449 service.config.getCredentials(function (err, credentials) {
6450 if (err) {
6451 req.response.error = err;
6452 return done();
6453 }
6454
6455 try {
6456 var date = service.getSkewCorrectedDate();
6457 var SignerClass = service.getSignerClass(req);
6458 var signer = new SignerClass(req.httpRequest,
6459 service.api.signingName || service.api.endpointPrefix,
6460 {
6461 signatureCache: service.config.signatureCache,
6462 operation: operation,
6463 signatureVersion: service.api.signatureVersion
6464 });
6465 signer.setServiceClientId(service._clientId);
6466
6467 // clear old authorization headers
6468 delete req.httpRequest.headers['Authorization'];
6469 delete req.httpRequest.headers['Date'];
6470 delete req.httpRequest.headers['X-Amz-Date'];
6471
6472 // add new authorization
6473 signer.addAuthorization(credentials, date);
6474 req.signedAt = date;
6475 } catch (e) {
6476 req.response.error = e;
6477 }
6478 done();
6479 });
6480 });
6481
6482 add('VALIDATE_RESPONSE', 'validateResponse', function VALIDATE_RESPONSE(resp) {
6483 if (this.service.successfulResponse(resp, this)) {
6484 resp.data = {};
6485 resp.error = null;
6486 } else {
6487 resp.data = null;
6488 resp.error = AWS.util.error(new Error(),
6489 {code: 'UnknownError', message: 'An unknown error occurred.'});
6490 }
6491 });
6492
6493 addAsync('SEND', 'send', function SEND(resp, done) {
6494 resp.httpResponse._abortCallback = done;
6495 resp.error = null;
6496 resp.data = null;
6497
6498 function callback(httpResp) {
6499 resp.httpResponse.stream = httpResp;
6500 var stream = resp.request.httpRequest.stream;
6501 var service = resp.request.service;
6502 var api = service.api;
6503 var operationName = resp.request.operation;
6504 var operation = api.operations[operationName] || {};
6505
6506 httpResp.on('headers', function onHeaders(statusCode, headers, statusMessage) {
6507 resp.request.emit(
6508 'httpHeaders',
6509 [statusCode, headers, resp, statusMessage]
6510 );
6511
6512 if (!resp.httpResponse.streaming) {
6513 if (AWS.HttpClient.streamsApiVersion === 2) { // streams2 API check
6514 // if we detect event streams, we're going to have to
6515 // return the stream immediately
6516 if (operation.hasEventOutput && service.successfulResponse(resp)) {
6517 // skip reading the IncomingStream
6518 resp.request.emit('httpDone');
6519 done();
6520 return;
6521 }
6522
6523 httpResp.on('readable', function onReadable() {
6524 var data = httpResp.read();
6525 if (data !== null) {
6526 resp.request.emit('httpData', [data, resp]);
6527 }
6528 });
6529 } else { // legacy streams API
6530 httpResp.on('data', function onData(data) {
6531 resp.request.emit('httpData', [data, resp]);
6532 });
6533 }
6534 }
6535 });
6536
6537 httpResp.on('end', function onEnd() {
6538 if (!stream || !stream.didCallback) {
6539 if (AWS.HttpClient.streamsApiVersion === 2 && (operation.hasEventOutput && service.successfulResponse(resp))) {
6540 // don't concatenate response chunks when streaming event stream data when response is successful
6541 return;
6542 }
6543 resp.request.emit('httpDone');
6544 done();
6545 }
6546 });
6547 }
6548
6549 function progress(httpResp) {
6550 httpResp.on('sendProgress', function onSendProgress(value) {
6551 resp.request.emit('httpUploadProgress', [value, resp]);
6552 });
6553
6554 httpResp.on('receiveProgress', function onReceiveProgress(value) {
6555 resp.request.emit('httpDownloadProgress', [value, resp]);
6556 });
6557 }
6558
6559 function error(err) {
6560 if (err.code !== 'RequestAbortedError') {
6561 var errCode = err.code === 'TimeoutError' ? err.code : 'NetworkingError';
6562 err = AWS.util.error(err, {
6563 code: errCode,
6564 region: resp.request.httpRequest.region,
6565 hostname: resp.request.httpRequest.endpoint.hostname,
6566 retryable: true
6567 });
6568 }
6569 resp.error = err;
6570 resp.request.emit('httpError', [resp.error, resp], function() {
6571 done();
6572 });
6573 }
6574
6575 function executeSend() {
6576 var http = AWS.HttpClient.getInstance();
6577 var httpOptions = resp.request.service.config.httpOptions || {};
6578 try {
6579 var stream = http.handleRequest(resp.request.httpRequest, httpOptions,
6580 callback, error);
6581 progress(stream);
6582 } catch (err) {
6583 error(err);
6584 }
6585 }
6586 var timeDiff = (resp.request.service.getSkewCorrectedDate() - this.signedAt) / 1000;
6587 if (timeDiff >= 60 * 10) { // if we signed 10min ago, re-sign
6588 this.emit('sign', [this], function(err) {
6589 if (err) done(err);
6590 else executeSend();
6591 });
6592 } else {
6593 executeSend();
6594 }
6595 });
6596
6597 add('HTTP_HEADERS', 'httpHeaders',
6598 function HTTP_HEADERS(statusCode, headers, resp, statusMessage) {
6599 resp.httpResponse.statusCode = statusCode;
6600 resp.httpResponse.statusMessage = statusMessage;
6601 resp.httpResponse.headers = headers;
6602 resp.httpResponse.body = new AWS.util.Buffer('');
6603 resp.httpResponse.buffers = [];
6604 resp.httpResponse.numBytes = 0;
6605 var dateHeader = headers.date || headers.Date;
6606 var service = resp.request.service;
6607 if (dateHeader) {
6608 var serverTime = Date.parse(dateHeader);
6609 if (service.config.correctClockSkew
6610 && service.isClockSkewed(serverTime)) {
6611 service.applyClockOffset(serverTime);
6612 }
6613 }
6614 });
6615
6616 add('HTTP_DATA', 'httpData', function HTTP_DATA(chunk, resp) {
6617 if (chunk) {
6618 if (AWS.util.isNode()) {
6619 resp.httpResponse.numBytes += chunk.length;
6620
6621 var total = resp.httpResponse.headers['content-length'];
6622 var progress = { loaded: resp.httpResponse.numBytes, total: total };
6623 resp.request.emit('httpDownloadProgress', [progress, resp]);
6624 }
6625
6626 resp.httpResponse.buffers.push(new AWS.util.Buffer(chunk));
6627 }
6628 });
6629
6630 add('HTTP_DONE', 'httpDone', function HTTP_DONE(resp) {
6631 // convert buffers array into single buffer
6632 if (resp.httpResponse.buffers && resp.httpResponse.buffers.length > 0) {
6633 var body = AWS.util.buffer.concat(resp.httpResponse.buffers);
6634 resp.httpResponse.body = body;
6635 }
6636 delete resp.httpResponse.numBytes;
6637 delete resp.httpResponse.buffers;
6638 });
6639
6640 add('FINALIZE_ERROR', 'retry', function FINALIZE_ERROR(resp) {
6641 if (resp.httpResponse.statusCode) {
6642 resp.error.statusCode = resp.httpResponse.statusCode;
6643 if (resp.error.retryable === undefined) {
6644 resp.error.retryable = this.service.retryableError(resp.error, this);
6645 }
6646 }
6647 });
6648
6649 add('INVALIDATE_CREDENTIALS', 'retry', function INVALIDATE_CREDENTIALS(resp) {
6650 if (!resp.error) return;
6651 switch (resp.error.code) {
6652 case 'RequestExpired': // EC2 only
6653 case 'ExpiredTokenException':
6654 case 'ExpiredToken':
6655 resp.error.retryable = true;
6656 resp.request.service.config.credentials.expired = true;
6657 }
6658 });
6659
6660 add('EXPIRED_SIGNATURE', 'retry', function EXPIRED_SIGNATURE(resp) {
6661 var err = resp.error;
6662 if (!err) return;
6663 if (typeof err.code === 'string' && typeof err.message === 'string') {
6664 if (err.code.match(/Signature/) && err.message.match(/expired/)) {
6665 resp.error.retryable = true;
6666 }
6667 }
6668 });
6669
6670 add('CLOCK_SKEWED', 'retry', function CLOCK_SKEWED(resp) {
6671 if (!resp.error) return;
6672 if (this.service.clockSkewError(resp.error)
6673 && this.service.config.correctClockSkew) {
6674 resp.error.retryable = true;
6675 }
6676 });
6677
6678 add('REDIRECT', 'retry', function REDIRECT(resp) {
6679 if (resp.error && resp.error.statusCode >= 300 &&
6680 resp.error.statusCode < 400 && resp.httpResponse.headers['location']) {
6681 this.httpRequest.endpoint =
6682 new AWS.Endpoint(resp.httpResponse.headers['location']);
6683 this.httpRequest.headers['Host'] = this.httpRequest.endpoint.host;
6684 resp.error.redirect = true;
6685 resp.error.retryable = true;
6686 }
6687 });
6688
6689 add('RETRY_CHECK', 'retry', function RETRY_CHECK(resp) {
6690 if (resp.error) {
6691 if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6692 resp.error.retryDelay = 0;
6693 } else if (resp.retryCount < resp.maxRetries) {
6694 resp.error.retryDelay = this.service.retryDelays(resp.retryCount) || 0;
6695 }
6696 }
6697 });
6698
6699 addAsync('RESET_RETRY_STATE', 'afterRetry', function RESET_RETRY_STATE(resp, done) {
6700 var delay, willRetry = false;
6701
6702 if (resp.error) {
6703 delay = resp.error.retryDelay || 0;
6704 if (resp.error.retryable && resp.retryCount < resp.maxRetries) {
6705 resp.retryCount++;
6706 willRetry = true;
6707 } else if (resp.error.redirect && resp.redirectCount < resp.maxRedirects) {
6708 resp.redirectCount++;
6709 willRetry = true;
6710 }
6711 }
6712
6713 if (willRetry) {
6714 resp.error = null;
6715 setTimeout(done, delay);
6716 } else {
6717 done();
6718 }
6719 });
6720 }),
6721
6722 CorePost: new SequentialExecutor().addNamedListeners(function(add) {
6723 add('EXTRACT_REQUEST_ID', 'extractData', AWS.util.extractRequestId);
6724 add('EXTRACT_REQUEST_ID', 'extractError', AWS.util.extractRequestId);
6725
6726 add('ENOTFOUND_ERROR', 'httpError', function ENOTFOUND_ERROR(err) {
6727 if (err.code === 'NetworkingError' && err.errno === 'ENOTFOUND') {
6728 var message = 'Inaccessible host: `' + err.hostname +
6729 '\'. This service may not be available in the `' + err.region +
6730 '\' region.';
6731 this.response.error = AWS.util.error(new Error(message), {
6732 code: 'UnknownEndpoint',
6733 region: err.region,
6734 hostname: err.hostname,
6735 retryable: true,
6736 originalError: err
6737 });
6738 }
6739 });
6740 }),
6741
6742 Logger: new SequentialExecutor().addNamedListeners(function(add) {
6743 add('LOG_REQUEST', 'complete', function LOG_REQUEST(resp) {
6744 var req = resp.request;
6745 var logger = req.service.config.logger;
6746 if (!logger) return;
6747 function filterSensitiveLog(inputShape, shape) {
6748 if (!shape) {
6749 return shape;
6750 }
6751 switch (inputShape.type) {
6752 case 'structure':
6753 var struct = {};
6754 AWS.util.each(shape, function(subShapeName, subShape) {
6755 if (Object.prototype.hasOwnProperty.call(inputShape.members, subShapeName)) {
6756 struct[subShapeName] = filterSensitiveLog(inputShape.members[subShapeName], subShape);
6757 } else {
6758 struct[subShapeName] = subShape;
6759 }
6760 });
6761 return struct;
6762 case 'list':
6763 var list = [];
6764 AWS.util.arrayEach(shape, function(subShape, index) {
6765 list.push(filterSensitiveLog(inputShape.member, subShape));
6766 });
6767 return list;
6768 case 'map':
6769 var map = {};
6770 AWS.util.each(shape, function(key, value) {
6771 map[key] = filterSensitiveLog(inputShape.value, value);
6772 });
6773 return map;
6774 default:
6775 if (inputShape.isSensitive) {
6776 return '***SensitiveInformation***';
6777 } else {
6778 return shape;
6779 }
6780 }
6781 }
6782
6783 function buildMessage() {
6784 var time = resp.request.service.getSkewCorrectedDate().getTime();
6785 var delta = (time - req.startTime.getTime()) / 1000;
6786 var ansi = logger.isTTY ? true : false;
6787 var status = resp.httpResponse.statusCode;
6788 var censoredParams = req.params;
6789 if (
6790 req.service.api.operations &&
6791 req.service.api.operations[req.operation] &&
6792 req.service.api.operations[req.operation].input
6793 ) {
6794 var inputShape = req.service.api.operations[req.operation].input;
6795 censoredParams = filterSensitiveLog(inputShape, req.params);
6796 }
6797 var params = __webpack_require__(46).inspect(censoredParams, true, null);
6798 var message = '';
6799 if (ansi) message += '\x1B[33m';
6800 message += '[AWS ' + req.service.serviceIdentifier + ' ' + status;
6801 message += ' ' + delta.toString() + 's ' + resp.retryCount + ' retries]';
6802 if (ansi) message += '\x1B[0;1m';
6803 message += ' ' + AWS.util.string.lowerFirst(req.operation);
6804 message += '(' + params + ')';
6805 if (ansi) message += '\x1B[0m';
6806 return message;
6807 }
6808
6809 var line = buildMessage();
6810 if (typeof logger.log === 'function') {
6811 logger.log(line);
6812 } else if (typeof logger.write === 'function') {
6813 logger.write(line + '\n');
6814 }
6815 });
6816 }),
6817
6818 Json: new SequentialExecutor().addNamedListeners(function(add) {
6819 var svc = __webpack_require__(13);
6820 add('BUILD', 'build', svc.buildRequest);
6821 add('EXTRACT_DATA', 'extractData', svc.extractData);
6822 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6823 }),
6824
6825 Rest: new SequentialExecutor().addNamedListeners(function(add) {
6826 var svc = __webpack_require__(21);
6827 add('BUILD', 'build', svc.buildRequest);
6828 add('EXTRACT_DATA', 'extractData', svc.extractData);
6829 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6830 }),
6831
6832 RestJson: new SequentialExecutor().addNamedListeners(function(add) {
6833 var svc = __webpack_require__(22);
6834 add('BUILD', 'build', svc.buildRequest);
6835 add('EXTRACT_DATA', 'extractData', svc.extractData);
6836 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6837 }),
6838
6839 RestXml: new SequentialExecutor().addNamedListeners(function(add) {
6840 var svc = __webpack_require__(23);
6841 add('BUILD', 'build', svc.buildRequest);
6842 add('EXTRACT_DATA', 'extractData', svc.extractData);
6843 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6844 }),
6845
6846 Query: new SequentialExecutor().addNamedListeners(function(add) {
6847 var svc = __webpack_require__(17);
6848 add('BUILD', 'build', svc.buildRequest);
6849 add('EXTRACT_DATA', 'extractData', svc.extractData);
6850 add('EXTRACT_ERROR', 'extractError', svc.extractError);
6851 })
6852 };
6853
6854
6855/***/ }),
6856/* 45 */
6857/***/ (function(module, exports, __webpack_require__) {
6858
6859 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
6860 var util = __webpack_require__(2);
6861 var endpointDiscoveryEnabledEnvs = ['AWS_ENABLE_ENDPOINT_DISCOVERY', 'AWS_ENDPOINT_DISCOVERY_ENABLED'];
6862
6863 /**
6864 * Generate key (except resources and operation part) to index the endpoints in the cache
6865 * If input shape has endpointdiscoveryid trait then use
6866 * accessKey + operation + resources + region + service as cache key
6867 * If input shape doesn't have endpointdiscoveryid trait then use
6868 * accessKey + region + service as cache key
6869 * @return [map<String,String>] object with keys to index endpoints.
6870 * @api private
6871 */
6872 function getCacheKey(request) {
6873 var service = request.service;
6874 var api = service.api || {};
6875 var operations = api.operations;
6876 var identifiers = {};
6877 if (service.config.region) {
6878 identifiers.region = service.config.region;
6879 }
6880 if (api.serviceId) {
6881 identifiers.serviceId = api.serviceId;
6882 }
6883 if (service.config.credentials.accessKeyId) {
6884 identifiers.accessKeyId = service.config.credentials.accessKeyId;
6885 }
6886 return identifiers;
6887 }
6888
6889 /**
6890 * Recursive helper for marshallCustomIdentifiers().
6891 * Looks for required string input members that have 'endpointdiscoveryid' trait.
6892 * @api private
6893 */
6894 function marshallCustomIdentifiersHelper(result, params, shape) {
6895 if (!shape || params === undefined || params === null) return;
6896 if (shape.type === 'structure' && shape.required && shape.required.length > 0) {
6897 util.arrayEach(shape.required, function(name) {
6898 var memberShape = shape.members[name];
6899 if (memberShape.endpointDiscoveryId === true) {
6900 var locationName = memberShape.isLocationName ? memberShape.name : name;
6901 result[locationName] = String(params[name]);
6902 } else {
6903 marshallCustomIdentifiersHelper(result, params[name], memberShape);
6904 }
6905 });
6906 }
6907 }
6908
6909 /**
6910 * Get custom identifiers for cache key.
6911 * Identifies custom identifiers by checking each shape's `endpointDiscoveryId` trait.
6912 * @param [object] request object
6913 * @param [object] input shape of the given operation's api
6914 * @api private
6915 */
6916 function marshallCustomIdentifiers(request, shape) {
6917 var identifiers = {};
6918 marshallCustomIdentifiersHelper(identifiers, request.params, shape);
6919 return identifiers;
6920 }
6921
6922 /**
6923 * Call endpoint discovery operation when it's optional.
6924 * When endpoint is available in cache then use the cached endpoints. If endpoints
6925 * are unavailable then use regional endpoints and call endpoint discovery operation
6926 * asynchronously. This is turned off by default.
6927 * @param [object] request object
6928 * @api private
6929 */
6930 function optionalDiscoverEndpoint(request) {
6931 var service = request.service;
6932 var api = service.api;
6933 var operationModel = api.operations ? api.operations[request.operation] : undefined;
6934 var inputShape = operationModel ? operationModel.input : undefined;
6935
6936 var identifiers = marshallCustomIdentifiers(request, inputShape);
6937 var cacheKey = getCacheKey(request);
6938 if (Object.keys(identifiers).length > 0) {
6939 cacheKey = util.update(cacheKey, identifiers);
6940 if (operationModel) cacheKey.operation = operationModel.name;
6941 }
6942 var endpoints = AWS.endpointCache.get(cacheKey);
6943 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
6944 //endpoint operation is being made but response not yet received
6945 //or endpoint operation just failed in 1 minute
6946 return;
6947 } else if (endpoints && endpoints.length > 0) {
6948 //found endpoint record from cache
6949 request.httpRequest.updateEndpoint(endpoints[0].Address);
6950 } else {
6951 //endpoint record not in cache or outdated. make discovery operation
6952 var endpointRequest = service.makeRequest(api.endpointOperation, {
6953 Operation: operationModel.name,
6954 Identifiers: identifiers,
6955 });
6956 addApiVersionHeader(endpointRequest);
6957 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
6958 endpointRequest.removeListener('retry', AWS.EventListeners.Core.RETRY_CHECK);
6959 //put in a placeholder for endpoints already requested, prevent
6960 //too much in-flight calls
6961 AWS.endpointCache.put(cacheKey, [{
6962 Address: '',
6963 CachePeriodInMinutes: 1
6964 }]);
6965 endpointRequest.send(function(err, data) {
6966 if (data && data.Endpoints) {
6967 AWS.endpointCache.put(cacheKey, data.Endpoints);
6968 } else if (err) {
6969 AWS.endpointCache.put(cacheKey, [{
6970 Address: '',
6971 CachePeriodInMinutes: 1 //not to make more endpoint operation in next 1 minute
6972 }]);
6973 }
6974 });
6975 }
6976 }
6977
6978 var requestQueue = {};
6979
6980 /**
6981 * Call endpoint discovery operation when it's required.
6982 * When endpoint is available in cache then use cached ones. If endpoints are
6983 * unavailable then SDK should call endpoint operation then use returned new
6984 * endpoint for the api call. SDK will automatically attempt to do endpoint
6985 * discovery. This is turned off by default
6986 * @param [object] request object
6987 * @api private
6988 */
6989 function requiredDiscoverEndpoint(request, done) {
6990 var service = request.service;
6991 var api = service.api;
6992 var operationModel = api.operations ? api.operations[request.operation] : undefined;
6993 var inputShape = operationModel ? operationModel.input : undefined;
6994
6995 var identifiers = marshallCustomIdentifiers(request, inputShape);
6996 var cacheKey = getCacheKey(request);
6997 if (Object.keys(identifiers).length > 0) {
6998 cacheKey = util.update(cacheKey, identifiers);
6999 if (operationModel) cacheKey.operation = operationModel.name;
7000 }
7001 var cacheKeyStr = AWS.EndpointCache.getKeyString(cacheKey);
7002 var endpoints = AWS.endpointCache.get(cacheKeyStr); //endpoint cache also accepts string keys
7003 if (endpoints && endpoints.length === 1 && endpoints[0].Address === '') {
7004 //endpoint operation is being made but response not yet received
7005 //push request object to a pending queue
7006 if (!requestQueue[cacheKeyStr]) requestQueue[cacheKeyStr] = [];
7007 requestQueue[cacheKeyStr].push({request: request, callback: done});
7008 return;
7009 } else if (endpoints && endpoints.length > 0) {
7010 request.httpRequest.updateEndpoint(endpoints[0].Address);
7011 done();
7012 } else {
7013 var endpointRequest = service.makeRequest(api.endpointOperation, {
7014 Operation: operationModel.name,
7015 Identifiers: identifiers,
7016 });
7017 endpointRequest.removeListener('validate', AWS.EventListeners.Core.VALIDATE_PARAMETERS);
7018 addApiVersionHeader(endpointRequest);
7019
7020 //put in a placeholder for endpoints already requested, prevent
7021 //too much in-flight calls
7022 AWS.endpointCache.put(cacheKeyStr, [{
7023 Address: '',
7024 CachePeriodInMinutes: 60 //long-live cache
7025 }]);
7026 endpointRequest.send(function(err, data) {
7027 if (err) {
7028 var errorParams = {
7029 code: 'EndpointDiscoveryException',
7030 message: 'Request cannot be fulfilled without specifying an endpoint',
7031 retryable: false
7032 };
7033 request.response.error = util.error(err, errorParams);
7034 AWS.endpointCache.remove(cacheKey);
7035
7036 //fail all the pending requests in batch
7037 if (requestQueue[cacheKeyStr]) {
7038 var pendingRequests = requestQueue[cacheKeyStr];
7039 util.arrayEach(pendingRequests, function(requestContext) {
7040 requestContext.request.response.error = util.error(err, errorParams);
7041 requestContext.callback();
7042 });
7043 delete requestQueue[cacheKeyStr];
7044 }
7045 } else if (data) {
7046 AWS.endpointCache.put(cacheKeyStr, data.Endpoints);
7047 request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7048
7049 //update the endpoint for all the pending requests in batch
7050 if (requestQueue[cacheKeyStr]) {
7051 var pendingRequests = requestQueue[cacheKeyStr];
7052 util.arrayEach(pendingRequests, function(requestContext) {
7053 requestContext.request.httpRequest.updateEndpoint(data.Endpoints[0].Address);
7054 requestContext.callback();
7055 });
7056 delete requestQueue[cacheKeyStr];
7057 }
7058 }
7059 done();
7060 });
7061 }
7062 }
7063
7064 /**
7065 * add api version header to endpoint operation
7066 * @api private
7067 */
7068 function addApiVersionHeader(endpointRequest) {
7069 var api = endpointRequest.service.api;
7070 var apiVersion = api.apiVersion;
7071 if (apiVersion && !endpointRequest.httpRequest.headers['x-amz-api-version']) {
7072 endpointRequest.httpRequest.headers['x-amz-api-version'] = apiVersion;
7073 }
7074 }
7075
7076 /**
7077 * If api call gets invalid endpoint exception, SDK should attempt to remove the invalid
7078 * endpoint from cache.
7079 * @api private
7080 */
7081 function invalidateCachedEndpoints(response) {
7082 var error = response.error;
7083 var httpResponse = response.httpResponse;
7084 if (error &&
7085 (error.code === 'InvalidEndpointException' || httpResponse.statusCode === 421)
7086 ) {
7087 var request = response.request;
7088 var operations = request.service.api.operations || {};
7089 var inputShape = operations[request.operation] ? operations[request.operation].input : undefined;
7090 var identifiers = marshallCustomIdentifiers(request, inputShape);
7091 var cacheKey = getCacheKey(request);
7092 if (Object.keys(identifiers).length > 0) {
7093 cacheKey = util.update(cacheKey, identifiers);
7094 if (operations[request.operation]) cacheKey.operation = operations[request.operation].name;
7095 }
7096 AWS.endpointCache.remove(cacheKey);
7097 }
7098 }
7099
7100 /**
7101 * If endpoint is explicitly configured, SDK should not do endpoint discovery in anytime.
7102 * @param [object] client Service client object.
7103 * @api private
7104 */
7105 function hasCustomEndpoint(client) {
7106 //if set endpoint is set for specific client, enable endpoint discovery will raise an error.
7107 if (client._originalConfig && client._originalConfig.endpoint && client._originalConfig.endpointDiscoveryEnabled === true) {
7108 throw util.error(new Error(), {
7109 code: 'ConfigurationException',
7110 message: 'Custom endpoint is supplied; endpointDiscoveryEnabled must not be true.'
7111 });
7112 };
7113 var svcConfig = AWS.config[client.serviceIdentifier] || {};
7114 return Boolean(AWS.config.endpoint || svcConfig.endpoint || (client._originalConfig && client._originalConfig.endpoint));
7115 }
7116
7117 /**
7118 * @api private
7119 */
7120 function isFalsy(value) {
7121 return ['false', '0'].indexOf(value) >= 0;
7122 }
7123
7124 /**
7125 * If endpoint discovery should perform for this request when endpoint discovery is optional.
7126 * SDK performs config resolution in order like below:
7127 * 1. If turned on client configuration(default to off) then turn on endpoint discovery.
7128 * 2. If turned on in env AWS_ENABLE_ENDPOINT_DISCOVERY then turn on endpoint discovery.
7129 * 3. If turned on in shared ini config file with key 'endpoint_discovery_enabled', then
7130 * turn on endpoint discovery.
7131 * @param [object] request request object.
7132 * @api private
7133 */
7134 function isEndpointDiscoveryApplicable(request) {
7135 var service = request.service || {};
7136 if (service.config.endpointDiscoveryEnabled === true) return true;
7137
7138 //shared ini file is only available in Node
7139 //not to check env in browser
7140 if (util.isBrowser()) return false;
7141
7142 for (var i = 0; i < endpointDiscoveryEnabledEnvs.length; i++) {
7143 var env = endpointDiscoveryEnabledEnvs[i];
7144 if (Object.prototype.hasOwnProperty.call(process.env, env)) {
7145 if (process.env[env] === '' || process.env[env] === undefined) {
7146 throw util.error(new Error(), {
7147 code: 'ConfigurationException',
7148 message: 'environmental variable ' + env + ' cannot be set to nothing'
7149 });
7150 }
7151 if (!isFalsy(process.env[env])) return true;
7152 }
7153 }
7154
7155 var configFile = {};
7156 try {
7157 configFile = AWS.util.iniLoader ? AWS.util.iniLoader.loadFrom({
7158 isConfig: true,
7159 filename: process.env[AWS.util.sharedConfigFileEnv]
7160 }) : {};
7161 } catch (e) {}
7162 var sharedFileConfig = configFile[
7163 process.env.AWS_PROFILE || AWS.util.defaultProfile
7164 ] || {};
7165 if (Object.prototype.hasOwnProperty.call(sharedFileConfig, 'endpoint_discovery_enabled')) {
7166 if (sharedFileConfig.endpoint_discovery_enabled === undefined) {
7167 throw util.error(new Error(), {
7168 code: 'ConfigurationException',
7169 message: 'config file entry \'endpoint_discovery_enabled\' cannot be set to nothing'
7170 });
7171 }
7172 if (!isFalsy(sharedFileConfig.endpoint_discovery_enabled)) return true;
7173 }
7174 return false;
7175 }
7176
7177 /**
7178 * attach endpoint discovery logic to request object
7179 * @param [object] request
7180 * @api private
7181 */
7182 function discoverEndpoint(request, done) {
7183 var service = request.service || {};
7184 if (hasCustomEndpoint(service) || request.isPresigned()) return done();
7185
7186 if (!isEndpointDiscoveryApplicable(request)) return done();
7187
7188 request.httpRequest.appendToUserAgent('endpoint-discovery');
7189
7190 var operations = service.api.operations || {};
7191 var operationModel = operations[request.operation];
7192 var isEndpointDiscoveryRequired = operationModel ? operationModel.endpointDiscoveryRequired : 'NULL';
7193 switch (isEndpointDiscoveryRequired) {
7194 case 'OPTIONAL':
7195 optionalDiscoverEndpoint(request);
7196 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7197 done();
7198 break;
7199 case 'REQUIRED':
7200 request.addNamedListener('INVALIDATE_CACHED_ENDPOINTS', 'extractError', invalidateCachedEndpoints);
7201 requiredDiscoverEndpoint(request, done);
7202 break;
7203 case 'NULL':
7204 default:
7205 done();
7206 break;
7207 }
7208 }
7209
7210 module.exports = {
7211 discoverEndpoint: discoverEndpoint,
7212 requiredDiscoverEndpoint: requiredDiscoverEndpoint,
7213 optionalDiscoverEndpoint: optionalDiscoverEndpoint,
7214 marshallCustomIdentifiers: marshallCustomIdentifiers,
7215 getCacheKey: getCacheKey,
7216 invalidateCachedEndpoint: invalidateCachedEndpoints,
7217 };
7218
7219 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
7220
7221/***/ }),
7222/* 46 */
7223/***/ (function(module, exports, __webpack_require__) {
7224
7225 /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
7226 //
7227 // Permission is hereby granted, free of charge, to any person obtaining a
7228 // copy of this software and associated documentation files (the
7229 // "Software"), to deal in the Software without restriction, including
7230 // without limitation the rights to use, copy, modify, merge, publish,
7231 // distribute, sublicense, and/or sell copies of the Software, and to permit
7232 // persons to whom the Software is furnished to do so, subject to the
7233 // following conditions:
7234 //
7235 // The above copyright notice and this permission notice shall be included
7236 // in all copies or substantial portions of the Software.
7237 //
7238 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
7239 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
7240 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
7241 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
7242 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
7243 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
7244 // USE OR OTHER DEALINGS IN THE SOFTWARE.
7245
7246 var formatRegExp = /%[sdj%]/g;
7247 exports.format = function(f) {
7248 if (!isString(f)) {
7249 var objects = [];
7250 for (var i = 0; i < arguments.length; i++) {
7251 objects.push(inspect(arguments[i]));
7252 }
7253 return objects.join(' ');
7254 }
7255
7256 var i = 1;
7257 var args = arguments;
7258 var len = args.length;
7259 var str = String(f).replace(formatRegExp, function(x) {
7260 if (x === '%%') return '%';
7261 if (i >= len) return x;
7262 switch (x) {
7263 case '%s': return String(args[i++]);
7264 case '%d': return Number(args[i++]);
7265 case '%j':
7266 try {
7267 return JSON.stringify(args[i++]);
7268 } catch (_) {
7269 return '[Circular]';
7270 }
7271 default:
7272 return x;
7273 }
7274 });
7275 for (var x = args[i]; i < len; x = args[++i]) {
7276 if (isNull(x) || !isObject(x)) {
7277 str += ' ' + x;
7278 } else {
7279 str += ' ' + inspect(x);
7280 }
7281 }
7282 return str;
7283 };
7284
7285
7286 // Mark that a method should not be used.
7287 // Returns a modified function which warns once by default.
7288 // If --no-deprecation is set, then it is a no-op.
7289 exports.deprecate = function(fn, msg) {
7290 // Allow for deprecating things in the process of starting up.
7291 if (isUndefined(global.process)) {
7292 return function() {
7293 return exports.deprecate(fn, msg).apply(this, arguments);
7294 };
7295 }
7296
7297 if (process.noDeprecation === true) {
7298 return fn;
7299 }
7300
7301 var warned = false;
7302 function deprecated() {
7303 if (!warned) {
7304 if (process.throwDeprecation) {
7305 throw new Error(msg);
7306 } else if (process.traceDeprecation) {
7307 console.trace(msg);
7308 } else {
7309 console.error(msg);
7310 }
7311 warned = true;
7312 }
7313 return fn.apply(this, arguments);
7314 }
7315
7316 return deprecated;
7317 };
7318
7319
7320 var debugs = {};
7321 var debugEnviron;
7322 exports.debuglog = function(set) {
7323 if (isUndefined(debugEnviron))
7324 debugEnviron = process.env.NODE_DEBUG || '';
7325 set = set.toUpperCase();
7326 if (!debugs[set]) {
7327 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
7328 var pid = process.pid;
7329 debugs[set] = function() {
7330 var msg = exports.format.apply(exports, arguments);
7331 console.error('%s %d: %s', set, pid, msg);
7332 };
7333 } else {
7334 debugs[set] = function() {};
7335 }
7336 }
7337 return debugs[set];
7338 };
7339
7340
7341 /**
7342 * Echos the value of a value. Trys to print the value out
7343 * in the best way possible given the different types.
7344 *
7345 * @param {Object} obj The object to print out.
7346 * @param {Object} opts Optional options object that alters the output.
7347 */
7348 /* legacy: obj, showHidden, depth, colors*/
7349 function inspect(obj, opts) {
7350 // default options
7351 var ctx = {
7352 seen: [],
7353 stylize: stylizeNoColor
7354 };
7355 // legacy...
7356 if (arguments.length >= 3) ctx.depth = arguments[2];
7357 if (arguments.length >= 4) ctx.colors = arguments[3];
7358 if (isBoolean(opts)) {
7359 // legacy...
7360 ctx.showHidden = opts;
7361 } else if (opts) {
7362 // got an "options" object
7363 exports._extend(ctx, opts);
7364 }
7365 // set default options
7366 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
7367 if (isUndefined(ctx.depth)) ctx.depth = 2;
7368 if (isUndefined(ctx.colors)) ctx.colors = false;
7369 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
7370 if (ctx.colors) ctx.stylize = stylizeWithColor;
7371 return formatValue(ctx, obj, ctx.depth);
7372 }
7373 exports.inspect = inspect;
7374
7375
7376 // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
7377 inspect.colors = {
7378 'bold' : [1, 22],
7379 'italic' : [3, 23],
7380 'underline' : [4, 24],
7381 'inverse' : [7, 27],
7382 'white' : [37, 39],
7383 'grey' : [90, 39],
7384 'black' : [30, 39],
7385 'blue' : [34, 39],
7386 'cyan' : [36, 39],
7387 'green' : [32, 39],
7388 'magenta' : [35, 39],
7389 'red' : [31, 39],
7390 'yellow' : [33, 39]
7391 };
7392
7393 // Don't use 'blue' not visible on cmd.exe
7394 inspect.styles = {
7395 'special': 'cyan',
7396 'number': 'yellow',
7397 'boolean': 'yellow',
7398 'undefined': 'grey',
7399 'null': 'bold',
7400 'string': 'green',
7401 'date': 'magenta',
7402 // "name": intentionally not styling
7403 'regexp': 'red'
7404 };
7405
7406
7407 function stylizeWithColor(str, styleType) {
7408 var style = inspect.styles[styleType];
7409
7410 if (style) {
7411 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
7412 '\u001b[' + inspect.colors[style][1] + 'm';
7413 } else {
7414 return str;
7415 }
7416 }
7417
7418
7419 function stylizeNoColor(str, styleType) {
7420 return str;
7421 }
7422
7423
7424 function arrayToHash(array) {
7425 var hash = {};
7426
7427 array.forEach(function(val, idx) {
7428 hash[val] = true;
7429 });
7430
7431 return hash;
7432 }
7433
7434
7435 function formatValue(ctx, value, recurseTimes) {
7436 // Provide a hook for user-specified inspect functions.
7437 // Check that value is an object with an inspect function on it
7438 if (ctx.customInspect &&
7439 value &&
7440 isFunction(value.inspect) &&
7441 // Filter out the util module, it's inspect function is special
7442 value.inspect !== exports.inspect &&
7443 // Also filter out any prototype objects using the circular check.
7444 !(value.constructor && value.constructor.prototype === value)) {
7445 var ret = value.inspect(recurseTimes, ctx);
7446 if (!isString(ret)) {
7447 ret = formatValue(ctx, ret, recurseTimes);
7448 }
7449 return ret;
7450 }
7451
7452 // Primitive types cannot have properties
7453 var primitive = formatPrimitive(ctx, value);
7454 if (primitive) {
7455 return primitive;
7456 }
7457
7458 // Look up the keys of the object.
7459 var keys = Object.keys(value);
7460 var visibleKeys = arrayToHash(keys);
7461
7462 if (ctx.showHidden) {
7463 keys = Object.getOwnPropertyNames(value);
7464 }
7465
7466 // IE doesn't make error fields non-enumerable
7467 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
7468 if (isError(value)
7469 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
7470 return formatError(value);
7471 }
7472
7473 // Some type of object without properties can be shortcutted.
7474 if (keys.length === 0) {
7475 if (isFunction(value)) {
7476 var name = value.name ? ': ' + value.name : '';
7477 return ctx.stylize('[Function' + name + ']', 'special');
7478 }
7479 if (isRegExp(value)) {
7480 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7481 }
7482 if (isDate(value)) {
7483 return ctx.stylize(Date.prototype.toString.call(value), 'date');
7484 }
7485 if (isError(value)) {
7486 return formatError(value);
7487 }
7488 }
7489
7490 var base = '', array = false, braces = ['{', '}'];
7491
7492 // Make Array say that they are Array
7493 if (isArray(value)) {
7494 array = true;
7495 braces = ['[', ']'];
7496 }
7497
7498 // Make functions say that they are functions
7499 if (isFunction(value)) {
7500 var n = value.name ? ': ' + value.name : '';
7501 base = ' [Function' + n + ']';
7502 }
7503
7504 // Make RegExps say that they are RegExps
7505 if (isRegExp(value)) {
7506 base = ' ' + RegExp.prototype.toString.call(value);
7507 }
7508
7509 // Make dates with properties first say the date
7510 if (isDate(value)) {
7511 base = ' ' + Date.prototype.toUTCString.call(value);
7512 }
7513
7514 // Make error with message first say the error
7515 if (isError(value)) {
7516 base = ' ' + formatError(value);
7517 }
7518
7519 if (keys.length === 0 && (!array || value.length == 0)) {
7520 return braces[0] + base + braces[1];
7521 }
7522
7523 if (recurseTimes < 0) {
7524 if (isRegExp(value)) {
7525 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
7526 } else {
7527 return ctx.stylize('[Object]', 'special');
7528 }
7529 }
7530
7531 ctx.seen.push(value);
7532
7533 var output;
7534 if (array) {
7535 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
7536 } else {
7537 output = keys.map(function(key) {
7538 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
7539 });
7540 }
7541
7542 ctx.seen.pop();
7543
7544 return reduceToSingleString(output, base, braces);
7545 }
7546
7547
7548 function formatPrimitive(ctx, value) {
7549 if (isUndefined(value))
7550 return ctx.stylize('undefined', 'undefined');
7551 if (isString(value)) {
7552 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
7553 .replace(/'/g, "\\'")
7554 .replace(/\\"/g, '"') + '\'';
7555 return ctx.stylize(simple, 'string');
7556 }
7557 if (isNumber(value))
7558 return ctx.stylize('' + value, 'number');
7559 if (isBoolean(value))
7560 return ctx.stylize('' + value, 'boolean');
7561 // For some reason typeof null is "object", so special case here.
7562 if (isNull(value))
7563 return ctx.stylize('null', 'null');
7564 }
7565
7566
7567 function formatError(value) {
7568 return '[' + Error.prototype.toString.call(value) + ']';
7569 }
7570
7571
7572 function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
7573 var output = [];
7574 for (var i = 0, l = value.length; i < l; ++i) {
7575 if (hasOwnProperty(value, String(i))) {
7576 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7577 String(i), true));
7578 } else {
7579 output.push('');
7580 }
7581 }
7582 keys.forEach(function(key) {
7583 if (!key.match(/^\d+$/)) {
7584 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
7585 key, true));
7586 }
7587 });
7588 return output;
7589 }
7590
7591
7592 function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
7593 var name, str, desc;
7594 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
7595 if (desc.get) {
7596 if (desc.set) {
7597 str = ctx.stylize('[Getter/Setter]', 'special');
7598 } else {
7599 str = ctx.stylize('[Getter]', 'special');
7600 }
7601 } else {
7602 if (desc.set) {
7603 str = ctx.stylize('[Setter]', 'special');
7604 }
7605 }
7606 if (!hasOwnProperty(visibleKeys, key)) {
7607 name = '[' + key + ']';
7608 }
7609 if (!str) {
7610 if (ctx.seen.indexOf(desc.value) < 0) {
7611 if (isNull(recurseTimes)) {
7612 str = formatValue(ctx, desc.value, null);
7613 } else {
7614 str = formatValue(ctx, desc.value, recurseTimes - 1);
7615 }
7616 if (str.indexOf('\n') > -1) {
7617 if (array) {
7618 str = str.split('\n').map(function(line) {
7619 return ' ' + line;
7620 }).join('\n').substr(2);
7621 } else {
7622 str = '\n' + str.split('\n').map(function(line) {
7623 return ' ' + line;
7624 }).join('\n');
7625 }
7626 }
7627 } else {
7628 str = ctx.stylize('[Circular]', 'special');
7629 }
7630 }
7631 if (isUndefined(name)) {
7632 if (array && key.match(/^\d+$/)) {
7633 return str;
7634 }
7635 name = JSON.stringify('' + key);
7636 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
7637 name = name.substr(1, name.length - 2);
7638 name = ctx.stylize(name, 'name');
7639 } else {
7640 name = name.replace(/'/g, "\\'")
7641 .replace(/\\"/g, '"')
7642 .replace(/(^"|"$)/g, "'");
7643 name = ctx.stylize(name, 'string');
7644 }
7645 }
7646
7647 return name + ': ' + str;
7648 }
7649
7650
7651 function reduceToSingleString(output, base, braces) {
7652 var numLinesEst = 0;
7653 var length = output.reduce(function(prev, cur) {
7654 numLinesEst++;
7655 if (cur.indexOf('\n') >= 0) numLinesEst++;
7656 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
7657 }, 0);
7658
7659 if (length > 60) {
7660 return braces[0] +
7661 (base === '' ? '' : base + '\n ') +
7662 ' ' +
7663 output.join(',\n ') +
7664 ' ' +
7665 braces[1];
7666 }
7667
7668 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
7669 }
7670
7671
7672 // NOTE: These type checking functions intentionally don't use `instanceof`
7673 // because it is fragile and can be easily faked with `Object.create()`.
7674 function isArray(ar) {
7675 return Array.isArray(ar);
7676 }
7677 exports.isArray = isArray;
7678
7679 function isBoolean(arg) {
7680 return typeof arg === 'boolean';
7681 }
7682 exports.isBoolean = isBoolean;
7683
7684 function isNull(arg) {
7685 return arg === null;
7686 }
7687 exports.isNull = isNull;
7688
7689 function isNullOrUndefined(arg) {
7690 return arg == null;
7691 }
7692 exports.isNullOrUndefined = isNullOrUndefined;
7693
7694 function isNumber(arg) {
7695 return typeof arg === 'number';
7696 }
7697 exports.isNumber = isNumber;
7698
7699 function isString(arg) {
7700 return typeof arg === 'string';
7701 }
7702 exports.isString = isString;
7703
7704 function isSymbol(arg) {
7705 return typeof arg === 'symbol';
7706 }
7707 exports.isSymbol = isSymbol;
7708
7709 function isUndefined(arg) {
7710 return arg === void 0;
7711 }
7712 exports.isUndefined = isUndefined;
7713
7714 function isRegExp(re) {
7715 return isObject(re) && objectToString(re) === '[object RegExp]';
7716 }
7717 exports.isRegExp = isRegExp;
7718
7719 function isObject(arg) {
7720 return typeof arg === 'object' && arg !== null;
7721 }
7722 exports.isObject = isObject;
7723
7724 function isDate(d) {
7725 return isObject(d) && objectToString(d) === '[object Date]';
7726 }
7727 exports.isDate = isDate;
7728
7729 function isError(e) {
7730 return isObject(e) &&
7731 (objectToString(e) === '[object Error]' || e instanceof Error);
7732 }
7733 exports.isError = isError;
7734
7735 function isFunction(arg) {
7736 return typeof arg === 'function';
7737 }
7738 exports.isFunction = isFunction;
7739
7740 function isPrimitive(arg) {
7741 return arg === null ||
7742 typeof arg === 'boolean' ||
7743 typeof arg === 'number' ||
7744 typeof arg === 'string' ||
7745 typeof arg === 'symbol' || // ES6 symbol
7746 typeof arg === 'undefined';
7747 }
7748 exports.isPrimitive = isPrimitive;
7749
7750 exports.isBuffer = __webpack_require__(47);
7751
7752 function objectToString(o) {
7753 return Object.prototype.toString.call(o);
7754 }
7755
7756
7757 function pad(n) {
7758 return n < 10 ? '0' + n.toString(10) : n.toString(10);
7759 }
7760
7761
7762 var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
7763 'Oct', 'Nov', 'Dec'];
7764
7765 // 26 Feb 16:19:34
7766 function timestamp() {
7767 var d = new Date();
7768 var time = [pad(d.getHours()),
7769 pad(d.getMinutes()),
7770 pad(d.getSeconds())].join(':');
7771 return [d.getDate(), months[d.getMonth()], time].join(' ');
7772 }
7773
7774
7775 // log is just a thin wrapper to console.log that prepends a timestamp
7776 exports.log = function() {
7777 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
7778 };
7779
7780
7781 /**
7782 * Inherit the prototype methods from one constructor into another.
7783 *
7784 * The Function.prototype.inherits from lang.js rewritten as a standalone
7785 * function (not on Function.prototype). NOTE: If this file is to be loaded
7786 * during bootstrapping this function needs to be rewritten using some native
7787 * functions as prototype setup using normal JavaScript does not work as
7788 * expected during bootstrapping (see mirror.js in r114903).
7789 *
7790 * @param {function} ctor Constructor function which needs to inherit the
7791 * prototype.
7792 * @param {function} superCtor Constructor function to inherit prototype from.
7793 */
7794 exports.inherits = __webpack_require__(48);
7795
7796 exports._extend = function(origin, add) {
7797 // Don't do anything if add isn't an object
7798 if (!add || !isObject(add)) return origin;
7799
7800 var keys = Object.keys(add);
7801 var i = keys.length;
7802 while (i--) {
7803 origin[keys[i]] = add[keys[i]];
7804 }
7805 return origin;
7806 };
7807
7808 function hasOwnProperty(obj, prop) {
7809 return Object.prototype.hasOwnProperty.call(obj, prop);
7810 }
7811
7812 /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(3)))
7813
7814/***/ }),
7815/* 47 */
7816/***/ (function(module, exports) {
7817
7818 module.exports = function isBuffer(arg) {
7819 return arg && typeof arg === 'object'
7820 && typeof arg.copy === 'function'
7821 && typeof arg.fill === 'function'
7822 && typeof arg.readUInt8 === 'function';
7823 }
7824
7825/***/ }),
7826/* 48 */
7827/***/ (function(module, exports) {
7828
7829 if (typeof Object.create === 'function') {
7830 // implementation from standard node.js 'util' module
7831 module.exports = function inherits(ctor, superCtor) {
7832 ctor.super_ = superCtor
7833 ctor.prototype = Object.create(superCtor.prototype, {
7834 constructor: {
7835 value: ctor,
7836 enumerable: false,
7837 writable: true,
7838 configurable: true
7839 }
7840 });
7841 };
7842 } else {
7843 // old school shim for old browsers
7844 module.exports = function inherits(ctor, superCtor) {
7845 ctor.super_ = superCtor
7846 var TempCtor = function () {}
7847 TempCtor.prototype = superCtor.prototype
7848 ctor.prototype = new TempCtor()
7849 ctor.prototype.constructor = ctor
7850 }
7851 }
7852
7853
7854/***/ }),
7855/* 49 */
7856/***/ (function(module, exports, __webpack_require__) {
7857
7858 /* WEBPACK VAR INJECTION */(function(process) {var AWS = __webpack_require__(1);
7859 var AcceptorStateMachine = __webpack_require__(50);
7860 var inherit = AWS.util.inherit;
7861 var domain = AWS.util.domain;
7862 var jmespath = __webpack_require__(51);
7863
7864 /**
7865 * @api private
7866 */
7867 var hardErrorStates = {success: 1, error: 1, complete: 1};
7868
7869 function isTerminalState(machine) {
7870 return Object.prototype.hasOwnProperty.call(hardErrorStates, machine._asm.currentState);
7871 }
7872
7873 var fsm = new AcceptorStateMachine();
7874 fsm.setupStates = function() {
7875 var transition = function(_, done) {
7876 var self = this;
7877 self._haltHandlersOnError = false;
7878
7879 self.emit(self._asm.currentState, function(err) {
7880 if (err) {
7881 if (isTerminalState(self)) {
7882 if (domain && self.domain instanceof domain.Domain) {
7883 err.domainEmitter = self;
7884 err.domain = self.domain;
7885 err.domainThrown = false;
7886 self.domain.emit('error', err);
7887 } else {
7888 throw err;
7889 }
7890 } else {
7891 self.response.error = err;
7892 done(err);
7893 }
7894 } else {
7895 done(self.response.error);
7896 }
7897 });
7898
7899 };
7900
7901 this.addState('validate', 'build', 'error', transition);
7902 this.addState('build', 'afterBuild', 'restart', transition);
7903 this.addState('afterBuild', 'sign', 'restart', transition);
7904 this.addState('sign', 'send', 'retry', transition);
7905 this.addState('retry', 'afterRetry', 'afterRetry', transition);
7906 this.addState('afterRetry', 'sign', 'error', transition);
7907 this.addState('send', 'validateResponse', 'retry', transition);
7908 this.addState('validateResponse', 'extractData', 'extractError', transition);
7909 this.addState('extractError', 'extractData', 'retry', transition);
7910 this.addState('extractData', 'success', 'retry', transition);
7911 this.addState('restart', 'build', 'error', transition);
7912 this.addState('success', 'complete', 'complete', transition);
7913 this.addState('error', 'complete', 'complete', transition);
7914 this.addState('complete', null, null, transition);
7915 };
7916 fsm.setupStates();
7917
7918 /**
7919 * ## Asynchronous Requests
7920 *
7921 * All requests made through the SDK are asynchronous and use a
7922 * callback interface. Each service method that kicks off a request
7923 * returns an `AWS.Request` object that you can use to register
7924 * callbacks.
7925 *
7926 * For example, the following service method returns the request
7927 * object as "request", which can be used to register callbacks:
7928 *
7929 * ```javascript
7930 * // request is an AWS.Request object
7931 * var request = ec2.describeInstances();
7932 *
7933 * // register callbacks on request to retrieve response data
7934 * request.on('success', function(response) {
7935 * console.log(response.data);
7936 * });
7937 * ```
7938 *
7939 * When a request is ready to be sent, the {send} method should
7940 * be called:
7941 *
7942 * ```javascript
7943 * request.send();
7944 * ```
7945 *
7946 * Since registered callbacks may or may not be idempotent, requests should only
7947 * be sent once. To perform the same operation multiple times, you will need to
7948 * create multiple request objects, each with its own registered callbacks.
7949 *
7950 * ## Removing Default Listeners for Events
7951 *
7952 * Request objects are built with default listeners for the various events,
7953 * depending on the service type. In some cases, you may want to remove
7954 * some built-in listeners to customize behaviour. Doing this requires
7955 * access to the built-in listener functions, which are exposed through
7956 * the {AWS.EventListeners.Core} namespace. For instance, you may
7957 * want to customize the HTTP handler used when sending a request. In this
7958 * case, you can remove the built-in listener associated with the 'send'
7959 * event, the {AWS.EventListeners.Core.SEND} listener and add your own.
7960 *
7961 * ## Multiple Callbacks and Chaining
7962 *
7963 * You can register multiple callbacks on any request object. The
7964 * callbacks can be registered for different events, or all for the
7965 * same event. In addition, you can chain callback registration, for
7966 * example:
7967 *
7968 * ```javascript
7969 * request.
7970 * on('success', function(response) {
7971 * console.log("Success!");
7972 * }).
7973 * on('error', function(response) {
7974 * console.log("Error!");
7975 * }).
7976 * on('complete', function(response) {
7977 * console.log("Always!");
7978 * }).
7979 * send();
7980 * ```
7981 *
7982 * The above example will print either "Success! Always!", or "Error! Always!",
7983 * depending on whether the request succeeded or not.
7984 *
7985 * @!attribute httpRequest
7986 * @readonly
7987 * @!group HTTP Properties
7988 * @return [AWS.HttpRequest] the raw HTTP request object
7989 * containing request headers and body information
7990 * sent by the service.
7991 *
7992 * @!attribute startTime
7993 * @readonly
7994 * @!group Operation Properties
7995 * @return [Date] the time that the request started
7996 *
7997 * @!group Request Building Events
7998 *
7999 * @!event validate(request)
8000 * Triggered when a request is being validated. Listeners
8001 * should throw an error if the request should not be sent.
8002 * @param request [Request] the request object being sent
8003 * @see AWS.EventListeners.Core.VALIDATE_CREDENTIALS
8004 * @see AWS.EventListeners.Core.VALIDATE_REGION
8005 * @example Ensuring that a certain parameter is set before sending a request
8006 * var req = s3.putObject(params);
8007 * req.on('validate', function() {
8008 * if (!req.params.Body.match(/^Hello\s/)) {
8009 * throw new Error('Body must start with "Hello "');
8010 * }
8011 * });
8012 * req.send(function(err, data) { ... });
8013 *
8014 * @!event build(request)
8015 * Triggered when the request payload is being built. Listeners
8016 * should fill the necessary information to send the request
8017 * over HTTP.
8018 * @param (see AWS.Request~validate)
8019 * @example Add a custom HTTP header to a request
8020 * var req = s3.putObject(params);
8021 * req.on('build', function() {
8022 * req.httpRequest.headers['Custom-Header'] = 'value';
8023 * });
8024 * req.send(function(err, data) { ... });
8025 *
8026 * @!event sign(request)
8027 * Triggered when the request is being signed. Listeners should
8028 * add the correct authentication headers and/or adjust the body,
8029 * depending on the authentication mechanism being used.
8030 * @param (see AWS.Request~validate)
8031 *
8032 * @!group Request Sending Events
8033 *
8034 * @!event send(response)
8035 * Triggered when the request is ready to be sent. Listeners
8036 * should call the underlying transport layer to initiate
8037 * the sending of the request.
8038 * @param response [Response] the response object
8039 * @context [Request] the request object that was sent
8040 * @see AWS.EventListeners.Core.SEND
8041 *
8042 * @!event retry(response)
8043 * Triggered when a request failed and might need to be retried or redirected.
8044 * If the response is retryable, the listener should set the
8045 * `response.error.retryable` property to `true`, and optionally set
8046 * `response.error.retryDelay` to the millisecond delay for the next attempt.
8047 * In the case of a redirect, `response.error.redirect` should be set to
8048 * `true` with `retryDelay` set to an optional delay on the next request.
8049 *
8050 * If a listener decides that a request should not be retried,
8051 * it should set both `retryable` and `redirect` to false.
8052 *
8053 * Note that a retryable error will be retried at most
8054 * {AWS.Config.maxRetries} times (based on the service object's config).
8055 * Similarly, a request that is redirected will only redirect at most
8056 * {AWS.Config.maxRedirects} times.
8057 *
8058 * @param (see AWS.Request~send)
8059 * @context (see AWS.Request~send)
8060 * @example Adding a custom retry for a 404 response
8061 * request.on('retry', function(response) {
8062 * // this resource is not yet available, wait 10 seconds to get it again
8063 * if (response.httpResponse.statusCode === 404 && response.error) {
8064 * response.error.retryable = true; // retry this error
8065 * response.error.retryDelay = 10000; // wait 10 seconds
8066 * }
8067 * });
8068 *
8069 * @!group Data Parsing Events
8070 *
8071 * @!event extractError(response)
8072 * Triggered on all non-2xx requests so that listeners can extract
8073 * error details from the response body. Listeners to this event
8074 * should set the `response.error` property.
8075 * @param (see AWS.Request~send)
8076 * @context (see AWS.Request~send)
8077 *
8078 * @!event extractData(response)
8079 * Triggered in successful requests to allow listeners to
8080 * de-serialize the response body into `response.data`.
8081 * @param (see AWS.Request~send)
8082 * @context (see AWS.Request~send)
8083 *
8084 * @!group Completion Events
8085 *
8086 * @!event success(response)
8087 * Triggered when the request completed successfully.
8088 * `response.data` will contain the response data and
8089 * `response.error` will be null.
8090 * @param (see AWS.Request~send)
8091 * @context (see AWS.Request~send)
8092 *
8093 * @!event error(error, response)
8094 * Triggered when an error occurs at any point during the
8095 * request. `response.error` will contain details about the error
8096 * that occurred. `response.data` will be null.
8097 * @param error [Error] the error object containing details about
8098 * the error that occurred.
8099 * @param (see AWS.Request~send)
8100 * @context (see AWS.Request~send)
8101 *
8102 * @!event complete(response)
8103 * Triggered whenever a request cycle completes. `response.error`
8104 * should be checked, since the request may have failed.
8105 * @param (see AWS.Request~send)
8106 * @context (see AWS.Request~send)
8107 *
8108 * @!group HTTP Events
8109 *
8110 * @!event httpHeaders(statusCode, headers, response, statusMessage)
8111 * Triggered when headers are sent by the remote server
8112 * @param statusCode [Integer] the HTTP response code
8113 * @param headers [map<String,String>] the response headers
8114 * @param (see AWS.Request~send)
8115 * @param statusMessage [String] A status message corresponding to the HTTP
8116 * response code
8117 * @context (see AWS.Request~send)
8118 *
8119 * @!event httpData(chunk, response)
8120 * Triggered when data is sent by the remote server
8121 * @param chunk [Buffer] the buffer data containing the next data chunk
8122 * from the server
8123 * @param (see AWS.Request~send)
8124 * @context (see AWS.Request~send)
8125 * @see AWS.EventListeners.Core.HTTP_DATA
8126 *
8127 * @!event httpUploadProgress(progress, response)
8128 * Triggered when the HTTP request has uploaded more data
8129 * @param progress [map] An object containing the `loaded` and `total` bytes
8130 * of the request.
8131 * @param (see AWS.Request~send)
8132 * @context (see AWS.Request~send)
8133 * @note This event will not be emitted in Node.js 0.8.x.
8134 *
8135 * @!event httpDownloadProgress(progress, response)
8136 * Triggered when the HTTP request has downloaded more data
8137 * @param progress [map] An object containing the `loaded` and `total` bytes
8138 * of the request.
8139 * @param (see AWS.Request~send)
8140 * @context (see AWS.Request~send)
8141 * @note This event will not be emitted in Node.js 0.8.x.
8142 *
8143 * @!event httpError(error, response)
8144 * Triggered when the HTTP request failed
8145 * @param error [Error] the error object that was thrown
8146 * @param (see AWS.Request~send)
8147 * @context (see AWS.Request~send)
8148 *
8149 * @!event httpDone(response)
8150 * Triggered when the server is finished sending data
8151 * @param (see AWS.Request~send)
8152 * @context (see AWS.Request~send)
8153 *
8154 * @see AWS.Response
8155 */
8156 AWS.Request = inherit({
8157
8158 /**
8159 * Creates a request for an operation on a given service with
8160 * a set of input parameters.
8161 *
8162 * @param service [AWS.Service] the service to perform the operation on
8163 * @param operation [String] the operation to perform on the service
8164 * @param params [Object] parameters to send to the operation.
8165 * See the operation's documentation for the format of the
8166 * parameters.
8167 */
8168 constructor: function Request(service, operation, params) {
8169 var endpoint = service.endpoint;
8170 var region = service.config.region;
8171 var customUserAgent = service.config.customUserAgent;
8172
8173 // global endpoints sign as us-east-1
8174 if (service.isGlobalEndpoint) region = 'us-east-1';
8175
8176 this.domain = domain && domain.active;
8177 this.service = service;
8178 this.operation = operation;
8179 this.params = params || {};
8180 this.httpRequest = new AWS.HttpRequest(endpoint, region);
8181 this.httpRequest.appendToUserAgent(customUserAgent);
8182 this.startTime = service.getSkewCorrectedDate();
8183
8184 this.response = new AWS.Response(this);
8185 this._asm = new AcceptorStateMachine(fsm.states, 'validate');
8186 this._haltHandlersOnError = false;
8187
8188 AWS.SequentialExecutor.call(this);
8189 this.emit = this.emitEvent;
8190 },
8191
8192 /**
8193 * @!group Sending a Request
8194 */
8195
8196 /**
8197 * @overload send(callback = null)
8198 * Sends the request object.
8199 *
8200 * @callback callback function(err, data)
8201 * If a callback is supplied, it is called when a response is returned
8202 * from the service.
8203 * @context [AWS.Request] the request object being sent.
8204 * @param err [Error] the error object returned from the request.
8205 * Set to `null` if the request is successful.
8206 * @param data [Object] the de-serialized data returned from
8207 * the request. Set to `null` if a request error occurs.
8208 * @example Sending a request with a callback
8209 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8210 * request.send(function(err, data) { console.log(err, data); });
8211 * @example Sending a request with no callback (using event handlers)
8212 * request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8213 * request.on('complete', function(response) { ... }); // register a callback
8214 * request.send();
8215 */
8216 send: function send(callback) {
8217 if (callback) {
8218 // append to user agent
8219 this.httpRequest.appendToUserAgent('callback');
8220 this.on('complete', function (resp) {
8221 callback.call(resp, resp.error, resp.data);
8222 });
8223 }
8224 this.runTo();
8225
8226 return this.response;
8227 },
8228
8229 /**
8230 * @!method promise()
8231 * Sends the request and returns a 'thenable' promise.
8232 *
8233 * Two callbacks can be provided to the `then` method on the returned promise.
8234 * The first callback will be called if the promise is fulfilled, and the second
8235 * callback will be called if the promise is rejected.
8236 * @callback fulfilledCallback function(data)
8237 * Called if the promise is fulfilled.
8238 * @param data [Object] the de-serialized data returned from the request.
8239 * @callback rejectedCallback function(error)
8240 * Called if the promise is rejected.
8241 * @param error [Error] the error object returned from the request.
8242 * @return [Promise] A promise that represents the state of the request.
8243 * @example Sending a request using promises.
8244 * var request = s3.putObject({Bucket: 'bucket', Key: 'key'});
8245 * var result = request.promise();
8246 * result.then(function(data) { ... }, function(error) { ... });
8247 */
8248
8249 /**
8250 * @api private
8251 */
8252 build: function build(callback) {
8253 return this.runTo('send', callback);
8254 },
8255
8256 /**
8257 * @api private
8258 */
8259 runTo: function runTo(state, done) {
8260 this._asm.runTo(state, done, this);
8261 return this;
8262 },
8263
8264 /**
8265 * Aborts a request, emitting the error and complete events.
8266 *
8267 * @!macro nobrowser
8268 * @example Aborting a request after sending
8269 * var params = {
8270 * Bucket: 'bucket', Key: 'key',
8271 * Body: new Buffer(1024 * 1024 * 5) // 5MB payload
8272 * };
8273 * var request = s3.putObject(params);
8274 * request.send(function (err, data) {
8275 * if (err) console.log("Error:", err.code, err.message);
8276 * else console.log(data);
8277 * });
8278 *
8279 * // abort request in 1 second
8280 * setTimeout(request.abort.bind(request), 1000);
8281 *
8282 * // prints "Error: RequestAbortedError Request aborted by user"
8283 * @return [AWS.Request] the same request object, for chaining.
8284 * @since v1.4.0
8285 */
8286 abort: function abort() {
8287 this.removeAllListeners('validateResponse');
8288 this.removeAllListeners('extractError');
8289 this.on('validateResponse', function addAbortedError(resp) {
8290 resp.error = AWS.util.error(new Error('Request aborted by user'), {
8291 code: 'RequestAbortedError', retryable: false
8292 });
8293 });
8294
8295 if (this.httpRequest.stream && !this.httpRequest.stream.didCallback) { // abort HTTP stream
8296 this.httpRequest.stream.abort();
8297 if (this.httpRequest._abortCallback) {
8298 this.httpRequest._abortCallback();
8299 } else {
8300 this.removeAllListeners('send'); // haven't sent yet, so let's not
8301 }
8302 }
8303
8304 return this;
8305 },
8306
8307 /**
8308 * Iterates over each page of results given a pageable request, calling
8309 * the provided callback with each page of data. After all pages have been
8310 * retrieved, the callback is called with `null` data.
8311 *
8312 * @note This operation can generate multiple requests to a service.
8313 * @example Iterating over multiple pages of objects in an S3 bucket
8314 * var pages = 1;
8315 * s3.listObjects().eachPage(function(err, data) {
8316 * if (err) return;
8317 * console.log("Page", pages++);
8318 * console.log(data);
8319 * });
8320 * @example Iterating over multiple pages with an asynchronous callback
8321 * s3.listObjects(params).eachPage(function(err, data, done) {
8322 * doSomethingAsyncAndOrExpensive(function() {
8323 * // The next page of results isn't fetched until done is called
8324 * done();
8325 * });
8326 * });
8327 * @callback callback function(err, data, [doneCallback])
8328 * Called with each page of resulting data from the request. If the
8329 * optional `doneCallback` is provided in the function, it must be called
8330 * when the callback is complete.
8331 *
8332 * @param err [Error] an error object, if an error occurred.
8333 * @param data [Object] a single page of response data. If there is no
8334 * more data, this object will be `null`.
8335 * @param doneCallback [Function] an optional done callback. If this
8336 * argument is defined in the function declaration, it should be called
8337 * when the next page is ready to be retrieved. This is useful for
8338 * controlling serial pagination across asynchronous operations.
8339 * @return [Boolean] if the callback returns `false`, pagination will
8340 * stop.
8341 *
8342 * @see AWS.Request.eachItem
8343 * @see AWS.Response.nextPage
8344 * @since v1.4.0
8345 */
8346 eachPage: function eachPage(callback) {
8347 // Make all callbacks async-ish
8348 callback = AWS.util.fn.makeAsync(callback, 3);
8349
8350 function wrappedCallback(response) {
8351 callback.call(response, response.error, response.data, function (result) {
8352 if (result === false) return;
8353
8354 if (response.hasNextPage()) {
8355 response.nextPage().on('complete', wrappedCallback).send();
8356 } else {
8357 callback.call(response, null, null, AWS.util.fn.noop);
8358 }
8359 });
8360 }
8361
8362 this.on('complete', wrappedCallback).send();
8363 },
8364
8365 /**
8366 * Enumerates over individual items of a request, paging the responses if
8367 * necessary.
8368 *
8369 * @api experimental
8370 * @since v1.4.0
8371 */
8372 eachItem: function eachItem(callback) {
8373 var self = this;
8374 function wrappedCallback(err, data) {
8375 if (err) return callback(err, null);
8376 if (data === null) return callback(null, null);
8377
8378 var config = self.service.paginationConfig(self.operation);
8379 var resultKey = config.resultKey;
8380 if (Array.isArray(resultKey)) resultKey = resultKey[0];
8381 var items = jmespath.search(data, resultKey);
8382 var continueIteration = true;
8383 AWS.util.arrayEach(items, function(item) {
8384 continueIteration = callback(null, item);
8385 if (continueIteration === false) {
8386 return AWS.util.abort;
8387 }
8388 });
8389 return continueIteration;
8390 }
8391
8392 this.eachPage(wrappedCallback);
8393 },
8394
8395 /**
8396 * @return [Boolean] whether the operation can return multiple pages of
8397 * response data.
8398 * @see AWS.Response.eachPage
8399 * @since v1.4.0
8400 */
8401 isPageable: function isPageable() {
8402 return this.service.paginationConfig(this.operation) ? true : false;
8403 },
8404
8405 /**
8406 * Sends the request and converts the request object into a readable stream
8407 * that can be read from or piped into a writable stream.
8408 *
8409 * @note The data read from a readable stream contains only
8410 * the raw HTTP body contents.
8411 * @example Manually reading from a stream
8412 * request.createReadStream().on('data', function(data) {
8413 * console.log("Got data:", data.toString());
8414 * });
8415 * @example Piping a request body into a file
8416 * var out = fs.createWriteStream('/path/to/outfile.jpg');
8417 * s3.service.getObject(params).createReadStream().pipe(out);
8418 * @return [Stream] the readable stream object that can be piped
8419 * or read from (by registering 'data' event listeners).
8420 * @!macro nobrowser
8421 */
8422 createReadStream: function createReadStream() {
8423 var streams = AWS.util.stream;
8424 var req = this;
8425 var stream = null;
8426
8427 if (AWS.HttpClient.streamsApiVersion === 2) {
8428 stream = new streams.PassThrough();
8429 process.nextTick(function() { req.send(); });
8430 } else {
8431 stream = new streams.Stream();
8432 stream.readable = true;
8433
8434 stream.sent = false;
8435 stream.on('newListener', function(event) {
8436 if (!stream.sent && event === 'data') {
8437 stream.sent = true;
8438 process.nextTick(function() { req.send(); });
8439 }
8440 });
8441 }
8442
8443 this.on('error', function(err) {
8444 stream.emit('error', err);
8445 });
8446
8447 this.on('httpHeaders', function streamHeaders(statusCode, headers, resp) {
8448 if (statusCode < 300) {
8449 req.removeListener('httpData', AWS.EventListeners.Core.HTTP_DATA);
8450 req.removeListener('httpError', AWS.EventListeners.Core.HTTP_ERROR);
8451 req.on('httpError', function streamHttpError(error) {
8452 resp.error = error;
8453 resp.error.retryable = false;
8454 });
8455
8456 var shouldCheckContentLength = false;
8457 var expectedLen;
8458 if (req.httpRequest.method !== 'HEAD') {
8459 expectedLen = parseInt(headers['content-length'], 10);
8460 }
8461 if (expectedLen !== undefined && !isNaN(expectedLen) && expectedLen >= 0) {
8462 shouldCheckContentLength = true;
8463 var receivedLen = 0;
8464 }
8465
8466 var checkContentLengthAndEmit = function checkContentLengthAndEmit() {
8467 if (shouldCheckContentLength && receivedLen !== expectedLen) {
8468 stream.emit('error', AWS.util.error(
8469 new Error('Stream content length mismatch. Received ' +
8470 receivedLen + ' of ' + expectedLen + ' bytes.'),
8471 { code: 'StreamContentLengthMismatch' }
8472 ));
8473 } else if (AWS.HttpClient.streamsApiVersion === 2) {
8474 stream.end();
8475 } else {
8476 stream.emit('end');
8477 }
8478 };
8479
8480 var httpStream = resp.httpResponse.createUnbufferedStream();
8481
8482 if (AWS.HttpClient.streamsApiVersion === 2) {
8483 if (shouldCheckContentLength) {
8484 var lengthAccumulator = new streams.PassThrough();
8485 lengthAccumulator._write = function(chunk) {
8486 if (chunk && chunk.length) {
8487 receivedLen += chunk.length;
8488 }
8489 return streams.PassThrough.prototype._write.apply(this, arguments);
8490 };
8491
8492 lengthAccumulator.on('end', checkContentLengthAndEmit);
8493 stream.on('error', function(err) {
8494 shouldCheckContentLength = false;
8495 httpStream.unpipe(lengthAccumulator);
8496 lengthAccumulator.emit('end');
8497 lengthAccumulator.end();
8498 });
8499 httpStream.pipe(lengthAccumulator).pipe(stream, { end: false });
8500 } else {
8501 httpStream.pipe(stream);
8502 }
8503 } else {
8504
8505 if (shouldCheckContentLength) {
8506 httpStream.on('data', function(arg) {
8507 if (arg && arg.length) {
8508 receivedLen += arg.length;
8509 }
8510 });
8511 }
8512
8513 httpStream.on('data', function(arg) {
8514 stream.emit('data', arg);
8515 });
8516 httpStream.on('end', checkContentLengthAndEmit);
8517 }
8518
8519 httpStream.on('error', function(err) {
8520 shouldCheckContentLength = false;
8521 stream.emit('error', err);
8522 });
8523 }
8524 });
8525
8526 return stream;
8527 },
8528
8529 /**
8530 * @param [Array,Response] args This should be the response object,
8531 * or an array of args to send to the event.
8532 * @api private
8533 */
8534 emitEvent: function emit(eventName, args, done) {
8535 if (typeof args === 'function') { done = args; args = null; }
8536 if (!done) done = function() { };
8537 if (!args) args = this.eventParameters(eventName, this.response);
8538
8539 var origEmit = AWS.SequentialExecutor.prototype.emit;
8540 origEmit.call(this, eventName, args, function (err) {
8541 if (err) this.response.error = err;
8542 done.call(this, err);
8543 });
8544 },
8545
8546 /**
8547 * @api private
8548 */
8549 eventParameters: function eventParameters(eventName) {
8550 switch (eventName) {
8551 case 'restart':
8552 case 'validate':
8553 case 'sign':
8554 case 'build':
8555 case 'afterValidate':
8556 case 'afterBuild':
8557 return [this];
8558 case 'error':
8559 return [this.response.error, this.response];
8560 default:
8561 return [this.response];
8562 }
8563 },
8564
8565 /**
8566 * @api private
8567 */
8568 presign: function presign(expires, callback) {
8569 if (!callback && typeof expires === 'function') {
8570 callback = expires;
8571 expires = null;
8572 }
8573 return new AWS.Signers.Presign().sign(this.toGet(), expires, callback);
8574 },
8575
8576 /**
8577 * @api private
8578 */
8579 isPresigned: function isPresigned() {
8580 return Object.prototype.hasOwnProperty.call(this.httpRequest.headers, 'presigned-expires');
8581 },
8582
8583 /**
8584 * @api private
8585 */
8586 toUnauthenticated: function toUnauthenticated() {
8587 this._unAuthenticated = true;
8588 this.removeListener('validate', AWS.EventListeners.Core.VALIDATE_CREDENTIALS);
8589 this.removeListener('sign', AWS.EventListeners.Core.SIGN);
8590 return this;
8591 },
8592
8593 /**
8594 * @api private
8595 */
8596 toGet: function toGet() {
8597 if (this.service.api.protocol === 'query' ||
8598 this.service.api.protocol === 'ec2') {
8599 this.removeListener('build', this.buildAsGet);
8600 this.addListener('build', this.buildAsGet);
8601 }
8602 return this;
8603 },
8604
8605 /**
8606 * @api private
8607 */
8608 buildAsGet: function buildAsGet(request) {
8609 request.httpRequest.method = 'GET';
8610 request.httpRequest.path = request.service.endpoint.path +
8611 '?' + request.httpRequest.body;
8612 request.httpRequest.body = '';
8613
8614 // don't need these headers on a GET request
8615 delete request.httpRequest.headers['Content-Length'];
8616 delete request.httpRequest.headers['Content-Type'];
8617 },
8618
8619 /**
8620 * @api private
8621 */
8622 haltHandlersOnError: function haltHandlersOnError() {
8623 this._haltHandlersOnError = true;
8624 }
8625 });
8626
8627 /**
8628 * @api private
8629 */
8630 AWS.Request.addPromisesToClass = function addPromisesToClass(PromiseDependency) {
8631 this.prototype.promise = function promise() {
8632 var self = this;
8633 // append to user agent
8634 this.httpRequest.appendToUserAgent('promise');
8635 return new PromiseDependency(function(resolve, reject) {
8636 self.on('complete', function(resp) {
8637 if (resp.error) {
8638 reject(resp.error);
8639 } else {
8640 // define $response property so that it is not enumberable
8641 // this prevents circular reference errors when stringifying the JSON object
8642 resolve(Object.defineProperty(
8643 resp.data || {},
8644 '$response',
8645 {value: resp}
8646 ));
8647 }
8648 });
8649 self.runTo();
8650 });
8651 };
8652 };
8653
8654 /**
8655 * @api private
8656 */
8657 AWS.Request.deletePromisesFromClass = function deletePromisesFromClass() {
8658 delete this.prototype.promise;
8659 };
8660
8661 AWS.util.addPromises(AWS.Request);
8662
8663 AWS.util.mixin(AWS.Request, AWS.SequentialExecutor);
8664
8665 /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
8666
8667/***/ }),
8668/* 50 */
8669/***/ (function(module, exports) {
8670
8671 function AcceptorStateMachine(states, state) {
8672 this.currentState = state || null;
8673 this.states = states || {};
8674 }
8675
8676 AcceptorStateMachine.prototype.runTo = function runTo(finalState, done, bindObject, inputError) {
8677 if (typeof finalState === 'function') {
8678 inputError = bindObject; bindObject = done;
8679 done = finalState; finalState = null;
8680 }
8681
8682 var self = this;
8683 var state = self.states[self.currentState];
8684 state.fn.call(bindObject || self, inputError, function(err) {
8685 if (err) {
8686 if (state.fail) self.currentState = state.fail;
8687 else return done ? done.call(bindObject, err) : null;
8688 } else {
8689 if (state.accept) self.currentState = state.accept;
8690 else return done ? done.call(bindObject) : null;
8691 }
8692 if (self.currentState === finalState) {
8693 return done ? done.call(bindObject, err) : null;
8694 }
8695
8696 self.runTo(finalState, done, bindObject, err);
8697 });
8698 };
8699
8700 AcceptorStateMachine.prototype.addState = function addState(name, acceptState, failState, fn) {
8701 if (typeof acceptState === 'function') {
8702 fn = acceptState; acceptState = null; failState = null;
8703 } else if (typeof failState === 'function') {
8704 fn = failState; failState = null;
8705 }
8706
8707 if (!this.currentState) this.currentState = name;
8708 this.states[name] = { accept: acceptState, fail: failState, fn: fn };
8709 return this;
8710 };
8711
8712 /**
8713 * @api private
8714 */
8715 module.exports = AcceptorStateMachine;
8716
8717
8718/***/ }),
8719/* 51 */
8720/***/ (function(module, exports, __webpack_require__) {
8721
8722 (function(exports) {
8723 "use strict";
8724
8725 function isArray(obj) {
8726 if (obj !== null) {
8727 return Object.prototype.toString.call(obj) === "[object Array]";
8728 } else {
8729 return false;
8730 }
8731 }
8732
8733 function isObject(obj) {
8734 if (obj !== null) {
8735 return Object.prototype.toString.call(obj) === "[object Object]";
8736 } else {
8737 return false;
8738 }
8739 }
8740
8741 function strictDeepEqual(first, second) {
8742 // Check the scalar case first.
8743 if (first === second) {
8744 return true;
8745 }
8746
8747 // Check if they are the same type.
8748 var firstType = Object.prototype.toString.call(first);
8749 if (firstType !== Object.prototype.toString.call(second)) {
8750 return false;
8751 }
8752 // We know that first and second have the same type so we can just check the
8753 // first type from now on.
8754 if (isArray(first) === true) {
8755 // Short circuit if they're not the same length;
8756 if (first.length !== second.length) {
8757 return false;
8758 }
8759 for (var i = 0; i < first.length; i++) {
8760 if (strictDeepEqual(first[i], second[i]) === false) {
8761 return false;
8762 }
8763 }
8764 return true;
8765 }
8766 if (isObject(first) === true) {
8767 // An object is equal if it has the same key/value pairs.
8768 var keysSeen = {};
8769 for (var key in first) {
8770 if (hasOwnProperty.call(first, key)) {
8771 if (strictDeepEqual(first[key], second[key]) === false) {
8772 return false;
8773 }
8774 keysSeen[key] = true;
8775 }
8776 }
8777 // Now check that there aren't any keys in second that weren't
8778 // in first.
8779 for (var key2 in second) {
8780 if (hasOwnProperty.call(second, key2)) {
8781 if (keysSeen[key2] !== true) {
8782 return false;
8783 }
8784 }
8785 }
8786 return true;
8787 }
8788 return false;
8789 }
8790
8791 function isFalse(obj) {
8792 // From the spec:
8793 // A false value corresponds to the following values:
8794 // Empty list
8795 // Empty object
8796 // Empty string
8797 // False boolean
8798 // null value
8799
8800 // First check the scalar values.
8801 if (obj === "" || obj === false || obj === null) {
8802 return true;
8803 } else if (isArray(obj) && obj.length === 0) {
8804 // Check for an empty array.
8805 return true;
8806 } else if (isObject(obj)) {
8807 // Check for an empty object.
8808 for (var key in obj) {
8809 // If there are any keys, then
8810 // the object is not empty so the object
8811 // is not false.
8812 if (obj.hasOwnProperty(key)) {
8813 return false;
8814 }
8815 }
8816 return true;
8817 } else {
8818 return false;
8819 }
8820 }
8821
8822 function objValues(obj) {
8823 var keys = Object.keys(obj);
8824 var values = [];
8825 for (var i = 0; i < keys.length; i++) {
8826 values.push(obj[keys[i]]);
8827 }
8828 return values;
8829 }
8830
8831 function merge(a, b) {
8832 var merged = {};
8833 for (var key in a) {
8834 merged[key] = a[key];
8835 }
8836 for (var key2 in b) {
8837 merged[key2] = b[key2];
8838 }
8839 return merged;
8840 }
8841
8842 var trimLeft;
8843 if (typeof String.prototype.trimLeft === "function") {
8844 trimLeft = function(str) {
8845 return str.trimLeft();
8846 };
8847 } else {
8848 trimLeft = function(str) {
8849 return str.match(/^\s*(.*)/)[1];
8850 };
8851 }
8852
8853 // Type constants used to define functions.
8854 var TYPE_NUMBER = 0;
8855 var TYPE_ANY = 1;
8856 var TYPE_STRING = 2;
8857 var TYPE_ARRAY = 3;
8858 var TYPE_OBJECT = 4;
8859 var TYPE_BOOLEAN = 5;
8860 var TYPE_EXPREF = 6;
8861 var TYPE_NULL = 7;
8862 var TYPE_ARRAY_NUMBER = 8;
8863 var TYPE_ARRAY_STRING = 9;
8864
8865 var TOK_EOF = "EOF";
8866 var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier";
8867 var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier";
8868 var TOK_RBRACKET = "Rbracket";
8869 var TOK_RPAREN = "Rparen";
8870 var TOK_COMMA = "Comma";
8871 var TOK_COLON = "Colon";
8872 var TOK_RBRACE = "Rbrace";
8873 var TOK_NUMBER = "Number";
8874 var TOK_CURRENT = "Current";
8875 var TOK_EXPREF = "Expref";
8876 var TOK_PIPE = "Pipe";
8877 var TOK_OR = "Or";
8878 var TOK_AND = "And";
8879 var TOK_EQ = "EQ";
8880 var TOK_GT = "GT";
8881 var TOK_LT = "LT";
8882 var TOK_GTE = "GTE";
8883 var TOK_LTE = "LTE";
8884 var TOK_NE = "NE";
8885 var TOK_FLATTEN = "Flatten";
8886 var TOK_STAR = "Star";
8887 var TOK_FILTER = "Filter";
8888 var TOK_DOT = "Dot";
8889 var TOK_NOT = "Not";
8890 var TOK_LBRACE = "Lbrace";
8891 var TOK_LBRACKET = "Lbracket";
8892 var TOK_LPAREN= "Lparen";
8893 var TOK_LITERAL= "Literal";
8894
8895 // The "&", "[", "<", ">" tokens
8896 // are not in basicToken because
8897 // there are two token variants
8898 // ("&&", "[?", "<=", ">="). This is specially handled
8899 // below.
8900
8901 var basicTokens = {
8902 ".": TOK_DOT,
8903 "*": TOK_STAR,
8904 ",": TOK_COMMA,
8905 ":": TOK_COLON,
8906 "{": TOK_LBRACE,
8907 "}": TOK_RBRACE,
8908 "]": TOK_RBRACKET,
8909 "(": TOK_LPAREN,
8910 ")": TOK_RPAREN,
8911 "@": TOK_CURRENT
8912 };
8913
8914 var operatorStartToken = {
8915 "<": true,
8916 ">": true,
8917 "=": true,
8918 "!": true
8919 };
8920
8921 var skipChars = {
8922 " ": true,
8923 "\t": true,
8924 "\n": true
8925 };
8926
8927
8928 function isAlpha(ch) {
8929 return (ch >= "a" && ch <= "z") ||
8930 (ch >= "A" && ch <= "Z") ||
8931 ch === "_";
8932 }
8933
8934 function isNum(ch) {
8935 return (ch >= "0" && ch <= "9") ||
8936 ch === "-";
8937 }
8938 function isAlphaNum(ch) {
8939 return (ch >= "a" && ch <= "z") ||
8940 (ch >= "A" && ch <= "Z") ||
8941 (ch >= "0" && ch <= "9") ||
8942 ch === "_";
8943 }
8944
8945 function Lexer() {
8946 }
8947 Lexer.prototype = {
8948 tokenize: function(stream) {
8949 var tokens = [];
8950 this._current = 0;
8951 var start;
8952 var identifier;
8953 var token;
8954 while (this._current < stream.length) {
8955 if (isAlpha(stream[this._current])) {
8956 start = this._current;
8957 identifier = this._consumeUnquotedIdentifier(stream);
8958 tokens.push({type: TOK_UNQUOTEDIDENTIFIER,
8959 value: identifier,
8960 start: start});
8961 } else if (basicTokens[stream[this._current]] !== undefined) {
8962 tokens.push({type: basicTokens[stream[this._current]],
8963 value: stream[this._current],
8964 start: this._current});
8965 this._current++;
8966 } else if (isNum(stream[this._current])) {
8967 token = this._consumeNumber(stream);
8968 tokens.push(token);
8969 } else if (stream[this._current] === "[") {
8970 // No need to increment this._current. This happens
8971 // in _consumeLBracket
8972 token = this._consumeLBracket(stream);
8973 tokens.push(token);
8974 } else if (stream[this._current] === "\"") {
8975 start = this._current;
8976 identifier = this._consumeQuotedIdentifier(stream);
8977 tokens.push({type: TOK_QUOTEDIDENTIFIER,
8978 value: identifier,
8979 start: start});
8980 } else if (stream[this._current] === "'") {
8981 start = this._current;
8982 identifier = this._consumeRawStringLiteral(stream);
8983 tokens.push({type: TOK_LITERAL,
8984 value: identifier,
8985 start: start});
8986 } else if (stream[this._current] === "`") {
8987 start = this._current;
8988 var literal = this._consumeLiteral(stream);
8989 tokens.push({type: TOK_LITERAL,
8990 value: literal,
8991 start: start});
8992 } else if (operatorStartToken[stream[this._current]] !== undefined) {
8993 tokens.push(this._consumeOperator(stream));
8994 } else if (skipChars[stream[this._current]] !== undefined) {
8995 // Ignore whitespace.
8996 this._current++;
8997 } else if (stream[this._current] === "&") {
8998 start = this._current;
8999 this._current++;
9000 if (stream[this._current] === "&") {
9001 this._current++;
9002 tokens.push({type: TOK_AND, value: "&&", start: start});
9003 } else {
9004 tokens.push({type: TOK_EXPREF, value: "&", start: start});
9005 }
9006 } else if (stream[this._current] === "|") {
9007 start = this._current;
9008 this._current++;
9009 if (stream[this._current] === "|") {
9010 this._current++;
9011 tokens.push({type: TOK_OR, value: "||", start: start});
9012 } else {
9013 tokens.push({type: TOK_PIPE, value: "|", start: start});
9014 }
9015 } else {
9016 var error = new Error("Unknown character:" + stream[this._current]);
9017 error.name = "LexerError";
9018 throw error;
9019 }
9020 }
9021 return tokens;
9022 },
9023
9024 _consumeUnquotedIdentifier: function(stream) {
9025 var start = this._current;
9026 this._current++;
9027 while (this._current < stream.length && isAlphaNum(stream[this._current])) {
9028 this._current++;
9029 }
9030 return stream.slice(start, this._current);
9031 },
9032
9033 _consumeQuotedIdentifier: function(stream) {
9034 var start = this._current;
9035 this._current++;
9036 var maxLength = stream.length;
9037 while (stream[this._current] !== "\"" && this._current < maxLength) {
9038 // You can escape a double quote and you can escape an escape.
9039 var current = this._current;
9040 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9041 stream[current + 1] === "\"")) {
9042 current += 2;
9043 } else {
9044 current++;
9045 }
9046 this._current = current;
9047 }
9048 this._current++;
9049 return JSON.parse(stream.slice(start, this._current));
9050 },
9051
9052 _consumeRawStringLiteral: function(stream) {
9053 var start = this._current;
9054 this._current++;
9055 var maxLength = stream.length;
9056 while (stream[this._current] !== "'" && this._current < maxLength) {
9057 // You can escape a single quote and you can escape an escape.
9058 var current = this._current;
9059 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9060 stream[current + 1] === "'")) {
9061 current += 2;
9062 } else {
9063 current++;
9064 }
9065 this._current = current;
9066 }
9067 this._current++;
9068 var literal = stream.slice(start + 1, this._current - 1);
9069 return literal.replace("\\'", "'");
9070 },
9071
9072 _consumeNumber: function(stream) {
9073 var start = this._current;
9074 this._current++;
9075 var maxLength = stream.length;
9076 while (isNum(stream[this._current]) && this._current < maxLength) {
9077 this._current++;
9078 }
9079 var value = parseInt(stream.slice(start, this._current));
9080 return {type: TOK_NUMBER, value: value, start: start};
9081 },
9082
9083 _consumeLBracket: function(stream) {
9084 var start = this._current;
9085 this._current++;
9086 if (stream[this._current] === "?") {
9087 this._current++;
9088 return {type: TOK_FILTER, value: "[?", start: start};
9089 } else if (stream[this._current] === "]") {
9090 this._current++;
9091 return {type: TOK_FLATTEN, value: "[]", start: start};
9092 } else {
9093 return {type: TOK_LBRACKET, value: "[", start: start};
9094 }
9095 },
9096
9097 _consumeOperator: function(stream) {
9098 var start = this._current;
9099 var startingChar = stream[start];
9100 this._current++;
9101 if (startingChar === "!") {
9102 if (stream[this._current] === "=") {
9103 this._current++;
9104 return {type: TOK_NE, value: "!=", start: start};
9105 } else {
9106 return {type: TOK_NOT, value: "!", start: start};
9107 }
9108 } else if (startingChar === "<") {
9109 if (stream[this._current] === "=") {
9110 this._current++;
9111 return {type: TOK_LTE, value: "<=", start: start};
9112 } else {
9113 return {type: TOK_LT, value: "<", start: start};
9114 }
9115 } else if (startingChar === ">") {
9116 if (stream[this._current] === "=") {
9117 this._current++;
9118 return {type: TOK_GTE, value: ">=", start: start};
9119 } else {
9120 return {type: TOK_GT, value: ">", start: start};
9121 }
9122 } else if (startingChar === "=") {
9123 if (stream[this._current] === "=") {
9124 this._current++;
9125 return {type: TOK_EQ, value: "==", start: start};
9126 }
9127 }
9128 },
9129
9130 _consumeLiteral: function(stream) {
9131 this._current++;
9132 var start = this._current;
9133 var maxLength = stream.length;
9134 var literal;
9135 while(stream[this._current] !== "`" && this._current < maxLength) {
9136 // You can escape a literal char or you can escape the escape.
9137 var current = this._current;
9138 if (stream[current] === "\\" && (stream[current + 1] === "\\" ||
9139 stream[current + 1] === "`")) {
9140 current += 2;
9141 } else {
9142 current++;
9143 }
9144 this._current = current;
9145 }
9146 var literalString = trimLeft(stream.slice(start, this._current));
9147 literalString = literalString.replace("\\`", "`");
9148 if (this._looksLikeJSON(literalString)) {
9149 literal = JSON.parse(literalString);
9150 } else {
9151 // Try to JSON parse it as "<literal>"
9152 literal = JSON.parse("\"" + literalString + "\"");
9153 }
9154 // +1 gets us to the ending "`", +1 to move on to the next char.
9155 this._current++;
9156 return literal;
9157 },
9158
9159 _looksLikeJSON: function(literalString) {
9160 var startingChars = "[{\"";
9161 var jsonLiterals = ["true", "false", "null"];
9162 var numberLooking = "-0123456789";
9163
9164 if (literalString === "") {
9165 return false;
9166 } else if (startingChars.indexOf(literalString[0]) >= 0) {
9167 return true;
9168 } else if (jsonLiterals.indexOf(literalString) >= 0) {
9169 return true;
9170 } else if (numberLooking.indexOf(literalString[0]) >= 0) {
9171 try {
9172 JSON.parse(literalString);
9173 return true;
9174 } catch (ex) {
9175 return false;
9176 }
9177 } else {
9178 return false;
9179 }
9180 }
9181 };
9182
9183 var bindingPower = {};
9184 bindingPower[TOK_EOF] = 0;
9185 bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0;
9186 bindingPower[TOK_QUOTEDIDENTIFIER] = 0;
9187 bindingPower[TOK_RBRACKET] = 0;
9188 bindingPower[TOK_RPAREN] = 0;
9189 bindingPower[TOK_COMMA] = 0;
9190 bindingPower[TOK_RBRACE] = 0;
9191 bindingPower[TOK_NUMBER] = 0;
9192 bindingPower[TOK_CURRENT] = 0;
9193 bindingPower[TOK_EXPREF] = 0;
9194 bindingPower[TOK_PIPE] = 1;
9195 bindingPower[TOK_OR] = 2;
9196 bindingPower[TOK_AND] = 3;
9197 bindingPower[TOK_EQ] = 5;
9198 bindingPower[TOK_GT] = 5;
9199 bindingPower[TOK_LT] = 5;
9200 bindingPower[TOK_GTE] = 5;
9201 bindingPower[TOK_LTE] = 5;
9202 bindingPower[TOK_NE] = 5;
9203 bindingPower[TOK_FLATTEN] = 9;
9204 bindingPower[TOK_STAR] = 20;
9205 bindingPower[TOK_FILTER] = 21;
9206 bindingPower[TOK_DOT] = 40;
9207 bindingPower[TOK_NOT] = 45;
9208 bindingPower[TOK_LBRACE] = 50;
9209 bindingPower[TOK_LBRACKET] = 55;
9210 bindingPower[TOK_LPAREN] = 60;
9211
9212 function Parser() {
9213 }
9214
9215 Parser.prototype = {
9216 parse: function(expression) {
9217 this._loadTokens(expression);
9218 this.index = 0;
9219 var ast = this.expression(0);
9220 if (this._lookahead(0) !== TOK_EOF) {
9221 var t = this._lookaheadToken(0);
9222 var error = new Error(
9223 "Unexpected token type: " + t.type + ", value: " + t.value);
9224 error.name = "ParserError";
9225 throw error;
9226 }
9227 return ast;
9228 },
9229
9230 _loadTokens: function(expression) {
9231 var lexer = new Lexer();
9232 var tokens = lexer.tokenize(expression);
9233 tokens.push({type: TOK_EOF, value: "", start: expression.length});
9234 this.tokens = tokens;
9235 },
9236
9237 expression: function(rbp) {
9238 var leftToken = this._lookaheadToken(0);
9239 this._advance();
9240 var left = this.nud(leftToken);
9241 var currentToken = this._lookahead(0);
9242 while (rbp < bindingPower[currentToken]) {
9243 this._advance();
9244 left = this.led(currentToken, left);
9245 currentToken = this._lookahead(0);
9246 }
9247 return left;
9248 },
9249
9250 _lookahead: function(number) {
9251 return this.tokens[this.index + number].type;
9252 },
9253
9254 _lookaheadToken: function(number) {
9255 return this.tokens[this.index + number];
9256 },
9257
9258 _advance: function() {
9259 this.index++;
9260 },
9261
9262 nud: function(token) {
9263 var left;
9264 var right;
9265 var expression;
9266 switch (token.type) {
9267 case TOK_LITERAL:
9268 return {type: "Literal", value: token.value};
9269 case TOK_UNQUOTEDIDENTIFIER:
9270 return {type: "Field", name: token.value};
9271 case TOK_QUOTEDIDENTIFIER:
9272 var node = {type: "Field", name: token.value};
9273 if (this._lookahead(0) === TOK_LPAREN) {
9274 throw new Error("Quoted identifier not allowed for function names.");
9275 } else {
9276 return node;
9277 }
9278 break;
9279 case TOK_NOT:
9280 right = this.expression(bindingPower.Not);
9281 return {type: "NotExpression", children: [right]};
9282 case TOK_STAR:
9283 left = {type: "Identity"};
9284 right = null;
9285 if (this._lookahead(0) === TOK_RBRACKET) {
9286 // This can happen in a multiselect,
9287 // [a, b, *]
9288 right = {type: "Identity"};
9289 } else {
9290 right = this._parseProjectionRHS(bindingPower.Star);
9291 }
9292 return {type: "ValueProjection", children: [left, right]};
9293 case TOK_FILTER:
9294 return this.led(token.type, {type: "Identity"});
9295 case TOK_LBRACE:
9296 return this._parseMultiselectHash();
9297 case TOK_FLATTEN:
9298 left = {type: TOK_FLATTEN, children: [{type: "Identity"}]};
9299 right = this._parseProjectionRHS(bindingPower.Flatten);
9300 return {type: "Projection", children: [left, right]};
9301 case TOK_LBRACKET:
9302 if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) {
9303 right = this._parseIndexExpression();
9304 return this._projectIfSlice({type: "Identity"}, right);
9305 } else if (this._lookahead(0) === TOK_STAR &&
9306 this._lookahead(1) === TOK_RBRACKET) {
9307 this._advance();
9308 this._advance();
9309 right = this._parseProjectionRHS(bindingPower.Star);
9310 return {type: "Projection",
9311 children: [{type: "Identity"}, right]};
9312 } else {
9313 return this._parseMultiselectList();
9314 }
9315 break;
9316 case TOK_CURRENT:
9317 return {type: TOK_CURRENT};
9318 case TOK_EXPREF:
9319 expression = this.expression(bindingPower.Expref);
9320 return {type: "ExpressionReference", children: [expression]};
9321 case TOK_LPAREN:
9322 var args = [];
9323 while (this._lookahead(0) !== TOK_RPAREN) {
9324 if (this._lookahead(0) === TOK_CURRENT) {
9325 expression = {type: TOK_CURRENT};
9326 this._advance();
9327 } else {
9328 expression = this.expression(0);
9329 }
9330 args.push(expression);
9331 }
9332 this._match(TOK_RPAREN);
9333 return args[0];
9334 default:
9335 this._errorToken(token);
9336 }
9337 },
9338
9339 led: function(tokenName, left) {
9340 var right;
9341 switch(tokenName) {
9342 case TOK_DOT:
9343 var rbp = bindingPower.Dot;
9344 if (this._lookahead(0) !== TOK_STAR) {
9345 right = this._parseDotRHS(rbp);
9346 return {type: "Subexpression", children: [left, right]};
9347 } else {
9348 // Creating a projection.
9349 this._advance();
9350 right = this._parseProjectionRHS(rbp);
9351 return {type: "ValueProjection", children: [left, right]};
9352 }
9353 break;
9354 case TOK_PIPE:
9355 right = this.expression(bindingPower.Pipe);
9356 return {type: TOK_PIPE, children: [left, right]};
9357 case TOK_OR:
9358 right = this.expression(bindingPower.Or);
9359 return {type: "OrExpression", children: [left, right]};
9360 case TOK_AND:
9361 right = this.expression(bindingPower.And);
9362 return {type: "AndExpression", children: [left, right]};
9363 case TOK_LPAREN:
9364 var name = left.name;
9365 var args = [];
9366 var expression, node;
9367 while (this._lookahead(0) !== TOK_RPAREN) {
9368 if (this._lookahead(0) === TOK_CURRENT) {
9369 expression = {type: TOK_CURRENT};
9370 this._advance();
9371 } else {
9372 expression = this.expression(0);
9373 }
9374 if (this._lookahead(0) === TOK_COMMA) {
9375 this._match(TOK_COMMA);
9376 }
9377 args.push(expression);
9378 }
9379 this._match(TOK_RPAREN);
9380 node = {type: "Function", name: name, children: args};
9381 return node;
9382 case TOK_FILTER:
9383 var condition = this.expression(0);
9384 this._match(TOK_RBRACKET);
9385 if (this._lookahead(0) === TOK_FLATTEN) {
9386 right = {type: "Identity"};
9387 } else {
9388 right = this._parseProjectionRHS(bindingPower.Filter);
9389 }
9390 return {type: "FilterProjection", children: [left, right, condition]};
9391 case TOK_FLATTEN:
9392 var leftNode = {type: TOK_FLATTEN, children: [left]};
9393 var rightNode = this._parseProjectionRHS(bindingPower.Flatten);
9394 return {type: "Projection", children: [leftNode, rightNode]};
9395 case TOK_EQ:
9396 case TOK_NE:
9397 case TOK_GT:
9398 case TOK_GTE:
9399 case TOK_LT:
9400 case TOK_LTE:
9401 return this._parseComparator(left, tokenName);
9402 case TOK_LBRACKET:
9403 var token = this._lookaheadToken(0);
9404 if (token.type === TOK_NUMBER || token.type === TOK_COLON) {
9405 right = this._parseIndexExpression();
9406 return this._projectIfSlice(left, right);
9407 } else {
9408 this._match(TOK_STAR);
9409 this._match(TOK_RBRACKET);
9410 right = this._parseProjectionRHS(bindingPower.Star);
9411 return {type: "Projection", children: [left, right]};
9412 }
9413 break;
9414 default:
9415 this._errorToken(this._lookaheadToken(0));
9416 }
9417 },
9418
9419 _match: function(tokenType) {
9420 if (this._lookahead(0) === tokenType) {
9421 this._advance();
9422 } else {
9423 var t = this._lookaheadToken(0);
9424 var error = new Error("Expected " + tokenType + ", got: " + t.type);
9425 error.name = "ParserError";
9426 throw error;
9427 }
9428 },
9429
9430 _errorToken: function(token) {
9431 var error = new Error("Invalid token (" +
9432 token.type + "): \"" +
9433 token.value + "\"");
9434 error.name = "ParserError";
9435 throw error;
9436 },
9437
9438
9439 _parseIndexExpression: function() {
9440 if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) {
9441 return this._parseSliceExpression();
9442 } else {
9443 var node = {
9444 type: "Index",
9445 value: this._lookaheadToken(0).value};
9446 this._advance();
9447 this._match(TOK_RBRACKET);
9448 return node;
9449 }
9450 },
9451
9452 _projectIfSlice: function(left, right) {
9453 var indexExpr = {type: "IndexExpression", children: [left, right]};
9454 if (right.type === "Slice") {
9455 return {
9456 type: "Projection",
9457 children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)]
9458 };
9459 } else {
9460 return indexExpr;
9461 }
9462 },
9463
9464 _parseSliceExpression: function() {
9465 // [start:end:step] where each part is optional, as well as the last
9466 // colon.
9467 var parts = [null, null, null];
9468 var index = 0;
9469 var currentToken = this._lookahead(0);
9470 while (currentToken !== TOK_RBRACKET && index < 3) {
9471 if (currentToken === TOK_COLON) {
9472 index++;
9473 this._advance();
9474 } else if (currentToken === TOK_NUMBER) {
9475 parts[index] = this._lookaheadToken(0).value;
9476 this._advance();
9477 } else {
9478 var t = this._lookahead(0);
9479 var error = new Error("Syntax error, unexpected token: " +
9480 t.value + "(" + t.type + ")");
9481 error.name = "Parsererror";
9482 throw error;
9483 }
9484 currentToken = this._lookahead(0);
9485 }
9486 this._match(TOK_RBRACKET);
9487 return {
9488 type: "Slice",
9489 children: parts
9490 };
9491 },
9492
9493 _parseComparator: function(left, comparator) {
9494 var right = this.expression(bindingPower[comparator]);
9495 return {type: "Comparator", name: comparator, children: [left, right]};
9496 },
9497
9498 _parseDotRHS: function(rbp) {
9499 var lookahead = this._lookahead(0);
9500 var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR];
9501 if (exprTokens.indexOf(lookahead) >= 0) {
9502 return this.expression(rbp);
9503 } else if (lookahead === TOK_LBRACKET) {
9504 this._match(TOK_LBRACKET);
9505 return this._parseMultiselectList();
9506 } else if (lookahead === TOK_LBRACE) {
9507 this._match(TOK_LBRACE);
9508 return this._parseMultiselectHash();
9509 }
9510 },
9511
9512 _parseProjectionRHS: function(rbp) {
9513 var right;
9514 if (bindingPower[this._lookahead(0)] < 10) {
9515 right = {type: "Identity"};
9516 } else if (this._lookahead(0) === TOK_LBRACKET) {
9517 right = this.expression(rbp);
9518 } else if (this._lookahead(0) === TOK_FILTER) {
9519 right = this.expression(rbp);
9520 } else if (this._lookahead(0) === TOK_DOT) {
9521 this._match(TOK_DOT);
9522 right = this._parseDotRHS(rbp);
9523 } else {
9524 var t = this._lookaheadToken(0);
9525 var error = new Error("Sytanx error, unexpected token: " +
9526 t.value + "(" + t.type + ")");
9527 error.name = "ParserError";
9528 throw error;
9529 }
9530 return right;
9531 },
9532
9533 _parseMultiselectList: function() {
9534 var expressions = [];
9535 while (this._lookahead(0) !== TOK_RBRACKET) {
9536 var expression = this.expression(0);
9537 expressions.push(expression);
9538 if (this._lookahead(0) === TOK_COMMA) {
9539 this._match(TOK_COMMA);
9540 if (this._lookahead(0) === TOK_RBRACKET) {
9541 throw new Error("Unexpected token Rbracket");
9542 }
9543 }
9544 }
9545 this._match(TOK_RBRACKET);
9546 return {type: "MultiSelectList", children: expressions};
9547 },
9548
9549 _parseMultiselectHash: function() {
9550 var pairs = [];
9551 var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER];
9552 var keyToken, keyName, value, node;
9553 for (;;) {
9554 keyToken = this._lookaheadToken(0);
9555 if (identifierTypes.indexOf(keyToken.type) < 0) {
9556 throw new Error("Expecting an identifier token, got: " +
9557 keyToken.type);
9558 }
9559 keyName = keyToken.value;
9560 this._advance();
9561 this._match(TOK_COLON);
9562 value = this.expression(0);
9563 node = {type: "KeyValuePair", name: keyName, value: value};
9564 pairs.push(node);
9565 if (this._lookahead(0) === TOK_COMMA) {
9566 this._match(TOK_COMMA);
9567 } else if (this._lookahead(0) === TOK_RBRACE) {
9568 this._match(TOK_RBRACE);
9569 break;
9570 }
9571 }
9572 return {type: "MultiSelectHash", children: pairs};
9573 }
9574 };
9575
9576
9577 function TreeInterpreter(runtime) {
9578 this.runtime = runtime;
9579 }
9580
9581 TreeInterpreter.prototype = {
9582 search: function(node, value) {
9583 return this.visit(node, value);
9584 },
9585
9586 visit: function(node, value) {
9587 var matched, current, result, first, second, field, left, right, collected, i;
9588 switch (node.type) {
9589 case "Field":
9590 if (value === null ) {
9591 return null;
9592 } else if (isObject(value)) {
9593 field = value[node.name];
9594 if (field === undefined) {
9595 return null;
9596 } else {
9597 return field;
9598 }
9599 } else {
9600 return null;
9601 }
9602 break;
9603 case "Subexpression":
9604 result = this.visit(node.children[0], value);
9605 for (i = 1; i < node.children.length; i++) {
9606 result = this.visit(node.children[1], result);
9607 if (result === null) {
9608 return null;
9609 }
9610 }
9611 return result;
9612 case "IndexExpression":
9613 left = this.visit(node.children[0], value);
9614 right = this.visit(node.children[1], left);
9615 return right;
9616 case "Index":
9617 if (!isArray(value)) {
9618 return null;
9619 }
9620 var index = node.value;
9621 if (index < 0) {
9622 index = value.length + index;
9623 }
9624 result = value[index];
9625 if (result === undefined) {
9626 result = null;
9627 }
9628 return result;
9629 case "Slice":
9630 if (!isArray(value)) {
9631 return null;
9632 }
9633 var sliceParams = node.children.slice(0);
9634 var computed = this.computeSliceParams(value.length, sliceParams);
9635 var start = computed[0];
9636 var stop = computed[1];
9637 var step = computed[2];
9638 result = [];
9639 if (step > 0) {
9640 for (i = start; i < stop; i += step) {
9641 result.push(value[i]);
9642 }
9643 } else {
9644 for (i = start; i > stop; i += step) {
9645 result.push(value[i]);
9646 }
9647 }
9648 return result;
9649 case "Projection":
9650 // Evaluate left child.
9651 var base = this.visit(node.children[0], value);
9652 if (!isArray(base)) {
9653 return null;
9654 }
9655 collected = [];
9656 for (i = 0; i < base.length; i++) {
9657 current = this.visit(node.children[1], base[i]);
9658 if (current !== null) {
9659 collected.push(current);
9660 }
9661 }
9662 return collected;
9663 case "ValueProjection":
9664 // Evaluate left child.
9665 base = this.visit(node.children[0], value);
9666 if (!isObject(base)) {
9667 return null;
9668 }
9669 collected = [];
9670 var values = objValues(base);
9671 for (i = 0; i < values.length; i++) {
9672 current = this.visit(node.children[1], values[i]);
9673 if (current !== null) {
9674 collected.push(current);
9675 }
9676 }
9677 return collected;
9678 case "FilterProjection":
9679 base = this.visit(node.children[0], value);
9680 if (!isArray(base)) {
9681 return null;
9682 }
9683 var filtered = [];
9684 var finalResults = [];
9685 for (i = 0; i < base.length; i++) {
9686 matched = this.visit(node.children[2], base[i]);
9687 if (!isFalse(matched)) {
9688 filtered.push(base[i]);
9689 }
9690 }
9691 for (var j = 0; j < filtered.length; j++) {
9692 current = this.visit(node.children[1], filtered[j]);
9693 if (current !== null) {
9694 finalResults.push(current);
9695 }
9696 }
9697 return finalResults;
9698 case "Comparator":
9699 first = this.visit(node.children[0], value);
9700 second = this.visit(node.children[1], value);
9701 switch(node.name) {
9702 case TOK_EQ:
9703 result = strictDeepEqual(first, second);
9704 break;
9705 case TOK_NE:
9706 result = !strictDeepEqual(first, second);
9707 break;
9708 case TOK_GT:
9709 result = first > second;
9710 break;
9711 case TOK_GTE:
9712 result = first >= second;
9713 break;
9714 case TOK_LT:
9715 result = first < second;
9716 break;
9717 case TOK_LTE:
9718 result = first <= second;
9719 break;
9720 default:
9721 throw new Error("Unknown comparator: " + node.name);
9722 }
9723 return result;
9724 case TOK_FLATTEN:
9725 var original = this.visit(node.children[0], value);
9726 if (!isArray(original)) {
9727 return null;
9728 }
9729 var merged = [];
9730 for (i = 0; i < original.length; i++) {
9731 current = original[i];
9732 if (isArray(current)) {
9733 merged.push.apply(merged, current);
9734 } else {
9735 merged.push(current);
9736 }
9737 }
9738 return merged;
9739 case "Identity":
9740 return value;
9741 case "MultiSelectList":
9742 if (value === null) {
9743 return null;
9744 }
9745 collected = [];
9746 for (i = 0; i < node.children.length; i++) {
9747 collected.push(this.visit(node.children[i], value));
9748 }
9749 return collected;
9750 case "MultiSelectHash":
9751 if (value === null) {
9752 return null;
9753 }
9754 collected = {};
9755 var child;
9756 for (i = 0; i < node.children.length; i++) {
9757 child = node.children[i];
9758 collected[child.name] = this.visit(child.value, value);
9759 }
9760 return collected;
9761 case "OrExpression":
9762 matched = this.visit(node.children[0], value);
9763 if (isFalse(matched)) {
9764 matched = this.visit(node.children[1], value);
9765 }
9766 return matched;
9767 case "AndExpression":
9768 first = this.visit(node.children[0], value);
9769
9770 if (isFalse(first) === true) {
9771 return first;
9772 }
9773 return this.visit(node.children[1], value);
9774 case "NotExpression":
9775 first = this.visit(node.children[0], value);
9776 return isFalse(first);
9777 case "Literal":
9778 return node.value;
9779 case TOK_PIPE:
9780 left = this.visit(node.children[0], value);
9781 return this.visit(node.children[1], left);
9782 case TOK_CURRENT:
9783 return value;
9784 case "Function":
9785 var resolvedArgs = [];
9786 for (i = 0; i < node.children.length; i++) {
9787 resolvedArgs.push(this.visit(node.children[i], value));
9788 }
9789 return this.runtime.callFunction(node.name, resolvedArgs);
9790 case "ExpressionReference":
9791 var refNode = node.children[0];
9792 // Tag the node with a specific attribute so the type
9793 // checker verify the type.
9794 refNode.jmespathType = TOK_EXPREF;
9795 return refNode;
9796 default:
9797 throw new Error("Unknown node type: " + node.type);
9798 }
9799 },
9800
9801 computeSliceParams: function(arrayLength, sliceParams) {
9802 var start = sliceParams[0];
9803 var stop = sliceParams[1];
9804 var step = sliceParams[2];
9805 var computed = [null, null, null];
9806 if (step === null) {
9807 step = 1;
9808 } else if (step === 0) {
9809 var error = new Error("Invalid slice, step cannot be 0");
9810 error.name = "RuntimeError";
9811 throw error;
9812 }
9813 var stepValueNegative = step < 0 ? true : false;
9814
9815 if (start === null) {
9816 start = stepValueNegative ? arrayLength - 1 : 0;
9817 } else {
9818 start = this.capSliceRange(arrayLength, start, step);
9819 }
9820
9821 if (stop === null) {
9822 stop = stepValueNegative ? -1 : arrayLength;
9823 } else {
9824 stop = this.capSliceRange(arrayLength, stop, step);
9825 }
9826 computed[0] = start;
9827 computed[1] = stop;
9828 computed[2] = step;
9829 return computed;
9830 },
9831
9832 capSliceRange: function(arrayLength, actualValue, step) {
9833 if (actualValue < 0) {
9834 actualValue += arrayLength;
9835 if (actualValue < 0) {
9836 actualValue = step < 0 ? -1 : 0;
9837 }
9838 } else if (actualValue >= arrayLength) {
9839 actualValue = step < 0 ? arrayLength - 1 : arrayLength;
9840 }
9841 return actualValue;
9842 }
9843
9844 };
9845
9846 function Runtime(interpreter) {
9847 this._interpreter = interpreter;
9848 this.functionTable = {
9849 // name: [function, <signature>]
9850 // The <signature> can be:
9851 //
9852 // {
9853 // args: [[type1, type2], [type1, type2]],
9854 // variadic: true|false
9855 // }
9856 //
9857 // Each arg in the arg list is a list of valid types
9858 // (if the function is overloaded and supports multiple
9859 // types. If the type is "any" then no type checking
9860 // occurs on the argument. Variadic is optional
9861 // and if not provided is assumed to be false.
9862 abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]},
9863 avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
9864 ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]},
9865 contains: {
9866 _func: this._functionContains,
9867 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]},
9868 {types: [TYPE_ANY]}]},
9869 "ends_with": {
9870 _func: this._functionEndsWith,
9871 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
9872 floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]},
9873 length: {
9874 _func: this._functionLength,
9875 _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]},
9876 map: {
9877 _func: this._functionMap,
9878 _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]},
9879 max: {
9880 _func: this._functionMax,
9881 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
9882 "merge": {
9883 _func: this._functionMerge,
9884 _signature: [{types: [TYPE_OBJECT], variadic: true}]
9885 },
9886 "max_by": {
9887 _func: this._functionMaxBy,
9888 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9889 },
9890 sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]},
9891 "starts_with": {
9892 _func: this._functionStartsWith,
9893 _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]},
9894 min: {
9895 _func: this._functionMin,
9896 _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]},
9897 "min_by": {
9898 _func: this._functionMinBy,
9899 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9900 },
9901 type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]},
9902 keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]},
9903 values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]},
9904 sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]},
9905 "sort_by": {
9906 _func: this._functionSortBy,
9907 _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}]
9908 },
9909 join: {
9910 _func: this._functionJoin,
9911 _signature: [
9912 {types: [TYPE_STRING]},
9913 {types: [TYPE_ARRAY_STRING]}
9914 ]
9915 },
9916 reverse: {
9917 _func: this._functionReverse,
9918 _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]},
9919 "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]},
9920 "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]},
9921 "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]},
9922 "not_null": {
9923 _func: this._functionNotNull,
9924 _signature: [{types: [TYPE_ANY], variadic: true}]
9925 }
9926 };
9927 }
9928
9929 Runtime.prototype = {
9930 callFunction: function(name, resolvedArgs) {
9931 var functionEntry = this.functionTable[name];
9932 if (functionEntry === undefined) {
9933 throw new Error("Unknown function: " + name + "()");
9934 }
9935 this._validateArgs(name, resolvedArgs, functionEntry._signature);
9936 return functionEntry._func.call(this, resolvedArgs);
9937 },
9938
9939 _validateArgs: function(name, args, signature) {
9940 // Validating the args requires validating
9941 // the correct arity and the correct type of each arg.
9942 // If the last argument is declared as variadic, then we need
9943 // a minimum number of args to be required. Otherwise it has to
9944 // be an exact amount.
9945 var pluralized;
9946 if (signature[signature.length - 1].variadic) {
9947 if (args.length < signature.length) {
9948 pluralized = signature.length === 1 ? " argument" : " arguments";
9949 throw new Error("ArgumentError: " + name + "() " +
9950 "takes at least" + signature.length + pluralized +
9951 " but received " + args.length);
9952 }
9953 } else if (args.length !== signature.length) {
9954 pluralized = signature.length === 1 ? " argument" : " arguments";
9955 throw new Error("ArgumentError: " + name + "() " +
9956 "takes " + signature.length + pluralized +
9957 " but received " + args.length);
9958 }
9959 var currentSpec;
9960 var actualType;
9961 var typeMatched;
9962 for (var i = 0; i < signature.length; i++) {
9963 typeMatched = false;
9964 currentSpec = signature[i].types;
9965 actualType = this._getTypeName(args[i]);
9966 for (var j = 0; j < currentSpec.length; j++) {
9967 if (this._typeMatches(actualType, currentSpec[j], args[i])) {
9968 typeMatched = true;
9969 break;
9970 }
9971 }
9972 if (!typeMatched) {
9973 throw new Error("TypeError: " + name + "() " +
9974 "expected argument " + (i + 1) +
9975 " to be type " + currentSpec +
9976 " but received type " + actualType +
9977 " instead.");
9978 }
9979 }
9980 },
9981
9982 _typeMatches: function(actual, expected, argValue) {
9983 if (expected === TYPE_ANY) {
9984 return true;
9985 }
9986 if (expected === TYPE_ARRAY_STRING ||
9987 expected === TYPE_ARRAY_NUMBER ||
9988 expected === TYPE_ARRAY) {
9989 // The expected type can either just be array,
9990 // or it can require a specific subtype (array of numbers).
9991 //
9992 // The simplest case is if "array" with no subtype is specified.
9993 if (expected === TYPE_ARRAY) {
9994 return actual === TYPE_ARRAY;
9995 } else if (actual === TYPE_ARRAY) {
9996 // Otherwise we need to check subtypes.
9997 // I think this has potential to be improved.
9998 var subtype;
9999 if (expected === TYPE_ARRAY_NUMBER) {
10000 subtype = TYPE_NUMBER;
10001 } else if (expected === TYPE_ARRAY_STRING) {
10002 subtype = TYPE_STRING;
10003 }
10004 for (var i = 0; i < argValue.length; i++) {
10005 if (!this._typeMatches(
10006 this._getTypeName(argValue[i]), subtype,
10007 argValue[i])) {
10008 return false;
10009 }
10010 }
10011 return true;
10012 }
10013 } else {
10014 return actual === expected;
10015 }
10016 },
10017 _getTypeName: function(obj) {
10018 switch (Object.prototype.toString.call(obj)) {
10019 case "[object String]":
10020 return TYPE_STRING;
10021 case "[object Number]":
10022 return TYPE_NUMBER;
10023 case "[object Array]":
10024 return TYPE_ARRAY;
10025 case "[object Boolean]":
10026 return TYPE_BOOLEAN;
10027 case "[object Null]":
10028 return TYPE_NULL;
10029 case "[object Object]":
10030 // Check if it's an expref. If it has, it's been
10031 // tagged with a jmespathType attr of 'Expref';
10032 if (obj.jmespathType === TOK_EXPREF) {
10033 return TYPE_EXPREF;
10034 } else {
10035 return TYPE_OBJECT;
10036 }
10037 }
10038 },
10039
10040 _functionStartsWith: function(resolvedArgs) {
10041 return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0;
10042 },
10043
10044 _functionEndsWith: function(resolvedArgs) {
10045 var searchStr = resolvedArgs[0];
10046 var suffix = resolvedArgs[1];
10047 return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1;
10048 },
10049
10050 _functionReverse: function(resolvedArgs) {
10051 var typeName = this._getTypeName(resolvedArgs[0]);
10052 if (typeName === TYPE_STRING) {
10053 var originalStr = resolvedArgs[0];
10054 var reversedStr = "";
10055 for (var i = originalStr.length - 1; i >= 0; i--) {
10056 reversedStr += originalStr[i];
10057 }
10058 return reversedStr;
10059 } else {
10060 var reversedArray = resolvedArgs[0].slice(0);
10061 reversedArray.reverse();
10062 return reversedArray;
10063 }
10064 },
10065
10066 _functionAbs: function(resolvedArgs) {
10067 return Math.abs(resolvedArgs[0]);
10068 },
10069
10070 _functionCeil: function(resolvedArgs) {
10071 return Math.ceil(resolvedArgs[0]);
10072 },
10073
10074 _functionAvg: function(resolvedArgs) {
10075 var sum = 0;
10076 var inputArray = resolvedArgs[0];
10077 for (var i = 0; i < inputArray.length; i++) {
10078 sum += inputArray[i];
10079 }
10080 return sum / inputArray.length;
10081 },
10082
10083 _functionContains: function(resolvedArgs) {
10084 return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0;
10085 },
10086
10087 _functionFloor: function(resolvedArgs) {
10088 return Math.floor(resolvedArgs[0]);
10089 },
10090
10091 _functionLength: function(resolvedArgs) {
10092 if (!isObject(resolvedArgs[0])) {
10093 return resolvedArgs[0].length;
10094 } else {
10095 // As far as I can tell, there's no way to get the length
10096 // of an object without O(n) iteration through the object.
10097 return Object.keys(resolvedArgs[0]).length;
10098 }
10099 },
10100
10101 _functionMap: function(resolvedArgs) {
10102 var mapped = [];
10103 var interpreter = this._interpreter;
10104 var exprefNode = resolvedArgs[0];
10105 var elements = resolvedArgs[1];
10106 for (var i = 0; i < elements.length; i++) {
10107 mapped.push(interpreter.visit(exprefNode, elements[i]));
10108 }
10109 return mapped;
10110 },
10111
10112 _functionMerge: function(resolvedArgs) {
10113 var merged = {};
10114 for (var i = 0; i < resolvedArgs.length; i++) {
10115 var current = resolvedArgs[i];
10116 for (var key in current) {
10117 merged[key] = current[key];
10118 }
10119 }
10120 return merged;
10121 },
10122
10123 _functionMax: function(resolvedArgs) {
10124 if (resolvedArgs[0].length > 0) {
10125 var typeName = this._getTypeName(resolvedArgs[0][0]);
10126 if (typeName === TYPE_NUMBER) {
10127 return Math.max.apply(Math, resolvedArgs[0]);
10128 } else {
10129 var elements = resolvedArgs[0];
10130 var maxElement = elements[0];
10131 for (var i = 1; i < elements.length; i++) {
10132 if (maxElement.localeCompare(elements[i]) < 0) {
10133 maxElement = elements[i];
10134 }
10135 }
10136 return maxElement;
10137 }
10138 } else {
10139 return null;
10140 }
10141 },
10142
10143 _functionMin: function(resolvedArgs) {
10144 if (resolvedArgs[0].length > 0) {
10145 var typeName = this._getTypeName(resolvedArgs[0][0]);
10146 if (typeName === TYPE_NUMBER) {
10147 return Math.min.apply(Math, resolvedArgs[0]);
10148 } else {
10149 var elements = resolvedArgs[0];
10150 var minElement = elements[0];
10151 for (var i = 1; i < elements.length; i++) {
10152 if (elements[i].localeCompare(minElement) < 0) {
10153 minElement = elements[i];
10154 }
10155 }
10156 return minElement;
10157 }
10158 } else {
10159 return null;
10160 }
10161 },
10162
10163 _functionSum: function(resolvedArgs) {
10164 var sum = 0;
10165 var listToSum = resolvedArgs[0];
10166 for (var i = 0; i < listToSum.length; i++) {
10167 sum += listToSum[i];
10168 }
10169 return sum;
10170 },
10171
10172 _functionType: function(resolvedArgs) {
10173 switch (this._getTypeName(resolvedArgs[0])) {
10174 case TYPE_NUMBER:
10175 return "number";
10176 case TYPE_STRING:
10177 return "string";
10178 case TYPE_ARRAY:
10179 return "array";
10180 case TYPE_OBJECT:
10181 return "object";
10182 case TYPE_BOOLEAN:
10183 return "boolean";
10184 case TYPE_EXPREF:
10185 return "expref";
10186 case TYPE_NULL:
10187 return "null";
10188 }
10189 },
10190
10191 _functionKeys: function(resolvedArgs) {
10192 return Object.keys(resolvedArgs[0]);
10193 },
10194
10195 _functionValues: function(resolvedArgs) {
10196 var obj = resolvedArgs[0];
10197 var keys = Object.keys(obj);
10198 var values = [];
10199 for (var i = 0; i < keys.length; i++) {
10200 values.push(obj[keys[i]]);
10201 }
10202 return values;
10203 },
10204
10205 _functionJoin: function(resolvedArgs) {
10206 var joinChar = resolvedArgs[0];
10207 var listJoin = resolvedArgs[1];
10208 return listJoin.join(joinChar);
10209 },
10210
10211 _functionToArray: function(resolvedArgs) {
10212 if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) {
10213 return resolvedArgs[0];
10214 } else {
10215 return [resolvedArgs[0]];
10216 }
10217 },
10218
10219 _functionToString: function(resolvedArgs) {
10220 if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) {
10221 return resolvedArgs[0];
10222 } else {
10223 return JSON.stringify(resolvedArgs[0]);
10224 }
10225 },
10226
10227 _functionToNumber: function(resolvedArgs) {
10228 var typeName = this._getTypeName(resolvedArgs[0]);
10229 var convertedValue;
10230 if (typeName === TYPE_NUMBER) {
10231 return resolvedArgs[0];
10232 } else if (typeName === TYPE_STRING) {
10233 convertedValue = +resolvedArgs[0];
10234 if (!isNaN(convertedValue)) {
10235 return convertedValue;
10236 }
10237 }
10238 return null;
10239 },
10240
10241 _functionNotNull: function(resolvedArgs) {
10242 for (var i = 0; i < resolvedArgs.length; i++) {
10243 if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) {
10244 return resolvedArgs[i];
10245 }
10246 }
10247 return null;
10248 },
10249
10250 _functionSort: function(resolvedArgs) {
10251 var sortedArray = resolvedArgs[0].slice(0);
10252 sortedArray.sort();
10253 return sortedArray;
10254 },
10255
10256 _functionSortBy: function(resolvedArgs) {
10257 var sortedArray = resolvedArgs[0].slice(0);
10258 if (sortedArray.length === 0) {
10259 return sortedArray;
10260 }
10261 var interpreter = this._interpreter;
10262 var exprefNode = resolvedArgs[1];
10263 var requiredType = this._getTypeName(
10264 interpreter.visit(exprefNode, sortedArray[0]));
10265 if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) {
10266 throw new Error("TypeError");
10267 }
10268 var that = this;
10269 // In order to get a stable sort out of an unstable
10270 // sort algorithm, we decorate/sort/undecorate (DSU)
10271 // by creating a new list of [index, element] pairs.
10272 // In the cmp function, if the evaluated elements are
10273 // equal, then the index will be used as the tiebreaker.
10274 // After the decorated list has been sorted, it will be
10275 // undecorated to extract the original elements.
10276 var decorated = [];
10277 for (var i = 0; i < sortedArray.length; i++) {
10278 decorated.push([i, sortedArray[i]]);
10279 }
10280 decorated.sort(function(a, b) {
10281 var exprA = interpreter.visit(exprefNode, a[1]);
10282 var exprB = interpreter.visit(exprefNode, b[1]);
10283 if (that._getTypeName(exprA) !== requiredType) {
10284 throw new Error(
10285 "TypeError: expected " + requiredType + ", received " +
10286 that._getTypeName(exprA));
10287 } else if (that._getTypeName(exprB) !== requiredType) {
10288 throw new Error(
10289 "TypeError: expected " + requiredType + ", received " +
10290 that._getTypeName(exprB));
10291 }
10292 if (exprA > exprB) {
10293 return 1;
10294 } else if (exprA < exprB) {
10295 return -1;
10296 } else {
10297 // If they're equal compare the items by their
10298 // order to maintain relative order of equal keys
10299 // (i.e. to get a stable sort).
10300 return a[0] - b[0];
10301 }
10302 });
10303 // Undecorate: extract out the original list elements.
10304 for (var j = 0; j < decorated.length; j++) {
10305 sortedArray[j] = decorated[j][1];
10306 }
10307 return sortedArray;
10308 },
10309
10310 _functionMaxBy: function(resolvedArgs) {
10311 var exprefNode = resolvedArgs[1];
10312 var resolvedArray = resolvedArgs[0];
10313 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10314 var maxNumber = -Infinity;
10315 var maxRecord;
10316 var current;
10317 for (var i = 0; i < resolvedArray.length; i++) {
10318 current = keyFunction(resolvedArray[i]);
10319 if (current > maxNumber) {
10320 maxNumber = current;
10321 maxRecord = resolvedArray[i];
10322 }
10323 }
10324 return maxRecord;
10325 },
10326
10327 _functionMinBy: function(resolvedArgs) {
10328 var exprefNode = resolvedArgs[1];
10329 var resolvedArray = resolvedArgs[0];
10330 var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]);
10331 var minNumber = Infinity;
10332 var minRecord;
10333 var current;
10334 for (var i = 0; i < resolvedArray.length; i++) {
10335 current = keyFunction(resolvedArray[i]);
10336 if (current < minNumber) {
10337 minNumber = current;
10338 minRecord = resolvedArray[i];
10339 }
10340 }
10341 return minRecord;
10342 },
10343
10344 createKeyFunction: function(exprefNode, allowedTypes) {
10345 var that = this;
10346 var interpreter = this._interpreter;
10347 var keyFunc = function(x) {
10348 var current = interpreter.visit(exprefNode, x);
10349 if (allowedTypes.indexOf(that._getTypeName(current)) < 0) {
10350 var msg = "TypeError: expected one of " + allowedTypes +
10351 ", received " + that._getTypeName(current);
10352 throw new Error(msg);
10353 }
10354 return current;
10355 };
10356 return keyFunc;
10357 }
10358
10359 };
10360
10361 function compile(stream) {
10362 var parser = new Parser();
10363 var ast = parser.parse(stream);
10364 return ast;
10365 }
10366
10367 function tokenize(stream) {
10368 var lexer = new Lexer();
10369 return lexer.tokenize(stream);
10370 }
10371
10372 function search(data, expression) {
10373 var parser = new Parser();
10374 // This needs to be improved. Both the interpreter and runtime depend on
10375 // each other. The runtime needs the interpreter to support exprefs.
10376 // There's likely a clean way to avoid the cyclic dependency.
10377 var runtime = new Runtime();
10378 var interpreter = new TreeInterpreter(runtime);
10379 runtime._interpreter = interpreter;
10380 var node = parser.parse(expression);
10381 return interpreter.search(node, data);
10382 }
10383
10384 exports.tokenize = tokenize;
10385 exports.compile = compile;
10386 exports.search = search;
10387 exports.strictDeepEqual = strictDeepEqual;
10388 })( false ? this.jmespath = {} : exports);
10389
10390
10391/***/ }),
10392/* 52 */
10393/***/ (function(module, exports, __webpack_require__) {
10394
10395 var AWS = __webpack_require__(1);
10396 var inherit = AWS.util.inherit;
10397 var jmespath = __webpack_require__(51);
10398
10399 /**
10400 * This class encapsulates the response information
10401 * from a service request operation sent through {AWS.Request}.
10402 * The response object has two main properties for getting information
10403 * back from a request:
10404 *
10405 * ## The `data` property
10406 *
10407 * The `response.data` property contains the serialized object data
10408 * retrieved from the service request. For instance, for an
10409 * Amazon DynamoDB `listTables` method call, the response data might
10410 * look like:
10411 *
10412 * ```
10413 * > resp.data
10414 * { TableNames:
10415 * [ 'table1', 'table2', ... ] }
10416 * ```
10417 *
10418 * The `data` property can be null if an error occurs (see below).
10419 *
10420 * ## The `error` property
10421 *
10422 * In the event of a service error (or transfer error), the
10423 * `response.error` property will be filled with the given
10424 * error data in the form:
10425 *
10426 * ```
10427 * { code: 'SHORT_UNIQUE_ERROR_CODE',
10428 * message: 'Some human readable error message' }
10429 * ```
10430 *
10431 * In the case of an error, the `data` property will be `null`.
10432 * Note that if you handle events that can be in a failure state,
10433 * you should always check whether `response.error` is set
10434 * before attempting to access the `response.data` property.
10435 *
10436 * @!attribute data
10437 * @readonly
10438 * @!group Data Properties
10439 * @note Inside of a {AWS.Request~httpData} event, this
10440 * property contains a single raw packet instead of the
10441 * full de-serialized service response.
10442 * @return [Object] the de-serialized response data
10443 * from the service.
10444 *
10445 * @!attribute error
10446 * An structure containing information about a service
10447 * or networking error.
10448 * @readonly
10449 * @!group Data Properties
10450 * @note This attribute is only filled if a service or
10451 * networking error occurs.
10452 * @return [Error]
10453 * * code [String] a unique short code representing the
10454 * error that was emitted.
10455 * * message [String] a longer human readable error message
10456 * * retryable [Boolean] whether the error message is
10457 * retryable.
10458 * * statusCode [Numeric] in the case of a request that reached the service,
10459 * this value contains the response status code.
10460 * * time [Date] the date time object when the error occurred.
10461 * * hostname [String] set when a networking error occurs to easily
10462 * identify the endpoint of the request.
10463 * * region [String] set when a networking error occurs to easily
10464 * identify the region of the request.
10465 *
10466 * @!attribute requestId
10467 * @readonly
10468 * @!group Data Properties
10469 * @return [String] the unique request ID associated with the response.
10470 * Log this value when debugging requests for AWS support.
10471 *
10472 * @!attribute retryCount
10473 * @readonly
10474 * @!group Operation Properties
10475 * @return [Integer] the number of retries that were
10476 * attempted before the request was completed.
10477 *
10478 * @!attribute redirectCount
10479 * @readonly
10480 * @!group Operation Properties
10481 * @return [Integer] the number of redirects that were
10482 * followed before the request was completed.
10483 *
10484 * @!attribute httpResponse
10485 * @readonly
10486 * @!group HTTP Properties
10487 * @return [AWS.HttpResponse] the raw HTTP response object
10488 * containing the response headers and body information
10489 * from the server.
10490 *
10491 * @see AWS.Request
10492 */
10493 AWS.Response = inherit({
10494
10495 /**
10496 * @api private
10497 */
10498 constructor: function Response(request) {
10499 this.request = request;
10500 this.data = null;
10501 this.error = null;
10502 this.retryCount = 0;
10503 this.redirectCount = 0;
10504 this.httpResponse = new AWS.HttpResponse();
10505 if (request) {
10506 this.maxRetries = request.service.numRetries();
10507 this.maxRedirects = request.service.config.maxRedirects;
10508 }
10509 },
10510
10511 /**
10512 * Creates a new request for the next page of response data, calling the
10513 * callback with the page data if a callback is provided.
10514 *
10515 * @callback callback function(err, data)
10516 * Called when a page of data is returned from the next request.
10517 *
10518 * @param err [Error] an error object, if an error occurred in the request
10519 * @param data [Object] the next page of data, or null, if there are no
10520 * more pages left.
10521 * @return [AWS.Request] the request object for the next page of data
10522 * @return [null] if no callback is provided and there are no pages left
10523 * to retrieve.
10524 * @since v1.4.0
10525 */
10526 nextPage: function nextPage(callback) {
10527 var config;
10528 var service = this.request.service;
10529 var operation = this.request.operation;
10530 try {
10531 config = service.paginationConfig(operation, true);
10532 } catch (e) { this.error = e; }
10533
10534 if (!this.hasNextPage()) {
10535 if (callback) callback(this.error, null);
10536 else if (this.error) throw this.error;
10537 return null;
10538 }
10539
10540 var params = AWS.util.copy(this.request.params);
10541 if (!this.nextPageTokens) {
10542 return callback ? callback(null, null) : null;
10543 } else {
10544 var inputTokens = config.inputToken;
10545 if (typeof inputTokens === 'string') inputTokens = [inputTokens];
10546 for (var i = 0; i < inputTokens.length; i++) {
10547 params[inputTokens[i]] = this.nextPageTokens[i];
10548 }
10549 return service.makeRequest(this.request.operation, params, callback);
10550 }
10551 },
10552
10553 /**
10554 * @return [Boolean] whether more pages of data can be returned by further
10555 * requests
10556 * @since v1.4.0
10557 */
10558 hasNextPage: function hasNextPage() {
10559 this.cacheNextPageTokens();
10560 if (this.nextPageTokens) return true;
10561 if (this.nextPageTokens === undefined) return undefined;
10562 else return false;
10563 },
10564
10565 /**
10566 * @api private
10567 */
10568 cacheNextPageTokens: function cacheNextPageTokens() {
10569 if (Object.prototype.hasOwnProperty.call(this, 'nextPageTokens')) return this.nextPageTokens;
10570 this.nextPageTokens = undefined;
10571
10572 var config = this.request.service.paginationConfig(this.request.operation);
10573 if (!config) return this.nextPageTokens;
10574
10575 this.nextPageTokens = null;
10576 if (config.moreResults) {
10577 if (!jmespath.search(this.data, config.moreResults)) {
10578 return this.nextPageTokens;
10579 }
10580 }
10581
10582 var exprs = config.outputToken;
10583 if (typeof exprs === 'string') exprs = [exprs];
10584 AWS.util.arrayEach.call(this, exprs, function (expr) {
10585 var output = jmespath.search(this.data, expr);
10586 if (output) {
10587 this.nextPageTokens = this.nextPageTokens || [];
10588 this.nextPageTokens.push(output);
10589 }
10590 });
10591
10592 return this.nextPageTokens;
10593 }
10594
10595 });
10596
10597
10598/***/ }),
10599/* 53 */
10600/***/ (function(module, exports, __webpack_require__) {
10601
10602 /**
10603 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
10604 *
10605 * Licensed under the Apache License, Version 2.0 (the "License"). You
10606 * may not use this file except in compliance with the License. A copy of
10607 * the License is located at
10608 *
10609 * http://aws.amazon.com/apache2.0/
10610 *
10611 * or in the "license" file accompanying this file. This file is
10612 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
10613 * ANY KIND, either express or implied. See the License for the specific
10614 * language governing permissions and limitations under the License.
10615 */
10616
10617 var AWS = __webpack_require__(1);
10618 var inherit = AWS.util.inherit;
10619 var jmespath = __webpack_require__(51);
10620
10621 /**
10622 * @api private
10623 */
10624 function CHECK_ACCEPTORS(resp) {
10625 var waiter = resp.request._waiter;
10626 var acceptors = waiter.config.acceptors;
10627 var acceptorMatched = false;
10628 var state = 'retry';
10629
10630 acceptors.forEach(function(acceptor) {
10631 if (!acceptorMatched) {
10632 var matcher = waiter.matchers[acceptor.matcher];
10633 if (matcher && matcher(resp, acceptor.expected, acceptor.argument)) {
10634 acceptorMatched = true;
10635 state = acceptor.state;
10636 }
10637 }
10638 });
10639
10640 if (!acceptorMatched && resp.error) state = 'failure';
10641
10642 if (state === 'success') {
10643 waiter.setSuccess(resp);
10644 } else {
10645 waiter.setError(resp, state === 'retry');
10646 }
10647 }
10648
10649 /**
10650 * @api private
10651 */
10652 AWS.ResourceWaiter = inherit({
10653 /**
10654 * Waits for a given state on a service object
10655 * @param service [Service] the service object to wait on
10656 * @param state [String] the state (defined in waiter configuration) to wait
10657 * for.
10658 * @example Create a waiter for running EC2 instances
10659 * var ec2 = new AWS.EC2;
10660 * var waiter = new AWS.ResourceWaiter(ec2, 'instanceRunning');
10661 */
10662 constructor: function constructor(service, state) {
10663 this.service = service;
10664 this.state = state;
10665 this.loadWaiterConfig(this.state);
10666 },
10667
10668 service: null,
10669
10670 state: null,
10671
10672 config: null,
10673
10674 matchers: {
10675 path: function(resp, expected, argument) {
10676 try {
10677 var result = jmespath.search(resp.data, argument);
10678 } catch (err) {
10679 return false;
10680 }
10681
10682 return jmespath.strictDeepEqual(result,expected);
10683 },
10684
10685 pathAll: function(resp, expected, argument) {
10686 try {
10687 var results = jmespath.search(resp.data, argument);
10688 } catch (err) {
10689 return false;
10690 }
10691
10692 if (!Array.isArray(results)) results = [results];
10693 var numResults = results.length;
10694 if (!numResults) return false;
10695 for (var ind = 0 ; ind < numResults; ind++) {
10696 if (!jmespath.strictDeepEqual(results[ind], expected)) {
10697 return false;
10698 }
10699 }
10700 return true;
10701 },
10702
10703 pathAny: function(resp, expected, argument) {
10704 try {
10705 var results = jmespath.search(resp.data, argument);
10706 } catch (err) {
10707 return false;
10708 }
10709
10710 if (!Array.isArray(results)) results = [results];
10711 var numResults = results.length;
10712 for (var ind = 0 ; ind < numResults; ind++) {
10713 if (jmespath.strictDeepEqual(results[ind], expected)) {
10714 return true;
10715 }
10716 }
10717 return false;
10718 },
10719
10720 status: function(resp, expected) {
10721 var statusCode = resp.httpResponse.statusCode;
10722 return (typeof statusCode === 'number') && (statusCode === expected);
10723 },
10724
10725 error: function(resp, expected) {
10726 if (typeof expected === 'string' && resp.error) {
10727 return expected === resp.error.code;
10728 }
10729 // if expected is not string, can be boolean indicating presence of error
10730 return expected === !!resp.error;
10731 }
10732 },
10733
10734 listeners: new AWS.SequentialExecutor().addNamedListeners(function(add) {
10735 add('RETRY_CHECK', 'retry', function(resp) {
10736 var waiter = resp.request._waiter;
10737 if (resp.error && resp.error.code === 'ResourceNotReady') {
10738 resp.error.retryDelay = (waiter.config.delay || 0) * 1000;
10739 }
10740 });
10741
10742 add('CHECK_OUTPUT', 'extractData', CHECK_ACCEPTORS);
10743
10744 add('CHECK_ERROR', 'extractError', CHECK_ACCEPTORS);
10745 }),
10746
10747 /**
10748 * @return [AWS.Request]
10749 */
10750 wait: function wait(params, callback) {
10751 if (typeof params === 'function') {
10752 callback = params; params = undefined;
10753 }
10754
10755 if (params && params.$waiter) {
10756 params = AWS.util.copy(params);
10757 if (typeof params.$waiter.delay === 'number') {
10758 this.config.delay = params.$waiter.delay;
10759 }
10760 if (typeof params.$waiter.maxAttempts === 'number') {
10761 this.config.maxAttempts = params.$waiter.maxAttempts;
10762 }
10763 delete params.$waiter;
10764 }
10765
10766 var request = this.service.makeRequest(this.config.operation, params);
10767 request._waiter = this;
10768 request.response.maxRetries = this.config.maxAttempts;
10769 request.addListeners(this.listeners);
10770
10771 if (callback) request.send(callback);
10772 return request;
10773 },
10774
10775 setSuccess: function setSuccess(resp) {
10776 resp.error = null;
10777 resp.data = resp.data || {};
10778 resp.request.removeAllListeners('extractData');
10779 },
10780
10781 setError: function setError(resp, retryable) {
10782 resp.data = null;
10783 resp.error = AWS.util.error(resp.error || new Error(), {
10784 code: 'ResourceNotReady',
10785 message: 'Resource is not in the state ' + this.state,
10786 retryable: retryable
10787 });
10788 },
10789
10790 /**
10791 * Loads waiter configuration from API configuration
10792 *
10793 * @api private
10794 */
10795 loadWaiterConfig: function loadWaiterConfig(state) {
10796 if (!this.service.api.waiters[state]) {
10797 throw new AWS.util.error(new Error(), {
10798 code: 'StateNotFoundError',
10799 message: 'State ' + state + ' not found.'
10800 });
10801 }
10802
10803 this.config = AWS.util.copy(this.service.api.waiters[state]);
10804 }
10805 });
10806
10807
10808/***/ }),
10809/* 54 */
10810/***/ (function(module, exports, __webpack_require__) {
10811
10812 var AWS = __webpack_require__(1);
10813
10814 var inherit = AWS.util.inherit;
10815
10816 /**
10817 * @api private
10818 */
10819 AWS.Signers.RequestSigner = inherit({
10820 constructor: function RequestSigner(request) {
10821 this.request = request;
10822 },
10823
10824 setServiceClientId: function setServiceClientId(id) {
10825 this.serviceClientId = id;
10826 },
10827
10828 getServiceClientId: function getServiceClientId() {
10829 return this.serviceClientId;
10830 }
10831 });
10832
10833 AWS.Signers.RequestSigner.getVersion = function getVersion(version) {
10834 switch (version) {
10835 case 'v2': return AWS.Signers.V2;
10836 case 'v3': return AWS.Signers.V3;
10837 case 's3v4': return AWS.Signers.V4;
10838 case 'v4': return AWS.Signers.V4;
10839 case 's3': return AWS.Signers.S3;
10840 case 'v3https': return AWS.Signers.V3Https;
10841 }
10842 throw new Error('Unknown signing version ' + version);
10843 };
10844
10845 __webpack_require__(55);
10846 __webpack_require__(56);
10847 __webpack_require__(57);
10848 __webpack_require__(58);
10849 __webpack_require__(60);
10850 __webpack_require__(61);
10851
10852
10853/***/ }),
10854/* 55 */
10855/***/ (function(module, exports, __webpack_require__) {
10856
10857 var AWS = __webpack_require__(1);
10858 var inherit = AWS.util.inherit;
10859
10860 /**
10861 * @api private
10862 */
10863 AWS.Signers.V2 = inherit(AWS.Signers.RequestSigner, {
10864 addAuthorization: function addAuthorization(credentials, date) {
10865
10866 if (!date) date = AWS.util.date.getDate();
10867
10868 var r = this.request;
10869
10870 r.params.Timestamp = AWS.util.date.iso8601(date);
10871 r.params.SignatureVersion = '2';
10872 r.params.SignatureMethod = 'HmacSHA256';
10873 r.params.AWSAccessKeyId = credentials.accessKeyId;
10874
10875 if (credentials.sessionToken) {
10876 r.params.SecurityToken = credentials.sessionToken;
10877 }
10878
10879 delete r.params.Signature; // delete old Signature for re-signing
10880 r.params.Signature = this.signature(credentials);
10881
10882 r.body = AWS.util.queryParamsToString(r.params);
10883 r.headers['Content-Length'] = r.body.length;
10884 },
10885
10886 signature: function signature(credentials) {
10887 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
10888 },
10889
10890 stringToSign: function stringToSign() {
10891 var parts = [];
10892 parts.push(this.request.method);
10893 parts.push(this.request.endpoint.host.toLowerCase());
10894 parts.push(this.request.pathname());
10895 parts.push(AWS.util.queryParamsToString(this.request.params));
10896 return parts.join('\n');
10897 }
10898
10899 });
10900
10901 /**
10902 * @api private
10903 */
10904 module.exports = AWS.Signers.V2;
10905
10906
10907/***/ }),
10908/* 56 */
10909/***/ (function(module, exports, __webpack_require__) {
10910
10911 var AWS = __webpack_require__(1);
10912 var inherit = AWS.util.inherit;
10913
10914 /**
10915 * @api private
10916 */
10917 AWS.Signers.V3 = inherit(AWS.Signers.RequestSigner, {
10918 addAuthorization: function addAuthorization(credentials, date) {
10919
10920 var datetime = AWS.util.date.rfc822(date);
10921
10922 this.request.headers['X-Amz-Date'] = datetime;
10923
10924 if (credentials.sessionToken) {
10925 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
10926 }
10927
10928 this.request.headers['X-Amzn-Authorization'] =
10929 this.authorization(credentials, datetime);
10930
10931 },
10932
10933 authorization: function authorization(credentials) {
10934 return 'AWS3 ' +
10935 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
10936 'Algorithm=HmacSHA256,' +
10937 'SignedHeaders=' + this.signedHeaders() + ',' +
10938 'Signature=' + this.signature(credentials);
10939 },
10940
10941 signedHeaders: function signedHeaders() {
10942 var headers = [];
10943 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
10944 headers.push(h.toLowerCase());
10945 });
10946 return headers.sort().join(';');
10947 },
10948
10949 canonicalHeaders: function canonicalHeaders() {
10950 var headers = this.request.headers;
10951 var parts = [];
10952 AWS.util.arrayEach(this.headersToSign(), function iterator(h) {
10953 parts.push(h.toLowerCase().trim() + ':' + String(headers[h]).trim());
10954 });
10955 return parts.sort().join('\n') + '\n';
10956 },
10957
10958 headersToSign: function headersToSign() {
10959 var headers = [];
10960 AWS.util.each(this.request.headers, function iterator(k) {
10961 if (k === 'Host' || k === 'Content-Encoding' || k.match(/^X-Amz/i)) {
10962 headers.push(k);
10963 }
10964 });
10965 return headers;
10966 },
10967
10968 signature: function signature(credentials) {
10969 return AWS.util.crypto.hmac(credentials.secretAccessKey, this.stringToSign(), 'base64');
10970 },
10971
10972 stringToSign: function stringToSign() {
10973 var parts = [];
10974 parts.push(this.request.method);
10975 parts.push('/');
10976 parts.push('');
10977 parts.push(this.canonicalHeaders());
10978 parts.push(this.request.body);
10979 return AWS.util.crypto.sha256(parts.join('\n'));
10980 }
10981
10982 });
10983
10984 /**
10985 * @api private
10986 */
10987 module.exports = AWS.Signers.V3;
10988
10989
10990/***/ }),
10991/* 57 */
10992/***/ (function(module, exports, __webpack_require__) {
10993
10994 var AWS = __webpack_require__(1);
10995 var inherit = AWS.util.inherit;
10996
10997 __webpack_require__(56);
10998
10999 /**
11000 * @api private
11001 */
11002 AWS.Signers.V3Https = inherit(AWS.Signers.V3, {
11003 authorization: function authorization(credentials) {
11004 return 'AWS3-HTTPS ' +
11005 'AWSAccessKeyId=' + credentials.accessKeyId + ',' +
11006 'Algorithm=HmacSHA256,' +
11007 'Signature=' + this.signature(credentials);
11008 },
11009
11010 stringToSign: function stringToSign() {
11011 return this.request.headers['X-Amz-Date'];
11012 }
11013 });
11014
11015 /**
11016 * @api private
11017 */
11018 module.exports = AWS.Signers.V3Https;
11019
11020
11021/***/ }),
11022/* 58 */
11023/***/ (function(module, exports, __webpack_require__) {
11024
11025 var AWS = __webpack_require__(1);
11026 var v4Credentials = __webpack_require__(59);
11027 var inherit = AWS.util.inherit;
11028
11029 /**
11030 * @api private
11031 */
11032 var expiresHeader = 'presigned-expires';
11033
11034 /**
11035 * @api private
11036 */
11037 AWS.Signers.V4 = inherit(AWS.Signers.RequestSigner, {
11038 constructor: function V4(request, serviceName, options) {
11039 AWS.Signers.RequestSigner.call(this, request);
11040 this.serviceName = serviceName;
11041 options = options || {};
11042 this.signatureCache = typeof options.signatureCache === 'boolean' ? options.signatureCache : true;
11043 this.operation = options.operation;
11044 this.signatureVersion = options.signatureVersion;
11045 },
11046
11047 algorithm: 'AWS4-HMAC-SHA256',
11048
11049 addAuthorization: function addAuthorization(credentials, date) {
11050 var datetime = AWS.util.date.iso8601(date).replace(/[:\-]|\.\d{3}/g, '');
11051
11052 if (this.isPresigned()) {
11053 this.updateForPresigned(credentials, datetime);
11054 } else {
11055 this.addHeaders(credentials, datetime);
11056 }
11057
11058 this.request.headers['Authorization'] =
11059 this.authorization(credentials, datetime);
11060 },
11061
11062 addHeaders: function addHeaders(credentials, datetime) {
11063 this.request.headers['X-Amz-Date'] = datetime;
11064 if (credentials.sessionToken) {
11065 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11066 }
11067 },
11068
11069 updateForPresigned: function updateForPresigned(credentials, datetime) {
11070 var credString = this.credentialString(datetime);
11071 var qs = {
11072 'X-Amz-Date': datetime,
11073 'X-Amz-Algorithm': this.algorithm,
11074 'X-Amz-Credential': credentials.accessKeyId + '/' + credString,
11075 'X-Amz-Expires': this.request.headers[expiresHeader],
11076 'X-Amz-SignedHeaders': this.signedHeaders()
11077 };
11078
11079 if (credentials.sessionToken) {
11080 qs['X-Amz-Security-Token'] = credentials.sessionToken;
11081 }
11082
11083 if (this.request.headers['Content-Type']) {
11084 qs['Content-Type'] = this.request.headers['Content-Type'];
11085 }
11086 if (this.request.headers['Content-MD5']) {
11087 qs['Content-MD5'] = this.request.headers['Content-MD5'];
11088 }
11089 if (this.request.headers['Cache-Control']) {
11090 qs['Cache-Control'] = this.request.headers['Cache-Control'];
11091 }
11092
11093 // need to pull in any other X-Amz-* headers
11094 AWS.util.each.call(this, this.request.headers, function(key, value) {
11095 if (key === expiresHeader) return;
11096 if (this.isSignableHeader(key)) {
11097 var lowerKey = key.toLowerCase();
11098 // Metadata should be normalized
11099 if (lowerKey.indexOf('x-amz-meta-') === 0) {
11100 qs[lowerKey] = value;
11101 } else if (lowerKey.indexOf('x-amz-') === 0) {
11102 qs[key] = value;
11103 }
11104 }
11105 });
11106
11107 var sep = this.request.path.indexOf('?') >= 0 ? '&' : '?';
11108 this.request.path += sep + AWS.util.queryParamsToString(qs);
11109 },
11110
11111 authorization: function authorization(credentials, datetime) {
11112 var parts = [];
11113 var credString = this.credentialString(datetime);
11114 parts.push(this.algorithm + ' Credential=' +
11115 credentials.accessKeyId + '/' + credString);
11116 parts.push('SignedHeaders=' + this.signedHeaders());
11117 parts.push('Signature=' + this.signature(credentials, datetime));
11118 return parts.join(', ');
11119 },
11120
11121 signature: function signature(credentials, datetime) {
11122 var signingKey = v4Credentials.getSigningKey(
11123 credentials,
11124 datetime.substr(0, 8),
11125 this.request.region,
11126 this.serviceName,
11127 this.signatureCache
11128 );
11129 return AWS.util.crypto.hmac(signingKey, this.stringToSign(datetime), 'hex');
11130 },
11131
11132 stringToSign: function stringToSign(datetime) {
11133 var parts = [];
11134 parts.push('AWS4-HMAC-SHA256');
11135 parts.push(datetime);
11136 parts.push(this.credentialString(datetime));
11137 parts.push(this.hexEncodedHash(this.canonicalString()));
11138 return parts.join('\n');
11139 },
11140
11141 canonicalString: function canonicalString() {
11142 var parts = [], pathname = this.request.pathname();
11143 if (this.serviceName !== 's3' && this.signatureVersion !== 's3v4') pathname = AWS.util.uriEscapePath(pathname);
11144
11145 parts.push(this.request.method);
11146 parts.push(pathname);
11147 parts.push(this.request.search());
11148 parts.push(this.canonicalHeaders() + '\n');
11149 parts.push(this.signedHeaders());
11150 parts.push(this.hexEncodedBodyHash());
11151 return parts.join('\n');
11152 },
11153
11154 canonicalHeaders: function canonicalHeaders() {
11155 var headers = [];
11156 AWS.util.each.call(this, this.request.headers, function (key, item) {
11157 headers.push([key, item]);
11158 });
11159 headers.sort(function (a, b) {
11160 return a[0].toLowerCase() < b[0].toLowerCase() ? -1 : 1;
11161 });
11162 var parts = [];
11163 AWS.util.arrayEach.call(this, headers, function (item) {
11164 var key = item[0].toLowerCase();
11165 if (this.isSignableHeader(key)) {
11166 var value = item[1];
11167 if (typeof value === 'undefined' || value === null || typeof value.toString !== 'function') {
11168 throw AWS.util.error(new Error('Header ' + key + ' contains invalid value'), {
11169 code: 'InvalidHeader'
11170 });
11171 }
11172 parts.push(key + ':' +
11173 this.canonicalHeaderValues(value.toString()));
11174 }
11175 });
11176 return parts.join('\n');
11177 },
11178
11179 canonicalHeaderValues: function canonicalHeaderValues(values) {
11180 return values.replace(/\s+/g, ' ').replace(/^\s+|\s+$/g, '');
11181 },
11182
11183 signedHeaders: function signedHeaders() {
11184 var keys = [];
11185 AWS.util.each.call(this, this.request.headers, function (key) {
11186 key = key.toLowerCase();
11187 if (this.isSignableHeader(key)) keys.push(key);
11188 });
11189 return keys.sort().join(';');
11190 },
11191
11192 credentialString: function credentialString(datetime) {
11193 return v4Credentials.createScope(
11194 datetime.substr(0, 8),
11195 this.request.region,
11196 this.serviceName
11197 );
11198 },
11199
11200 hexEncodedHash: function hash(string) {
11201 return AWS.util.crypto.sha256(string, 'hex');
11202 },
11203
11204 hexEncodedBodyHash: function hexEncodedBodyHash() {
11205 var request = this.request;
11206 if (this.isPresigned() && this.serviceName === 's3' && !request.body) {
11207 return 'UNSIGNED-PAYLOAD';
11208 } else if (request.headers['X-Amz-Content-Sha256']) {
11209 return request.headers['X-Amz-Content-Sha256'];
11210 } else {
11211 return this.hexEncodedHash(this.request.body || '');
11212 }
11213 },
11214
11215 unsignableHeaders: [
11216 'authorization',
11217 'content-type',
11218 'content-length',
11219 'user-agent',
11220 expiresHeader,
11221 'expect',
11222 'x-amzn-trace-id'
11223 ],
11224
11225 isSignableHeader: function isSignableHeader(key) {
11226 if (key.toLowerCase().indexOf('x-amz-') === 0) return true;
11227 return this.unsignableHeaders.indexOf(key) < 0;
11228 },
11229
11230 isPresigned: function isPresigned() {
11231 return this.request.headers[expiresHeader] ? true : false;
11232 }
11233
11234 });
11235
11236 /**
11237 * @api private
11238 */
11239 module.exports = AWS.Signers.V4;
11240
11241
11242/***/ }),
11243/* 59 */
11244/***/ (function(module, exports, __webpack_require__) {
11245
11246 var AWS = __webpack_require__(1);
11247
11248 /**
11249 * @api private
11250 */
11251 var cachedSecret = {};
11252
11253 /**
11254 * @api private
11255 */
11256 var cacheQueue = [];
11257
11258 /**
11259 * @api private
11260 */
11261 var maxCacheEntries = 50;
11262
11263 /**
11264 * @api private
11265 */
11266 var v4Identifier = 'aws4_request';
11267
11268 /**
11269 * @api private
11270 */
11271 module.exports = {
11272 /**
11273 * @api private
11274 *
11275 * @param date [String]
11276 * @param region [String]
11277 * @param serviceName [String]
11278 * @return [String]
11279 */
11280 createScope: function createScope(date, region, serviceName) {
11281 return [
11282 date.substr(0, 8),
11283 region,
11284 serviceName,
11285 v4Identifier
11286 ].join('/');
11287 },
11288
11289 /**
11290 * @api private
11291 *
11292 * @param credentials [Credentials]
11293 * @param date [String]
11294 * @param region [String]
11295 * @param service [String]
11296 * @param shouldCache [Boolean]
11297 * @return [String]
11298 */
11299 getSigningKey: function getSigningKey(
11300 credentials,
11301 date,
11302 region,
11303 service,
11304 shouldCache
11305 ) {
11306 var credsIdentifier = AWS.util.crypto
11307 .hmac(credentials.secretAccessKey, credentials.accessKeyId, 'base64');
11308 var cacheKey = [credsIdentifier, date, region, service].join('_');
11309 shouldCache = shouldCache !== false;
11310 if (shouldCache && (cacheKey in cachedSecret)) {
11311 return cachedSecret[cacheKey];
11312 }
11313
11314 var kDate = AWS.util.crypto.hmac(
11315 'AWS4' + credentials.secretAccessKey,
11316 date,
11317 'buffer'
11318 );
11319 var kRegion = AWS.util.crypto.hmac(kDate, region, 'buffer');
11320 var kService = AWS.util.crypto.hmac(kRegion, service, 'buffer');
11321
11322 var signingKey = AWS.util.crypto.hmac(kService, v4Identifier, 'buffer');
11323 if (shouldCache) {
11324 cachedSecret[cacheKey] = signingKey;
11325 cacheQueue.push(cacheKey);
11326 if (cacheQueue.length > maxCacheEntries) {
11327 // remove the oldest entry (not the least recently used)
11328 delete cachedSecret[cacheQueue.shift()];
11329 }
11330 }
11331
11332 return signingKey;
11333 },
11334
11335 /**
11336 * @api private
11337 *
11338 * Empties the derived signing key cache. Made available for testing purposes
11339 * only.
11340 */
11341 emptyCache: function emptyCache() {
11342 cachedSecret = {};
11343 cacheQueue = [];
11344 }
11345 };
11346
11347
11348/***/ }),
11349/* 60 */
11350/***/ (function(module, exports, __webpack_require__) {
11351
11352 var AWS = __webpack_require__(1);
11353 var inherit = AWS.util.inherit;
11354
11355 /**
11356 * @api private
11357 */
11358 AWS.Signers.S3 = inherit(AWS.Signers.RequestSigner, {
11359 /**
11360 * When building the stringToSign, these sub resource params should be
11361 * part of the canonical resource string with their NON-decoded values
11362 */
11363 subResources: {
11364 'acl': 1,
11365 'accelerate': 1,
11366 'analytics': 1,
11367 'cors': 1,
11368 'lifecycle': 1,
11369 'delete': 1,
11370 'inventory': 1,
11371 'location': 1,
11372 'logging': 1,
11373 'metrics': 1,
11374 'notification': 1,
11375 'partNumber': 1,
11376 'policy': 1,
11377 'requestPayment': 1,
11378 'replication': 1,
11379 'restore': 1,
11380 'tagging': 1,
11381 'torrent': 1,
11382 'uploadId': 1,
11383 'uploads': 1,
11384 'versionId': 1,
11385 'versioning': 1,
11386 'versions': 1,
11387 'website': 1
11388 },
11389
11390 // when building the stringToSign, these querystring params should be
11391 // part of the canonical resource string with their NON-encoded values
11392 responseHeaders: {
11393 'response-content-type': 1,
11394 'response-content-language': 1,
11395 'response-expires': 1,
11396 'response-cache-control': 1,
11397 'response-content-disposition': 1,
11398 'response-content-encoding': 1
11399 },
11400
11401 addAuthorization: function addAuthorization(credentials, date) {
11402 if (!this.request.headers['presigned-expires']) {
11403 this.request.headers['X-Amz-Date'] = AWS.util.date.rfc822(date);
11404 }
11405
11406 if (credentials.sessionToken) {
11407 // presigned URLs require this header to be lowercased
11408 this.request.headers['x-amz-security-token'] = credentials.sessionToken;
11409 }
11410
11411 var signature = this.sign(credentials.secretAccessKey, this.stringToSign());
11412 var auth = 'AWS ' + credentials.accessKeyId + ':' + signature;
11413
11414 this.request.headers['Authorization'] = auth;
11415 },
11416
11417 stringToSign: function stringToSign() {
11418 var r = this.request;
11419
11420 var parts = [];
11421 parts.push(r.method);
11422 parts.push(r.headers['Content-MD5'] || '');
11423 parts.push(r.headers['Content-Type'] || '');
11424
11425 // This is the "Date" header, but we use X-Amz-Date.
11426 // The S3 signing mechanism requires us to pass an empty
11427 // string for this Date header regardless.
11428 parts.push(r.headers['presigned-expires'] || '');
11429
11430 var headers = this.canonicalizedAmzHeaders();
11431 if (headers) parts.push(headers);
11432 parts.push(this.canonicalizedResource());
11433
11434 return parts.join('\n');
11435
11436 },
11437
11438 canonicalizedAmzHeaders: function canonicalizedAmzHeaders() {
11439
11440 var amzHeaders = [];
11441
11442 AWS.util.each(this.request.headers, function (name) {
11443 if (name.match(/^x-amz-/i))
11444 amzHeaders.push(name);
11445 });
11446
11447 amzHeaders.sort(function (a, b) {
11448 return a.toLowerCase() < b.toLowerCase() ? -1 : 1;
11449 });
11450
11451 var parts = [];
11452 AWS.util.arrayEach.call(this, amzHeaders, function (name) {
11453 parts.push(name.toLowerCase() + ':' + String(this.request.headers[name]));
11454 });
11455
11456 return parts.join('\n');
11457
11458 },
11459
11460 canonicalizedResource: function canonicalizedResource() {
11461
11462 var r = this.request;
11463
11464 var parts = r.path.split('?');
11465 var path = parts[0];
11466 var querystring = parts[1];
11467
11468 var resource = '';
11469
11470 if (r.virtualHostedBucket)
11471 resource += '/' + r.virtualHostedBucket;
11472
11473 resource += path;
11474
11475 if (querystring) {
11476
11477 // collect a list of sub resources and query params that need to be signed
11478 var resources = [];
11479
11480 AWS.util.arrayEach.call(this, querystring.split('&'), function (param) {
11481 var name = param.split('=')[0];
11482 var value = param.split('=')[1];
11483 if (this.subResources[name] || this.responseHeaders[name]) {
11484 var subresource = { name: name };
11485 if (value !== undefined) {
11486 if (this.subResources[name]) {
11487 subresource.value = value;
11488 } else {
11489 subresource.value = decodeURIComponent(value);
11490 }
11491 }
11492 resources.push(subresource);
11493 }
11494 });
11495
11496 resources.sort(function (a, b) { return a.name < b.name ? -1 : 1; });
11497
11498 if (resources.length) {
11499
11500 querystring = [];
11501 AWS.util.arrayEach(resources, function (res) {
11502 if (res.value === undefined) {
11503 querystring.push(res.name);
11504 } else {
11505 querystring.push(res.name + '=' + res.value);
11506 }
11507 });
11508
11509 resource += '?' + querystring.join('&');
11510 }
11511
11512 }
11513
11514 return resource;
11515
11516 },
11517
11518 sign: function sign(secret, string) {
11519 return AWS.util.crypto.hmac(secret, string, 'base64', 'sha1');
11520 }
11521 });
11522
11523 /**
11524 * @api private
11525 */
11526 module.exports = AWS.Signers.S3;
11527
11528
11529/***/ }),
11530/* 61 */
11531/***/ (function(module, exports, __webpack_require__) {
11532
11533 var AWS = __webpack_require__(1);
11534 var inherit = AWS.util.inherit;
11535
11536 /**
11537 * @api private
11538 */
11539 var expiresHeader = 'presigned-expires';
11540
11541 /**
11542 * @api private
11543 */
11544 function signedUrlBuilder(request) {
11545 var expires = request.httpRequest.headers[expiresHeader];
11546 var signerClass = request.service.getSignerClass(request);
11547
11548 delete request.httpRequest.headers['User-Agent'];
11549 delete request.httpRequest.headers['X-Amz-User-Agent'];
11550
11551 if (signerClass === AWS.Signers.V4) {
11552 if (expires > 604800) { // one week expiry is invalid
11553 var message = 'Presigning does not support expiry time greater ' +
11554 'than a week with SigV4 signing.';
11555 throw AWS.util.error(new Error(), {
11556 code: 'InvalidExpiryTime', message: message, retryable: false
11557 });
11558 }
11559 request.httpRequest.headers[expiresHeader] = expires;
11560 } else if (signerClass === AWS.Signers.S3) {
11561 var now = request.service ? request.service.getSkewCorrectedDate() : AWS.util.date.getDate();
11562 request.httpRequest.headers[expiresHeader] = parseInt(
11563 AWS.util.date.unixTimestamp(now) + expires, 10).toString();
11564 } else {
11565 throw AWS.util.error(new Error(), {
11566 message: 'Presigning only supports S3 or SigV4 signing.',
11567 code: 'UnsupportedSigner', retryable: false
11568 });
11569 }
11570 }
11571
11572 /**
11573 * @api private
11574 */
11575 function signedUrlSigner(request) {
11576 var endpoint = request.httpRequest.endpoint;
11577 var parsedUrl = AWS.util.urlParse(request.httpRequest.path);
11578 var queryParams = {};
11579
11580 if (parsedUrl.search) {
11581 queryParams = AWS.util.queryStringParse(parsedUrl.search.substr(1));
11582 }
11583
11584 var auth = request.httpRequest.headers['Authorization'].split(' ');
11585 if (auth[0] === 'AWS') {
11586 auth = auth[1].split(':');
11587 queryParams['AWSAccessKeyId'] = auth[0];
11588 queryParams['Signature'] = auth[1];
11589
11590 AWS.util.each(request.httpRequest.headers, function (key, value) {
11591 if (key === expiresHeader) key = 'Expires';
11592 if (key.indexOf('x-amz-meta-') === 0) {
11593 // Delete existing, potentially not normalized key
11594 delete queryParams[key];
11595 key = key.toLowerCase();
11596 }
11597 queryParams[key] = value;
11598 });
11599 delete request.httpRequest.headers[expiresHeader];
11600 delete queryParams['Authorization'];
11601 delete queryParams['Host'];
11602 } else if (auth[0] === 'AWS4-HMAC-SHA256') { // SigV4 signing
11603 auth.shift();
11604 var rest = auth.join(' ');
11605 var signature = rest.match(/Signature=(.*?)(?:,|\s|\r?\n|$)/)[1];
11606 queryParams['X-Amz-Signature'] = signature;
11607 delete queryParams['Expires'];
11608 }
11609
11610 // build URL
11611 endpoint.pathname = parsedUrl.pathname;
11612 endpoint.search = AWS.util.queryParamsToString(queryParams);
11613 }
11614
11615 /**
11616 * @api private
11617 */
11618 AWS.Signers.Presign = inherit({
11619 /**
11620 * @api private
11621 */
11622 sign: function sign(request, expireTime, callback) {
11623 request.httpRequest.headers[expiresHeader] = expireTime || 3600;
11624 request.on('build', signedUrlBuilder);
11625 request.on('sign', signedUrlSigner);
11626 request.removeListener('afterBuild',
11627 AWS.EventListeners.Core.SET_CONTENT_LENGTH);
11628 request.removeListener('afterBuild',
11629 AWS.EventListeners.Core.COMPUTE_SHA256);
11630
11631 request.emit('beforePresign', [request]);
11632
11633 if (callback) {
11634 request.build(function() {
11635 if (this.response.error) callback(this.response.error);
11636 else {
11637 callback(null, AWS.util.urlFormat(request.httpRequest.endpoint));
11638 }
11639 });
11640 } else {
11641 request.build();
11642 if (request.response.error) throw request.response.error;
11643 return AWS.util.urlFormat(request.httpRequest.endpoint);
11644 }
11645 }
11646 });
11647
11648 /**
11649 * @api private
11650 */
11651 module.exports = AWS.Signers.Presign;
11652
11653
11654/***/ }),
11655/* 62 */
11656/***/ (function(module, exports, __webpack_require__) {
11657
11658 var AWS = __webpack_require__(1);
11659
11660 /**
11661 * @api private
11662 */
11663 AWS.ParamValidator = AWS.util.inherit({
11664 /**
11665 * Create a new validator object.
11666 *
11667 * @param validation [Boolean|map] whether input parameters should be
11668 * validated against the operation description before sending the
11669 * request. Pass a map to enable any of the following specific
11670 * validation features:
11671 *
11672 * * **min** [Boolean] &mdash; Validates that a value meets the min
11673 * constraint. This is enabled by default when paramValidation is set
11674 * to `true`.
11675 * * **max** [Boolean] &mdash; Validates that a value meets the max
11676 * constraint.
11677 * * **pattern** [Boolean] &mdash; Validates that a string value matches a
11678 * regular expression.
11679 * * **enum** [Boolean] &mdash; Validates that a string value matches one
11680 * of the allowable enum values.
11681 */
11682 constructor: function ParamValidator(validation) {
11683 if (validation === true || validation === undefined) {
11684 validation = {'min': true};
11685 }
11686 this.validation = validation;
11687 },
11688
11689 validate: function validate(shape, params, context) {
11690 this.errors = [];
11691 this.validateMember(shape, params || {}, context || 'params');
11692
11693 if (this.errors.length > 1) {
11694 var msg = this.errors.join('\n* ');
11695 msg = 'There were ' + this.errors.length +
11696 ' validation errors:\n* ' + msg;
11697 throw AWS.util.error(new Error(msg),
11698 {code: 'MultipleValidationErrors', errors: this.errors});
11699 } else if (this.errors.length === 1) {
11700 throw this.errors[0];
11701 } else {
11702 return true;
11703 }
11704 },
11705
11706 fail: function fail(code, message) {
11707 this.errors.push(AWS.util.error(new Error(message), {code: code}));
11708 },
11709
11710 validateStructure: function validateStructure(shape, params, context) {
11711 this.validateType(params, context, ['object'], 'structure');
11712
11713 var paramName;
11714 for (var i = 0; shape.required && i < shape.required.length; i++) {
11715 paramName = shape.required[i];
11716 var value = params[paramName];
11717 if (value === undefined || value === null) {
11718 this.fail('MissingRequiredParameter',
11719 'Missing required key \'' + paramName + '\' in ' + context);
11720 }
11721 }
11722
11723 // validate hash members
11724 for (paramName in params) {
11725 if (!Object.prototype.hasOwnProperty.call(params, paramName)) continue;
11726
11727 var paramValue = params[paramName],
11728 memberShape = shape.members[paramName];
11729
11730 if (memberShape !== undefined) {
11731 var memberContext = [context, paramName].join('.');
11732 this.validateMember(memberShape, paramValue, memberContext);
11733 } else {
11734 this.fail('UnexpectedParameter',
11735 'Unexpected key \'' + paramName + '\' found in ' + context);
11736 }
11737 }
11738
11739 return true;
11740 },
11741
11742 validateMember: function validateMember(shape, param, context) {
11743 switch (shape.type) {
11744 case 'structure':
11745 return this.validateStructure(shape, param, context);
11746 case 'list':
11747 return this.validateList(shape, param, context);
11748 case 'map':
11749 return this.validateMap(shape, param, context);
11750 default:
11751 return this.validateScalar(shape, param, context);
11752 }
11753 },
11754
11755 validateList: function validateList(shape, params, context) {
11756 if (this.validateType(params, context, [Array])) {
11757 this.validateRange(shape, params.length, context, 'list member count');
11758 // validate array members
11759 for (var i = 0; i < params.length; i++) {
11760 this.validateMember(shape.member, params[i], context + '[' + i + ']');
11761 }
11762 }
11763 },
11764
11765 validateMap: function validateMap(shape, params, context) {
11766 if (this.validateType(params, context, ['object'], 'map')) {
11767 // Build up a count of map members to validate range traits.
11768 var mapCount = 0;
11769 for (var param in params) {
11770 if (!Object.prototype.hasOwnProperty.call(params, param)) continue;
11771 // Validate any map key trait constraints
11772 this.validateMember(shape.key, param,
11773 context + '[key=\'' + param + '\']');
11774 this.validateMember(shape.value, params[param],
11775 context + '[\'' + param + '\']');
11776 mapCount++;
11777 }
11778 this.validateRange(shape, mapCount, context, 'map member count');
11779 }
11780 },
11781
11782 validateScalar: function validateScalar(shape, value, context) {
11783 switch (shape.type) {
11784 case null:
11785 case undefined:
11786 case 'string':
11787 return this.validateString(shape, value, context);
11788 case 'base64':
11789 case 'binary':
11790 return this.validatePayload(value, context);
11791 case 'integer':
11792 case 'float':
11793 return this.validateNumber(shape, value, context);
11794 case 'boolean':
11795 return this.validateType(value, context, ['boolean']);
11796 case 'timestamp':
11797 return this.validateType(value, context, [Date,
11798 /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/, 'number'],
11799 'Date object, ISO-8601 string, or a UNIX timestamp');
11800 default:
11801 return this.fail('UnkownType', 'Unhandled type ' +
11802 shape.type + ' for ' + context);
11803 }
11804 },
11805
11806 validateString: function validateString(shape, value, context) {
11807 var validTypes = ['string'];
11808 if (shape.isJsonValue) {
11809 validTypes = validTypes.concat(['number', 'object', 'boolean']);
11810 }
11811 if (value !== null && this.validateType(value, context, validTypes)) {
11812 this.validateEnum(shape, value, context);
11813 this.validateRange(shape, value.length, context, 'string length');
11814 this.validatePattern(shape, value, context);
11815 this.validateUri(shape, value, context);
11816 }
11817 },
11818
11819 validateUri: function validateUri(shape, value, context) {
11820 if (shape['location'] === 'uri') {
11821 if (value.length === 0) {
11822 this.fail('UriParameterError', 'Expected uri parameter to have length >= 1,'
11823 + ' but found "' + value +'" for ' + context);
11824 }
11825 }
11826 },
11827
11828 validatePattern: function validatePattern(shape, value, context) {
11829 if (this.validation['pattern'] && shape['pattern'] !== undefined) {
11830 if (!(new RegExp(shape['pattern'])).test(value)) {
11831 this.fail('PatternMatchError', 'Provided value "' + value + '" '
11832 + 'does not match regex pattern /' + shape['pattern'] + '/ for '
11833 + context);
11834 }
11835 }
11836 },
11837
11838 validateRange: function validateRange(shape, value, context, descriptor) {
11839 if (this.validation['min']) {
11840 if (shape['min'] !== undefined && value < shape['min']) {
11841 this.fail('MinRangeError', 'Expected ' + descriptor + ' >= '
11842 + shape['min'] + ', but found ' + value + ' for ' + context);
11843 }
11844 }
11845 if (this.validation['max']) {
11846 if (shape['max'] !== undefined && value > shape['max']) {
11847 this.fail('MaxRangeError', 'Expected ' + descriptor + ' <= '
11848 + shape['max'] + ', but found ' + value + ' for ' + context);
11849 }
11850 }
11851 },
11852
11853 validateEnum: function validateRange(shape, value, context) {
11854 if (this.validation['enum'] && shape['enum'] !== undefined) {
11855 // Fail if the string value is not present in the enum list
11856 if (shape['enum'].indexOf(value) === -1) {
11857 this.fail('EnumError', 'Found string value of ' + value + ', but '
11858 + 'expected ' + shape['enum'].join('|') + ' for ' + context);
11859 }
11860 }
11861 },
11862
11863 validateType: function validateType(value, context, acceptedTypes, type) {
11864 // We will not log an error for null or undefined, but we will return
11865 // false so that callers know that the expected type was not strictly met.
11866 if (value === null || value === undefined) return false;
11867
11868 var foundInvalidType = false;
11869 for (var i = 0; i < acceptedTypes.length; i++) {
11870 if (typeof acceptedTypes[i] === 'string') {
11871 if (typeof value === acceptedTypes[i]) return true;
11872 } else if (acceptedTypes[i] instanceof RegExp) {
11873 if ((value || '').toString().match(acceptedTypes[i])) return true;
11874 } else {
11875 if (value instanceof acceptedTypes[i]) return true;
11876 if (AWS.util.isType(value, acceptedTypes[i])) return true;
11877 if (!type && !foundInvalidType) acceptedTypes = acceptedTypes.slice();
11878 acceptedTypes[i] = AWS.util.typeName(acceptedTypes[i]);
11879 }
11880 foundInvalidType = true;
11881 }
11882
11883 var acceptedType = type;
11884 if (!acceptedType) {
11885 acceptedType = acceptedTypes.join(', ').replace(/,([^,]+)$/, ', or$1');
11886 }
11887
11888 var vowel = acceptedType.match(/^[aeiou]/i) ? 'n' : '';
11889 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a' +
11890 vowel + ' ' + acceptedType);
11891 return false;
11892 },
11893
11894 validateNumber: function validateNumber(shape, value, context) {
11895 if (value === null || value === undefined) return;
11896 if (typeof value === 'string') {
11897 var castedValue = parseFloat(value);
11898 if (castedValue.toString() === value) value = castedValue;
11899 }
11900 if (this.validateType(value, context, ['number'])) {
11901 this.validateRange(shape, value, context, 'numeric value');
11902 }
11903 },
11904
11905 validatePayload: function validatePayload(value, context) {
11906 if (value === null || value === undefined) return;
11907 if (typeof value === 'string') return;
11908 if (value && typeof value.byteLength === 'number') return; // typed arrays
11909 if (AWS.util.isNode()) { // special check for buffer/stream in Node.js
11910 var Stream = AWS.util.stream.Stream;
11911 if (AWS.util.Buffer.isBuffer(value) || value instanceof Stream) return;
11912 } else {
11913 if (typeof Blob !== void 0 && value instanceof Blob) return;
11914 }
11915
11916 var types = ['Buffer', 'Stream', 'File', 'Blob', 'ArrayBuffer', 'DataView'];
11917 if (value) {
11918 for (var i = 0; i < types.length; i++) {
11919 if (AWS.util.isType(value, types[i])) return;
11920 if (AWS.util.typeName(value.constructor) === types[i]) return;
11921 }
11922 }
11923
11924 this.fail('InvalidParameterType', 'Expected ' + context + ' to be a ' +
11925 'string, Buffer, Stream, Blob, or typed array object');
11926 }
11927 });
11928
11929
11930/***/ })
11931/******/ ])
11932});
11933;
\No newline at end of file