UNPKG

225 kBJavaScriptView Raw
1/*
2 Rollup.js v0.21.1
3 Fri Nov 27 2015 21:36:24 GMT-0500 (EST) - commit 34c22139b6bba247fafc44695d5745d36bd96398
4
5
6 https://github.com/rollup/rollup
7
8 Released under the MIT License.
9*/
10
11(function (global, factory) {
12 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
13 typeof define === 'function' && define.amd ? define(['exports'], factory) :
14 factory((global.rollup = {}));
15}(this, function (exports) { 'use strict';
16
17 var babelHelpers = {};
18
19 babelHelpers.classCallCheck = function (instance, Constructor) {
20 if (!(instance instanceof Constructor)) {
21 throw new TypeError("Cannot call a class as a function");
22 }
23 };
24 var Promise = window.Promise;
25
26 // TODO does this all work on windows?
27
28 var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|\/])/;
29
30 function isAbsolute(path) {
31 return absolutePath.test(path);
32 }
33
34 function _basename(path) {
35 return path.split(/(\/|\\)/).pop();
36 }
37
38 function dirname(path) {
39 var match = /(\/|\\)[^\/\\]*$/.exec(path);
40 if (!match) return '.';
41
42 var dir = path.slice(0, -match[0].length);
43
44 // If `dir` is the empty string, we're at root.
45 return dir ? dir : '/';
46 }
47
48 function extname(path) {
49 var match = /\.[^\.]+$/.exec(_basename(path));
50 if (!match) return '';
51 return match[0];
52 }
53
54 function resolve() {
55 for (var _len = arguments.length, paths = Array(_len), _key = 0; _key < _len; _key++) {
56 paths[_key] = arguments[_key];
57 }
58
59 var resolvedParts = paths.shift().split(/[\/\\]/);
60
61 paths.forEach(function (path) {
62 if (isAbsolute(path)) {
63 resolvedParts = path.split(/[\/\\]/);
64 } else {
65 var parts = path.split(/[\/\\]/);
66
67 while (parts[0] === '.' || parts[0] === '..') {
68 var part = parts.shift();
69 if (part === '..') {
70 resolvedParts.pop();
71 }
72 }
73
74 resolvedParts.push.apply(resolvedParts, parts);
75 }
76 });
77
78 return resolvedParts.join('/'); // TODO windows...
79 }
80
81 var nope = function (method) {
82 return 'Cannot use fs.' + method + ' inside browser';
83 };
84
85 var isFile = function () {
86 return false;
87 };
88 var readdirSync = nope('readdirSync');
89 var readFileSync = nope('readFileSync');
90 var writeFile = nope('writeFile');
91
92 var keys = Object.keys;
93
94 function blank() {
95 return Object.create(null);
96 }
97
98 // this looks ridiculous, but it prevents sourcemap tooling from mistaking
99 // this for an actual sourceMappingURL
100 var SOURCEMAPPING_URL = 'sourceMa';
101 SOURCEMAPPING_URL += 'ppingURL';
102
103 var SOURCEMAPPING_URL$1 = SOURCEMAPPING_URL;
104
105 var charToInteger = {};
106 var integerToChar = {};
107
108 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split( '' ).forEach( function ( char, i ) {
109 charToInteger[ char ] = i;
110 integerToChar[ i ] = char;
111 });
112
113 function encode ( value ) {
114 var result, i;
115
116 if ( typeof value === 'number' ) {
117 result = encodeInteger( value );
118 } else {
119 result = '';
120 for ( i = 0; i < value.length; i += 1 ) {
121 result += encodeInteger( value[i] );
122 }
123 }
124
125 return result;
126 }
127
128 function encodeInteger ( num ) {
129 var result = '', clamped;
130
131 if ( num < 0 ) {
132 num = ( -num << 1 ) | 1;
133 } else {
134 num <<= 1;
135 }
136
137 do {
138 clamped = num & 31;
139 num >>= 5;
140
141 if ( num > 0 ) {
142 clamped |= 32;
143 }
144
145 result += integerToChar[ clamped ];
146 } while ( num > 0 );
147
148 return result;
149 }
150
151 var babelHelpers_classCallCheck = function (instance, Constructor) {
152 if (!(instance instanceof Constructor)) {
153 throw new TypeError("Cannot call a class as a function");
154 }
155 };
156
157 var _btoa = undefined;
158
159 if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
160 _btoa = window.btoa;
161 } else if (typeof Buffer === 'function') {
162 /* global Buffer */
163 _btoa = function (str) {
164 return new Buffer(str).toString('base64');
165 };
166 } else {
167 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
168 }
169
170 var btoa = _btoa;
171
172 var SourceMap = (function () {
173 function SourceMap(properties) {
174 babelHelpers_classCallCheck(this, SourceMap);
175
176 this.version = 3;
177
178 this.file = properties.file;
179 this.sources = properties.sources;
180 this.sourcesContent = properties.sourcesContent;
181 this.names = properties.names;
182 this.mappings = properties.mappings;
183 }
184
185 SourceMap.prototype.toString = function toString() {
186 return JSON.stringify(this);
187 };
188
189 SourceMap.prototype.toUrl = function toUrl() {
190 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
191 };
192
193 return SourceMap;
194 })();
195
196 function guessIndent(code) {
197 var lines = code.split('\n');
198
199 var tabbed = lines.filter(function (line) {
200 return (/^\t+/.test(line)
201 );
202 });
203 var spaced = lines.filter(function (line) {
204 return (/^ {2,}/.test(line)
205 );
206 });
207
208 if (tabbed.length === 0 && spaced.length === 0) {
209 return null;
210 }
211
212 // More lines tabbed than spaced? Assume tabs, and
213 // default to tabs in the case of a tie (or nothing
214 // to go on)
215 if (tabbed.length >= spaced.length) {
216 return '\t';
217 }
218
219 // Otherwise, we need to guess the multiple
220 var min = spaced.reduce(function (previous, current) {
221 var numSpaces = /^ +/.exec(current)[0].length;
222 return Math.min(numSpaces, previous);
223 }, Infinity);
224
225 return new Array(min + 1).join(' ');
226 }
227
228 function encodeMappings(original, str, mappings, hires, sourcemapLocations, sourceIndex, offsets, names, nameLocations) {
229 // store locations, for fast lookup
230 var lineStart = 0;
231 var locations = original.split('\n').map(function (line) {
232 var start = lineStart;
233 lineStart += line.length + 1; // +1 for the newline
234
235 return start;
236 });
237
238 var inverseMappings = invert(str, mappings);
239
240 var charOffset = 0;
241 var lines = str.split('\n').map(function (line) {
242 var segments = [];
243
244 var char = undefined; // TODO put these inside loop, once we've determined it's safe to do so transpilation-wise
245 var origin = undefined;
246 var lastOrigin = -1;
247 var location = undefined;
248 var nameIndex = undefined;
249
250 var i = undefined;
251
252 var len = line.length;
253 for (i = 0; i < len; i += 1) {
254 char = i + charOffset;
255 origin = inverseMappings[char];
256
257 nameIndex = -1;
258 location = null;
259
260 // if this character has no mapping, but the last one did,
261 // create a new segment
262 if (! ~origin && ~lastOrigin) {
263 location = getLocation(locations, lastOrigin + 1);
264
265 if (lastOrigin + 1 in nameLocations) nameIndex = names.indexOf(nameLocations[lastOrigin + 1]);
266 } else if (~origin && (hires || ~lastOrigin && origin !== lastOrigin + 1 || sourcemapLocations[origin])) {
267 location = getLocation(locations, origin);
268 }
269
270 if (location) {
271 segments.push({
272 generatedCodeColumn: i,
273 sourceIndex: sourceIndex,
274 sourceCodeLine: location.line,
275 sourceCodeColumn: location.column,
276 sourceCodeName: nameIndex
277 });
278 }
279
280 lastOrigin = origin;
281 }
282
283 charOffset += line.length + 1;
284 return segments;
285 });
286
287 offsets.sourceIndex = offsets.sourceIndex || 0;
288 offsets.sourceCodeLine = offsets.sourceCodeLine || 0;
289 offsets.sourceCodeColumn = offsets.sourceCodeColumn || 0;
290 offsets.sourceCodeName = offsets.sourceCodeName || 0;
291
292 var encoded = lines.map(function (segments) {
293 var generatedCodeColumn = 0;
294
295 return segments.map(function (segment) {
296 var arr = [segment.generatedCodeColumn - generatedCodeColumn, segment.sourceIndex - offsets.sourceIndex, segment.sourceCodeLine - offsets.sourceCodeLine, segment.sourceCodeColumn - offsets.sourceCodeColumn];
297
298 generatedCodeColumn = segment.generatedCodeColumn;
299 offsets.sourceIndex = segment.sourceIndex;
300 offsets.sourceCodeLine = segment.sourceCodeLine;
301 offsets.sourceCodeColumn = segment.sourceCodeColumn;
302
303 if (~segment.sourceCodeName) {
304 arr.push(segment.sourceCodeName - offsets.sourceCodeName);
305 offsets.sourceCodeName = segment.sourceCodeName;
306 }
307
308 return encode(arr);
309 }).join(',');
310 }).join(';');
311
312 return encoded;
313 }
314
315 function invert(str, mappings) {
316 var inverted = new Uint32Array(str.length);
317
318 // initialise everything to -1
319 var i = str.length;
320 while (i--) {
321 inverted[i] = -1;
322 }
323
324 // then apply the actual mappings
325 i = mappings.length;
326 while (i--) {
327 if (~mappings[i]) {
328 inverted[mappings[i]] = i;
329 }
330 }
331
332 return inverted;
333 }
334
335 function getLocation(locations, char) {
336 var i = locations.length;
337 while (i--) {
338 if (locations[i] <= char) {
339 return {
340 line: i,
341 column: char - locations[i]
342 };
343 }
344 }
345
346 throw new Error('Character out of bounds');
347 }
348
349 function getRelativePath(from, to) {
350 var fromParts = from.split(/[\/\\]/);
351 var toParts = to.split(/[\/\\]/);
352
353 fromParts.pop(); // get dirname
354
355 while (fromParts[0] === toParts[0]) {
356 fromParts.shift();
357 toParts.shift();
358 }
359
360 if (fromParts.length) {
361 var i = fromParts.length;
362 while (i--) fromParts[i] = '..';
363 }
364
365 return fromParts.concat(toParts).join('/');
366 }
367
368 var warned = false;
369
370 var MagicString = (function () {
371 function MagicString(string) {
372 var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
373 babelHelpers_classCallCheck(this, MagicString);
374
375 Object.defineProperties(this, {
376 original: { writable: true, value: string },
377 str: { writable: true, value: string },
378 mappings: { writable: true, value: initMappings(string.length) },
379 filename: { writable: true, value: options.filename },
380 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
381 sourcemapLocations: { writable: true, value: {} },
382 nameLocations: { writable: true, value: {} },
383 indentStr: { writable: true, value: guessIndent(string) }
384 });
385 }
386
387 MagicString.prototype.addSourcemapLocation = function addSourcemapLocation(char) {
388 this.sourcemapLocations[char] = true;
389 };
390
391 MagicString.prototype.append = function append(content) {
392 if (typeof content !== 'string') {
393 throw new TypeError('appended content must be a string');
394 }
395
396 this.str += content;
397 return this;
398 };
399
400 MagicString.prototype.clone = function clone() {
401 var clone = new MagicString(this.original, { filename: this.filename });
402 clone.str = this.str;
403
404 var i = clone.mappings.length;
405 while (i--) {
406 clone.mappings[i] = this.mappings[i];
407 }
408
409 if (this.indentExclusionRanges) {
410 clone.indentExclusionRanges = typeof this.indentExclusionRanges[0] === 'number' ? [this.indentExclusionRanges[0], this.indentExclusionRanges[1]] : this.indentExclusionRanges.map(function (range) {
411 return [range.start, range.end];
412 });
413 }
414
415 Object.keys(this.sourcemapLocations).forEach(function (loc) {
416 clone.sourcemapLocations[loc] = true;
417 });
418
419 return clone;
420 };
421
422 MagicString.prototype.generateMap = function generateMap(options) {
423 var _this = this;
424
425 options = options || {};
426
427 var names = [];
428 Object.keys(this.nameLocations).forEach(function (location) {
429 var name = _this.nameLocations[location];
430 if (! ~names.indexOf(name)) names.push(name);
431 });
432
433 return new SourceMap({
434 file: options.file ? options.file.split(/[\/\\]/).pop() : null,
435 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
436 sourcesContent: options.includeContent ? [this.original] : [null],
437 names: names,
438 mappings: this.getMappings(options.hires, 0, {}, names)
439 });
440 };
441
442 MagicString.prototype.getIndentString = function getIndentString() {
443 return this.indentStr === null ? '\t' : this.indentStr;
444 };
445
446 MagicString.prototype.getMappings = function getMappings(hires, sourceIndex, offsets, names) {
447 return encodeMappings(this.original, this.str, this.mappings, hires, this.sourcemapLocations, sourceIndex, offsets, names, this.nameLocations);
448 };
449
450 MagicString.prototype.indent = function indent(indentStr, options) {
451 var _this2 = this;
452
453 var mappings = this.mappings;
454 var reverseMappings = reverse(mappings, this.str.length);
455 var pattern = /^[^\r\n]/gm;
456
457 if (typeof indentStr === 'object') {
458 options = indentStr;
459 indentStr = undefined;
460 }
461
462 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
463
464 if (indentStr === '') return this; // noop
465
466 options = options || {};
467
468 // Process exclusion ranges
469 var exclusions = undefined;
470
471 if (options.exclude) {
472 exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
473
474 exclusions = exclusions.map(function (range) {
475 var rangeStart = _this2.locate(range[0]);
476 var rangeEnd = _this2.locate(range[1]);
477
478 if (rangeStart === null || rangeEnd === null) {
479 throw new Error('Cannot use indices of replaced characters as exclusion ranges');
480 }
481
482 return [rangeStart, rangeEnd];
483 });
484
485 exclusions.sort(function (a, b) {
486 return a[0] - b[0];
487 });
488
489 // check for overlaps
490 lastEnd = -1;
491 exclusions.forEach(function (range) {
492 if (range[0] < lastEnd) {
493 throw new Error('Exclusion ranges cannot overlap');
494 }
495
496 lastEnd = range[1];
497 });
498 }
499
500 var indentStart = options.indentStart !== false;
501 var inserts = [];
502
503 if (!exclusions) {
504 this.str = this.str.replace(pattern, function (match, index) {
505 if (!indentStart && index === 0) {
506 return match;
507 }
508
509 inserts.push(index);
510 return indentStr + match;
511 });
512 } else {
513 this.str = this.str.replace(pattern, function (match, index) {
514 if (!indentStart && index === 0 || isExcluded(index - 1)) {
515 return match;
516 }
517
518 inserts.push(index);
519 return indentStr + match;
520 });
521 }
522
523 var adjustments = inserts.map(function (index) {
524 var origin = undefined;
525
526 do {
527 origin = reverseMappings[index++];
528 } while (! ~origin && index < _this2.str.length);
529
530 return origin;
531 });
532
533 var i = adjustments.length;
534 var lastEnd = this.mappings.length;
535 while (i--) {
536 adjust(this.mappings, adjustments[i], lastEnd, (i + 1) * indentStr.length);
537 lastEnd = adjustments[i];
538 }
539
540 return this;
541
542 function isExcluded(index) {
543 var i = exclusions.length;
544 var range = undefined;
545
546 while (i--) {
547 range = exclusions[i];
548
549 if (range[1] < index) {
550 return false;
551 }
552
553 if (range[0] <= index) {
554 return true;
555 }
556 }
557 }
558 };
559
560 MagicString.prototype.insert = function insert(index, content) {
561 if (typeof content !== 'string') {
562 throw new TypeError('inserted content must be a string');
563 }
564
565 if (index === this.original.length) {
566 this.append(content);
567 } else {
568 var mapped = this.locate(index);
569
570 if (mapped === null) {
571 throw new Error('Cannot insert at replaced character index: ' + index);
572 }
573
574 this.str = this.str.substr(0, mapped) + content + this.str.substr(mapped);
575 adjust(this.mappings, index, this.mappings.length, content.length);
576 }
577
578 return this;
579 };
580
581 // get current location of character in original string
582
583 MagicString.prototype.locate = function locate(character) {
584 if (character < 0 || character > this.mappings.length) {
585 throw new Error('Character is out of bounds');
586 }
587
588 var loc = this.mappings[character];
589 return ~loc ? loc : null;
590 };
591
592 MagicString.prototype.locateOrigin = function locateOrigin(character) {
593 if (character < 0 || character >= this.str.length) {
594 throw new Error('Character is out of bounds');
595 }
596
597 var i = this.mappings.length;
598 while (i--) {
599 if (this.mappings[i] === character) {
600 return i;
601 }
602 }
603
604 return null;
605 };
606
607 MagicString.prototype.overwrite = function overwrite(start, end, content, storeName) {
608 if (typeof content !== 'string') {
609 throw new TypeError('replacement content must be a string');
610 }
611
612 var firstChar = this.locate(start);
613 var lastChar = this.locate(end - 1);
614
615 if (firstChar === null || lastChar === null) {
616 throw new Error('Cannot overwrite the same content twice: \'' + this.original.slice(start, end).replace(/\n/g, '\\n') + '\'');
617 }
618
619 if (firstChar > lastChar + 1) {
620 throw new Error('BUG! First character mapped to a position after the last character: ' + '[' + start + ', ' + end + '] -> [' + firstChar + ', ' + (lastChar + 1) + ']');
621 }
622
623 if (storeName) {
624 this.nameLocations[start] = this.original.slice(start, end);
625 }
626
627 this.str = this.str.substr(0, firstChar) + content + this.str.substring(lastChar + 1);
628
629 var d = content.length - (lastChar + 1 - firstChar);
630
631 blank$1(this.mappings, start, end);
632 adjust(this.mappings, end, this.mappings.length, d);
633 return this;
634 };
635
636 MagicString.prototype.prepend = function prepend(content) {
637 this.str = content + this.str;
638 adjust(this.mappings, 0, this.mappings.length, content.length);
639 return this;
640 };
641
642 MagicString.prototype.remove = function remove(start, end) {
643 if (start < 0 || end > this.mappings.length) {
644 throw new Error('Character is out of bounds');
645 }
646
647 var currentStart = -1;
648 var currentEnd = -1;
649 for (var i = start; i < end; i += 1) {
650 var loc = this.mappings[i];
651
652 if (~loc) {
653 if (! ~currentStart) currentStart = loc;
654
655 currentEnd = loc + 1;
656 this.mappings[i] = -1;
657 }
658 }
659
660 this.str = this.str.slice(0, currentStart) + this.str.slice(currentEnd);
661
662 adjust(this.mappings, end, this.mappings.length, currentStart - currentEnd);
663 return this;
664 };
665
666 MagicString.prototype.replace = function replace(start, end, content) {
667 if (!warned) {
668 console.warn('magicString.replace(...) is deprecated. Use magicString.overwrite(...) instead');
669 warned = true;
670 }
671
672 return this.overwrite(start, end, content);
673 };
674
675 MagicString.prototype.slice = function slice(start) {
676 var end = arguments.length <= 1 || arguments[1] === undefined ? this.original.length : arguments[1];
677
678 while (start < 0) start += this.original.length;
679 while (end < 0) end += this.original.length;
680
681 var firstChar = this.locate(start);
682 var lastChar = this.locate(end - 1);
683
684 if (firstChar === null || lastChar === null) {
685 throw new Error('Cannot use replaced characters as slice anchors');
686 }
687
688 return this.str.slice(firstChar, lastChar + 1);
689 };
690
691 MagicString.prototype.snip = function snip(start, end) {
692 var clone = this.clone();
693 clone.remove(0, start);
694 clone.remove(end, clone.original.length);
695
696 return clone;
697 };
698
699 MagicString.prototype.toString = function toString() {
700 return this.str;
701 };
702
703 MagicString.prototype.trimLines = function trimLines() {
704 return this.trim('[\\r\\n]');
705 };
706
707 MagicString.prototype.trim = function trim(charType) {
708 return this.trimStart(charType).trimEnd(charType);
709 };
710
711 MagicString.prototype.trimEnd = function trimEnd(charType) {
712 var _this3 = this;
713
714 var rx = new RegExp((charType || '\\s') + '+$');
715
716 this.str = this.str.replace(rx, function (trailing, index, str) {
717 var strLength = str.length;
718 var length = trailing.length;
719
720 var chars = [];
721
722 var i = strLength;
723 while (i-- > strLength - length) {
724 chars.push(_this3.locateOrigin(i));
725 }
726
727 i = chars.length;
728 while (i--) {
729 if (chars[i] !== null) {
730 _this3.mappings[chars[i]] = -1;
731 }
732 }
733
734 return '';
735 });
736
737 return this;
738 };
739
740 MagicString.prototype.trimStart = function trimStart(charType) {
741 var _this4 = this;
742
743 var rx = new RegExp('^' + (charType || '\\s') + '+');
744
745 this.str = this.str.replace(rx, function (leading) {
746 var length = leading.length;
747
748 var chars = [];
749 var adjustmentStart = 0;
750
751 var i = length;
752 while (i--) {
753 chars.push(_this4.locateOrigin(i));
754 }
755
756 i = chars.length;
757 while (i--) {
758 if (chars[i] !== null) {
759 _this4.mappings[chars[i]] = -1;
760 adjustmentStart += 1;
761 }
762 }
763
764 adjust(_this4.mappings, adjustmentStart, _this4.mappings.length, -length);
765
766 return '';
767 });
768
769 return this;
770 };
771
772 return MagicString;
773 })();
774
775 function adjust(mappings, start, end, d) {
776 if (!d) return; // replacement is same length as replaced string
777
778 var i = end;
779 while (i-- > start) {
780 if (~mappings[i]) {
781 mappings[i] += d;
782 }
783 }
784 }
785
786 function initMappings(i) {
787 var mappings = new Uint32Array(i);
788
789 while (i--) mappings[i] = i;
790 return mappings;
791 }
792
793 function blank$1(mappings, start, i) {
794 while (i-- > start) mappings[i] = -1;
795 }
796
797 function reverse(mappings, i) {
798 var result = new Uint32Array(i);
799
800 while (i--) {
801 result[i] = -1;
802 }
803
804 var location = undefined;
805 i = mappings.length;
806 while (i--) {
807 location = mappings[i];
808
809 if (~location) {
810 result[location] = i;
811 }
812 }
813
814 return result;
815 }
816
817 var hasOwnProp = Object.prototype.hasOwnProperty;
818
819 var Bundle$1 = (function () {
820 function Bundle() {
821 var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
822 babelHelpers_classCallCheck(this, Bundle);
823
824 this.intro = options.intro || '';
825 this.outro = options.outro || '';
826 this.separator = options.separator !== undefined ? options.separator : '\n';
827
828 this.sources = [];
829
830 this.uniqueSources = [];
831 this.uniqueSourceIndexByFilename = {};
832 }
833
834 Bundle.prototype.addSource = function addSource(source) {
835 if (source instanceof MagicString) {
836 return this.addSource({
837 content: source,
838 filename: source.filename,
839 separator: this.separator
840 });
841 }
842
843 if (typeof source !== 'object' || !source.content) {
844 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
845 }
846
847 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
848 if (!hasOwnProp.call(source, option)) source[option] = source.content[option];
849 });
850
851 if (source.separator === undefined) {
852 // TODO there's a bunch of this sort of thing, needs cleaning up
853 source.separator = this.separator;
854 }
855
856 if (source.filename) {
857 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
858 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
859 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
860 } else {
861 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
862 if (source.content.original !== uniqueSource.content) {
863 throw new Error('Illegal source: same filename (' + source.filename + '), different contents');
864 }
865 }
866 }
867
868 this.sources.push(source);
869 return this;
870 };
871
872 Bundle.prototype.append = function append(str, options) {
873 this.addSource({
874 content: new MagicString(str),
875 separator: options && options.separator || ''
876 });
877
878 return this;
879 };
880
881 Bundle.prototype.clone = function clone() {
882 var bundle = new Bundle({
883 intro: this.intro,
884 outro: this.outro,
885 separator: this.separator
886 });
887
888 this.sources.forEach(function (source) {
889 bundle.addSource({
890 filename: source.filename,
891 content: source.content.clone(),
892 separator: source.separator
893 });
894 });
895
896 return bundle;
897 };
898
899 Bundle.prototype.generateMap = function generateMap(options) {
900 var _this = this;
901
902 var offsets = {};
903
904 var names = [];
905 this.sources.forEach(function (source) {
906 Object.keys(source.content.nameLocations).forEach(function (location) {
907 var name = source.content.nameLocations[location];
908 if (! ~names.indexOf(name)) names.push(name);
909 });
910 });
911
912 var encoded = getSemis(this.intro) + this.sources.map(function (source, i) {
913 var prefix = i > 0 ? getSemis(source.separator) || ',' : '';
914 var mappings = undefined;
915
916 // we don't bother encoding sources without a filename
917 if (!source.filename) {
918 mappings = getSemis(source.content.toString());
919 } else {
920 var sourceIndex = _this.uniqueSourceIndexByFilename[source.filename];
921 mappings = source.content.getMappings(options.hires, sourceIndex, offsets, names);
922 }
923
924 return prefix + mappings;
925 }).join('') + getSemis(this.outro);
926
927 return new SourceMap({
928 file: options.file ? options.file.split(/[\/\\]/).pop() : null,
929 sources: this.uniqueSources.map(function (source) {
930 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
931 }),
932 sourcesContent: this.uniqueSources.map(function (source) {
933 return options.includeContent ? source.content : null;
934 }),
935 names: names,
936 mappings: encoded
937 });
938 };
939
940 Bundle.prototype.getIndentString = function getIndentString() {
941 var indentStringCounts = {};
942
943 this.sources.forEach(function (source) {
944 var indentStr = source.content.indentStr;
945
946 if (indentStr === null) return;
947
948 if (!indentStringCounts[indentStr]) indentStringCounts[indentStr] = 0;
949 indentStringCounts[indentStr] += 1;
950 });
951
952 return Object.keys(indentStringCounts).sort(function (a, b) {
953 return indentStringCounts[a] - indentStringCounts[b];
954 })[0] || '\t';
955 };
956
957 Bundle.prototype.indent = function indent(indentStr) {
958 var _this2 = this;
959
960 if (!arguments.length) {
961 indentStr = this.getIndentString();
962 }
963
964 if (indentStr === '') return this; // noop
965
966 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
967
968 this.sources.forEach(function (source, i) {
969 var separator = source.separator !== undefined ? source.separator : _this2.separator;
970 var indentStart = trailingNewline || i > 0 && /\r?\n$/.test(separator);
971
972 source.content.indent(indentStr, {
973 exclude: source.indentExclusionRanges,
974 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
975 });
976
977 trailingNewline = source.content.str.slice(0, -1) === '\n';
978 });
979
980 if (this.intro) {
981 this.intro = indentStr + this.intro.replace(/^[^\n]/gm, function (match, index) {
982 return index > 0 ? indentStr + match : match;
983 });
984 }
985
986 this.outro = this.outro.replace(/^[^\n]/gm, indentStr + '$&');
987
988 return this;
989 };
990
991 Bundle.prototype.prepend = function prepend(str) {
992 this.intro = str + this.intro;
993 return this;
994 };
995
996 Bundle.prototype.toString = function toString() {
997 var _this3 = this;
998
999 var body = this.sources.map(function (source, i) {
1000 var separator = source.separator !== undefined ? source.separator : _this3.separator;
1001 var str = (i > 0 ? separator : '') + source.content.toString();
1002
1003 return str;
1004 }).join('');
1005
1006 return this.intro + body + this.outro;
1007 };
1008
1009 Bundle.prototype.trimLines = function trimLines() {
1010 return this.trim('[\\r\\n]');
1011 };
1012
1013 Bundle.prototype.trim = function trim(charType) {
1014 return this.trimStart(charType).trimEnd(charType);
1015 };
1016
1017 Bundle.prototype.trimStart = function trimStart(charType) {
1018 var rx = new RegExp('^' + (charType || '\\s') + '+');
1019 this.intro = this.intro.replace(rx, '');
1020
1021 if (!this.intro) {
1022 var source = undefined; // TODO put inside loop if safe
1023 var i = 0;
1024
1025 do {
1026 source = this.sources[i];
1027
1028 if (!source) {
1029 this.outro = this.outro.replace(rx, '');
1030 break;
1031 }
1032
1033 source.content.trimStart();
1034 i += 1;
1035 } while (source.content.str === '');
1036 }
1037
1038 return this;
1039 };
1040
1041 Bundle.prototype.trimEnd = function trimEnd(charType) {
1042 var rx = new RegExp((charType || '\\s') + '+$');
1043 this.outro = this.outro.replace(rx, '');
1044
1045 if (!this.outro) {
1046 var source = undefined;
1047 var i = this.sources.length - 1;
1048
1049 do {
1050 source = this.sources[i];
1051
1052 if (!source) {
1053 this.intro = this.intro.replace(rx, '');
1054 break;
1055 }
1056
1057 source.content.trimEnd(charType);
1058 i -= 1;
1059 } while (source.content.str === '');
1060 }
1061
1062 return this;
1063 };
1064
1065 return Bundle;
1066 })();
1067
1068 function getSemis(str) {
1069 return new Array(str.split('\n').length).join(';');
1070 }
1071
1072 MagicString.Bundle = Bundle$1;
1073
1074 // Return the first non-falsy result from an array of
1075 // maybe-sync, maybe-promise-returning functions
1076
1077 function first(candidates) {
1078 return function () {
1079 for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
1080 args[_key] = arguments[_key];
1081 }
1082
1083 return candidates.reduce(function (promise, candidate) {
1084 return promise.then(function (result) {
1085 return result != null ? result : Promise.resolve(candidate.apply(undefined, args));
1086 });
1087 }, Promise.resolve());
1088 };
1089 }
1090
1091 // This is a trick taken from Esprima. It turns out that, on
1092 // non-Chrome browsers, to check whether a string is in a set, a
1093 // predicate containing a big ugly `switch` statement is faster than
1094 // a regular expression, and on Chrome the two are about on par.
1095 // This function uses `eval` (non-lexical) to produce such a
1096 // predicate from a space-separated string of words.
1097 //
1098 // It starts by sorting the words by length.
1099
1100 // Reserved word lists for various dialects of the language
1101
1102 var reservedWords$1 = {
1103 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
1104 5: "class enum extends super const export import",
1105 6: "enum",
1106 strict: "implements interface let package private protected public static yield",
1107 strictBind: "eval arguments"
1108 };
1109
1110 // And the keywords
1111
1112 var ecma5AndLessKeywords = "break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this";
1113
1114 var keywords = {
1115 5: ecma5AndLessKeywords,
1116 6: ecma5AndLessKeywords + " let const class extends export import yield super"
1117 };
1118
1119 // ## Character categories
1120
1121 // Big ugly regular expressions that match characters in the
1122 // whitespace, identifier, and identifier-start categories. These
1123 // are only applied when a character is found to actually have a
1124 // code point above 128.
1125 // Generated by `bin/generate-identifier-regex.js`.
1126
1127 var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0-\u08b2\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua7ad\ua7b0\ua7b1\ua7f7-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab5f\uab64\uab65\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
1128 var nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08e4-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c03\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d01-\u0d03\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19b0-\u19c0\u19c8\u19c9\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf2-\u1cf4\u1cf8\u1cf9\u1dc0-\u1df5\u1dfc-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua880\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f1\ua900-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2d\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
1129
1130 var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
1131 var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
1132
1133 nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
1134
1135 // These are a run-length and offset encoded representation of the
1136 // >0xffff code points that are a valid part of identifiers. The
1137 // offset starts at 0x10000, and each pair of numbers represents an
1138 // offset to the next range, and then a size of the range. They were
1139 // generated by tools/generate-identifier-regex.js
1140 var astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 17, 26, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 99, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 98, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 26, 45, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 955, 52, 76, 44, 33, 24, 27, 35, 42, 34, 4, 0, 13, 47, 15, 3, 22, 0, 38, 17, 2, 24, 133, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 32, 4, 287, 47, 21, 1, 2, 0, 185, 46, 82, 47, 21, 0, 60, 42, 502, 63, 32, 0, 449, 56, 1288, 920, 104, 110, 2962, 1070, 13266, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 881, 68, 12, 0, 67, 12, 16481, 1, 3071, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 4149, 196, 1340, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42710, 42, 4148, 12, 221, 16355, 541];
1141 var astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 1306, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 52, 0, 13, 2, 49, 13, 16, 9, 83, 11, 168, 11, 6, 9, 8, 2, 57, 0, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 316, 19, 13, 9, 214, 6, 3, 8, 112, 16, 16, 9, 82, 12, 9, 9, 535, 9, 20855, 9, 135, 4, 60, 6, 26, 9, 1016, 45, 17, 3, 19723, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 4305, 6, 792618, 239];
1142
1143 // This has a complexity linear to the value of the code. The
1144 // assumption is that looking up astral identifier characters is
1145 // rare.
1146 function isInAstralSet(code, set) {
1147 var pos = 0x10000;
1148 for (var i = 0; i < set.length; i += 2) {
1149 pos += set[i];
1150 if (pos > code) return false;
1151 pos += set[i + 1];
1152 if (pos >= code) return true;
1153 }
1154 }
1155
1156 // Test whether a given character code starts an identifier.
1157
1158 function isIdentifierStart(code, astral) {
1159 if (code < 65) return code === 36;
1160 if (code < 91) return true;
1161 if (code < 97) return code === 95;
1162 if (code < 123) return true;
1163 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
1164 if (astral === false) return false;
1165 return isInAstralSet(code, astralIdentifierStartCodes);
1166 }
1167
1168 // Test whether a given character is part of an identifier.
1169
1170 function isIdentifierChar(code, astral) {
1171 if (code < 48) return code === 36;
1172 if (code < 58) return true;
1173 if (code < 65) return false;
1174 if (code < 91) return true;
1175 if (code < 97) return code === 95;
1176 if (code < 123) return true;
1177 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
1178 if (astral === false) return false;
1179 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
1180 }
1181
1182 // ## Token types
1183
1184 // The assignment of fine-grained, information-carrying type objects
1185 // allows the tokenizer to store the information it has about a
1186 // token in a way that is very cheap for the parser to look up.
1187
1188 // All token type variables start with an underscore, to make them
1189 // easy to recognize.
1190
1191 // The `beforeExpr` property is used to disambiguate between regular
1192 // expressions and divisions. It is set on all token types that can
1193 // be followed by an expression (thus, a slash after them would be a
1194 // regular expression).
1195 //
1196 // The `startsExpr` property is used to check if the token ends a
1197 // `yield` expression. It is set on all token types that either can
1198 // directly start an expression (like a quotation mark) or can
1199 // continue an expression (like the body of a string).
1200 //
1201 // `isLoop` marks a keyword as starting a loop, which is important
1202 // to know when parsing a label, in order to allow or disallow
1203 // continue jumps to that label.
1204
1205 var TokenType = function TokenType(label) {
1206 var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
1207 babelHelpers.classCallCheck(this, TokenType);
1208
1209 this.label = label;
1210 this.keyword = conf.keyword;
1211 this.beforeExpr = !!conf.beforeExpr;
1212 this.startsExpr = !!conf.startsExpr;
1213 this.isLoop = !!conf.isLoop;
1214 this.isAssign = !!conf.isAssign;
1215 this.prefix = !!conf.prefix;
1216 this.postfix = !!conf.postfix;
1217 this.binop = conf.binop || null;
1218 this.updateContext = null;
1219 };
1220
1221 function binop(name, prec) {
1222 return new TokenType(name, { beforeExpr: true, binop: prec });
1223 }
1224 var beforeExpr = { beforeExpr: true };
1225 var startsExpr = { startsExpr: true };
1226 var tt = {
1227 num: new TokenType("num", startsExpr),
1228 regexp: new TokenType("regexp", startsExpr),
1229 string: new TokenType("string", startsExpr),
1230 name: new TokenType("name", startsExpr),
1231 eof: new TokenType("eof"),
1232
1233 // Punctuation token types.
1234 bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
1235 bracketR: new TokenType("]"),
1236 braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
1237 braceR: new TokenType("}"),
1238 parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
1239 parenR: new TokenType(")"),
1240 comma: new TokenType(",", beforeExpr),
1241 semi: new TokenType(";", beforeExpr),
1242 colon: new TokenType(":", beforeExpr),
1243 dot: new TokenType("."),
1244 question: new TokenType("?", beforeExpr),
1245 arrow: new TokenType("=>", beforeExpr),
1246 template: new TokenType("template"),
1247 ellipsis: new TokenType("...", beforeExpr),
1248 backQuote: new TokenType("`", startsExpr),
1249 dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
1250
1251 // Operators. These carry several kinds of properties to help the
1252 // parser use them properly (the presence of these properties is
1253 // what categorizes them as operators).
1254 //
1255 // `binop`, when present, specifies that this operator is a binary
1256 // operator, and will refer to its precedence.
1257 //
1258 // `prefix` and `postfix` mark the operator as a prefix or postfix
1259 // unary operator.
1260 //
1261 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
1262 // binary operators with a very low precedence, that should result
1263 // in AssignmentExpression nodes.
1264
1265 eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
1266 assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
1267 incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
1268 prefix: new TokenType("prefix", { beforeExpr: true, prefix: true, startsExpr: true }),
1269 logicalOR: binop("||", 1),
1270 logicalAND: binop("&&", 2),
1271 bitwiseOR: binop("|", 3),
1272 bitwiseXOR: binop("^", 4),
1273 bitwiseAND: binop("&", 5),
1274 equality: binop("==/!=", 6),
1275 relational: binop("</>", 7),
1276 bitShift: binop("<</>>", 8),
1277 plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
1278 modulo: binop("%", 10),
1279 star: binop("*", 10),
1280 slash: binop("/", 10)
1281 };
1282
1283 // Map keyword names to token types.
1284
1285 var keywordTypes = {};
1286
1287 // Succinct definitions of keyword token types
1288 function kw(name) {
1289 var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
1290
1291 options.keyword = name;
1292 keywordTypes[name] = tt["_" + name] = new TokenType(name, options);
1293 }
1294
1295 kw("break");
1296 kw("case", beforeExpr);
1297 kw("catch");
1298 kw("continue");
1299 kw("debugger");
1300 kw("default", beforeExpr);
1301 kw("do", { isLoop: true, beforeExpr: true });
1302 kw("else", beforeExpr);
1303 kw("finally");
1304 kw("for", { isLoop: true });
1305 kw("function", startsExpr);
1306 kw("if");
1307 kw("return", beforeExpr);
1308 kw("switch");
1309 kw("throw", beforeExpr);
1310 kw("try");
1311 kw("var");
1312 kw("let");
1313 kw("const");
1314 kw("while", { isLoop: true });
1315 kw("with");
1316 kw("new", { beforeExpr: true, startsExpr: true });
1317 kw("this", startsExpr);
1318 kw("super", startsExpr);
1319 kw("class");
1320 kw("extends", beforeExpr);
1321 kw("export");
1322 kw("import");
1323 kw("yield", { beforeExpr: true, startsExpr: true });
1324 kw("null", startsExpr);
1325 kw("true", startsExpr);
1326 kw("false", startsExpr);
1327 kw("in", { beforeExpr: true, binop: 7 });
1328 kw("instanceof", { beforeExpr: true, binop: 7 });
1329 kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true });
1330 kw("void", { beforeExpr: true, prefix: true, startsExpr: true });
1331 kw("delete", { beforeExpr: true, prefix: true, startsExpr: true });
1332
1333 // Matches a whole line break (where CRLF is considered a single
1334 // line break). Used to count lines.
1335
1336 var lineBreak = /\r\n?|\n|\u2028|\u2029/;
1337 var lineBreakG = new RegExp(lineBreak.source, "g");
1338
1339 function isNewLine(code) {
1340 return code === 10 || code === 13 || code === 0x2028 || code == 0x2029;
1341 }
1342
1343 var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
1344
1345 function isArray$1(obj) {
1346 return Object.prototype.toString.call(obj) === "[object Array]";
1347 }
1348
1349 // Checks if an object has a property.
1350
1351 function has(obj, propName) {
1352 return Object.prototype.hasOwnProperty.call(obj, propName);
1353 }
1354
1355 // These are used when `options.locations` is on, for the
1356 // `startLoc` and `endLoc` properties.
1357
1358 var Position = (function () {
1359 function Position(line, col) {
1360 babelHelpers.classCallCheck(this, Position);
1361
1362 this.line = line;
1363 this.column = col;
1364 }
1365
1366 Position.prototype.offset = function offset(n) {
1367 return new Position(this.line, this.column + n);
1368 };
1369
1370 return Position;
1371 })();
1372
1373 var SourceLocation = function SourceLocation(p, start, end) {
1374 babelHelpers.classCallCheck(this, SourceLocation);
1375
1376 this.start = start;
1377 this.end = end;
1378 if (p.sourceFile !== null) this.source = p.sourceFile;
1379 }
1380
1381 // The `getLineInfo` function is mostly useful when the
1382 // `locations` option is off (for performance reasons) and you
1383 // want to find the line/column position for a given character
1384 // offset. `input` should be the code string that the offset refers
1385 // into.
1386
1387 ;
1388
1389 function getLineInfo(input, offset) {
1390 for (var line = 1, cur = 0;;) {
1391 lineBreakG.lastIndex = cur;
1392 var match = lineBreakG.exec(input);
1393 if (match && match.index < offset) {
1394 ++line;
1395 cur = match.index + match[0].length;
1396 } else {
1397 return new Position(line, offset - cur);
1398 }
1399 }
1400 }
1401
1402 // A second optional argument can be given to further configure
1403 // the parser process. These options are recognized:
1404
1405 var defaultOptions = {
1406 // `ecmaVersion` indicates the ECMAScript version to parse. Must
1407 // be either 3, or 5, or 6. This influences support for strict
1408 // mode, the set of reserved words, support for getters and
1409 // setters and other features.
1410 ecmaVersion: 5,
1411 // Source type ("script" or "module") for different semantics
1412 sourceType: "script",
1413 // `onInsertedSemicolon` can be a callback that will be called
1414 // when a semicolon is automatically inserted. It will be passed
1415 // th position of the comma as an offset, and if `locations` is
1416 // enabled, it is given the location as a `{line, column}` object
1417 // as second argument.
1418 onInsertedSemicolon: null,
1419 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
1420 // trailing commas.
1421 onTrailingComma: null,
1422 // By default, reserved words are only enforced if ecmaVersion >= 5.
1423 // Set `allowReserved` to a boolean value to explicitly turn this on
1424 // an off. When this option has the value "never", reserved words
1425 // and keywords can also not be used as property names.
1426 allowReserved: null,
1427 // When enabled, a return at the top level is not considered an
1428 // error.
1429 allowReturnOutsideFunction: false,
1430 // When enabled, import/export statements are not constrained to
1431 // appearing at the top of the program.
1432 allowImportExportEverywhere: false,
1433 // When enabled, hashbang directive in the beginning of file
1434 // is allowed and treated as a line comment.
1435 allowHashBang: false,
1436 // When `locations` is on, `loc` properties holding objects with
1437 // `start` and `end` properties in `{line, column}` form (with
1438 // line being 1-based and column 0-based) will be attached to the
1439 // nodes.
1440 locations: false,
1441 // A function can be passed as `onToken` option, which will
1442 // cause Acorn to call that function with object in the same
1443 // format as tokens returned from `tokenizer().getToken()`. Note
1444 // that you are not allowed to call the parser from the
1445 // callback—that will corrupt its internal state.
1446 onToken: null,
1447 // A function can be passed as `onComment` option, which will
1448 // cause Acorn to call that function with `(block, text, start,
1449 // end)` parameters whenever a comment is skipped. `block` is a
1450 // boolean indicating whether this is a block (`/* */`) comment,
1451 // `text` is the content of the comment, and `start` and `end` are
1452 // character offsets that denote the start and end of the comment.
1453 // When the `locations` option is on, two more parameters are
1454 // passed, the full `{line, column}` locations of the start and
1455 // end of the comments. Note that you are not allowed to call the
1456 // parser from the callback—that will corrupt its internal state.
1457 onComment: null,
1458 // Nodes have their start and end characters offsets recorded in
1459 // `start` and `end` properties (directly on the node, rather than
1460 // the `loc` object, which holds line/column data. To also add a
1461 // [semi-standardized][range] `range` property holding a `[start,
1462 // end]` array with the same numbers, set the `ranges` option to
1463 // `true`.
1464 //
1465 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
1466 ranges: false,
1467 // It is possible to parse multiple files into a single AST by
1468 // passing the tree produced by parsing the first file as
1469 // `program` option in subsequent parses. This will add the
1470 // toplevel forms of the parsed file to the `Program` (top) node
1471 // of an existing parse tree.
1472 program: null,
1473 // When `locations` is on, you can pass this to record the source
1474 // file in every node's `loc` object.
1475 sourceFile: null,
1476 // This value, if given, is stored in every node, whether
1477 // `locations` is on or off.
1478 directSourceFile: null,
1479 // When enabled, parenthesized expressions are represented by
1480 // (non-standard) ParenthesizedExpression nodes
1481 preserveParens: false,
1482 plugins: {}
1483 };
1484
1485 // Interpret and default an options object
1486
1487 function getOptions(opts) {
1488 var options = {};
1489 for (var opt in defaultOptions) {
1490 options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt];
1491 }if (options.allowReserved == null) options.allowReserved = options.ecmaVersion < 5;
1492
1493 if (isArray$1(options.onToken)) {
1494 (function () {
1495 var tokens = options.onToken;
1496 options.onToken = function (token) {
1497 return tokens.push(token);
1498 };
1499 })();
1500 }
1501 if (isArray$1(options.onComment)) options.onComment = pushComment(options, options.onComment);
1502
1503 return options;
1504 }
1505
1506 function pushComment(options, array) {
1507 return function (block, text, start, end, startLoc, endLoc) {
1508 var comment = {
1509 type: block ? 'Block' : 'Line',
1510 value: text,
1511 start: start,
1512 end: end
1513 };
1514 if (options.locations) comment.loc = new SourceLocation(this, startLoc, endLoc);
1515 if (options.ranges) comment.range = [start, end];
1516 array.push(comment);
1517 };
1518 }
1519
1520 // Registered plugins
1521 var plugins = {};
1522
1523 function keywordRegexp(words) {
1524 return new RegExp("^(" + words.replace(/ /g, "|") + ")$");
1525 }
1526
1527 var Parser = (function () {
1528 function Parser(options, input, startPos) {
1529 babelHelpers.classCallCheck(this, Parser);
1530
1531 this.options = options = getOptions(options);
1532 this.sourceFile = options.sourceFile;
1533 this.keywords = keywordRegexp(keywords[options.ecmaVersion >= 6 ? 6 : 5]);
1534 var reserved = options.allowReserved ? "" : reservedWords$1[options.ecmaVersion] + (options.sourceType == "module" ? " await" : "");
1535 this.reservedWords = keywordRegexp(reserved);
1536 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$1.strict;
1537 this.reservedWordsStrict = keywordRegexp(reservedStrict);
1538 this.reservedWordsStrictBind = keywordRegexp(reservedStrict + " " + reservedWords$1.strictBind);
1539 this.input = String(input);
1540
1541 // Used to signal to callers of `readWord1` whether the word
1542 // contained any escape sequences. This is needed because words with
1543 // escape sequences must not be interpreted as keywords.
1544 this.containsEsc = false;
1545
1546 // Load plugins
1547 this.loadPlugins(options.plugins);
1548
1549 // Set up token state
1550
1551 // The current position of the tokenizer in the input.
1552 if (startPos) {
1553 this.pos = startPos;
1554 this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos));
1555 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
1556 } else {
1557 this.pos = this.lineStart = 0;
1558 this.curLine = 1;
1559 }
1560
1561 // Properties of the current token:
1562 // Its type
1563 this.type = tt.eof;
1564 // For tokens that include more information than their type, the value
1565 this.value = null;
1566 // Its start and end offset
1567 this.start = this.end = this.pos;
1568 // And, if locations are used, the {line, column} object
1569 // corresponding to those offsets
1570 this.startLoc = this.endLoc = this.curPosition();
1571
1572 // Position information for the previous token
1573 this.lastTokEndLoc = this.lastTokStartLoc = null;
1574 this.lastTokStart = this.lastTokEnd = this.pos;
1575
1576 // The context stack is used to superficially track syntactic
1577 // context to predict whether a regular expression is allowed in a
1578 // given position.
1579 this.context = this.initialContext();
1580 this.exprAllowed = true;
1581
1582 // Figure out if it's a module code.
1583 this.strict = this.inModule = options.sourceType === "module";
1584
1585 // Used to signify the start of a potential arrow function
1586 this.potentialArrowAt = -1;
1587
1588 // Flags to track whether we are in a function, a generator.
1589 this.inFunction = this.inGenerator = false;
1590 // Labels in scope.
1591 this.labels = [];
1592
1593 // If enabled, skip leading hashbang line.
1594 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === '#!') this.skipLineComment(2);
1595 }
1596
1597 // DEPRECATED Kept for backwards compatibility until 3.0 in case a plugin uses them
1598
1599 Parser.prototype.isKeyword = function isKeyword(word) {
1600 return this.keywords.test(word);
1601 };
1602
1603 Parser.prototype.isReservedWord = function isReservedWord(word) {
1604 return this.reservedWords.test(word);
1605 };
1606
1607 Parser.prototype.extend = function extend(name, f) {
1608 this[name] = f(this[name]);
1609 };
1610
1611 Parser.prototype.loadPlugins = function loadPlugins(pluginConfigs) {
1612 for (var _name in pluginConfigs) {
1613 var plugin = plugins[_name];
1614 if (!plugin) throw new Error("Plugin '" + _name + "' not found");
1615 plugin(this, pluginConfigs[_name]);
1616 }
1617 };
1618
1619 Parser.prototype.parse = function parse() {
1620 var node = this.options.program || this.startNode();
1621 this.nextToken();
1622 return this.parseTopLevel(node);
1623 };
1624
1625 return Parser;
1626 })();
1627
1628 var pp = Parser.prototype;
1629
1630 // ## Parser utilities
1631
1632 // Test whether a statement node is the string literal `"use strict"`.
1633
1634 pp.isUseStrict = function (stmt) {
1635 return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.raw.slice(1, -1) === "use strict";
1636 };
1637
1638 // Predicate that tests whether the next token is of the given
1639 // type, and if yes, consumes it as a side effect.
1640
1641 pp.eat = function (type) {
1642 if (this.type === type) {
1643 this.next();
1644 return true;
1645 } else {
1646 return false;
1647 }
1648 };
1649
1650 // Tests whether parsed token is a contextual keyword.
1651
1652 pp.isContextual = function (name) {
1653 return this.type === tt.name && this.value === name;
1654 };
1655
1656 // Consumes contextual keyword if possible.
1657
1658 pp.eatContextual = function (name) {
1659 return this.value === name && this.eat(tt.name);
1660 };
1661
1662 // Asserts that following token is given contextual keyword.
1663
1664 pp.expectContextual = function (name) {
1665 if (!this.eatContextual(name)) this.unexpected();
1666 };
1667
1668 // Test whether a semicolon can be inserted at the current position.
1669
1670 pp.canInsertSemicolon = function () {
1671 return this.type === tt.eof || this.type === tt.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
1672 };
1673
1674 pp.insertSemicolon = function () {
1675 if (this.canInsertSemicolon()) {
1676 if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
1677 return true;
1678 }
1679 };
1680
1681 // Consume a semicolon, or, failing that, see if we are allowed to
1682 // pretend that there is a semicolon at this position.
1683
1684 pp.semicolon = function () {
1685 if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected();
1686 };
1687
1688 pp.afterTrailingComma = function (tokType) {
1689 if (this.type == tokType) {
1690 if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
1691 this.next();
1692 return true;
1693 }
1694 };
1695
1696 // Expect a token of a given type. If found, consume it, otherwise,
1697 // raise an unexpected token error.
1698
1699 pp.expect = function (type) {
1700 this.eat(type) || this.unexpected();
1701 };
1702
1703 // Raise an unexpected token error.
1704
1705 pp.unexpected = function (pos) {
1706 this.raise(pos != null ? pos : this.start, "Unexpected token");
1707 };
1708
1709 pp.checkPatternErrors = function (refDestructuringErrors, andThrow) {
1710 var pos = refDestructuringErrors && refDestructuringErrors.trailingComma;
1711 if (!andThrow) return !!pos;
1712 if (pos) this.raise(pos, "Trailing comma is not permitted in destructuring patterns");
1713 };
1714
1715 pp.checkExpressionErrors = function (refDestructuringErrors, andThrow) {
1716 var pos = refDestructuringErrors && refDestructuringErrors.shorthandAssign;
1717 if (!andThrow) return !!pos;
1718 if (pos) this.raise(pos, "Shorthand property assignments are valid only in destructuring patterns");
1719 };
1720
1721 var pp$1 = Parser.prototype;
1722
1723 // ### Statement parsing
1724
1725 // Parse a program. Initializes the parser, reads any number of
1726 // statements, and wraps them in a Program node. Optionally takes a
1727 // `program` argument. If present, the statements will be appended
1728 // to its body instead of creating a new node.
1729
1730 pp$1.parseTopLevel = function (node) {
1731 var first = true;
1732 if (!node.body) node.body = [];
1733 while (this.type !== tt.eof) {
1734 var stmt = this.parseStatement(true, true);
1735 node.body.push(stmt);
1736 if (first) {
1737 if (this.isUseStrict(stmt)) this.setStrict(true);
1738 first = false;
1739 }
1740 }
1741 this.next();
1742 if (this.options.ecmaVersion >= 6) {
1743 node.sourceType = this.options.sourceType;
1744 }
1745 return this.finishNode(node, "Program");
1746 };
1747
1748 var loopLabel = { kind: "loop" };
1749 var switchLabel = { kind: "switch" };
1750 // Parse a single statement.
1751 //
1752 // If expecting a statement and finding a slash operator, parse a
1753 // regular expression literal. This is to handle cases like
1754 // `if (foo) /blah/.exec(foo)`, where looking at the previous token
1755 // does not help.
1756
1757 pp$1.parseStatement = function (declaration, topLevel) {
1758 var starttype = this.type,
1759 node = this.startNode();
1760
1761 // Most types of statements are recognized by the keyword they
1762 // start with. Many are trivial to parse, some require a bit of
1763 // complexity.
1764
1765 switch (starttype) {
1766 case tt._break:case tt._continue:
1767 return this.parseBreakContinueStatement(node, starttype.keyword);
1768 case tt._debugger:
1769 return this.parseDebuggerStatement(node);
1770 case tt._do:
1771 return this.parseDoStatement(node);
1772 case tt._for:
1773 return this.parseForStatement(node);
1774 case tt._function:
1775 if (!declaration && this.options.ecmaVersion >= 6) this.unexpected();
1776 return this.parseFunctionStatement(node);
1777 case tt._class:
1778 if (!declaration) this.unexpected();
1779 return this.parseClass(node, true);
1780 case tt._if:
1781 return this.parseIfStatement(node);
1782 case tt._return:
1783 return this.parseReturnStatement(node);
1784 case tt._switch:
1785 return this.parseSwitchStatement(node);
1786 case tt._throw:
1787 return this.parseThrowStatement(node);
1788 case tt._try:
1789 return this.parseTryStatement(node);
1790 case tt._let:case tt._const:
1791 if (!declaration) this.unexpected(); // NOTE: falls through to _var
1792 case tt._var:
1793 return this.parseVarStatement(node, starttype);
1794 case tt._while:
1795 return this.parseWhileStatement(node);
1796 case tt._with:
1797 return this.parseWithStatement(node);
1798 case tt.braceL:
1799 return this.parseBlock();
1800 case tt.semi:
1801 return this.parseEmptyStatement(node);
1802 case tt._export:
1803 case tt._import:
1804 if (!this.options.allowImportExportEverywhere) {
1805 if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level");
1806 if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
1807 }
1808 return starttype === tt._import ? this.parseImport(node) : this.parseExport(node);
1809
1810 // If the statement does not start with a statement keyword or a
1811 // brace, it's an ExpressionStatement or LabeledStatement. We
1812 // simply start parsing an expression, and afterwards, if the
1813 // next token is a colon and the expression was a simple
1814 // Identifier node, we switch to interpreting it as a label.
1815 default:
1816 var maybeName = this.value,
1817 expr = this.parseExpression();
1818 if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) return this.parseLabeledStatement(node, maybeName, expr);else return this.parseExpressionStatement(node, expr);
1819 }
1820 };
1821
1822 pp$1.parseBreakContinueStatement = function (node, keyword) {
1823 var isBreak = keyword == "break";
1824 this.next();
1825 if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null;else if (this.type !== tt.name) this.unexpected();else {
1826 node.label = this.parseIdent();
1827 this.semicolon();
1828 }
1829
1830 // Verify that there is an actual destination to break or
1831 // continue to.
1832 for (var i = 0; i < this.labels.length; ++i) {
1833 var lab = this.labels[i];
1834 if (node.label == null || lab.name === node.label.name) {
1835 if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
1836 if (node.label && isBreak) break;
1837 }
1838 }
1839 if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
1840 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
1841 };
1842
1843 pp$1.parseDebuggerStatement = function (node) {
1844 this.next();
1845 this.semicolon();
1846 return this.finishNode(node, "DebuggerStatement");
1847 };
1848
1849 pp$1.parseDoStatement = function (node) {
1850 this.next();
1851 this.labels.push(loopLabel);
1852 node.body = this.parseStatement(false);
1853 this.labels.pop();
1854 this.expect(tt._while);
1855 node.test = this.parseParenExpression();
1856 if (this.options.ecmaVersion >= 6) this.eat(tt.semi);else this.semicolon();
1857 return this.finishNode(node, "DoWhileStatement");
1858 };
1859
1860 // Disambiguating between a `for` and a `for`/`in` or `for`/`of`
1861 // loop is non-trivial. Basically, we have to parse the init `var`
1862 // statement or expression, disallowing the `in` operator (see
1863 // the second parameter to `parseExpression`), and then check
1864 // whether the next token is `in` or `of`. When there is no init
1865 // part (semicolon immediately after the opening parenthesis), it
1866 // is a regular `for` loop.
1867
1868 pp$1.parseForStatement = function (node) {
1869 this.next();
1870 this.labels.push(loopLabel);
1871 this.expect(tt.parenL);
1872 if (this.type === tt.semi) return this.parseFor(node, null);
1873 if (this.type === tt._var || this.type === tt._let || this.type === tt._const) {
1874 var _init = this.startNode(),
1875 varKind = this.type;
1876 this.next();
1877 this.parseVar(_init, true, varKind);
1878 this.finishNode(_init, "VariableDeclaration");
1879 if ((this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) && _init.declarations.length === 1 && !(varKind !== tt._var && _init.declarations[0].init)) return this.parseForIn(node, _init);
1880 return this.parseFor(node, _init);
1881 }
1882 var refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 };
1883 var init = this.parseExpression(true, refDestructuringErrors);
1884 if (this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
1885 this.checkPatternErrors(refDestructuringErrors, true);
1886 this.toAssignable(init);
1887 this.checkLVal(init);
1888 return this.parseForIn(node, init);
1889 } else {
1890 this.checkExpressionErrors(refDestructuringErrors, true);
1891 }
1892 return this.parseFor(node, init);
1893 };
1894
1895 pp$1.parseFunctionStatement = function (node) {
1896 this.next();
1897 return this.parseFunction(node, true);
1898 };
1899
1900 pp$1.parseIfStatement = function (node) {
1901 this.next();
1902 node.test = this.parseParenExpression();
1903 node.consequent = this.parseStatement(false);
1904 node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null;
1905 return this.finishNode(node, "IfStatement");
1906 };
1907
1908 pp$1.parseReturnStatement = function (node) {
1909 if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function");
1910 this.next();
1911
1912 // In `return` (and `break`/`continue`), the keywords with
1913 // optional arguments, we eagerly look for a semicolon or the
1914 // possibility to insert one.
1915
1916 if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null;else {
1917 node.argument = this.parseExpression();this.semicolon();
1918 }
1919 return this.finishNode(node, "ReturnStatement");
1920 };
1921
1922 pp$1.parseSwitchStatement = function (node) {
1923 this.next();
1924 node.discriminant = this.parseParenExpression();
1925 node.cases = [];
1926 this.expect(tt.braceL);
1927 this.labels.push(switchLabel);
1928
1929 // Statements under must be grouped (by label) in SwitchCase
1930 // nodes. `cur` is used to keep the node that we are currently
1931 // adding statements to.
1932
1933 for (var cur, sawDefault = false; this.type != tt.braceR;) {
1934 if (this.type === tt._case || this.type === tt._default) {
1935 var isCase = this.type === tt._case;
1936 if (cur) this.finishNode(cur, "SwitchCase");
1937 node.cases.push(cur = this.startNode());
1938 cur.consequent = [];
1939 this.next();
1940 if (isCase) {
1941 cur.test = this.parseExpression();
1942 } else {
1943 if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses");
1944 sawDefault = true;
1945 cur.test = null;
1946 }
1947 this.expect(tt.colon);
1948 } else {
1949 if (!cur) this.unexpected();
1950 cur.consequent.push(this.parseStatement(true));
1951 }
1952 }
1953 if (cur) this.finishNode(cur, "SwitchCase");
1954 this.next(); // Closing brace
1955 this.labels.pop();
1956 return this.finishNode(node, "SwitchStatement");
1957 };
1958
1959 pp$1.parseThrowStatement = function (node) {
1960 this.next();
1961 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw");
1962 node.argument = this.parseExpression();
1963 this.semicolon();
1964 return this.finishNode(node, "ThrowStatement");
1965 };
1966
1967 // Reused empty array added for node fields that are always empty.
1968
1969 var empty = [];
1970
1971 pp$1.parseTryStatement = function (node) {
1972 this.next();
1973 node.block = this.parseBlock();
1974 node.handler = null;
1975 if (this.type === tt._catch) {
1976 var clause = this.startNode();
1977 this.next();
1978 this.expect(tt.parenL);
1979 clause.param = this.parseBindingAtom();
1980 this.checkLVal(clause.param, true);
1981 this.expect(tt.parenR);
1982 clause.body = this.parseBlock();
1983 node.handler = this.finishNode(clause, "CatchClause");
1984 }
1985 node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
1986 if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause");
1987 return this.finishNode(node, "TryStatement");
1988 };
1989
1990 pp$1.parseVarStatement = function (node, kind) {
1991 this.next();
1992 this.parseVar(node, false, kind);
1993 this.semicolon();
1994 return this.finishNode(node, "VariableDeclaration");
1995 };
1996
1997 pp$1.parseWhileStatement = function (node) {
1998 this.next();
1999 node.test = this.parseParenExpression();
2000 this.labels.push(loopLabel);
2001 node.body = this.parseStatement(false);
2002 this.labels.pop();
2003 return this.finishNode(node, "WhileStatement");
2004 };
2005
2006 pp$1.parseWithStatement = function (node) {
2007 if (this.strict) this.raise(this.start, "'with' in strict mode");
2008 this.next();
2009 node.object = this.parseParenExpression();
2010 node.body = this.parseStatement(false);
2011 return this.finishNode(node, "WithStatement");
2012 };
2013
2014 pp$1.parseEmptyStatement = function (node) {
2015 this.next();
2016 return this.finishNode(node, "EmptyStatement");
2017 };
2018
2019 pp$1.parseLabeledStatement = function (node, maybeName, expr) {
2020 for (var i = 0; i < this.labels.length; ++i) {
2021 if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared");
2022 }var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null;
2023 for (var i = this.labels.length - 1; i >= 0; i--) {
2024 var label = this.labels[i];
2025 if (label.statementStart == node.start) {
2026 label.statementStart = this.start;
2027 label.kind = kind;
2028 } else break;
2029 }
2030 this.labels.push({ name: maybeName, kind: kind, statementStart: this.start });
2031 node.body = this.parseStatement(true);
2032 this.labels.pop();
2033 node.label = expr;
2034 return this.finishNode(node, "LabeledStatement");
2035 };
2036
2037 pp$1.parseExpressionStatement = function (node, expr) {
2038 node.expression = expr;
2039 this.semicolon();
2040 return this.finishNode(node, "ExpressionStatement");
2041 };
2042
2043 // Parse a semicolon-enclosed block of statements, handling `"use
2044 // strict"` declarations when `allowStrict` is true (used for
2045 // function bodies).
2046
2047 pp$1.parseBlock = function (allowStrict) {
2048 var node = this.startNode(),
2049 first = true,
2050 oldStrict = undefined;
2051 node.body = [];
2052 this.expect(tt.braceL);
2053 while (!this.eat(tt.braceR)) {
2054 var stmt = this.parseStatement(true);
2055 node.body.push(stmt);
2056 if (first && allowStrict && this.isUseStrict(stmt)) {
2057 oldStrict = this.strict;
2058 this.setStrict(this.strict = true);
2059 }
2060 first = false;
2061 }
2062 if (oldStrict === false) this.setStrict(false);
2063 return this.finishNode(node, "BlockStatement");
2064 };
2065
2066 // Parse a regular `for` loop. The disambiguation code in
2067 // `parseStatement` will already have parsed the init statement or
2068 // expression.
2069
2070 pp$1.parseFor = function (node, init) {
2071 node.init = init;
2072 this.expect(tt.semi);
2073 node.test = this.type === tt.semi ? null : this.parseExpression();
2074 this.expect(tt.semi);
2075 node.update = this.type === tt.parenR ? null : this.parseExpression();
2076 this.expect(tt.parenR);
2077 node.body = this.parseStatement(false);
2078 this.labels.pop();
2079 return this.finishNode(node, "ForStatement");
2080 };
2081
2082 // Parse a `for`/`in` and `for`/`of` loop, which are almost
2083 // same from parser's perspective.
2084
2085 pp$1.parseForIn = function (node, init) {
2086 var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement";
2087 this.next();
2088 node.left = init;
2089 node.right = this.parseExpression();
2090 this.expect(tt.parenR);
2091 node.body = this.parseStatement(false);
2092 this.labels.pop();
2093 return this.finishNode(node, type);
2094 };
2095
2096 // Parse a list of variable declarations.
2097
2098 pp$1.parseVar = function (node, isFor, kind) {
2099 node.declarations = [];
2100 node.kind = kind.keyword;
2101 for (;;) {
2102 var decl = this.startNode();
2103 this.parseVarId(decl);
2104 if (this.eat(tt.eq)) {
2105 decl.init = this.parseMaybeAssign(isFor);
2106 } else if (kind === tt._const && !(this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
2107 this.unexpected();
2108 } else if (decl.id.type != "Identifier" && !(isFor && (this.type === tt._in || this.isContextual("of")))) {
2109 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
2110 } else {
2111 decl.init = null;
2112 }
2113 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
2114 if (!this.eat(tt.comma)) break;
2115 }
2116 return node;
2117 };
2118
2119 pp$1.parseVarId = function (decl) {
2120 decl.id = this.parseBindingAtom();
2121 this.checkLVal(decl.id, true);
2122 };
2123
2124 // Parse a function declaration or literal (depending on the
2125 // `isStatement` parameter).
2126
2127 pp$1.parseFunction = function (node, isStatement, allowExpressionBody) {
2128 this.initFunction(node);
2129 if (this.options.ecmaVersion >= 6) node.generator = this.eat(tt.star);
2130 if (isStatement || this.type === tt.name) node.id = this.parseIdent();
2131 this.parseFunctionParams(node);
2132 this.parseFunctionBody(node, allowExpressionBody);
2133 return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
2134 };
2135
2136 pp$1.parseFunctionParams = function (node) {
2137 this.expect(tt.parenL);
2138 node.params = this.parseBindingList(tt.parenR, false, false, true);
2139 };
2140
2141 // Parse a class declaration or literal (depending on the
2142 // `isStatement` parameter).
2143
2144 pp$1.parseClass = function (node, isStatement) {
2145 this.next();
2146 this.parseClassId(node, isStatement);
2147 this.parseClassSuper(node);
2148 var classBody = this.startNode();
2149 var hadConstructor = false;
2150 classBody.body = [];
2151 this.expect(tt.braceL);
2152 while (!this.eat(tt.braceR)) {
2153 if (this.eat(tt.semi)) continue;
2154 var method = this.startNode();
2155 var isGenerator = this.eat(tt.star);
2156 var isMaybeStatic = this.type === tt.name && this.value === "static";
2157 this.parsePropertyName(method);
2158 method.static = isMaybeStatic && this.type !== tt.parenL;
2159 if (method.static) {
2160 if (isGenerator) this.unexpected();
2161 isGenerator = this.eat(tt.star);
2162 this.parsePropertyName(method);
2163 }
2164 method.kind = "method";
2165 var isGetSet = false;
2166 if (!method.computed) {
2167 var key = method.key;
2168
2169 if (!isGenerator && key.type === "Identifier" && this.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
2170 isGetSet = true;
2171 method.kind = key.name;
2172 key = this.parsePropertyName(method);
2173 }
2174 if (!method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
2175 if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class");
2176 if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier");
2177 if (isGenerator) this.raise(key.start, "Constructor can't be a generator");
2178 method.kind = "constructor";
2179 hadConstructor = true;
2180 }
2181 }
2182 this.parseClassMethod(classBody, method, isGenerator);
2183 if (isGetSet) {
2184 var paramCount = method.kind === "get" ? 0 : 1;
2185 if (method.value.params.length !== paramCount) {
2186 var start = method.value.start;
2187 if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
2188 }
2189 }
2190 }
2191 node.body = this.finishNode(classBody, "ClassBody");
2192 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
2193 };
2194
2195 pp$1.parseClassMethod = function (classBody, method, isGenerator) {
2196 method.value = this.parseMethod(isGenerator);
2197 classBody.body.push(this.finishNode(method, "MethodDefinition"));
2198 };
2199
2200 pp$1.parseClassId = function (node, isStatement) {
2201 node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null;
2202 };
2203
2204 pp$1.parseClassSuper = function (node) {
2205 node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null;
2206 };
2207
2208 // Parses module export declaration.
2209
2210 pp$1.parseExport = function (node) {
2211 this.next();
2212 // export * from '...'
2213 if (this.eat(tt.star)) {
2214 this.expectContextual("from");
2215 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2216 this.semicolon();
2217 return this.finishNode(node, "ExportAllDeclaration");
2218 }
2219 if (this.eat(tt._default)) {
2220 // export default ...
2221 var expr = this.parseMaybeAssign();
2222 var needsSemi = true;
2223 if (expr.type == "FunctionExpression" || expr.type == "ClassExpression") {
2224 needsSemi = false;
2225 if (expr.id) {
2226 expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration";
2227 }
2228 }
2229 node.declaration = expr;
2230 if (needsSemi) this.semicolon();
2231 return this.finishNode(node, "ExportDefaultDeclaration");
2232 }
2233 // export var|const|let|function|class ...
2234 if (this.shouldParseExportStatement()) {
2235 node.declaration = this.parseStatement(true);
2236 node.specifiers = [];
2237 node.source = null;
2238 } else {
2239 // export { x, y as z } [from '...']
2240 node.declaration = null;
2241 node.specifiers = this.parseExportSpecifiers();
2242 if (this.eatContextual("from")) {
2243 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2244 } else {
2245 // check for keywords used as local names
2246 for (var i = 0; i < node.specifiers.length; i++) {
2247 if (this.keywords.test(node.specifiers[i].local.name) || this.reservedWords.test(node.specifiers[i].local.name)) {
2248 this.unexpected(node.specifiers[i].local.start);
2249 }
2250 }
2251
2252 node.source = null;
2253 }
2254 this.semicolon();
2255 }
2256 return this.finishNode(node, "ExportNamedDeclaration");
2257 };
2258
2259 pp$1.shouldParseExportStatement = function () {
2260 return this.type.keyword;
2261 };
2262
2263 // Parses a comma-separated list of module exports.
2264
2265 pp$1.parseExportSpecifiers = function () {
2266 var nodes = [],
2267 first = true;
2268 // export { x, y as z } [from '...']
2269 this.expect(tt.braceL);
2270 while (!this.eat(tt.braceR)) {
2271 if (!first) {
2272 this.expect(tt.comma);
2273 if (this.afterTrailingComma(tt.braceR)) break;
2274 } else first = false;
2275
2276 var node = this.startNode();
2277 node.local = this.parseIdent(this.type === tt._default);
2278 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
2279 nodes.push(this.finishNode(node, "ExportSpecifier"));
2280 }
2281 return nodes;
2282 };
2283
2284 // Parses import declaration.
2285
2286 pp$1.parseImport = function (node) {
2287 this.next();
2288 // import '...'
2289 if (this.type === tt.string) {
2290 node.specifiers = empty;
2291 node.source = this.parseExprAtom();
2292 } else {
2293 node.specifiers = this.parseImportSpecifiers();
2294 this.expectContextual("from");
2295 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
2296 }
2297 this.semicolon();
2298 return this.finishNode(node, "ImportDeclaration");
2299 };
2300
2301 // Parses a comma-separated list of module imports.
2302
2303 pp$1.parseImportSpecifiers = function () {
2304 var nodes = [],
2305 first = true;
2306 if (this.type === tt.name) {
2307 // import defaultObj, { x, y as z } from '...'
2308 var node = this.startNode();
2309 node.local = this.parseIdent();
2310 this.checkLVal(node.local, true);
2311 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
2312 if (!this.eat(tt.comma)) return nodes;
2313 }
2314 if (this.type === tt.star) {
2315 var node = this.startNode();
2316 this.next();
2317 this.expectContextual("as");
2318 node.local = this.parseIdent();
2319 this.checkLVal(node.local, true);
2320 nodes.push(this.finishNode(node, "ImportNamespaceSpecifier"));
2321 return nodes;
2322 }
2323 this.expect(tt.braceL);
2324 while (!this.eat(tt.braceR)) {
2325 if (!first) {
2326 this.expect(tt.comma);
2327 if (this.afterTrailingComma(tt.braceR)) break;
2328 } else first = false;
2329
2330 var node = this.startNode();
2331 node.imported = this.parseIdent(true);
2332 node.local = this.eatContextual("as") ? this.parseIdent() : node.imported;
2333 this.checkLVal(node.local, true);
2334 nodes.push(this.finishNode(node, "ImportSpecifier"));
2335 }
2336 return nodes;
2337 };
2338
2339 var pp$2 = Parser.prototype;
2340
2341 // Convert existing expression atom to assignable pattern
2342 // if possible.
2343
2344 pp$2.toAssignable = function (node, isBinding) {
2345 if (this.options.ecmaVersion >= 6 && node) {
2346 switch (node.type) {
2347 case "Identifier":
2348 case "ObjectPattern":
2349 case "ArrayPattern":
2350 break;
2351
2352 case "ObjectExpression":
2353 node.type = "ObjectPattern";
2354 for (var i = 0; i < node.properties.length; i++) {
2355 var prop = node.properties[i];
2356 if (prop.kind !== "init") this.raise(prop.key.start, "Object pattern can't contain getter or setter");
2357 this.toAssignable(prop.value, isBinding);
2358 }
2359 break;
2360
2361 case "ArrayExpression":
2362 node.type = "ArrayPattern";
2363 this.toAssignableList(node.elements, isBinding);
2364 break;
2365
2366 case "AssignmentExpression":
2367 if (node.operator === "=") {
2368 node.type = "AssignmentPattern";
2369 delete node.operator;
2370 // falls through to AssignmentPattern
2371 } else {
2372 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
2373 break;
2374 }
2375
2376 case "AssignmentPattern":
2377 if (node.right.type === "YieldExpression") this.raise(node.right.start, "Yield expression cannot be a default value");
2378 break;
2379
2380 case "ParenthesizedExpression":
2381 node.expression = this.toAssignable(node.expression, isBinding);
2382 break;
2383
2384 case "MemberExpression":
2385 if (!isBinding) break;
2386
2387 default:
2388 this.raise(node.start, "Assigning to rvalue");
2389 }
2390 }
2391 return node;
2392 };
2393
2394 // Convert list of expression atoms to binding list.
2395
2396 pp$2.toAssignableList = function (exprList, isBinding) {
2397 var end = exprList.length;
2398 if (end) {
2399 var last = exprList[end - 1];
2400 if (last && last.type == "RestElement") {
2401 --end;
2402 } else if (last && last.type == "SpreadElement") {
2403 last.type = "RestElement";
2404 var arg = last.argument;
2405 this.toAssignable(arg, isBinding);
2406 if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start);
2407 --end;
2408 }
2409
2410 if (isBinding && last.type === "RestElement" && last.argument.type !== "Identifier") this.unexpected(last.argument.start);
2411 }
2412 for (var i = 0; i < end; i++) {
2413 var elt = exprList[i];
2414 if (elt) this.toAssignable(elt, isBinding);
2415 }
2416 return exprList;
2417 };
2418
2419 // Parses spread element.
2420
2421 pp$2.parseSpread = function (refDestructuringErrors) {
2422 var node = this.startNode();
2423 this.next();
2424 node.argument = this.parseMaybeAssign(refDestructuringErrors);
2425 return this.finishNode(node, "SpreadElement");
2426 };
2427
2428 pp$2.parseRest = function (allowNonIdent) {
2429 var node = this.startNode();
2430 this.next();
2431
2432 // RestElement inside of a function parameter must be an identifier
2433 if (allowNonIdent) node.argument = this.type === tt.name ? this.parseIdent() : this.unexpected();else node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected();
2434
2435 return this.finishNode(node, "RestElement");
2436 };
2437
2438 // Parses lvalue (assignable) atom.
2439
2440 pp$2.parseBindingAtom = function () {
2441 if (this.options.ecmaVersion < 6) return this.parseIdent();
2442 switch (this.type) {
2443 case tt.name:
2444 return this.parseIdent();
2445
2446 case tt.bracketL:
2447 var node = this.startNode();
2448 this.next();
2449 node.elements = this.parseBindingList(tt.bracketR, true, true);
2450 return this.finishNode(node, "ArrayPattern");
2451
2452 case tt.braceL:
2453 return this.parseObj(true);
2454
2455 default:
2456 this.unexpected();
2457 }
2458 };
2459
2460 pp$2.parseBindingList = function (close, allowEmpty, allowTrailingComma, allowNonIdent) {
2461 var elts = [],
2462 first = true;
2463 while (!this.eat(close)) {
2464 if (first) first = false;else this.expect(tt.comma);
2465 if (allowEmpty && this.type === tt.comma) {
2466 elts.push(null);
2467 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
2468 break;
2469 } else if (this.type === tt.ellipsis) {
2470 var rest = this.parseRest(allowNonIdent);
2471 this.parseBindingListItem(rest);
2472 elts.push(rest);
2473 this.expect(close);
2474 break;
2475 } else {
2476 var elem = this.parseMaybeDefault(this.start, this.startLoc);
2477 this.parseBindingListItem(elem);
2478 elts.push(elem);
2479 }
2480 }
2481 return elts;
2482 };
2483
2484 pp$2.parseBindingListItem = function (param) {
2485 return param;
2486 };
2487
2488 // Parses assignment pattern around given atom if possible.
2489
2490 pp$2.parseMaybeDefault = function (startPos, startLoc, left) {
2491 left = left || this.parseBindingAtom();
2492 if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left;
2493 var node = this.startNodeAt(startPos, startLoc);
2494 node.left = left;
2495 node.right = this.parseMaybeAssign();
2496 return this.finishNode(node, "AssignmentPattern");
2497 };
2498
2499 // Verify that a node is an lval — something that can be assigned
2500 // to.
2501
2502 pp$2.checkLVal = function (expr, isBinding, checkClashes) {
2503 switch (expr.type) {
2504 case "Identifier":
2505 if (this.strict && this.reservedWordsStrictBind.test(expr.name)) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
2506 if (checkClashes) {
2507 if (has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash");
2508 checkClashes[expr.name] = true;
2509 }
2510 break;
2511
2512 case "MemberExpression":
2513 if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
2514 break;
2515
2516 case "ObjectPattern":
2517 for (var i = 0; i < expr.properties.length; i++) {
2518 this.checkLVal(expr.properties[i].value, isBinding, checkClashes);
2519 }break;
2520
2521 case "ArrayPattern":
2522 for (var i = 0; i < expr.elements.length; i++) {
2523 var elem = expr.elements[i];
2524 if (elem) this.checkLVal(elem, isBinding, checkClashes);
2525 }
2526 break;
2527
2528 case "AssignmentPattern":
2529 this.checkLVal(expr.left, isBinding, checkClashes);
2530 break;
2531
2532 case "RestElement":
2533 this.checkLVal(expr.argument, isBinding, checkClashes);
2534 break;
2535
2536 case "ParenthesizedExpression":
2537 this.checkLVal(expr.expression, isBinding, checkClashes);
2538 break;
2539
2540 default:
2541 this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue");
2542 }
2543 };
2544
2545 var pp$3 = Parser.prototype;
2546
2547 // Check if property name clashes with already added.
2548 // Object/class getters and setters are not allowed to clash —
2549 // either with each other or with an init property — and in
2550 // strict mode, init properties are also not allowed to be repeated.
2551
2552 pp$3.checkPropClash = function (prop, propHash) {
2553 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return;
2554 var key = prop.key;var name = undefined;
2555 switch (key.type) {
2556 case "Identifier":
2557 name = key.name;break;
2558 case "Literal":
2559 name = String(key.value);break;
2560 default:
2561 return;
2562 }
2563 var kind = prop.kind;
2564
2565 if (this.options.ecmaVersion >= 6) {
2566 if (name === "__proto__" && kind === "init") {
2567 if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
2568 propHash.proto = true;
2569 }
2570 return;
2571 }
2572 name = "$" + name;
2573 var other = propHash[name];
2574 if (other) {
2575 var isGetSet = kind !== "init";
2576 if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property");
2577 } else {
2578 other = propHash[name] = {
2579 init: false,
2580 get: false,
2581 set: false
2582 };
2583 }
2584 other[kind] = true;
2585 };
2586
2587 // ### Expression parsing
2588
2589 // These nest, from the most general expression type at the top to
2590 // 'atomic', nondivisible expression types at the bottom. Most of
2591 // the functions will simply let the function(s) below them parse,
2592 // and, *if* the syntactic construct they handle is present, wrap
2593 // the AST node that the inner parser gave them in another node.
2594
2595 // Parse a full expression. The optional arguments are used to
2596 // forbid the `in` operator (in for loops initalization expressions)
2597 // and provide reference for storing '=' operator inside shorthand
2598 // property assignment in contexts where both object expression
2599 // and object pattern might appear (so it's possible to raise
2600 // delayed syntax error at correct position).
2601
2602 pp$3.parseExpression = function (noIn, refDestructuringErrors) {
2603 var startPos = this.start,
2604 startLoc = this.startLoc;
2605 var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
2606 if (this.type === tt.comma) {
2607 var node = this.startNodeAt(startPos, startLoc);
2608 node.expressions = [expr];
2609 while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors));
2610 return this.finishNode(node, "SequenceExpression");
2611 }
2612 return expr;
2613 };
2614
2615 // Parse an assignment expression. This includes applications of
2616 // operators like `+=`.
2617
2618 pp$3.parseMaybeAssign = function (noIn, refDestructuringErrors, afterLeftParse) {
2619 if (this.type == tt._yield && this.inGenerator) return this.parseYield();
2620
2621 var validateDestructuring = false;
2622 if (!refDestructuringErrors) {
2623 refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 };
2624 validateDestructuring = true;
2625 }
2626 var startPos = this.start,
2627 startLoc = this.startLoc;
2628 if (this.type == tt.parenL || this.type == tt.name) this.potentialArrowAt = this.start;
2629 var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
2630 if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
2631 if (this.type.isAssign) {
2632 if (validateDestructuring) this.checkPatternErrors(refDestructuringErrors, true);
2633 var node = this.startNodeAt(startPos, startLoc);
2634 node.operator = this.value;
2635 node.left = this.type === tt.eq ? this.toAssignable(left) : left;
2636 refDestructuringErrors.shorthandAssign = 0; // reset because shorthand default was used correctly
2637 this.checkLVal(left);
2638 this.next();
2639 node.right = this.parseMaybeAssign(noIn);
2640 return this.finishNode(node, "AssignmentExpression");
2641 } else {
2642 if (validateDestructuring) this.checkExpressionErrors(refDestructuringErrors, true);
2643 }
2644 return left;
2645 };
2646
2647 // Parse a ternary conditional (`?:`) operator.
2648
2649 pp$3.parseMaybeConditional = function (noIn, refDestructuringErrors) {
2650 var startPos = this.start,
2651 startLoc = this.startLoc;
2652 var expr = this.parseExprOps(noIn, refDestructuringErrors);
2653 if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
2654 if (this.eat(tt.question)) {
2655 var node = this.startNodeAt(startPos, startLoc);
2656 node.test = expr;
2657 node.consequent = this.parseMaybeAssign();
2658 this.expect(tt.colon);
2659 node.alternate = this.parseMaybeAssign(noIn);
2660 return this.finishNode(node, "ConditionalExpression");
2661 }
2662 return expr;
2663 };
2664
2665 // Start the precedence parser.
2666
2667 pp$3.parseExprOps = function (noIn, refDestructuringErrors) {
2668 var startPos = this.start,
2669 startLoc = this.startLoc;
2670 var expr = this.parseMaybeUnary(refDestructuringErrors);
2671 if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
2672 return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
2673 };
2674
2675 // Parse binary operators with the operator precedence parsing
2676 // algorithm. `left` is the left-hand side of the operator.
2677 // `minPrec` provides context that allows the function to stop and
2678 // defer further parser to one of its callers when it encounters an
2679 // operator that has a lower precedence than the set it is parsing.
2680
2681 pp$3.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
2682 var prec = this.type.binop;
2683 if (prec != null && (!noIn || this.type !== tt._in)) {
2684 if (prec > minPrec) {
2685 var node = this.startNodeAt(leftStartPos, leftStartLoc);
2686 node.left = left;
2687 node.operator = this.value;
2688 var op = this.type;
2689 this.next();
2690 var startPos = this.start,
2691 startLoc = this.startLoc;
2692 node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
2693 this.finishNode(node, op === tt.logicalOR || op === tt.logicalAND ? "LogicalExpression" : "BinaryExpression");
2694 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
2695 }
2696 }
2697 return left;
2698 };
2699
2700 // Parse unary operators, both prefix and postfix.
2701
2702 pp$3.parseMaybeUnary = function (refDestructuringErrors) {
2703 if (this.type.prefix) {
2704 var node = this.startNode(),
2705 update = this.type === tt.incDec;
2706 node.operator = this.value;
2707 node.prefix = true;
2708 this.next();
2709 node.argument = this.parseMaybeUnary();
2710 this.checkExpressionErrors(refDestructuringErrors, true);
2711 if (update) this.checkLVal(node.argument);else if (this.strict && node.operator === "delete" && node.argument.type === "Identifier") this.raise(node.start, "Deleting local variable in strict mode");
2712 return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
2713 }
2714 var startPos = this.start,
2715 startLoc = this.startLoc;
2716 var expr = this.parseExprSubscripts(refDestructuringErrors);
2717 if (this.checkExpressionErrors(refDestructuringErrors)) return expr;
2718 while (this.type.postfix && !this.canInsertSemicolon()) {
2719 var node = this.startNodeAt(startPos, startLoc);
2720 node.operator = this.value;
2721 node.prefix = false;
2722 node.argument = expr;
2723 this.checkLVal(expr);
2724 this.next();
2725 expr = this.finishNode(node, "UpdateExpression");
2726 }
2727 return expr;
2728 };
2729
2730 // Parse call, dot, and `[]`-subscript expressions.
2731
2732 pp$3.parseExprSubscripts = function (refDestructuringErrors) {
2733 var startPos = this.start,
2734 startLoc = this.startLoc;
2735 var expr = this.parseExprAtom(refDestructuringErrors);
2736 var skipArrowSubscripts = expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")";
2737 if (this.checkExpressionErrors(refDestructuringErrors) || skipArrowSubscripts) return expr;
2738 return this.parseSubscripts(expr, startPos, startLoc);
2739 };
2740
2741 pp$3.parseSubscripts = function (base, startPos, startLoc, noCalls) {
2742 for (;;) {
2743 if (this.eat(tt.dot)) {
2744 var node = this.startNodeAt(startPos, startLoc);
2745 node.object = base;
2746 node.property = this.parseIdent(true);
2747 node.computed = false;
2748 base = this.finishNode(node, "MemberExpression");
2749 } else if (this.eat(tt.bracketL)) {
2750 var node = this.startNodeAt(startPos, startLoc);
2751 node.object = base;
2752 node.property = this.parseExpression();
2753 node.computed = true;
2754 this.expect(tt.bracketR);
2755 base = this.finishNode(node, "MemberExpression");
2756 } else if (!noCalls && this.eat(tt.parenL)) {
2757 var node = this.startNodeAt(startPos, startLoc);
2758 node.callee = base;
2759 node.arguments = this.parseExprList(tt.parenR, false);
2760 base = this.finishNode(node, "CallExpression");
2761 } else if (this.type === tt.backQuote) {
2762 var node = this.startNodeAt(startPos, startLoc);
2763 node.tag = base;
2764 node.quasi = this.parseTemplate();
2765 base = this.finishNode(node, "TaggedTemplateExpression");
2766 } else {
2767 return base;
2768 }
2769 }
2770 };
2771
2772 // Parse an atomic expression — either a single token that is an
2773 // expression, an expression started by a keyword like `function` or
2774 // `new`, or an expression wrapped in punctuation like `()`, `[]`,
2775 // or `{}`.
2776
2777 pp$3.parseExprAtom = function (refDestructuringErrors) {
2778 var node = undefined,
2779 canBeArrow = this.potentialArrowAt == this.start;
2780 switch (this.type) {
2781 case tt._super:
2782 if (!this.inFunction) this.raise(this.start, "'super' outside of function or class");
2783 case tt._this:
2784 var type = this.type === tt._this ? "ThisExpression" : "Super";
2785 node = this.startNode();
2786 this.next();
2787 return this.finishNode(node, type);
2788
2789 case tt._yield:
2790 if (this.inGenerator) this.unexpected();
2791
2792 case tt.name:
2793 var startPos = this.start,
2794 startLoc = this.startLoc;
2795 var id = this.parseIdent(this.type !== tt.name);
2796 if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id]);
2797 return id;
2798
2799 case tt.regexp:
2800 var value = this.value;
2801 node = this.parseLiteral(value.value);
2802 node.regex = { pattern: value.pattern, flags: value.flags };
2803 return node;
2804
2805 case tt.num:case tt.string:
2806 return this.parseLiteral(this.value);
2807
2808 case tt._null:case tt._true:case tt._false:
2809 node = this.startNode();
2810 node.value = this.type === tt._null ? null : this.type === tt._true;
2811 node.raw = this.type.keyword;
2812 this.next();
2813 return this.finishNode(node, "Literal");
2814
2815 case tt.parenL:
2816 return this.parseParenAndDistinguishExpression(canBeArrow);
2817
2818 case tt.bracketL:
2819 node = this.startNode();
2820 this.next();
2821 // check whether this is array comprehension or regular array
2822 if (this.options.ecmaVersion >= 7 && this.type === tt._for) {
2823 return this.parseComprehension(node, false);
2824 }
2825 node.elements = this.parseExprList(tt.bracketR, true, true, refDestructuringErrors);
2826 return this.finishNode(node, "ArrayExpression");
2827
2828 case tt.braceL:
2829 return this.parseObj(false, refDestructuringErrors);
2830
2831 case tt._function:
2832 node = this.startNode();
2833 this.next();
2834 return this.parseFunction(node, false);
2835
2836 case tt._class:
2837 return this.parseClass(this.startNode(), false);
2838
2839 case tt._new:
2840 return this.parseNew();
2841
2842 case tt.backQuote:
2843 return this.parseTemplate();
2844
2845 default:
2846 this.unexpected();
2847 }
2848 };
2849
2850 pp$3.parseLiteral = function (value) {
2851 var node = this.startNode();
2852 node.value = value;
2853 node.raw = this.input.slice(this.start, this.end);
2854 this.next();
2855 return this.finishNode(node, "Literal");
2856 };
2857
2858 pp$3.parseParenExpression = function () {
2859 this.expect(tt.parenL);
2860 var val = this.parseExpression();
2861 this.expect(tt.parenR);
2862 return val;
2863 };
2864
2865 pp$3.parseParenAndDistinguishExpression = function (canBeArrow) {
2866 var startPos = this.start,
2867 startLoc = this.startLoc,
2868 val = undefined;
2869 if (this.options.ecmaVersion >= 6) {
2870 this.next();
2871
2872 if (this.options.ecmaVersion >= 7 && this.type === tt._for) {
2873 return this.parseComprehension(this.startNodeAt(startPos, startLoc), true);
2874 }
2875
2876 var innerStartPos = this.start,
2877 innerStartLoc = this.startLoc;
2878 var exprList = [],
2879 first = true;
2880 var refDestructuringErrors = { shorthandAssign: 0, trailingComma: 0 },
2881 spreadStart = undefined,
2882 innerParenStart = undefined;
2883 while (this.type !== tt.parenR) {
2884 first ? first = false : this.expect(tt.comma);
2885 if (this.type === tt.ellipsis) {
2886 spreadStart = this.start;
2887 exprList.push(this.parseParenItem(this.parseRest()));
2888 break;
2889 } else {
2890 if (this.type === tt.parenL && !innerParenStart) {
2891 innerParenStart = this.start;
2892 }
2893 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
2894 }
2895 }
2896 var innerEndPos = this.start,
2897 innerEndLoc = this.startLoc;
2898 this.expect(tt.parenR);
2899
2900 if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
2901 this.checkPatternErrors(refDestructuringErrors, true);
2902 if (innerParenStart) this.unexpected(innerParenStart);
2903 return this.parseParenArrowList(startPos, startLoc, exprList);
2904 }
2905
2906 if (!exprList.length) this.unexpected(this.lastTokStart);
2907 if (spreadStart) this.unexpected(spreadStart);
2908 this.checkExpressionErrors(refDestructuringErrors, true);
2909
2910 if (exprList.length > 1) {
2911 val = this.startNodeAt(innerStartPos, innerStartLoc);
2912 val.expressions = exprList;
2913 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
2914 } else {
2915 val = exprList[0];
2916 }
2917 } else {
2918 val = this.parseParenExpression();
2919 }
2920
2921 if (this.options.preserveParens) {
2922 var par = this.startNodeAt(startPos, startLoc);
2923 par.expression = val;
2924 return this.finishNode(par, "ParenthesizedExpression");
2925 } else {
2926 return val;
2927 }
2928 };
2929
2930 pp$3.parseParenItem = function (item) {
2931 return item;
2932 };
2933
2934 pp$3.parseParenArrowList = function (startPos, startLoc, exprList) {
2935 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
2936 };
2937
2938 // New's precedence is slightly tricky. It must allow its argument
2939 // to be a `[]` or dot subscript expression, but not a call — at
2940 // least, not without wrapping it in parentheses. Thus, it uses the
2941
2942 var empty$1 = [];
2943
2944 pp$3.parseNew = function () {
2945 var node = this.startNode();
2946 var meta = this.parseIdent(true);
2947 if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
2948 node.meta = meta;
2949 node.property = this.parseIdent(true);
2950 if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target");
2951 if (!this.inFunction) this.raise(node.start, "new.target can only be used in functions");
2952 return this.finishNode(node, "MetaProperty");
2953 }
2954 var startPos = this.start,
2955 startLoc = this.startLoc;
2956 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
2957 if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, false);else node.arguments = empty$1;
2958 return this.finishNode(node, "NewExpression");
2959 };
2960
2961 // Parse template expression.
2962
2963 pp$3.parseTemplateElement = function () {
2964 var elem = this.startNode();
2965 elem.value = {
2966 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'),
2967 cooked: this.value
2968 };
2969 this.next();
2970 elem.tail = this.type === tt.backQuote;
2971 return this.finishNode(elem, "TemplateElement");
2972 };
2973
2974 pp$3.parseTemplate = function () {
2975 var node = this.startNode();
2976 this.next();
2977 node.expressions = [];
2978 var curElt = this.parseTemplateElement();
2979 node.quasis = [curElt];
2980 while (!curElt.tail) {
2981 this.expect(tt.dollarBraceL);
2982 node.expressions.push(this.parseExpression());
2983 this.expect(tt.braceR);
2984 node.quasis.push(curElt = this.parseTemplateElement());
2985 }
2986 this.next();
2987 return this.finishNode(node, "TemplateLiteral");
2988 };
2989
2990 // Parse an object literal or binding pattern.
2991
2992 pp$3.parseObj = function (isPattern, refDestructuringErrors) {
2993 var node = this.startNode(),
2994 first = true,
2995 propHash = {};
2996 node.properties = [];
2997 this.next();
2998 while (!this.eat(tt.braceR)) {
2999 if (!first) {
3000 this.expect(tt.comma);
3001 if (this.afterTrailingComma(tt.braceR)) break;
3002 } else first = false;
3003
3004 var prop = this.startNode(),
3005 isGenerator = undefined,
3006 startPos = undefined,
3007 startLoc = undefined;
3008 if (this.options.ecmaVersion >= 6) {
3009 prop.method = false;
3010 prop.shorthand = false;
3011 if (isPattern || refDestructuringErrors) {
3012 startPos = this.start;
3013 startLoc = this.startLoc;
3014 }
3015 if (!isPattern) isGenerator = this.eat(tt.star);
3016 }
3017 this.parsePropertyName(prop);
3018 this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors);
3019 this.checkPropClash(prop, propHash);
3020 node.properties.push(this.finishNode(prop, "Property"));
3021 }
3022 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
3023 };
3024
3025 pp$3.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startLoc, refDestructuringErrors) {
3026 if (this.eat(tt.colon)) {
3027 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
3028 prop.kind = "init";
3029 } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
3030 if (isPattern) this.unexpected();
3031 prop.kind = "init";
3032 prop.method = true;
3033 prop.value = this.parseMethod(isGenerator);
3034 } else if (this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" && (prop.key.name === "get" || prop.key.name === "set") && this.type != tt.comma && this.type != tt.braceR) {
3035 if (isGenerator || isPattern) this.unexpected();
3036 prop.kind = prop.key.name;
3037 this.parsePropertyName(prop);
3038 prop.value = this.parseMethod(false);
3039 var paramCount = prop.kind === "get" ? 0 : 1;
3040 if (prop.value.params.length !== paramCount) {
3041 var start = prop.value.start;
3042 if (prop.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
3043 }
3044 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
3045 prop.kind = "init";
3046 if (isPattern) {
3047 if (this.keywords.test(prop.key.name) || (this.strict ? this.reservedWordsStrictBind : this.reservedWords).test(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name);
3048 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
3049 } else if (this.type === tt.eq && refDestructuringErrors) {
3050 if (!refDestructuringErrors.shorthandAssign) refDestructuringErrors.shorthandAssign = this.start;
3051 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
3052 } else {
3053 prop.value = prop.key;
3054 }
3055 prop.shorthand = true;
3056 } else this.unexpected();
3057 };
3058
3059 pp$3.parsePropertyName = function (prop) {
3060 if (this.options.ecmaVersion >= 6) {
3061 if (this.eat(tt.bracketL)) {
3062 prop.computed = true;
3063 prop.key = this.parseMaybeAssign();
3064 this.expect(tt.bracketR);
3065 return prop.key;
3066 } else {
3067 prop.computed = false;
3068 }
3069 }
3070 return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true);
3071 };
3072
3073 // Initialize empty function node.
3074
3075 pp$3.initFunction = function (node) {
3076 node.id = null;
3077 if (this.options.ecmaVersion >= 6) {
3078 node.generator = false;
3079 node.expression = false;
3080 }
3081 };
3082
3083 // Parse object or class method.
3084
3085 pp$3.parseMethod = function (isGenerator) {
3086 var node = this.startNode();
3087 this.initFunction(node);
3088 this.expect(tt.parenL);
3089 node.params = this.parseBindingList(tt.parenR, false, false);
3090 if (this.options.ecmaVersion >= 6) node.generator = isGenerator;
3091 this.parseFunctionBody(node, false);
3092 return this.finishNode(node, "FunctionExpression");
3093 };
3094
3095 // Parse arrow function expression with given parameters.
3096
3097 pp$3.parseArrowExpression = function (node, params) {
3098 this.initFunction(node);
3099 node.params = this.toAssignableList(params, true);
3100 this.parseFunctionBody(node, true);
3101 return this.finishNode(node, "ArrowFunctionExpression");
3102 };
3103
3104 // Parse function body and check parameters.
3105
3106 pp$3.parseFunctionBody = function (node, isArrowFunction) {
3107 var isExpression = isArrowFunction && this.type !== tt.braceL;
3108
3109 if (isExpression) {
3110 node.body = this.parseMaybeAssign();
3111 node.expression = true;
3112 } else {
3113 // Start a new scope with regard to labels and the `inFunction`
3114 // flag (restore them to their old value afterwards).
3115 var oldInFunc = this.inFunction,
3116 oldInGen = this.inGenerator,
3117 oldLabels = this.labels;
3118 this.inFunction = true;this.inGenerator = node.generator;this.labels = [];
3119 node.body = this.parseBlock(true);
3120 node.expression = false;
3121 this.inFunction = oldInFunc;this.inGenerator = oldInGen;this.labels = oldLabels;
3122 }
3123
3124 // If this is a strict mode function, verify that argument names
3125 // are not repeated, and it does not try to bind the words `eval`
3126 // or `arguments`.
3127 if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) {
3128 var oldStrict = this.strict;
3129 this.strict = true;
3130 if (node.id) this.checkLVal(node.id, true);
3131 this.checkParams(node);
3132 this.strict = oldStrict;
3133 } else if (isArrowFunction) {
3134 this.checkParams(node);
3135 }
3136 };
3137
3138 // Checks function params for various disallowed patterns such as using "eval"
3139 // or "arguments" and duplicate parameters.
3140
3141 pp$3.checkParams = function (node) {
3142 var nameHash = {};
3143 for (var i = 0; i < node.params.length; i++) {
3144 this.checkLVal(node.params[i], true, nameHash);
3145 }
3146 };
3147
3148 // Parses a comma-separated list of expressions, and returns them as
3149 // an array. `close` is the token type that ends the list, and
3150 // `allowEmpty` can be turned on to allow subsequent commas with
3151 // nothing in between them to be parsed as `null` (which is needed
3152 // for array literals).
3153
3154 pp$3.parseExprList = function (close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
3155 var elts = [],
3156 first = true;
3157 while (!this.eat(close)) {
3158 if (!first) {
3159 this.expect(tt.comma);
3160 if (this.type === close && refDestructuringErrors && !refDestructuringErrors.trailingComma) {
3161 refDestructuringErrors.trailingComma = this.lastTokStart;
3162 }
3163 if (allowTrailingComma && this.afterTrailingComma(close)) break;
3164 } else first = false;
3165
3166 var elt = undefined;
3167 if (allowEmpty && this.type === tt.comma) elt = null;else if (this.type === tt.ellipsis) elt = this.parseSpread(refDestructuringErrors);else elt = this.parseMaybeAssign(false, refDestructuringErrors);
3168 elts.push(elt);
3169 }
3170 return elts;
3171 };
3172
3173 // Parse the next token as an identifier. If `liberal` is true (used
3174 // when parsing properties), it will also convert keywords into
3175 // identifiers.
3176
3177 pp$3.parseIdent = function (liberal) {
3178 var node = this.startNode();
3179 if (liberal && this.options.allowReserved == "never") liberal = false;
3180 if (this.type === tt.name) {
3181 if (!liberal && (this.strict ? this.reservedWordsStrict : this.reservedWords).test(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1)) this.raise(this.start, "The keyword '" + this.value + "' is reserved");
3182 node.name = this.value;
3183 } else if (liberal && this.type.keyword) {
3184 node.name = this.type.keyword;
3185 } else {
3186 this.unexpected();
3187 }
3188 this.next();
3189 return this.finishNode(node, "Identifier");
3190 };
3191
3192 // Parses yield expression inside generator.
3193
3194 pp$3.parseYield = function () {
3195 var node = this.startNode();
3196 this.next();
3197 if (this.type == tt.semi || this.canInsertSemicolon() || this.type != tt.star && !this.type.startsExpr) {
3198 node.delegate = false;
3199 node.argument = null;
3200 } else {
3201 node.delegate = this.eat(tt.star);
3202 node.argument = this.parseMaybeAssign();
3203 }
3204 return this.finishNode(node, "YieldExpression");
3205 };
3206
3207 // Parses array and generator comprehensions.
3208
3209 pp$3.parseComprehension = function (node, isGenerator) {
3210 node.blocks = [];
3211 while (this.type === tt._for) {
3212 var block = this.startNode();
3213 this.next();
3214 this.expect(tt.parenL);
3215 block.left = this.parseBindingAtom();
3216 this.checkLVal(block.left, true);
3217 this.expectContextual("of");
3218 block.right = this.parseExpression();
3219 this.expect(tt.parenR);
3220 node.blocks.push(this.finishNode(block, "ComprehensionBlock"));
3221 }
3222 node.filter = this.eat(tt._if) ? this.parseParenExpression() : null;
3223 node.body = this.parseExpression();
3224 this.expect(isGenerator ? tt.parenR : tt.bracketR);
3225 node.generator = isGenerator;
3226 return this.finishNode(node, "ComprehensionExpression");
3227 };
3228
3229 var pp$4 = Parser.prototype;
3230
3231 // This function is used to raise exceptions on parse errors. It
3232 // takes an offset integer (into the current `input`) to indicate
3233 // the location of the error, attaches the position to the end
3234 // of the error message, and then raises a `SyntaxError` with that
3235 // message.
3236
3237 pp$4.raise = function (pos, message) {
3238 var loc = getLineInfo(this.input, pos);
3239 message += " (" + loc.line + ":" + loc.column + ")";
3240 var err = new SyntaxError(message);
3241 err.pos = pos;err.loc = loc;err.raisedAt = this.pos;
3242 throw err;
3243 };
3244
3245 pp$4.curPosition = function () {
3246 if (this.options.locations) {
3247 return new Position(this.curLine, this.pos - this.lineStart);
3248 }
3249 };
3250
3251 var Node = function Node(parser, pos, loc) {
3252 babelHelpers.classCallCheck(this, Node);
3253
3254 this.type = "";
3255 this.start = pos;
3256 this.end = 0;
3257 if (parser.options.locations) this.loc = new SourceLocation(parser, loc);
3258 if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile;
3259 if (parser.options.ranges) this.range = [pos, 0];
3260 }
3261
3262 // Start an AST node, attaching a start offset.
3263
3264 ;
3265
3266 var pp$5 = Parser.prototype;
3267
3268 pp$5.startNode = function () {
3269 return new Node(this, this.start, this.startLoc);
3270 };
3271
3272 pp$5.startNodeAt = function (pos, loc) {
3273 return new Node(this, pos, loc);
3274 };
3275
3276 // Finish an AST node, adding `type` and `end` properties.
3277
3278 function finishNodeAt(node, type, pos, loc) {
3279 node.type = type;
3280 node.end = pos;
3281 if (this.options.locations) node.loc.end = loc;
3282 if (this.options.ranges) node.range[1] = pos;
3283 return node;
3284 }
3285
3286 pp$5.finishNode = function (node, type) {
3287 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
3288 };
3289
3290 // Finish node at given position
3291
3292 pp$5.finishNodeAt = function (node, type, pos, loc) {
3293 return finishNodeAt.call(this, node, type, pos, loc);
3294 };
3295
3296 var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
3297 babelHelpers.classCallCheck(this, TokContext);
3298
3299 this.token = token;
3300 this.isExpr = !!isExpr;
3301 this.preserveSpace = !!preserveSpace;
3302 this.override = override;
3303 };
3304
3305 var types = {
3306 b_stat: new TokContext("{", false),
3307 b_expr: new TokContext("{", true),
3308 b_tmpl: new TokContext("${", true),
3309 p_stat: new TokContext("(", false),
3310 p_expr: new TokContext("(", true),
3311 q_tmpl: new TokContext("`", true, true, function (p) {
3312 return p.readTmplToken();
3313 }),
3314 f_expr: new TokContext("function", true)
3315 };
3316
3317 var pp$6 = Parser.prototype;
3318
3319 pp$6.initialContext = function () {
3320 return [types.b_stat];
3321 };
3322
3323 pp$6.braceIsBlock = function (prevType) {
3324 if (prevType === tt.colon) {
3325 var _parent = this.curContext();
3326 if (_parent === types.b_stat || _parent === types.b_expr) return !_parent.isExpr;
3327 }
3328 if (prevType === tt._return) return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
3329 if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) return true;
3330 if (prevType == tt.braceL) return this.curContext() === types.b_stat;
3331 return !this.exprAllowed;
3332 };
3333
3334 pp$6.updateContext = function (prevType) {
3335 var update = undefined,
3336 type = this.type;
3337 if (type.keyword && prevType == tt.dot) this.exprAllowed = false;else if (update = type.updateContext) update.call(this, prevType);else this.exprAllowed = type.beforeExpr;
3338 };
3339
3340 // Token-specific context update code
3341
3342 tt.parenR.updateContext = tt.braceR.updateContext = function () {
3343 if (this.context.length == 1) {
3344 this.exprAllowed = true;
3345 return;
3346 }
3347 var out = this.context.pop();
3348 if (out === types.b_stat && this.curContext() === types.f_expr) {
3349 this.context.pop();
3350 this.exprAllowed = false;
3351 } else if (out === types.b_tmpl) {
3352 this.exprAllowed = true;
3353 } else {
3354 this.exprAllowed = !out.isExpr;
3355 }
3356 };
3357
3358 tt.braceL.updateContext = function (prevType) {
3359 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
3360 this.exprAllowed = true;
3361 };
3362
3363 tt.dollarBraceL.updateContext = function () {
3364 this.context.push(types.b_tmpl);
3365 this.exprAllowed = true;
3366 };
3367
3368 tt.parenL.updateContext = function (prevType) {
3369 var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while;
3370 this.context.push(statementParens ? types.p_stat : types.p_expr);
3371 this.exprAllowed = true;
3372 };
3373
3374 tt.incDec.updateContext = function () {
3375 // tokExprAllowed stays unchanged
3376 };
3377
3378 tt._function.updateContext = function () {
3379 if (this.curContext() !== types.b_stat) this.context.push(types.f_expr);
3380 this.exprAllowed = false;
3381 };
3382
3383 tt.backQuote.updateContext = function () {
3384 if (this.curContext() === types.q_tmpl) this.context.pop();else this.context.push(types.q_tmpl);
3385 this.exprAllowed = false;
3386 };
3387
3388 // Object type used to represent tokens. Note that normally, tokens
3389 // simply exist as properties on the parser object. This is only
3390 // used for the onToken callback and the external tokenizer.
3391
3392 var Token = function Token(p) {
3393 babelHelpers.classCallCheck(this, Token);
3394
3395 this.type = p.type;
3396 this.value = p.value;
3397 this.start = p.start;
3398 this.end = p.end;
3399 if (p.options.locations) this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
3400 if (p.options.ranges) this.range = [p.start, p.end];
3401 }
3402
3403 // ## Tokenizer
3404
3405 ;
3406
3407 var pp$7 = Parser.prototype;
3408
3409 // Are we running under Rhino?
3410 var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
3411
3412 // Move to the next token
3413
3414 pp$7.next = function () {
3415 if (this.options.onToken) this.options.onToken(new Token(this));
3416
3417 this.lastTokEnd = this.end;
3418 this.lastTokStart = this.start;
3419 this.lastTokEndLoc = this.endLoc;
3420 this.lastTokStartLoc = this.startLoc;
3421 this.nextToken();
3422 };
3423
3424 pp$7.getToken = function () {
3425 this.next();
3426 return new Token(this);
3427 };
3428
3429 // If we're in an ES6 environment, make parsers iterable
3430 if (typeof Symbol !== "undefined") pp$7[Symbol.iterator] = function () {
3431 var self = this;
3432 return { next: function () {
3433 var token = self.getToken();
3434 return {
3435 done: token.type === tt.eof,
3436 value: token
3437 };
3438 } };
3439 };
3440
3441 // Toggle strict mode. Re-reads the next number or string to please
3442 // pedantic tests (`"use strict"; 010;` should fail).
3443
3444 pp$7.setStrict = function (strict) {
3445 this.strict = strict;
3446 if (this.type !== tt.num && this.type !== tt.string) return;
3447 this.pos = this.start;
3448 if (this.options.locations) {
3449 while (this.pos < this.lineStart) {
3450 this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
3451 --this.curLine;
3452 }
3453 }
3454 this.nextToken();
3455 };
3456
3457 pp$7.curContext = function () {
3458 return this.context[this.context.length - 1];
3459 };
3460
3461 // Read a single token, updating the parser object's token-related
3462 // properties.
3463
3464 pp$7.nextToken = function () {
3465 var curContext = this.curContext();
3466 if (!curContext || !curContext.preserveSpace) this.skipSpace();
3467
3468 this.start = this.pos;
3469 if (this.options.locations) this.startLoc = this.curPosition();
3470 if (this.pos >= this.input.length) return this.finishToken(tt.eof);
3471
3472 if (curContext.override) return curContext.override(this);else this.readToken(this.fullCharCodeAtPos());
3473 };
3474
3475 pp$7.readToken = function (code) {
3476 // Identifier or keyword. '\uXXXX' sequences are allowed in
3477 // identifiers, so '\' also dispatches to that.
3478 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord();
3479
3480 return this.getTokenFromCode(code);
3481 };
3482
3483 pp$7.fullCharCodeAtPos = function () {
3484 var code = this.input.charCodeAt(this.pos);
3485 if (code <= 0xd7ff || code >= 0xe000) return code;
3486 var next = this.input.charCodeAt(this.pos + 1);
3487 return (code << 10) + next - 0x35fdc00;
3488 };
3489
3490 pp$7.skipBlockComment = function () {
3491 var startLoc = this.options.onComment && this.curPosition();
3492 var start = this.pos,
3493 end = this.input.indexOf("*/", this.pos += 2);
3494 if (end === -1) this.raise(this.pos - 2, "Unterminated comment");
3495 this.pos = end + 2;
3496 if (this.options.locations) {
3497 lineBreakG.lastIndex = start;
3498 var match = undefined;
3499 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
3500 ++this.curLine;
3501 this.lineStart = match.index + match[0].length;
3502 }
3503 }
3504 if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
3505 };
3506
3507 pp$7.skipLineComment = function (startSkip) {
3508 var start = this.pos;
3509 var startLoc = this.options.onComment && this.curPosition();
3510 var ch = this.input.charCodeAt(this.pos += startSkip);
3511 while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
3512 ++this.pos;
3513 ch = this.input.charCodeAt(this.pos);
3514 }
3515 if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
3516 };
3517
3518 // Called at the start of the parse and after every token. Skips
3519 // whitespace and comments, and.
3520
3521 pp$7.skipSpace = function () {
3522 loop: while (this.pos < this.input.length) {
3523 var ch = this.input.charCodeAt(this.pos);
3524 switch (ch) {
3525 case 32:case 160:
3526 // ' '
3527 ++this.pos;
3528 break;
3529 case 13:
3530 if (this.input.charCodeAt(this.pos + 1) === 10) {
3531 ++this.pos;
3532 }
3533 case 10:case 8232:case 8233:
3534 ++this.pos;
3535 if (this.options.locations) {
3536 ++this.curLine;
3537 this.lineStart = this.pos;
3538 }
3539 break;
3540 case 47:
3541 // '/'
3542 switch (this.input.charCodeAt(this.pos + 1)) {
3543 case 42:
3544 // '*'
3545 this.skipBlockComment();
3546 break;
3547 case 47:
3548 this.skipLineComment(2);
3549 break;
3550 default:
3551 break loop;
3552 }
3553 break;
3554 default:
3555 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
3556 ++this.pos;
3557 } else {
3558 break loop;
3559 }
3560 }
3561 }
3562 };
3563
3564 // Called at the end of every token. Sets `end`, `val`, and
3565 // maintains `context` and `exprAllowed`, and skips the space after
3566 // the token, so that the next one's `start` will point at the
3567 // right position.
3568
3569 pp$7.finishToken = function (type, val) {
3570 this.end = this.pos;
3571 if (this.options.locations) this.endLoc = this.curPosition();
3572 var prevType = this.type;
3573 this.type = type;
3574 this.value = val;
3575
3576 this.updateContext(prevType);
3577 };
3578
3579 // ### Token reading
3580
3581 // This is the function that is called to fetch the next token. It
3582 // is somewhat obscure, because it works in character codes rather
3583 // than characters, and because operator parsing has been inlined
3584 // into it.
3585 //
3586 // All in the name of speed.
3587 //
3588 pp$7.readToken_dot = function () {
3589 var next = this.input.charCodeAt(this.pos + 1);
3590 if (next >= 48 && next <= 57) return this.readNumber(true);
3591 var next2 = this.input.charCodeAt(this.pos + 2);
3592 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
3593 // 46 = dot '.'
3594 this.pos += 3;
3595 return this.finishToken(tt.ellipsis);
3596 } else {
3597 ++this.pos;
3598 return this.finishToken(tt.dot);
3599 }
3600 };
3601
3602 pp$7.readToken_slash = function () {
3603 // '/'
3604 var next = this.input.charCodeAt(this.pos + 1);
3605 if (this.exprAllowed) {
3606 ++this.pos;return this.readRegexp();
3607 }
3608 if (next === 61) return this.finishOp(tt.assign, 2);
3609 return this.finishOp(tt.slash, 1);
3610 };
3611
3612 pp$7.readToken_mult_modulo = function (code) {
3613 // '%*'
3614 var next = this.input.charCodeAt(this.pos + 1);
3615 if (next === 61) return this.finishOp(tt.assign, 2);
3616 return this.finishOp(code === 42 ? tt.star : tt.modulo, 1);
3617 };
3618
3619 pp$7.readToken_pipe_amp = function (code) {
3620 // '|&'
3621 var next = this.input.charCodeAt(this.pos + 1);
3622 if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2);
3623 if (next === 61) return this.finishOp(tt.assign, 2);
3624 return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1);
3625 };
3626
3627 pp$7.readToken_caret = function () {
3628 // '^'
3629 var next = this.input.charCodeAt(this.pos + 1);
3630 if (next === 61) return this.finishOp(tt.assign, 2);
3631 return this.finishOp(tt.bitwiseXOR, 1);
3632 };
3633
3634 pp$7.readToken_plus_min = function (code) {
3635 // '+-'
3636 var next = this.input.charCodeAt(this.pos + 1);
3637 if (next === code) {
3638 if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
3639 // A `-->` line comment
3640 this.skipLineComment(3);
3641 this.skipSpace();
3642 return this.nextToken();
3643 }
3644 return this.finishOp(tt.incDec, 2);
3645 }
3646 if (next === 61) return this.finishOp(tt.assign, 2);
3647 return this.finishOp(tt.plusMin, 1);
3648 };
3649
3650 pp$7.readToken_lt_gt = function (code) {
3651 // '<>'
3652 var next = this.input.charCodeAt(this.pos + 1);
3653 var size = 1;
3654 if (next === code) {
3655 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
3656 if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1);
3657 return this.finishOp(tt.bitShift, size);
3658 }
3659 if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) {
3660 if (this.inModule) this.unexpected();
3661 // `<!--`, an XML-style comment that should be interpreted as a line comment
3662 this.skipLineComment(4);
3663 this.skipSpace();
3664 return this.nextToken();
3665 }
3666 if (next === 61) size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2;
3667 return this.finishOp(tt.relational, size);
3668 };
3669
3670 pp$7.readToken_eq_excl = function (code) {
3671 // '=!'
3672 var next = this.input.charCodeAt(this.pos + 1);
3673 if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
3674 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
3675 // '=>'
3676 this.pos += 2;
3677 return this.finishToken(tt.arrow);
3678 }
3679 return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1);
3680 };
3681
3682 pp$7.getTokenFromCode = function (code) {
3683 switch (code) {
3684 // The interpretation of a dot depends on whether it is followed
3685 // by a digit or another two dots.
3686 case 46:
3687 // '.'
3688 return this.readToken_dot();
3689
3690 // Punctuation tokens.
3691 case 40:
3692 ++this.pos;return this.finishToken(tt.parenL);
3693 case 41:
3694 ++this.pos;return this.finishToken(tt.parenR);
3695 case 59:
3696 ++this.pos;return this.finishToken(tt.semi);
3697 case 44:
3698 ++this.pos;return this.finishToken(tt.comma);
3699 case 91:
3700 ++this.pos;return this.finishToken(tt.bracketL);
3701 case 93:
3702 ++this.pos;return this.finishToken(tt.bracketR);
3703 case 123:
3704 ++this.pos;return this.finishToken(tt.braceL);
3705 case 125:
3706 ++this.pos;return this.finishToken(tt.braceR);
3707 case 58:
3708 ++this.pos;return this.finishToken(tt.colon);
3709 case 63:
3710 ++this.pos;return this.finishToken(tt.question);
3711
3712 case 96:
3713 // '`'
3714 if (this.options.ecmaVersion < 6) break;
3715 ++this.pos;
3716 return this.finishToken(tt.backQuote);
3717
3718 case 48:
3719 // '0'
3720 var next = this.input.charCodeAt(this.pos + 1);
3721 if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
3722 if (this.options.ecmaVersion >= 6) {
3723 if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
3724 if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
3725 }
3726 // Anything else beginning with a digit is an integer, octal
3727 // number, or float.
3728 case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:
3729 // 1-9
3730 return this.readNumber(false);
3731
3732 // Quotes produce strings.
3733 case 34:case 39:
3734 // '"', "'"
3735 return this.readString(code);
3736
3737 // Operators are parsed inline in tiny state machines. '=' (61) is
3738 // often referred to. `finishOp` simply skips the amount of
3739 // characters it is given as second argument, and returns a token
3740 // of the type given by its first argument.
3741
3742 case 47:
3743 // '/'
3744 return this.readToken_slash();
3745
3746 case 37:case 42:
3747 // '%*'
3748 return this.readToken_mult_modulo(code);
3749
3750 case 124:case 38:
3751 // '|&'
3752 return this.readToken_pipe_amp(code);
3753
3754 case 94:
3755 // '^'
3756 return this.readToken_caret();
3757
3758 case 43:case 45:
3759 // '+-'
3760 return this.readToken_plus_min(code);
3761
3762 case 60:case 62:
3763 // '<>'
3764 return this.readToken_lt_gt(code);
3765
3766 case 61:case 33:
3767 // '=!'
3768 return this.readToken_eq_excl(code);
3769
3770 case 126:
3771 // '~'
3772 return this.finishOp(tt.prefix, 1);
3773 }
3774
3775 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
3776 };
3777
3778 pp$7.finishOp = function (type, size) {
3779 var str = this.input.slice(this.pos, this.pos + size);
3780 this.pos += size;
3781 return this.finishToken(type, str);
3782 };
3783
3784 // Parse a regular expression. Some context-awareness is necessary,
3785 // since a '/' inside a '[]' set does not end the expression.
3786
3787 function tryCreateRegexp(src, flags, throwErrorAt, parser) {
3788 try {
3789 return new RegExp(src, flags);
3790 } catch (e) {
3791 if (throwErrorAt !== undefined) {
3792 if (e instanceof SyntaxError) parser.raise(throwErrorAt, "Error parsing regular expression: " + e.message);
3793 throw e;
3794 }
3795 }
3796 }
3797
3798 var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
3799
3800 pp$7.readRegexp = function () {
3801 var _this = this;
3802
3803 var escaped = undefined,
3804 inClass = undefined,
3805 start = this.pos;
3806 for (;;) {
3807 if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
3808 var ch = this.input.charAt(this.pos);
3809 if (lineBreak.test(ch)) this.raise(start, "Unterminated regular expression");
3810 if (!escaped) {
3811 if (ch === "[") inClass = true;else if (ch === "]" && inClass) inClass = false;else if (ch === "/" && !inClass) break;
3812 escaped = ch === "\\";
3813 } else escaped = false;
3814 ++this.pos;
3815 }
3816 var content = this.input.slice(start, this.pos);
3817 ++this.pos;
3818 // Need to use `readWord1` because '\uXXXX' sequences are allowed
3819 // here (don't ask).
3820 var mods = this.readWord1();
3821 var tmp = content;
3822 if (mods) {
3823 var validFlags = /^[gmsiy]*$/;
3824 if (this.options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/;
3825 if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
3826 if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) {
3827 // Replace each astral symbol and every Unicode escape sequence that
3828 // possibly represents an astral symbol or a paired surrogate with a
3829 // single ASCII symbol to avoid throwing on regular expressions that
3830 // are only valid in combination with the `/u` flag.
3831 // Note: replacing with the ASCII symbol `x` might cause false
3832 // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
3833 // perfectly valid pattern that is equivalent to `[a-b]`, but it would
3834 // be replaced by `[x-b]` which throws an error.
3835 tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (_match, code, offset) {
3836 code = Number("0x" + code);
3837 if (code > 0x10FFFF) _this.raise(start + offset + 3, "Code point out of bounds");
3838 return "x";
3839 });
3840 tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
3841 }
3842 }
3843 // Detect invalid regular expressions.
3844 var value = null;
3845 // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
3846 // so don't do detection if we are running under Rhino
3847 if (!isRhino) {
3848 tryCreateRegexp(tmp, undefined, start, this);
3849 // Get a regular expression object for this pattern-flag pair, or `null` in
3850 // case the current environment doesn't support the flags it uses.
3851 value = tryCreateRegexp(content, mods);
3852 }
3853 return this.finishToken(tt.regexp, { pattern: content, flags: mods, value: value });
3854 };
3855
3856 // Read an integer in the given radix. Return null if zero digits
3857 // were read, the integer value otherwise. When `len` is given, this
3858 // will return `null` unless the integer has exactly `len` digits.
3859
3860 pp$7.readInt = function (radix, len) {
3861 var start = this.pos,
3862 total = 0;
3863 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
3864 var code = this.input.charCodeAt(this.pos),
3865 val = undefined;
3866 if (code >= 97) val = code - 97 + 10; // a
3867 else if (code >= 65) val = code - 65 + 10; // A
3868 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
3869 else val = Infinity;
3870 if (val >= radix) break;
3871 ++this.pos;
3872 total = total * radix + val;
3873 }
3874 if (this.pos === start || len != null && this.pos - start !== len) return null;
3875
3876 return total;
3877 };
3878
3879 pp$7.readRadixNumber = function (radix) {
3880 this.pos += 2; // 0x
3881 var val = this.readInt(radix);
3882 if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix);
3883 if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
3884 return this.finishToken(tt.num, val);
3885 };
3886
3887 // Read an integer, octal integer, or floating-point number.
3888
3889 pp$7.readNumber = function (startsWithDot) {
3890 var start = this.pos,
3891 isFloat = false,
3892 octal = this.input.charCodeAt(this.pos) === 48;
3893 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
3894 var next = this.input.charCodeAt(this.pos);
3895 if (next === 46) {
3896 // '.'
3897 ++this.pos;
3898 this.readInt(10);
3899 isFloat = true;
3900 next = this.input.charCodeAt(this.pos);
3901 }
3902 if (next === 69 || next === 101) {
3903 // 'eE'
3904 next = this.input.charCodeAt(++this.pos);
3905 if (next === 43 || next === 45) ++this.pos; // '+-'
3906 if (this.readInt(10) === null) this.raise(start, "Invalid number");
3907 isFloat = true;
3908 }
3909 if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
3910
3911 var str = this.input.slice(start, this.pos),
3912 val = undefined;
3913 if (isFloat) val = parseFloat(str);else if (!octal || str.length === 1) val = parseInt(str, 10);else if (/[89]/.test(str) || this.strict) this.raise(start, "Invalid number");else val = parseInt(str, 8);
3914 return this.finishToken(tt.num, val);
3915 };
3916
3917 // Read a string value, interpreting backslash-escapes.
3918
3919 pp$7.readCodePoint = function () {
3920 var ch = this.input.charCodeAt(this.pos),
3921 code = undefined;
3922
3923 if (ch === 123) {
3924 if (this.options.ecmaVersion < 6) this.unexpected();
3925 var codePos = ++this.pos;
3926 code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos);
3927 ++this.pos;
3928 if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds");
3929 } else {
3930 code = this.readHexChar(4);
3931 }
3932 return code;
3933 };
3934
3935 function codePointToString(code) {
3936 // UTF-16 Decoding
3937 if (code <= 0xFFFF) return String.fromCharCode(code);
3938 code -= 0x10000;
3939 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00);
3940 }
3941
3942 pp$7.readString = function (quote) {
3943 var out = "",
3944 chunkStart = ++this.pos;
3945 for (;;) {
3946 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant");
3947 var ch = this.input.charCodeAt(this.pos);
3948 if (ch === quote) break;
3949 if (ch === 92) {
3950 // '\'
3951 out += this.input.slice(chunkStart, this.pos);
3952 out += this.readEscapedChar(false);
3953 chunkStart = this.pos;
3954 } else {
3955 if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant");
3956 ++this.pos;
3957 }
3958 }
3959 out += this.input.slice(chunkStart, this.pos++);
3960 return this.finishToken(tt.string, out);
3961 };
3962
3963 // Reads template string tokens.
3964
3965 pp$7.readTmplToken = function () {
3966 var out = "",
3967 chunkStart = this.pos;
3968 for (;;) {
3969 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template");
3970 var ch = this.input.charCodeAt(this.pos);
3971 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
3972 // '`', '${'
3973 if (this.pos === this.start && this.type === tt.template) {
3974 if (ch === 36) {
3975 this.pos += 2;
3976 return this.finishToken(tt.dollarBraceL);
3977 } else {
3978 ++this.pos;
3979 return this.finishToken(tt.backQuote);
3980 }
3981 }
3982 out += this.input.slice(chunkStart, this.pos);
3983 return this.finishToken(tt.template, out);
3984 }
3985 if (ch === 92) {
3986 // '\'
3987 out += this.input.slice(chunkStart, this.pos);
3988 out += this.readEscapedChar(true);
3989 chunkStart = this.pos;
3990 } else if (isNewLine(ch)) {
3991 out += this.input.slice(chunkStart, this.pos);
3992 ++this.pos;
3993 switch (ch) {
3994 case 13:
3995 if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
3996 case 10:
3997 out += "\n";
3998 break;
3999 default:
4000 out += String.fromCharCode(ch);
4001 break;
4002 }
4003 if (this.options.locations) {
4004 ++this.curLine;
4005 this.lineStart = this.pos;
4006 }
4007 chunkStart = this.pos;
4008 } else {
4009 ++this.pos;
4010 }
4011 }
4012 };
4013
4014 // Used to read escaped characters
4015
4016 pp$7.readEscapedChar = function (inTemplate) {
4017 var ch = this.input.charCodeAt(++this.pos);
4018 ++this.pos;
4019 switch (ch) {
4020 case 110:
4021 return "\n"; // 'n' -> '\n'
4022 case 114:
4023 return "\r"; // 'r' -> '\r'
4024 case 120:
4025 return String.fromCharCode(this.readHexChar(2)); // 'x'
4026 case 117:
4027 return codePointToString(this.readCodePoint()); // 'u'
4028 case 116:
4029 return "\t"; // 't' -> '\t'
4030 case 98:
4031 return "\b"; // 'b' -> '\b'
4032 case 118:
4033 return "\u000b"; // 'v' -> '\u000b'
4034 case 102:
4035 return "\f"; // 'f' -> '\f'
4036 case 13:
4037 if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
4038 case 10:
4039 // ' \n'
4040 if (this.options.locations) {
4041 this.lineStart = this.pos;++this.curLine;
4042 }
4043 return "";
4044 default:
4045 if (ch >= 48 && ch <= 55) {
4046 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
4047 var octal = parseInt(octalStr, 8);
4048 if (octal > 255) {
4049 octalStr = octalStr.slice(0, -1);
4050 octal = parseInt(octalStr, 8);
4051 }
4052 if (octal > 0 && (this.strict || inTemplate)) {
4053 this.raise(this.pos - 2, "Octal literal in strict mode");
4054 }
4055 this.pos += octalStr.length - 1;
4056 return String.fromCharCode(octal);
4057 }
4058 return String.fromCharCode(ch);
4059 }
4060 };
4061
4062 // Used to read character escape sequences ('\x', '\u', '\U').
4063
4064 pp$7.readHexChar = function (len) {
4065 var codePos = this.pos;
4066 var n = this.readInt(16, len);
4067 if (n === null) this.raise(codePos, "Bad character escape sequence");
4068 return n;
4069 };
4070
4071 // Read an identifier, and return it as a string. Sets `this.containsEsc`
4072 // to whether the word contained a '\u' escape.
4073 //
4074 // Incrementally adds only escaped chars, adding other chunks as-is
4075 // as a micro-optimization.
4076
4077 pp$7.readWord1 = function () {
4078 this.containsEsc = false;
4079 var word = "",
4080 first = true,
4081 chunkStart = this.pos;
4082 var astral = this.options.ecmaVersion >= 6;
4083 while (this.pos < this.input.length) {
4084 var ch = this.fullCharCodeAtPos();
4085 if (isIdentifierChar(ch, astral)) {
4086 this.pos += ch <= 0xffff ? 1 : 2;
4087 } else if (ch === 92) {
4088 // "\"
4089 this.containsEsc = true;
4090 word += this.input.slice(chunkStart, this.pos);
4091 var escStart = this.pos;
4092 if (this.input.charCodeAt(++this.pos) != 117) // "u"
4093 this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX");
4094 ++this.pos;
4095 var esc = this.readCodePoint();
4096 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) this.raise(escStart, "Invalid Unicode escape");
4097 word += codePointToString(esc);
4098 chunkStart = this.pos;
4099 } else {
4100 break;
4101 }
4102 first = false;
4103 }
4104 return word + this.input.slice(chunkStart, this.pos);
4105 };
4106
4107 // Read an identifier or keyword token. Will check for reserved
4108 // words when necessary.
4109
4110 pp$7.readWord = function () {
4111 var word = this.readWord1();
4112 var type = tt.name;
4113 if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.keywords.test(word)) type = keywordTypes[word];
4114 return this.finishToken(type, word);
4115 };
4116
4117 // The main exported interface (under `self.acorn` when in the
4118 // browser) is a `parse` function that takes a code string and
4119 // returns an abstract syntax tree as specified by [Mozilla parser
4120 // API][api].
4121 //
4122 // [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
4123
4124 function parse(input, options) {
4125 return new Parser(options, input).parse();
4126 }
4127
4128 function walk(ast, _ref) {
4129 var enter = _ref.enter;
4130 var leave = _ref.leave;
4131
4132 visit(ast, null, enter, leave);
4133 }
4134
4135 var context = {
4136 skip: function skip() {
4137 return context.shouldSkip = true;
4138 }
4139 };
4140
4141 var childKeys = {};
4142
4143 var toString = Object.prototype.toString;
4144
4145 function isArray(thing) {
4146 return toString.call(thing) === '[object Array]';
4147 }
4148
4149 function visit(node, parent, enter, leave, prop, index) {
4150 if (!node) return;
4151
4152 if (enter) {
4153 context.shouldSkip = false;
4154 enter.call(context, node, parent, prop, index);
4155 if (context.shouldSkip) return;
4156 }
4157
4158 var keys = childKeys[node.type] || (childKeys[node.type] = Object.keys(node).filter(function (prop) {
4159 return typeof node[prop] === 'object';
4160 }));
4161
4162 var key = undefined,
4163 value = undefined,
4164 i = undefined,
4165 j = undefined;
4166
4167 i = keys.length;
4168 while (i--) {
4169 key = keys[i];
4170 value = node[key];
4171
4172 if (isArray(value)) {
4173 j = value.length;
4174 while (j--) {
4175 visit(value[j], node, enter, leave, key, j);
4176 }
4177 } else if (value && value.type) {
4178 visit(value, node, enter, leave, key, null);
4179 }
4180 }
4181
4182 if (leave) {
4183 leave(node, parent, prop, index);
4184 }
4185 }
4186
4187 var modifierNodes = {
4188 AssignmentExpression: 'left',
4189 UpdateExpression: 'argument'
4190 };
4191
4192 function isReference(node, parent) {
4193 if (node.type === 'MemberExpression') {
4194 return !node.computed && isReference(node.object, node);
4195 }
4196
4197 if (node.type === 'Identifier') {
4198 // TODO is this right?
4199 if (parent.type === 'MemberExpression') return parent.computed || node === parent.object;
4200
4201 // disregard the `bar` in { bar: foo }
4202 if (parent.type === 'Property' && node !== parent.value) return false;
4203
4204 // disregard the `bar` in `class Foo { bar () {...} }`
4205 if (parent.type === 'MethodDefinition') return false;
4206
4207 // disregard the `bar` in `export { foo as bar }`
4208 if (parent.type === 'ExportSpecifier' && node !== parent.local) return;
4209
4210 return true;
4211 }
4212 }
4213
4214 function flatten(node) {
4215 var parts = [];
4216 while (node.type === 'MemberExpression') {
4217 if (node.computed) return null;
4218 parts.unshift(node.property.name);
4219
4220 node = node.object;
4221 }
4222
4223 if (node.type !== 'Identifier') return null;
4224
4225 var name = node.name;
4226 parts.unshift(name);
4227
4228 return { name: name, keypath: parts.join('.') };
4229 }
4230
4231 var pureFunctions = {};
4232
4233 var arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' ');
4234 var simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split(' ');
4235 var simdMethods = 'abs add and bool check div equal extractLane fromFloat32x4 fromFloat32x4Bits fromFloat64x2 fromFloat64x2Bits fromInt16x8Bits fromInt32x4 fromInt32x4Bits fromInt8x16Bits greaterThan greaterThanOrEqual lessThan lessThanOrEqual load max maxNum min minNum mul neg not notEqual or reciprocalApproximation reciprocalSqrtApproximation replaceLane select selectBits shiftLeftByScalar shiftRightArithmeticByScalar shiftRightLogicalByScalar shuffle splat sqrt store sub swizzle xor'.split(' ');
4236 var allSimdMethods = [];
4237 simdTypes.forEach(function (t) {
4238 simdMethods.forEach(function (m) {
4239 allSimdMethods.push('SIMD.' + t + '.' + m);
4240 });
4241 });
4242
4243 ['Array.isArray', 'Error', 'EvalError', 'InternalError', 'RangeError', 'ReferenceError', 'SyntaxError', 'TypeError', 'URIError', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', 'unescape', 'Object', 'Object.create', 'Object.getNotifier', 'Object.getOwn', 'Object.getOwnPropertyDescriptor', 'Object.getOwnPropertyNames', 'Object.getOwnPropertySymbols', 'Object.getPrototypeOf', 'Object.is', 'Object.isExtensible', 'Object.isFrozen', 'Object.isSealed', 'Object.keys', 'Function', 'Boolean', 'Number', 'Number.isFinite', 'Number.isInteger', 'Number.isNaN', 'Number.isSafeInteger', 'Number.parseFloat', 'Number.parseInt', 'Symbol', 'Symbol.for', 'Symbol.keyFor', 'Math.abs', 'Math.acos', 'Math.acosh', 'Math.asin', 'Math.asinh', 'Math.atan', 'Math.atan2', 'Math.atanh', 'Math.cbrt', 'Math.ceil', 'Math.clz32', 'Math.cos', 'Math.cosh', 'Math.exp', 'Math.expm1', 'Math.floor', 'Math.fround', 'Math.hypot', 'Math.imul', 'Math.log', 'Math.log10', 'Math.log1p', 'Math.log2', 'Math.max', 'Math.min', 'Math.pow', 'Math.random', 'Math.round', 'Math.sign', 'Math.sin', 'Math.sinh', 'Math.sqrt', 'Math.tan', 'Math.tanh', 'Math.trunc', 'Date', 'Date.UTC', 'Date.now', 'Date.parse', 'String', 'String.fromCharCode', 'String.fromCodePoint', 'String.raw', 'RegExp', 'Map', 'Set', 'WeakMap', 'WeakSet', 'ArrayBuffer', 'ArrayBuffer.isView', 'DataView', 'JSON.parse', 'JSON.stringify', 'Promise', 'Promise.all', 'Promise.race', 'Promise.reject', 'Promise.resolve', 'Intl.Collator', 'Intl.Collator.supportedLocalesOf', 'Intl.DateTimeFormat', 'Intl.DateTimeFormat.supportedLocalesOf', 'Intl.NumberFormat', 'Intl.NumberFormat.supportedLocalesOf'
4244
4245 // TODO properties of e.g. window...
4246 ].concat(arrayTypes, arrayTypes.map(function (t) {
4247 return t + '.from';
4248 }), arrayTypes.map(function (t) {
4249 return t + '.of';
4250 }), simdTypes.map(function (t) {
4251 return 'SIMD.' + t;
4252 }), allSimdMethods).forEach(function (name) {
4253 return pureFunctions[name] = true;
4254 });
4255 // TODO add others to this list from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects
4256
4257 function run(node, scope, statement, strongDependencies, force) {
4258 var hasSideEffect = false;
4259
4260 walk(node, {
4261 enter: function (node, parent) {
4262 if (!force && /Function/.test(node.type)) return this.skip();
4263
4264 if (node._scope) scope = node._scope;
4265
4266 if (isReference(node, parent)) {
4267 var flattened = flatten(node);
4268
4269 if (flattened.name === 'arguments') {
4270 hasSideEffect = true;
4271 } else if (!scope.contains(flattened.name)) {
4272 var declaration = statement.module.trace(flattened.name);
4273 if (declaration && !declaration.isExternal) {
4274 var _module = declaration.module || declaration.statement.module; // TODO is this right?
4275 if (!_module.isExternal && ! ~strongDependencies.indexOf(_module)) strongDependencies.push(_module);
4276 }
4277 }
4278 } else if (node.type === 'ThrowStatement') {
4279 // we only care about errors thrown at the top level, otherwise
4280 // any function with error checking gets included if called
4281 if (scope.isTopLevel) hasSideEffect = true;
4282 } else if (node.type === 'CallExpression' || node.type === 'NewExpression') {
4283 if (node.callee.type === 'Identifier') {
4284 var declaration = scope.findDeclaration(node.callee.name) || statement.module.trace(node.callee.name);
4285
4286 if (declaration) {
4287 if (declaration.run(strongDependencies)) {
4288 hasSideEffect = true;
4289 }
4290 } else if (!pureFunctions[node.callee.name]) {
4291 hasSideEffect = true;
4292 }
4293 } else if (node.callee.type === 'MemberExpression') {
4294 var flattened = flatten(node.callee);
4295
4296 if (flattened) {
4297 // if we're calling e.g. Object.keys(thing), there are no side-effects
4298 // TODO make pureFunctions configurable
4299 var declaration = scope.findDeclaration(flattened.name) || statement.module.trace(flattened.name);
4300
4301 if (!!declaration || !pureFunctions[flattened.keypath]) {
4302 hasSideEffect = true;
4303 }
4304 } else {
4305 // is not a keypath like `foo.bar.baz` – could be e.g.
4306 // `foo[bar].baz()`. Err on the side of caution
4307 hasSideEffect = true;
4308 }
4309 }
4310
4311 // otherwise we're probably dealing with a function expression
4312 else if (run(node.callee, scope, statement, strongDependencies, true)) {
4313 hasSideEffect = true;
4314 }
4315 } else if (node.type in modifierNodes) {
4316 var subject = node[modifierNodes[node.type]];
4317 while (subject.type === 'MemberExpression') subject = subject.object;
4318
4319 var declaration = scope.findDeclaration(subject.name);
4320
4321 if (declaration) {
4322 if (declaration.isParam) hasSideEffect = true;
4323 } else {
4324 declaration = statement.module.trace(subject.name);
4325
4326 if (!declaration || declaration.isExternal || declaration.isUsed) {
4327 hasSideEffect = true;
4328 }
4329 }
4330 }
4331 },
4332 leave: function (node) {
4333 if (node._scope) scope = scope.parent;
4334 }
4335 });
4336
4337 return hasSideEffect;
4338 }
4339
4340 var Declaration = (function () {
4341 function Declaration(node, isParam, statement) {
4342 babelHelpers.classCallCheck(this, Declaration);
4343
4344 if (node) {
4345 if (node.type === 'FunctionDeclaration') {
4346 this.isFunctionDeclaration = true;
4347 this.functionNode = node;
4348 } else if (node.type === 'VariableDeclarator' && node.init && /FunctionExpression/.test(node.init.type)) {
4349 this.isFunctionDeclaration = true;
4350 this.functionNode = node.init;
4351 }
4352 }
4353
4354 this.statement = statement;
4355 this.name = null;
4356 this.isParam = isParam;
4357
4358 this.isReassigned = false;
4359 this.aliases = [];
4360 }
4361
4362 Declaration.prototype.addAlias = function addAlias(declaration) {
4363 this.aliases.push(declaration);
4364 };
4365
4366 Declaration.prototype.addReference = function addReference(reference) {
4367 reference.declaration = this;
4368 this.name = reference.name; // TODO handle differences of opinion
4369
4370 if (reference.isReassignment) this.isReassigned = true;
4371 };
4372
4373 Declaration.prototype.render = function render(es6) {
4374 if (es6) return this.name;
4375 if (!this.isReassigned || !this.isExported) return this.name;
4376
4377 return 'exports.' + this.name;
4378 };
4379
4380 Declaration.prototype.run = function run$$(strongDependencies) {
4381 if (this.tested) return this.hasSideEffects;
4382 this.tested = true;
4383
4384 if (!this.functionNode) {
4385 this.hasSideEffects = true; // err on the side of caution. TODO handle unambiguous `var x; x = y => z` cases
4386 } else {
4387 this.hasSideEffects = run(this.functionNode.body, this.functionNode._scope, this.statement, strongDependencies, false);
4388 }
4389
4390 return this.hasSideEffects;
4391 };
4392
4393 Declaration.prototype.use = function use() {
4394 this.isUsed = true;
4395 if (this.statement) this.statement.mark();
4396
4397 this.aliases.forEach(function (alias) {
4398 return alias.use();
4399 });
4400 };
4401
4402 return Declaration;
4403 })();
4404
4405 var SyntheticDefaultDeclaration = (function () {
4406 function SyntheticDefaultDeclaration(node, statement, name) {
4407 babelHelpers.classCallCheck(this, SyntheticDefaultDeclaration);
4408
4409 this.node = node;
4410 this.statement = statement;
4411 this.name = name;
4412
4413 this.original = null;
4414 this.isExported = false;
4415 this.aliases = [];
4416 }
4417
4418 SyntheticDefaultDeclaration.prototype.addAlias = function addAlias(declaration) {
4419 this.aliases.push(declaration);
4420 };
4421
4422 SyntheticDefaultDeclaration.prototype.addReference = function addReference(reference) {
4423 // Bind the reference to `this` declaration.
4424 reference.declaration = this;
4425
4426 // Don't change the name to `default`; it's not a valid identifier name.
4427 if (reference.name === 'default') return;
4428
4429 this.name = reference.name;
4430 };
4431
4432 SyntheticDefaultDeclaration.prototype.bind = function bind(declaration) {
4433 this.original = declaration;
4434 };
4435
4436 SyntheticDefaultDeclaration.prototype.render = function render() {
4437 return !this.original || this.original.isReassigned ? this.name : this.original.render();
4438 };
4439
4440 SyntheticDefaultDeclaration.prototype.run = function run$$(strongDependencies) {
4441 if (this.original) {
4442 return this.original.run(strongDependencies);
4443 }
4444
4445 if (/FunctionExpression/.test(this.node.declaration.type)) {
4446 return run(this.node.declaration.body, this.statement.scope, this.statement, strongDependencies, false);
4447 }
4448 };
4449
4450 SyntheticDefaultDeclaration.prototype.use = function use() {
4451 this.isUsed = true;
4452 this.statement.mark();
4453
4454 if (this.original) this.original.use();
4455
4456 this.aliases.forEach(function (alias) {
4457 return alias.use();
4458 });
4459 };
4460
4461 return SyntheticDefaultDeclaration;
4462 })();
4463
4464 var SyntheticNamespaceDeclaration = (function () {
4465 function SyntheticNamespaceDeclaration(module) {
4466 var _this = this;
4467
4468 babelHelpers.classCallCheck(this, SyntheticNamespaceDeclaration);
4469
4470 this.module = module;
4471 this.name = null;
4472
4473 this.needsNamespaceBlock = false;
4474 this.aliases = [];
4475
4476 this.originals = blank();
4477 module.getExports().forEach(function (name) {
4478 _this.originals[name] = module.traceExport(name);
4479 });
4480 }
4481
4482 SyntheticNamespaceDeclaration.prototype.addAlias = function addAlias(declaration) {
4483 this.aliases.push(declaration);
4484 };
4485
4486 SyntheticNamespaceDeclaration.prototype.addReference = function addReference(reference) {
4487 // if we have e.g. `foo.bar`, we can optimise
4488 // the reference by pointing directly to `bar`
4489 if (reference.parts.length) {
4490 reference.name = reference.parts.shift();
4491
4492 reference.end += reference.name.length + 1; // TODO this is brittle
4493
4494 var original = this.originals[reference.name];
4495
4496 // throw with an informative error message if the reference doesn't exist.
4497 if (!original) {
4498 this.module.bundle.onwarn('Export \'' + reference.name + '\' is not defined by \'' + this.module.id + '\'');
4499 reference.isUndefined = true;
4500 return;
4501 }
4502
4503 original.addReference(reference);
4504 return;
4505 }
4506
4507 // otherwise we're accessing the namespace directly,
4508 // which means we need to mark all of this module's
4509 // exports and render a namespace block in the bundle
4510 if (!this.needsNamespaceBlock) {
4511 this.needsNamespaceBlock = true;
4512 this.module.bundle.internalNamespaces.push(this);
4513 }
4514
4515 reference.declaration = this;
4516 this.name = reference.name;
4517 };
4518
4519 SyntheticNamespaceDeclaration.prototype.renderBlock = function renderBlock(indentString) {
4520 var _this2 = this;
4521
4522 var members = keys(this.originals).map(function (name) {
4523 var original = _this2.originals[name];
4524
4525 if (original.isReassigned) {
4526 return indentString + 'get ' + name + ' () { return ' + original.render() + '; }';
4527 }
4528
4529 return '' + indentString + name + ': ' + original.render();
4530 });
4531
4532 return 'var ' + this.render() + ' = Object.freeze({\n' + members.join(',\n') + '\n});\n\n';
4533 };
4534
4535 SyntheticNamespaceDeclaration.prototype.render = function render() {
4536 return this.name;
4537 };
4538
4539 SyntheticNamespaceDeclaration.prototype.use = function use() {
4540 var _this3 = this;
4541
4542 keys(this.originals).forEach(function (name) {
4543 _this3.originals[name].use();
4544 });
4545
4546 this.aliases.forEach(function (alias) {
4547 return alias.use();
4548 });
4549 };
4550
4551 return SyntheticNamespaceDeclaration;
4552 })();
4553
4554 var ExternalDeclaration = (function () {
4555 function ExternalDeclaration(module, name) {
4556 babelHelpers.classCallCheck(this, ExternalDeclaration);
4557
4558 this.module = module;
4559 this.name = name;
4560 this.isExternal = true;
4561 }
4562
4563 ExternalDeclaration.prototype.addAlias = function addAlias() {
4564 // noop
4565 };
4566
4567 ExternalDeclaration.prototype.addReference = function addReference(reference) {
4568 reference.declaration = this;
4569
4570 if (this.name === 'default' || this.name === '*') {
4571 this.module.suggestName(reference.name);
4572 }
4573 };
4574
4575 ExternalDeclaration.prototype.render = function render(es6) {
4576 if (this.name === '*') {
4577 return this.module.name;
4578 }
4579
4580 if (this.name === 'default') {
4581 return !es6 && this.module.exportsNames ? this.module.name + '__default' : this.module.name;
4582 }
4583
4584 return es6 ? this.name : this.module.name + '.' + this.name;
4585 };
4586
4587 ExternalDeclaration.prototype.run = function run() {
4588 return true;
4589 };
4590
4591 ExternalDeclaration.prototype.use = function use() {
4592 // noop?
4593 };
4594
4595 return ExternalDeclaration;
4596 })();
4597
4598 var extractors = {
4599 Identifier: function (names, param) {
4600 names.push(param.name);
4601 },
4602
4603 ObjectPattern: function (names, param) {
4604 param.properties.forEach(function (prop) {
4605 extractors[prop.key.type](names, prop.key);
4606 });
4607 },
4608
4609 ArrayPattern: function (names, param) {
4610 param.elements.forEach(function (element) {
4611 if (element) extractors[element.type](names, element);
4612 });
4613 },
4614
4615 RestElement: function (names, param) {
4616 extractors[param.argument.type](names, param.argument);
4617 },
4618
4619 AssignmentPattern: function (names, param) {
4620 return extractors[param.left.type](names, param.left);
4621 }
4622 };
4623
4624 function extractNames(param) {
4625 var names = [];
4626
4627 extractors[param.type](names, param);
4628 return names;
4629 }
4630
4631 var Scope = (function () {
4632 function Scope(options) {
4633 var _this = this;
4634
4635 babelHelpers.classCallCheck(this, Scope);
4636
4637 options = options || {};
4638
4639 this.parent = options.parent;
4640 this.statement = options.statement || this.parent.statement;
4641 this.isBlockScope = !!options.block;
4642 this.isTopLevel = !this.parent || this.parent.isTopLevel && this.isBlockScope;
4643
4644 this.declarations = blank();
4645
4646 if (options.params) {
4647 options.params.forEach(function (param) {
4648 extractNames(param).forEach(function (name) {
4649 _this.declarations[name] = new Declaration(param, true, _this.statement);
4650 });
4651 });
4652 }
4653 }
4654
4655 Scope.prototype.addDeclaration = function addDeclaration(node, isBlockDeclaration, isVar) {
4656 var _this2 = this;
4657
4658 if (!isBlockDeclaration && this.isBlockScope) {
4659 // it's a `var` or function node, and this
4660 // is a block scope, so we need to go up
4661 this.parent.addDeclaration(node, isBlockDeclaration, isVar);
4662 } else {
4663 extractNames(node.id).forEach(function (name) {
4664 _this2.declarations[name] = new Declaration(node, false, _this2.statement);
4665 });
4666 }
4667 };
4668
4669 Scope.prototype.contains = function contains(name) {
4670 return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
4671 };
4672
4673 Scope.prototype.eachDeclaration = function eachDeclaration(fn) {
4674 var _this3 = this;
4675
4676 keys(this.declarations).forEach(function (key) {
4677 fn(key, _this3.declarations[key]);
4678 });
4679 };
4680
4681 Scope.prototype.findDeclaration = function findDeclaration(name) {
4682 return this.declarations[name] || this.parent && this.parent.findDeclaration(name);
4683 };
4684
4685 return Scope;
4686 })();
4687
4688 var blockDeclarations = {
4689 'const': true,
4690 'let': true
4691 };
4692 function attachScopes(statement) {
4693 var node = statement.node;
4694 var scope = statement.scope;
4695
4696 walk(node, {
4697 enter: function (node, parent) {
4698 // function foo () {...}
4699 // class Foo {...}
4700 if (/(Function|Class)Declaration/.test(node.type)) {
4701 scope.addDeclaration(node, false, false);
4702 }
4703
4704 // var foo = 1, bar = 2
4705 if (node.type === 'VariableDeclaration') {
4706 (function () {
4707 var isBlockDeclaration = blockDeclarations[node.kind];
4708
4709 node.declarations.forEach(function (declarator) {
4710 scope.addDeclaration(declarator, isBlockDeclaration, true);
4711 });
4712 })();
4713 }
4714
4715 var newScope = undefined;
4716
4717 // create new function scope
4718 if (/Function/.test(node.type)) {
4719 newScope = new Scope({
4720 parent: scope,
4721 block: false,
4722 params: node.params
4723 });
4724
4725 // named function expressions - the name is considered
4726 // part of the function's scope
4727 if (node.type === 'FunctionExpression' && node.id) {
4728 newScope.addDeclaration(node, false, false);
4729 }
4730 }
4731
4732 // create new block scope
4733 if (node.type === 'BlockStatement' && (!parent || !/Function/.test(parent.type))) {
4734 newScope = new Scope({
4735 parent: scope,
4736 block: true
4737 });
4738 }
4739
4740 // catch clause has its own block scope
4741 if (node.type === 'CatchClause') {
4742 newScope = new Scope({
4743 parent: scope,
4744 params: [node.param],
4745 block: true
4746 });
4747 }
4748
4749 if (newScope) {
4750 Object.defineProperty(node, '_scope', {
4751 value: newScope,
4752 configurable: true
4753 });
4754
4755 scope = newScope;
4756 }
4757 },
4758 leave: function (node) {
4759 if (node._scope) {
4760 scope = scope.parent;
4761 }
4762 }
4763 });
4764 }
4765
4766 function isFunctionDeclaration(node) {
4767 if (!node) return false;
4768
4769 return node.type === 'FunctionDeclaration' || node.type === 'VariableDeclaration' && node.init && /FunctionExpression/.test(node.init.type);
4770 }
4771
4772 function getLocation$1(source, charIndex) {
4773 var lines = source.split('\n');
4774 var len = lines.length;
4775
4776 var lineStart = 0;
4777 var i = undefined;
4778
4779 for (i = 0; i < len; i += 1) {
4780 var line = lines[i];
4781 var lineEnd = lineStart + line.length + 1; // +1 for newline
4782
4783 if (lineEnd > charIndex) {
4784 return { line: i + 1, column: charIndex - lineStart };
4785 }
4786
4787 lineStart = lineEnd;
4788 }
4789
4790 throw new Error('Could not determine location of character');
4791 }
4792
4793 var Reference = function Reference(node, scope, statement) {
4794 babelHelpers.classCallCheck(this, Reference);
4795
4796 this.node = node;
4797 this.scope = scope;
4798 this.statement = statement;
4799
4800 this.declaration = null; // bound later
4801
4802 this.parts = [];
4803
4804 var root = node;
4805 while (root.type === 'MemberExpression') {
4806 this.parts.unshift(root.property.name);
4807 root = root.object;
4808 }
4809
4810 this.name = root.name;
4811
4812 this.start = node.start;
4813 this.end = node.start + this.name.length; // can be overridden in the case of namespace members
4814 this.rewritten = false;
4815 };
4816
4817 var Statement = (function () {
4818 function Statement(node, module, start, end) {
4819 babelHelpers.classCallCheck(this, Statement);
4820
4821 this.node = node;
4822 this.module = module;
4823 this.start = start;
4824 this.end = end;
4825 this.next = null; // filled in later
4826
4827 this.scope = new Scope({ statement: this });
4828
4829 this.references = [];
4830 this.stringLiteralRanges = [];
4831
4832 this.isIncluded = false;
4833 this.ran = false;
4834
4835 this.isImportDeclaration = node.type === 'ImportDeclaration';
4836 this.isExportDeclaration = /^Export/.test(node.type);
4837 this.isReexportDeclaration = this.isExportDeclaration && !!node.source;
4838
4839 this.isFunctionDeclaration = isFunctionDeclaration(node) || this.isExportDeclaration && isFunctionDeclaration(node.declaration);
4840 }
4841
4842 Statement.prototype.firstPass = function firstPass() {
4843 if (this.isImportDeclaration) return; // nothing to analyse
4844
4845 // attach scopes
4846 attachScopes(this);
4847
4848 // find references
4849 var statement = this;
4850 var module = this.module;
4851 var references = this.references;
4852 var scope = this.scope;
4853 var stringLiteralRanges = this.stringLiteralRanges;
4854
4855 var readDepth = 0;
4856
4857 walk(this.node, {
4858 enter: function (node, parent) {
4859 // warn about eval
4860 if (node.type === 'CallExpression' && node.callee.name === 'eval' && !scope.contains('eval')) {
4861 module.bundle.onwarn('Use of `eval` (in ' + module.id + ') is discouraged, as it may cause issues with minification. See https://github.com/rollup/rollup/wiki/Troubleshooting#avoiding-eval for more details');
4862 }
4863
4864 // skip re-export declarations
4865 if (node.type === 'ExportNamedDeclaration' && node.source) return this.skip();
4866
4867 if (node.type === 'TemplateElement') stringLiteralRanges.push([node.start, node.end]);
4868 if (node.type === 'Literal' && typeof node.value === 'string' && /\n/.test(node.raw)) {
4869 stringLiteralRanges.push([node.start + 1, node.end - 1]);
4870 }
4871
4872 if (node._scope) scope = node._scope;
4873 if (/Function/.test(node.type)) readDepth += 1;
4874
4875 // special case – shorthand properties. because node.key === node.value,
4876 // we can't differentiate once we've descended into the node
4877 if (node.type === 'Property' && node.shorthand) {
4878 var reference = new Reference(node.key, scope);
4879 reference.isShorthandProperty = true; // TODO feels a bit kludgy
4880 references.push(reference);
4881 return this.skip();
4882 }
4883
4884 var isReassignment = undefined;
4885
4886 if (parent && parent.type in modifierNodes) {
4887 var subject = parent[modifierNodes[parent.type]];
4888 var depth = 0;
4889
4890 while (subject.type === 'MemberExpression') {
4891 subject = subject.object;
4892 depth += 1;
4893 }
4894
4895 var importDeclaration = module.imports[subject.name];
4896
4897 if (!scope.contains(subject.name) && importDeclaration) {
4898 var minDepth = importDeclaration.name === '*' ? 2 : // cannot do e.g. `namespace.foo = bar`
4899 1; // cannot do e.g. `foo = bar`, but `foo.bar = bar` is fine
4900
4901 if (depth < minDepth) {
4902 var err = new Error('Illegal reassignment to import \'' + subject.name + '\'');
4903 err.file = module.id;
4904 err.loc = getLocation$1(module.magicString.toString(), subject.start);
4905 throw err;
4906 }
4907 }
4908
4909 isReassignment = !depth;
4910 }
4911
4912 if (isReference(node, parent)) {
4913 // function declaration IDs are a special case – they're associated
4914 // with the parent scope
4915 var referenceScope = parent.type === 'FunctionDeclaration' && node === parent.id ? scope.parent : scope;
4916
4917 var reference = new Reference(node, referenceScope, statement);
4918 reference.isReassignment = isReassignment;
4919
4920 references.push(reference);
4921
4922 this.skip(); // don't descend from `foo.bar.baz` into `foo.bar`
4923 }
4924 },
4925 leave: function (node) {
4926 if (node._scope) scope = scope.parent;
4927 if (/Function/.test(node.type)) readDepth -= 1;
4928 }
4929 });
4930 };
4931
4932 Statement.prototype.mark = function mark() {
4933 if (this.isIncluded) return; // prevent infinite loops
4934 this.isIncluded = true;
4935
4936 this.references.forEach(function (reference) {
4937 if (reference.declaration) reference.declaration.use();
4938 });
4939 };
4940
4941 Statement.prototype.run = function run$$(strongDependencies, safe) {
4942 if (this.ran && this.isIncluded || this.isImportDeclaration || this.isFunctionDeclaration) return;
4943 this.ran = true;
4944
4945 if (run(this.node, this.scope, this, strongDependencies, false, safe)) {
4946 this.mark();
4947 return true;
4948 }
4949 };
4950
4951 Statement.prototype.source = function source() {
4952 return this.module.source.slice(this.start, this.end);
4953 };
4954
4955 Statement.prototype.toString = function toString() {
4956 return this.module.magicString.slice(this.start, this.end);
4957 };
4958
4959 return Statement;
4960 })();
4961
4962 var reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public'.split(' ');
4963 var builtins = 'Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl'.split(' ');
4964
4965 var blacklisted = blank();
4966 reservedWords.concat(builtins).forEach(function (word) {
4967 return blacklisted[word] = true;
4968 });
4969 function makeLegalIdentifier(str) {
4970 str = str.replace(/-(\w)/g, function (_, letter) {
4971 return letter.toUpperCase();
4972 }).replace(/[^$_a-zA-Z0-9]/g, '_');
4973
4974 if (/\d/.test(str[0]) || blacklisted[str]) str = '_' + str;
4975
4976 return str;
4977 }
4978
4979 function isTruthy(node) {
4980 if (node.type === 'Literal') return !!node.value;
4981 if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
4982 if (node.operator in operators) return operators[node.operator](node);
4983 }
4984
4985 function isFalsy(node) {
4986 return not(isTruthy(node));
4987 }
4988
4989 function not(value) {
4990 return value === undefined ? value : !value;
4991 }
4992
4993 function equals(a, b, strict) {
4994 if (a.type !== b.type) return undefined;
4995 if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
4996 }
4997
4998 var operators = {
4999 '==': function (x) {
5000 return equals(x.left, x.right, false);
5001 },
5002
5003 '!=': function (x) {
5004 return not(operators['=='](x));
5005 },
5006
5007 '===': function (x) {
5008 return equals(x.left, x.right, true);
5009 },
5010
5011 '!==': function (x) {
5012 return not(operators['==='](x));
5013 },
5014
5015 '!': function (x) {
5016 return isFalsy(x.argument);
5017 },
5018
5019 '&&': function (x) {
5020 return isTruthy(x.left) && isTruthy(x.right);
5021 },
5022
5023 '||': function (x) {
5024 return isTruthy(x.left) || isTruthy(x.right);
5025 }
5026 };
5027
5028 function emptyBlockStatement(start, end) {
5029 return {
5030 start: start, end: end,
5031 type: 'BlockStatement',
5032 body: []
5033 };
5034 }
5035
5036 var Module = (function () {
5037 function Module(_ref) {
5038 var id = _ref.id;
5039 var code = _ref.code;
5040 var originalCode = _ref.originalCode;
5041 var ast = _ref.ast;
5042 var sourceMapChain = _ref.sourceMapChain;
5043 var bundle = _ref.bundle;
5044 babelHelpers.classCallCheck(this, Module);
5045
5046 this.code = code;
5047 this.originalCode = originalCode;
5048 this.sourceMapChain = sourceMapChain;
5049
5050 this.bundle = bundle;
5051 this.id = id;
5052
5053 // all dependencies
5054 this.dependencies = [];
5055 this.resolvedIds = blank();
5056
5057 // imports and exports, indexed by local name
5058 this.imports = blank();
5059 this.exports = blank();
5060 this.reexports = blank();
5061
5062 this.exportAllSources = [];
5063 this.exportAllModules = null;
5064
5065 // By default, `id` is the filename. Custom resolvers and loaders
5066 // can change that, but it makes sense to use it for the source filename
5067 this.magicString = new MagicString(code, {
5068 filename: id,
5069 indentExclusionRanges: []
5070 });
5071
5072 // remove existing sourceMappingURL comments
5073 var pattern = new RegExp('\\/\\/#\\s+' + SOURCEMAPPING_URL$1 + '=.+\\n?', 'g');
5074 var match = undefined;
5075 while (match = pattern.exec(code)) {
5076 this.magicString.remove(match.index, match.index + match[0].length);
5077 }
5078
5079 this.comments = [];
5080 this.statements = this.parse(ast);
5081
5082 this.declarations = blank();
5083 this.analyse();
5084
5085 this.strongDependencies = [];
5086 }
5087
5088 Module.prototype.addExport = function addExport(statement) {
5089 var _this = this;
5090
5091 var node = statement.node;
5092 var source = node.source && node.source.value;
5093
5094 // export { name } from './other.js'
5095 if (source) {
5096 if (! ~this.dependencies.indexOf(source)) this.dependencies.push(source);
5097
5098 if (node.type === 'ExportAllDeclaration') {
5099 // Store `export * from '...'` statements in an array of delegates.
5100 // When an unknown import is encountered, we see if one of them can satisfy it.
5101 this.exportAllSources.push(source);
5102 } else {
5103 node.specifiers.forEach(function (specifier) {
5104 _this.reexports[specifier.exported.name] = {
5105 start: specifier.start,
5106 source: source,
5107 localName: specifier.local.name,
5108 module: null // filled in later
5109 };
5110 });
5111 }
5112 }
5113
5114 // export default function foo () {}
5115 // export default foo;
5116 // export default 42;
5117 else if (node.type === 'ExportDefaultDeclaration') {
5118 var identifier = node.declaration.id && node.declaration.id.name || node.declaration.name;
5119
5120 this.exports.default = {
5121 localName: 'default',
5122 identifier: identifier
5123 };
5124
5125 // create a synthetic declaration
5126 this.declarations.default = new SyntheticDefaultDeclaration(node, statement, identifier || this.basename());
5127 }
5128
5129 // export { foo, bar, baz }
5130 // export var foo = 42;
5131 // export var a = 1, b = 2, c = 3;
5132 // export function foo () {}
5133 else if (node.type === 'ExportNamedDeclaration') {
5134 if (node.specifiers.length) {
5135 // export { foo, bar, baz }
5136 node.specifiers.forEach(function (specifier) {
5137 var localName = specifier.local.name;
5138 var exportedName = specifier.exported.name;
5139
5140 _this.exports[exportedName] = { localName: localName };
5141 });
5142 } else {
5143 var declaration = node.declaration;
5144
5145 var _name = undefined;
5146
5147 if (declaration.type === 'VariableDeclaration') {
5148 // export var foo = 42
5149 _name = declaration.declarations[0].id.name;
5150 } else {
5151 // export function foo () {}
5152 _name = declaration.id.name;
5153 }
5154
5155 this.exports[_name] = { localName: _name };
5156 }
5157 }
5158 };
5159
5160 Module.prototype.addImport = function addImport(statement) {
5161 var _this2 = this;
5162
5163 var node = statement.node;
5164 var source = node.source.value;
5165
5166 if (! ~this.dependencies.indexOf(source)) this.dependencies.push(source);
5167
5168 node.specifiers.forEach(function (specifier) {
5169 var localName = specifier.local.name;
5170
5171 if (_this2.imports[localName]) {
5172 var err = new Error('Duplicated import \'' + localName + '\'');
5173 err.file = _this2.id;
5174 err.loc = getLocation$1(_this2.code, specifier.start);
5175 throw err;
5176 }
5177
5178 var isDefault = specifier.type === 'ImportDefaultSpecifier';
5179 var isNamespace = specifier.type === 'ImportNamespaceSpecifier';
5180
5181 var name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
5182 _this2.imports[localName] = { source: source, name: name, module: null };
5183 });
5184 };
5185
5186 Module.prototype.analyse = function analyse() {
5187 var _this3 = this;
5188
5189 // discover this module's imports and exports
5190 this.statements.forEach(function (statement) {
5191 if (statement.isImportDeclaration) _this3.addImport(statement);else if (statement.isExportDeclaration) _this3.addExport(statement);
5192
5193 statement.firstPass();
5194
5195 statement.scope.eachDeclaration(function (name, declaration) {
5196 _this3.declarations[name] = declaration;
5197 });
5198 });
5199 };
5200
5201 Module.prototype.basename = function basename() {
5202 var base = _basename(this.id);
5203 var ext = extname(this.id);
5204
5205 return makeLegalIdentifier(ext ? base.slice(0, -ext.length) : base);
5206 };
5207
5208 Module.prototype.bindAliases = function bindAliases() {
5209 var _this4 = this;
5210
5211 keys(this.declarations).forEach(function (name) {
5212 if (name === '*') return;
5213
5214 var declaration = _this4.declarations[name];
5215 var statement = declaration.statement;
5216
5217 if (statement.node.type !== 'VariableDeclaration') return;
5218
5219 var init = statement.node.declarations[0].init;
5220 if (!init || init.type === 'FunctionExpression') return;
5221
5222 statement.references.forEach(function (reference) {
5223 if (reference.name === name) return;
5224
5225 var otherDeclaration = _this4.trace(reference.name);
5226 if (otherDeclaration) otherDeclaration.addAlias(declaration);
5227 });
5228 });
5229 };
5230
5231 Module.prototype.bindImportSpecifiers = function bindImportSpecifiers() {
5232 var _this5 = this;
5233
5234 [this.imports, this.reexports].forEach(function (specifiers) {
5235 keys(specifiers).forEach(function (name) {
5236 var specifier = specifiers[name];
5237
5238 var id = _this5.resolvedIds[specifier.source];
5239 specifier.module = _this5.bundle.moduleById[id];
5240 });
5241 });
5242
5243 this.exportAllModules = this.exportAllSources.map(function (source) {
5244 var id = _this5.resolvedIds[source];
5245 return _this5.bundle.moduleById[id];
5246 });
5247 };
5248
5249 Module.prototype.bindReferences = function bindReferences() {
5250 var _this6 = this;
5251
5252 if (this.declarations.default) {
5253 if (this.exports.default.identifier) {
5254 var declaration = this.trace(this.exports.default.identifier);
5255 if (declaration) this.declarations.default.bind(declaration);
5256 }
5257 }
5258
5259 this.statements.forEach(function (statement) {
5260 // skip `export { foo, bar, baz }`...
5261 if (statement.node.type === 'ExportNamedDeclaration' && statement.node.specifiers.length) {
5262 // ...unless this is the entry module
5263 if (_this6 !== _this6.bundle.entryModule) return;
5264 }
5265
5266 statement.references.forEach(function (reference) {
5267 var declaration = reference.scope.findDeclaration(reference.name) || _this6.trace(reference.name);
5268
5269 if (declaration) {
5270 declaration.addReference(reference);
5271 } else {
5272 // TODO handle globals
5273 _this6.bundle.assumedGlobals[reference.name] = true;
5274 }
5275 });
5276 });
5277 };
5278
5279 Module.prototype.consolidateDependencies = function consolidateDependencies() {
5280 var _this7 = this;
5281
5282 var strongDependencies = [];
5283 var weakDependencies = [];
5284
5285 // treat all imports as weak dependencies
5286 this.dependencies.forEach(function (source) {
5287 var id = _this7.resolvedIds[source];
5288 var dependency = _this7.bundle.moduleById[id];
5289
5290 if (!dependency.isExternal && ! ~weakDependencies.indexOf(dependency)) {
5291 weakDependencies.push(dependency);
5292 }
5293 });
5294
5295 strongDependencies = this.strongDependencies.filter(function (module) {
5296 return module !== _this7;
5297 });
5298
5299 return { strongDependencies: strongDependencies, weakDependencies: weakDependencies };
5300 };
5301
5302 Module.prototype.getExports = function getExports() {
5303 var exports = blank();
5304
5305 keys(this.exports).forEach(function (name) {
5306 exports[name] = true;
5307 });
5308
5309 keys(this.reexports).forEach(function (name) {
5310 exports[name] = true;
5311 });
5312
5313 this.exportAllModules.forEach(function (module) {
5314 module.getExports().forEach(function (name) {
5315 if (name !== 'default') exports[name] = true;
5316 });
5317 });
5318
5319 return keys(exports);
5320 };
5321
5322 Module.prototype.namespace = function namespace() {
5323 if (!this.declarations['*']) {
5324 this.declarations['*'] = new SyntheticNamespaceDeclaration(this);
5325 }
5326
5327 return this.declarations['*'];
5328 };
5329
5330 Module.prototype.parse = function parse$$(ast) {
5331 var _this8 = this;
5332
5333 // The ast can be supplied programmatically (but usually won't be)
5334 if (!ast) {
5335 // Try to extract a list of top-level statements/declarations. If
5336 // the parse fails, attach file info and abort
5337 try {
5338 ast = parse(this.code, {
5339 ecmaVersion: 6,
5340 sourceType: 'module',
5341 onComment: function (block, text, start, end) {
5342 return _this8.comments.push({ block: block, text: text, start: start, end: end });
5343 },
5344 preserveParens: true
5345 });
5346 } catch (err) {
5347 err.code = 'PARSE_ERROR';
5348 err.file = this.id; // see above - not necessarily true, but true enough
5349 err.message += ' in ' + this.id;
5350 throw err;
5351 }
5352 }
5353
5354 walk(ast, {
5355 enter: function (node) {
5356 // eliminate dead branches early
5357 if (node.type === 'IfStatement') {
5358 if (isFalsy(node.test)) {
5359 _this8.magicString.overwrite(node.consequent.start, node.consequent.end, '{}');
5360 node.consequent = emptyBlockStatement(node.consequent.start, node.consequent.end);
5361 } else if (node.alternate && isTruthy(node.test)) {
5362 _this8.magicString.overwrite(node.alternate.start, node.alternate.end, '{}');
5363 node.alternate = emptyBlockStatement(node.alternate.start, node.alternate.end);
5364 }
5365 }
5366
5367 _this8.magicString.addSourcemapLocation(node.start);
5368 _this8.magicString.addSourcemapLocation(node.end);
5369 }
5370 });
5371
5372 var statements = [];
5373 var lastChar = 0;
5374 var commentIndex = 0;
5375
5376 ast.body.forEach(function (node) {
5377 if (node.type === 'EmptyStatement') return;
5378
5379 if (node.type === 'ExportNamedDeclaration' && node.declaration && node.declaration.type === 'VariableDeclaration' && node.declaration.declarations && node.declaration.declarations.length > 1) {
5380 // push a synthetic export declaration
5381 var syntheticNode = {
5382 type: 'ExportNamedDeclaration',
5383 specifiers: node.declaration.declarations.map(function (declarator) {
5384 var id = { name: declarator.id.name };
5385 return {
5386 local: id,
5387 exported: id
5388 };
5389 }),
5390 isSynthetic: true
5391 };
5392
5393 var statement = new Statement(syntheticNode, _this8, node.start, node.start);
5394 statements.push(statement);
5395
5396 _this8.magicString.remove(node.start, node.declaration.start);
5397 node = node.declaration;
5398 }
5399
5400 // special case - top-level var declarations with multiple declarators
5401 // should be split up. Otherwise, we may end up including code we
5402 // don't need, just because an unwanted declarator is included
5403 if (node.type === 'VariableDeclaration' && node.declarations.length > 1) {
5404 // remove the leading var/let/const... UNLESS the previous node
5405 // was also a synthetic node, in which case it'll get removed anyway
5406 var lastStatement = statements[statements.length - 1];
5407 if (!lastStatement || !lastStatement.node.isSynthetic) {
5408 _this8.magicString.remove(node.start, node.declarations[0].start);
5409 }
5410
5411 node.declarations.forEach(function (declarator) {
5412 var start = declarator.start;
5413 var end = declarator.end;
5414
5415 var syntheticNode = {
5416 type: 'VariableDeclaration',
5417 kind: node.kind,
5418 start: start,
5419 end: end,
5420 declarations: [declarator],
5421 isSynthetic: true
5422 };
5423
5424 var statement = new Statement(syntheticNode, _this8, start, end);
5425 statements.push(statement);
5426 });
5427
5428 lastChar = node.end; // TODO account for trailing line comment
5429 } else {
5430 var comment = undefined;
5431 do {
5432 comment = _this8.comments[commentIndex];
5433 if (!comment) break;
5434 if (comment.start > node.start) break;
5435 commentIndex += 1;
5436 } while (comment.end < lastChar);
5437
5438 var start = comment ? Math.min(comment.start, node.start) : node.start;
5439 var end = node.end; // TODO account for trailing line comment
5440
5441 var statement = new Statement(node, _this8, start, end);
5442 statements.push(statement);
5443
5444 lastChar = end;
5445 }
5446 });
5447
5448 var i = statements.length;
5449 var next = this.code.length;
5450 while (i--) {
5451 statements[i].next = next;
5452 if (!statements[i].isSynthetic) next = statements[i].start;
5453 }
5454
5455 return statements;
5456 };
5457
5458 Module.prototype.render = function render(es6) {
5459 var _this9 = this;
5460
5461 var magicString = this.magicString.clone();
5462
5463 this.statements.forEach(function (statement) {
5464 if (!statement.isIncluded) {
5465 magicString.remove(statement.start, statement.next);
5466 return;
5467 }
5468
5469 statement.stringLiteralRanges.forEach(function (range) {
5470 return magicString.indentExclusionRanges.push(range);
5471 });
5472
5473 // skip `export { foo, bar, baz }`
5474 if (statement.node.type === 'ExportNamedDeclaration') {
5475 if (statement.node.isSynthetic) return;
5476
5477 // skip `export { foo, bar, baz }`
5478 if (statement.node.specifiers.length) {
5479 magicString.remove(statement.start, statement.next);
5480 return;
5481 }
5482 }
5483
5484 // split up/remove var declarations as necessary
5485 if (statement.node.isSynthetic) {
5486 // insert `var/let/const` if necessary
5487 var declaration = _this9.declarations[statement.node.declarations[0].id.name];
5488 if (!(declaration.isExported && declaration.isReassigned)) {
5489 // TODO encapsulate this
5490 magicString.insert(statement.start, statement.node.kind + ' ');
5491 }
5492
5493 magicString.overwrite(statement.end, statement.next, ';\n'); // TODO account for trailing newlines
5494 }
5495
5496 var toDeshadow = blank();
5497
5498 statement.references.forEach(function (reference) {
5499 var start = reference.start;
5500 var end = reference.end;
5501
5502 if (reference.isUndefined) {
5503 magicString.overwrite(start, end, 'undefined', true);
5504 }
5505
5506 var declaration = reference.declaration;
5507
5508 if (declaration) {
5509 var _name2 = declaration.render(es6);
5510
5511 // the second part of this check is necessary because of
5512 // namespace optimisation – name of `foo.bar` could be `bar`
5513 if (reference.name === _name2 && _name2.length === end - start) return;
5514
5515 reference.rewritten = true;
5516
5517 // prevent local variables from shadowing renamed references
5518 var identifier = _name2.match(/[^\.]+/)[0];
5519 if (reference.scope.contains(identifier)) {
5520 toDeshadow[identifier] = identifier + '$$'; // TODO more robust mechanism
5521 }
5522
5523 if (reference.isShorthandProperty) {
5524 magicString.insert(end, ': ' + _name2);
5525 } else {
5526 magicString.overwrite(start, end, _name2, true);
5527 }
5528 }
5529 });
5530
5531 if (keys(toDeshadow).length) {
5532 statement.references.forEach(function (reference) {
5533 if (!reference.rewritten && reference.name in toDeshadow) {
5534 magicString.overwrite(reference.start, reference.end, toDeshadow[reference.name], true);
5535 }
5536 });
5537 }
5538
5539 // modify exports as necessary
5540 if (statement.isExportDeclaration) {
5541 // remove `export` from `export var foo = 42`
5542 if (statement.node.type === 'ExportNamedDeclaration' && statement.node.declaration.type === 'VariableDeclaration') {
5543 var _name3 = statement.node.declaration.declarations[0].id.name;
5544 var declaration = _this9.declarations[_name3];
5545
5546 var end = declaration.isExported && declaration.isReassigned ? statement.node.declaration.declarations[0].start : statement.node.declaration.start;
5547
5548 magicString.remove(statement.node.start, end);
5549 } else if (statement.node.type === 'ExportAllDeclaration') {
5550 // TODO: remove once `export * from 'external'` is supported.
5551 magicString.remove(statement.start, statement.next);
5552 }
5553
5554 // remove `export` from `export class Foo {...}` or `export default Foo`
5555 // TODO default exports need different treatment
5556 else if (statement.node.declaration.id) {
5557 magicString.remove(statement.node.start, statement.node.declaration.start);
5558 } else if (statement.node.type === 'ExportDefaultDeclaration') {
5559 var defaultDeclaration = _this9.declarations.default;
5560
5561 // prevent `var foo = foo`
5562 if (defaultDeclaration.original && !defaultDeclaration.original.isReassigned) {
5563 magicString.remove(statement.start, statement.next);
5564 return;
5565 }
5566
5567 var defaultName = defaultDeclaration.render();
5568
5569 // prevent `var undefined = sideEffectyDefault(foo)`
5570 if (!defaultDeclaration.isExported && !defaultDeclaration.isUsed) {
5571 magicString.remove(statement.start, statement.node.declaration.start);
5572 return;
5573 }
5574
5575 // anonymous functions should be converted into declarations
5576 if (statement.node.declaration.type === 'FunctionExpression') {
5577 magicString.overwrite(statement.node.start, statement.node.declaration.start + 8, 'function ' + defaultName);
5578 } else {
5579 magicString.overwrite(statement.node.start, statement.node.declaration.start, 'var ' + defaultName + ' = ');
5580 }
5581 } else {
5582 throw new Error('Unhandled export');
5583 }
5584 }
5585 });
5586
5587 // add namespace block if necessary
5588 var namespace = this.declarations['*'];
5589 if (namespace && namespace.needsNamespaceBlock) {
5590 magicString.append('\n\n' + namespace.renderBlock(magicString.getIndentString()));
5591 }
5592
5593 return magicString.trim();
5594 };
5595
5596 Module.prototype.run = function run(safe) {
5597 var _this10 = this;
5598
5599 var marked = false;
5600
5601 this.statements.forEach(function (statement) {
5602 marked = marked || statement.run(_this10.strongDependencies, safe);
5603 });
5604
5605 return marked;
5606 };
5607
5608 Module.prototype.trace = function trace(name) {
5609 if (name in this.declarations) return this.declarations[name];
5610 if (name in this.imports) {
5611 var importDeclaration = this.imports[name];
5612 var otherModule = importDeclaration.module;
5613
5614 if (importDeclaration.name === '*' && !otherModule.isExternal) {
5615 return otherModule.namespace();
5616 }
5617
5618 var declaration = otherModule.traceExport(importDeclaration.name);
5619
5620 if (!declaration) throw new Error('Module ' + otherModule.id + ' does not export ' + importDeclaration.name + ' (imported by ' + this.id + ')');
5621 return declaration;
5622 }
5623
5624 return null;
5625 };
5626
5627 Module.prototype.traceExport = function traceExport(name) {
5628 // export { foo } from './other.js'
5629 var reexportDeclaration = this.reexports[name];
5630 if (reexportDeclaration) {
5631 var declaration = reexportDeclaration.module.traceExport(reexportDeclaration.localName);
5632
5633 if (!declaration) {
5634 var err = new Error('\'' + reexportDeclaration.localName + '\' is not exported by \'' + reexportDeclaration.module.id + '\' (imported by \'' + this.id + '\')');
5635 err.file = this.id;
5636 err.loc = getLocation$1(this.code, reexportDeclaration.start);
5637 throw err;
5638 }
5639
5640 return declaration;
5641 }
5642
5643 var exportDeclaration = this.exports[name];
5644 if (exportDeclaration) {
5645 return this.trace(exportDeclaration.localName);
5646 }
5647
5648 for (var i = 0; i < this.exportAllModules.length; i += 1) {
5649 var _module = this.exportAllModules[i];
5650 var declaration = _module.traceExport(name);
5651
5652 if (declaration) return declaration;
5653 }
5654 };
5655
5656 return Module;
5657 })();
5658
5659 var ExternalModule = (function () {
5660 function ExternalModule(id) {
5661 babelHelpers.classCallCheck(this, ExternalModule);
5662
5663 this.id = id;
5664 this.name = makeLegalIdentifier(id);
5665
5666 this.nameSuggestions = blank();
5667 this.mostCommonSuggestion = 0;
5668
5669 this.isExternal = true;
5670 this.declarations = blank();
5671
5672 this.exportsNames = false;
5673 }
5674
5675 ExternalModule.prototype.suggestName = function suggestName(name) {
5676 if (!this.nameSuggestions[name]) this.nameSuggestions[name] = 0;
5677 this.nameSuggestions[name] += 1;
5678
5679 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
5680 this.mostCommonSuggestion = this.nameSuggestions[name];
5681 this.name = name;
5682 }
5683 };
5684
5685 ExternalModule.prototype.traceExport = function traceExport(name) {
5686 if (name !== 'default' && name !== '*') {
5687 this.exportsNames = true;
5688 }
5689
5690 return this.declarations[name] || (this.declarations[name] = new ExternalDeclaration(this, name));
5691 };
5692
5693 return ExternalModule;
5694 })();
5695
5696 function getName(x) {
5697 return x.name;
5698 }
5699
5700 function quoteId(x) {
5701 return "'" + x.id + "'";
5702 }
5703
5704 function req(x) {
5705 return "require('" + x.id + "')";
5706 }
5707
5708 function getInteropBlock(bundle) {
5709 return bundle.externalModules.map(function (module) {
5710 return module.declarations.default ? module.exportsNames ? 'var ' + module.name + '__default = \'default\' in ' + module.name + ' ? ' + module.name + '[\'default\'] : ' + module.name + ';' : module.name + ' = \'default\' in ' + module.name + ' ? ' + module.name + '[\'default\'] : ' + module.name + ';' : null;
5711 }).filter(Boolean).join('\n');
5712 }
5713
5714 function getExportBlock(entryModule, exportMode) {
5715 var mechanism = arguments.length <= 2 || arguments[2] === undefined ? 'return' : arguments[2];
5716
5717 if (exportMode === 'default') {
5718 return mechanism + ' ' + entryModule.declarations.default.render(false) + ';';
5719 }
5720
5721 return entryModule.getExports().map(function (name) {
5722 var prop = name === 'default' ? '[\'default\']' : '.' + name;
5723 var declaration = entryModule.traceExport(name);
5724
5725 var lhs = 'exports' + prop;
5726 var rhs = declaration.render(false);
5727
5728 // prevent `exports.count = exports.count`
5729 if (lhs === rhs) return null;
5730
5731 return lhs + ' = ' + rhs + ';';
5732 }).filter(Boolean).join('\n');
5733 }
5734
5735 function umd(bundle, magicString, _ref, options) {
5736 var exportMode = _ref.exportMode;
5737 var indentString = _ref.indentString;
5738
5739 if (exportMode !== 'none' && !options.moduleName) {
5740 throw new Error('You must supply options.moduleName for UMD bundles');
5741 }
5742
5743 var globalNames = options.globals || blank();
5744
5745 var amdDeps = bundle.externalModules.map(quoteId);
5746 var cjsDeps = bundle.externalModules.map(req);
5747 var globalDeps = bundle.externalModules.map(function (module) {
5748 return 'global.' + (globalNames[module.id] || module.name);
5749 });
5750
5751 var args = bundle.externalModules.map(getName);
5752
5753 if (exportMode === 'named') {
5754 amdDeps.unshift('\'exports\'');
5755 cjsDeps.unshift('exports');
5756 globalDeps.unshift('(global.' + options.moduleName + ' = {})');
5757
5758 args.unshift('exports');
5759 }
5760
5761 var amdParams = (options.moduleId ? '\'' + options.moduleId + '\', ' : '') + (amdDeps.length ? '[' + amdDeps.join(', ') + '], ' : '');
5762
5763 var cjsExport = exportMode === 'default' ? 'module.exports = ' : '';
5764 var defaultExport = exportMode === 'default' ? 'global.' + options.moduleName + ' = ' : '';
5765
5766 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5767
5768 var intro = ('(function (global, factory) {\n\t\t\ttypeof exports === \'object\' && typeof module !== \'undefined\' ? ' + cjsExport + 'factory(' + cjsDeps.join(', ') + ') :\n\t\t\ttypeof define === \'function\' && define.amd ? define(' + amdParams + 'factory) :\n\t\t\t' + defaultExport + 'factory(' + globalDeps + ');\n\t\t}(this, function (' + args + ') {' + useStrict + '\n\n\t\t').replace(/^\t\t/gm, '').replace(/^\t/gm, magicString.getIndentString());
5769
5770 // var foo__default = 'default' in foo ? foo['default'] : foo;
5771 var interopBlock = getInteropBlock(bundle);
5772 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5773
5774 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5775 if (exportBlock) magicString.append('\n\n' + exportBlock);
5776
5777 return magicString.trim().indent(indentString).append('\n\n}));').prepend(intro);
5778 }
5779
5780 function iife(bundle, magicString, _ref, options) {
5781 var exportMode = _ref.exportMode;
5782 var indentString = _ref.indentString;
5783
5784 var globalNames = options.globals || blank();
5785
5786 var dependencies = bundle.externalModules.map(function (module) {
5787 return globalNames[module.id] || module.name;
5788 });
5789
5790 var args = bundle.externalModules.map(getName);
5791
5792 if (exportMode !== 'none' && !options.moduleName) {
5793 throw new Error('You must supply options.moduleName for IIFE bundles');
5794 }
5795
5796 if (exportMode === 'named') {
5797 dependencies.unshift('(this.' + options.moduleName + ' = {})');
5798 args.unshift('exports');
5799 }
5800
5801 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5802 var intro = '(function (' + args + ') {' + useStrict + '\n\n';
5803 var outro = '\n\n})(' + dependencies + ');';
5804
5805 if (exportMode === 'default') {
5806 intro = 'var ' + options.moduleName + ' = ' + intro;
5807 }
5808
5809 // var foo__default = 'default' in foo ? foo['default'] : foo;
5810 var interopBlock = getInteropBlock(bundle);
5811 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5812
5813 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5814 if (exportBlock) magicString.append('\n\n' + exportBlock);
5815
5816 return magicString.indent(indentString).prepend(intro).append(outro);
5817 }
5818
5819 function notDefault(name) {
5820 return name !== 'default';
5821 }
5822 function es6(bundle, magicString) {
5823 var importBlock = bundle.externalModules.map(function (module) {
5824 var specifiers = [];
5825 var importedNames = keys(module.declarations).filter(function (name) {
5826 return name !== '*' && name !== 'default';
5827 });
5828
5829 if (module.declarations.default) {
5830 specifiers.push(module.name);
5831 }
5832
5833 if (module.declarations['*']) {
5834 specifiers.push('* as ' + module.name);
5835 }
5836
5837 if (importedNames.length) {
5838 specifiers.push('{ ' + importedNames.join(', ') + ' }');
5839 }
5840
5841 return specifiers.length ? 'import ' + specifiers.join(', ') + ' from \'' + module.id + '\';' : 'import \'' + module.id + '\';';
5842 }).join('\n');
5843
5844 if (importBlock) {
5845 magicString.prepend(importBlock + '\n\n');
5846 }
5847
5848 var module = bundle.entryModule;
5849
5850 var specifiers = module.getExports().filter(notDefault).map(function (name) {
5851 var declaration = module.traceExport(name);
5852
5853 return declaration.name === name ? name : declaration.name + ' as ' + name;
5854 });
5855
5856 var exportBlock = specifiers.length ? 'export { ' + specifiers.join(', ') + ' };' : '';
5857
5858 var defaultExport = module.exports.default || module.reexports.default;
5859 if (defaultExport) {
5860 exportBlock += 'export default ' + module.traceExport('default').name + ';';
5861 }
5862
5863 if (exportBlock) {
5864 magicString.append('\n\n' + exportBlock.trim());
5865 }
5866
5867 return magicString.trim();
5868 }
5869
5870 function cjs(bundle, magicString, _ref, options) {
5871 var exportMode = _ref.exportMode;
5872
5873 var intro = options.useStrict === false ? '' : '\'use strict\';\n\n';
5874
5875 // TODO handle empty imports, once they're supported
5876 var importBlock = bundle.externalModules.map(function (module) {
5877 var requireStatement = 'var ' + module.name + ' = require(\'' + module.id + '\');';
5878
5879 if (module.declarations.default) {
5880 requireStatement += '\n' + (module.exportsNames ? 'var ' + module.name + '__default = ' : module.name + ' = ') + ('\'default\' in ' + module.name + ' ? ' + module.name + '[\'default\'] : ' + module.name + ';');
5881 }
5882
5883 return requireStatement;
5884 }).join('\n');
5885
5886 if (importBlock) {
5887 intro += importBlock + '\n\n';
5888 }
5889
5890 magicString.prepend(intro);
5891
5892 var exportBlock = getExportBlock(bundle.entryModule, exportMode, 'module.exports =');
5893 if (exportBlock) magicString.append('\n\n' + exportBlock);
5894
5895 return magicString;
5896 }
5897
5898 function amd(bundle, magicString, _ref, options) {
5899 var exportMode = _ref.exportMode;
5900 var indentString = _ref.indentString;
5901
5902 var deps = bundle.externalModules.map(quoteId);
5903 var args = bundle.externalModules.map(getName);
5904
5905 if (exportMode === 'named') {
5906 args.unshift('exports');
5907 deps.unshift('\'exports\'');
5908 }
5909
5910 var params = (options.moduleId ? '\'' + options.moduleId + '\', ' : '') + (deps.length ? '[' + deps.join(', ') + '], ' : '');
5911
5912 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
5913 var intro = 'define(' + params + 'function (' + args.join(', ') + ') {' + useStrict + '\n\n';
5914
5915 // var foo__default = 'default' in foo ? foo['default'] : foo;
5916 var interopBlock = getInteropBlock(bundle);
5917 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
5918
5919 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
5920 if (exportBlock) magicString.append('\n\n' + exportBlock);
5921
5922 return magicString.indent(indentString).append('\n\n});').prepend(intro);
5923 }
5924
5925 var finalisers = { amd: amd, cjs: cjs, es6: es6, iife: iife, umd: umd };
5926
5927 function ensureArray(thing) {
5928 if (Array.isArray(thing)) return thing;
5929 if (thing == undefined) return [];
5930 return [thing];
5931 }
5932
5933 function load(id) {
5934 return readFileSync(id, 'utf-8');
5935 }
5936
5937 function addJsExtensionIfNecessary(file) {
5938 if (isFile(file)) return file;
5939
5940 file += '.js';
5941 if (isFile(file)) return file;
5942
5943 return null;
5944 }
5945
5946 function resolveId(importee, importer) {
5947 // absolute paths are left untouched
5948 if (isAbsolute(importee)) return addJsExtensionIfNecessary(importee);
5949
5950 // if this is the entry point, resolve against cwd
5951 if (importer === undefined) return addJsExtensionIfNecessary(resolve(process.cwd(), importee));
5952
5953 // external modules are skipped at this stage
5954 if (importee[0] !== '.') return null;
5955
5956 return addJsExtensionIfNecessary(resolve(dirname(importer), importee));
5957 }
5958
5959 function onwarn(msg) {
5960 console.error(msg); //eslint-disable-line no-console
5961 }
5962
5963 function badExports(option, keys) {
5964 throw new Error('\'' + option + '\' was specified for options.exports, but entry module has following exports: ' + keys.join(', '));
5965 }
5966 function getExportMode(bundle, exportMode) {
5967 var exportKeys = keys(bundle.entryModule.exports).concat(keys(bundle.entryModule.reexports)).concat(bundle.entryModule.exportAllSources); // not keys, but makes our job easier this way
5968
5969 if (exportMode === 'default') {
5970 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
5971 badExports('default', exportKeys);
5972 }
5973 } else if (exportMode === 'none' && exportKeys.length) {
5974 badExports('none', exportKeys);
5975 }
5976
5977 if (!exportMode || exportMode === 'auto') {
5978 if (exportKeys.length === 0) {
5979 exportMode = 'none';
5980 } else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
5981 exportMode = 'default';
5982 } else {
5983 exportMode = 'named';
5984 }
5985 }
5986
5987 if (!/(?:default|named|none)/.test(exportMode)) {
5988 throw new Error('options.exports must be \'default\', \'named\', \'none\', \'auto\', or left unspecified (defaults to \'auto\')');
5989 }
5990
5991 return exportMode;
5992 }
5993
5994 function getIndentString(magicString, options) {
5995 if (!('indent' in options) || options.indent === true) {
5996 return magicString.getIndentString();
5997 }
5998
5999 return options.indent || '';
6000 }
6001
6002 function unixizePath(path) {
6003 return path.split(/[\/\\]/).join('/');
6004 }
6005
6006 function transform(source, id, transformers) {
6007 var sourceMapChain = [];
6008
6009 if (typeof source === 'string') {
6010 source = {
6011 code: source,
6012 ast: null
6013 };
6014 }
6015
6016 var originalCode = source.code;
6017 var ast = source.ast;
6018
6019 return transformers.reduce(function (promise, transformer) {
6020 return promise.then(function (previous) {
6021 return Promise.resolve(transformer(previous, id)).then(function (result) {
6022 if (result == null) return previous;
6023
6024 if (typeof result === 'string') {
6025 result = {
6026 code: result,
6027 ast: null,
6028 map: null
6029 };
6030 }
6031
6032 sourceMapChain.push(result.map);
6033 ast = result.ast;
6034
6035 return result.code;
6036 });
6037 });
6038 }, Promise.resolve(source.code)).then(function (code) {
6039 return { code: code, originalCode: originalCode, ast: ast, sourceMapChain: sourceMapChain };
6040 });
6041 }
6042
6043 var charToInteger$1 = {};
6044 var integerToChar$1 = {};
6045
6046 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('').forEach(function (char, i) {
6047 charToInteger$1[char] = i;
6048 integerToChar$1[i] = char;
6049 });
6050
6051 function decode$1(string) {
6052 var result = [],
6053 len = string.length,
6054 i,
6055 hasContinuationBit,
6056 shift = 0,
6057 value = 0,
6058 integer,
6059 shouldNegate;
6060
6061 for (i = 0; i < len; i += 1) {
6062 integer = charToInteger$1[string[i]];
6063
6064 if (integer === undefined) {
6065 throw new Error('Invalid character (' + string[i] + ')');
6066 }
6067
6068 hasContinuationBit = integer & 32;
6069
6070 integer &= 31;
6071 value += integer << shift;
6072
6073 if (hasContinuationBit) {
6074 shift += 5;
6075 } else {
6076 shouldNegate = value & 1;
6077 value >>= 1;
6078
6079 result.push(shouldNegate ? -value : value);
6080
6081 // reset
6082 value = shift = 0;
6083 }
6084 }
6085
6086 return result;
6087 }
6088
6089 function encode$1(value) {
6090 var result, i;
6091
6092 if (typeof value === 'number') {
6093 result = encodeInteger$1(value);
6094 } else {
6095 result = '';
6096 for (i = 0; i < value.length; i += 1) {
6097 result += encodeInteger$1(value[i]);
6098 }
6099 }
6100
6101 return result;
6102 }
6103
6104 function encodeInteger$1(num) {
6105 var result = '',
6106 clamped;
6107
6108 if (num < 0) {
6109 num = -num << 1 | 1;
6110 } else {
6111 num <<= 1;
6112 }
6113
6114 do {
6115 clamped = num & 31;
6116 num >>= 5;
6117
6118 if (num > 0) {
6119 clamped |= 32;
6120 }
6121
6122 result += integerToChar$1[clamped];
6123 } while (num > 0);
6124
6125 return result;
6126 }
6127
6128 function decodeSegments(encodedSegments) {
6129 var i = encodedSegments.length;
6130 var segments = new Array(i);
6131
6132 while (i--) segments[i] = decode$1(encodedSegments[i]);
6133 return segments;
6134 }
6135
6136 function decode$1$1(mappings) {
6137 var sourceFileIndex = 0; // second field
6138 var sourceCodeLine = 0; // third field
6139 var sourceCodeColumn = 0; // fourth field
6140 var nameIndex = 0; // fifth field
6141
6142 var lines = mappings.split(';');
6143 var numLines = lines.length;
6144 var decoded = new Array(numLines);
6145
6146 var i = undefined;
6147 var j = undefined;
6148 var line = undefined;
6149 var generatedCodeColumn = undefined;
6150 var decodedLine = undefined;
6151 var segments = undefined;
6152 var segment = undefined;
6153 var result = undefined;
6154
6155 for (i = 0; i < numLines; i += 1) {
6156 line = lines[i];
6157
6158 generatedCodeColumn = 0; // first field - reset each time
6159 decodedLine = [];
6160
6161 segments = decodeSegments(line.split(','));
6162
6163 for (j = 0; j < segments.length; j += 1) {
6164 segment = segments[j];
6165
6166 if (!segment.length) {
6167 break;
6168 }
6169
6170 generatedCodeColumn += segment[0];
6171
6172 result = [generatedCodeColumn];
6173 decodedLine.push(result);
6174
6175 if (segment.length === 1) {
6176 // only one field!
6177 continue;
6178 }
6179
6180 sourceFileIndex += segment[1];
6181 sourceCodeLine += segment[2];
6182 sourceCodeColumn += segment[3];
6183
6184 result.push(sourceFileIndex, sourceCodeLine, sourceCodeColumn);
6185
6186 if (segment.length === 5) {
6187 nameIndex += segment[4];
6188 result.push(nameIndex);
6189 }
6190 }
6191
6192 decoded[i] = decodedLine;
6193 }
6194
6195 return decoded;
6196 }
6197
6198 function encode$1$1(decoded) {
6199 var offsets = {
6200 generatedCodeColumn: 0,
6201 sourceFileIndex: 0, // second field
6202 sourceCodeLine: 0, // third field
6203 sourceCodeColumn: 0, // fourth field
6204 nameIndex: 0 // fifth field
6205 };
6206
6207 return decoded.map(function (line) {
6208 offsets.generatedCodeColumn = 0; // first field - reset each time
6209 return line.map(encodeSegment).join(',');
6210 }).join(';');
6211
6212 function encodeSegment(segment) {
6213 if (!segment.length) {
6214 return segment;
6215 }
6216
6217 var result = new Array(segment.length);
6218
6219 result[0] = segment[0] - offsets.generatedCodeColumn;
6220 offsets.generatedCodeColumn = segment[0];
6221
6222 if (segment.length === 1) {
6223 // only one field!
6224 return encode$1(result);
6225 }
6226
6227 result[1] = segment[1] - offsets.sourceFileIndex;
6228 result[2] = segment[2] - offsets.sourceCodeLine;
6229 result[3] = segment[3] - offsets.sourceCodeColumn;
6230
6231 offsets.sourceFileIndex = segment[1];
6232 offsets.sourceCodeLine = segment[2];
6233 offsets.sourceCodeColumn = segment[3];
6234
6235 if (segment.length === 5) {
6236 result[4] = segment[4] - offsets.nameIndex;
6237 offsets.nameIndex = segment[4];
6238 }
6239
6240 return encode$1(result);
6241 }
6242 }
6243
6244 function traceSegment(loc, mappings) {
6245 var line = loc[0];
6246 var column = loc[1];
6247
6248 var segments = mappings[line];
6249
6250 if (!segments) return null;
6251
6252 for (var i = 0; i < segments.length; i += 1) {
6253 var segment = segments[i];
6254
6255 if (segment[0] > column) return null;
6256
6257 if (segment[0] === column) {
6258 if (segment[1] !== 0) {
6259 throw new Error('Bad sourcemap');
6260 }
6261
6262 return [segment[2], segment[3]];
6263 }
6264 }
6265
6266 return null;
6267 }
6268 function collapseSourcemaps(map, modules) {
6269 var chains = modules.map(function (module) {
6270 return module.sourceMapChain.map(function (map) {
6271 if (!map) throw new Error('Cannot generate a sourcemap if non-sourcemap-generating transformers are used');
6272 return decode$1$1(map.mappings);
6273 });
6274 });
6275
6276 var decodedMappings = decode$1$1(map.mappings);
6277
6278 var tracedMappings = decodedMappings.map(function (line) {
6279 var tracedLine = [];
6280
6281 line.forEach(function (segment) {
6282 var sourceIndex = segment[1];
6283 var sourceCodeLine = segment[2];
6284 var sourceCodeColumn = segment[3];
6285
6286 var chain = chains[sourceIndex];
6287
6288 var i = chain.length;
6289 var traced = [sourceCodeLine, sourceCodeColumn];
6290
6291 while (i-- && traced) {
6292 traced = traceSegment(traced, chain[i]);
6293 }
6294
6295 if (traced) {
6296 tracedLine.push([segment[0], segment[1], traced[0], traced[1]
6297 // TODO name?
6298 ]);
6299 }
6300 });
6301
6302 return tracedLine;
6303 });
6304
6305 map.sourcesContent = modules.map(function (module) {
6306 return module.originalCode;
6307 });
6308 map.mappings = encode$1$1(tracedMappings);
6309 return map;
6310 }
6311
6312 function callIfFunction(thing) {
6313 return typeof thing === 'function' ? thing() : thing;
6314 }
6315
6316 var Bundle = (function () {
6317 function Bundle(options) {
6318 var _this = this;
6319
6320 babelHelpers.classCallCheck(this, Bundle);
6321
6322 this.entry = options.entry;
6323 this.entryModule = null;
6324
6325 this.plugins = ensureArray(options.plugins);
6326
6327 this.resolveId = first(this.plugins.map(function (plugin) {
6328 return plugin.resolveId;
6329 }).filter(Boolean).concat(resolveId));
6330
6331 this.load = first(this.plugins.map(function (plugin) {
6332 return plugin.load;
6333 }).filter(Boolean).concat(load));
6334
6335 this.transformers = this.plugins.map(function (plugin) {
6336 return plugin.transform;
6337 }).filter(Boolean);
6338
6339 this.moduleById = blank();
6340 this.modules = [];
6341
6342 this.externalModules = [];
6343 this.internalNamespaces = [];
6344
6345 this.assumedGlobals = blank();
6346
6347 this.external = options.external || [];
6348 this.onwarn = options.onwarn || onwarn;
6349
6350 // TODO strictly speaking, this only applies with non-ES6, non-default-only bundles
6351 ['module', 'exports'].forEach(function (global) {
6352 return _this.assumedGlobals[global] = true;
6353 });
6354 }
6355
6356 Bundle.prototype.build = function build() {
6357 var _this2 = this;
6358
6359 // Phase 1 – discovery. We load the entry module and find which
6360 // modules it imports, and import those, until we have all
6361 // of the entry module's dependencies
6362 return Promise.resolve(this.resolveId(this.entry, undefined)).then(function (id) {
6363 return _this2.fetchModule(id, undefined);
6364 }).then(function (entryModule) {
6365 _this2.entryModule = entryModule;
6366
6367 // Phase 2 – binding. We link references to their declarations
6368 // to generate a complete picture of the bundle
6369 _this2.modules.forEach(function (module) {
6370 return module.bindImportSpecifiers();
6371 });
6372 _this2.modules.forEach(function (module) {
6373 return module.bindAliases();
6374 });
6375 _this2.modules.forEach(function (module) {
6376 return module.bindReferences();
6377 });
6378
6379 // Phase 3 – marking. We 'run' each statement to see which ones
6380 // need to be included in the generated bundle
6381
6382 // mark all export statements
6383 entryModule.getExports().forEach(function (name) {
6384 var declaration = entryModule.traceExport(name);
6385 declaration.isExported = true;
6386
6387 declaration.use();
6388 });
6389
6390 // mark statements that should appear in the bundle
6391 var settled = false;
6392 while (!settled) {
6393 settled = true;
6394
6395 _this2.modules.forEach(function (module) {
6396 if (module.run()) settled = false;
6397 });
6398 }
6399
6400 // Phase 4 – final preparation. We order the modules with an
6401 // enhanced topological sort that accounts for cycles, then
6402 // ensure that names are deconflicted throughout the bundle
6403 _this2.orderedModules = _this2.sort();
6404 _this2.deconflict();
6405 });
6406 };
6407
6408 Bundle.prototype.deconflict = function deconflict() {
6409 var used = blank();
6410
6411 // ensure no conflicts with globals
6412 keys(this.assumedGlobals).forEach(function (name) {
6413 return used[name] = 1;
6414 });
6415
6416 function getSafeName(name) {
6417 while (used[name]) {
6418 name += '$' + used[name]++;
6419 }
6420
6421 used[name] = 1;
6422 return name;
6423 }
6424
6425 this.externalModules.forEach(function (module) {
6426 module.name = getSafeName(module.name);
6427 });
6428
6429 this.modules.forEach(function (module) {
6430 keys(module.declarations).forEach(function (originalName) {
6431 var declaration = module.declarations[originalName];
6432
6433 if (originalName === 'default') {
6434 if (declaration.original && !declaration.original.isReassigned) return;
6435 }
6436
6437 declaration.name = getSafeName(declaration.name);
6438 });
6439 });
6440 };
6441
6442 Bundle.prototype.fetchModule = function fetchModule(id, importer) {
6443 var _this3 = this;
6444
6445 // short-circuit cycles
6446 if (id in this.moduleById) return null;
6447 this.moduleById[id] = null;
6448
6449 return Promise.resolve(this.load(id)).catch(function (err) {
6450 var msg = 'Could not load ' + id;
6451 if (importer) msg += ' (imported by ' + importer + ')';
6452
6453 msg += ': ' + err.message;
6454 throw new Error(msg);
6455 }).then(function (source) {
6456 return transform(source, id, _this3.transformers);
6457 }).then(function (source) {
6458 var code = source.code;
6459 var originalCode = source.originalCode;
6460 var ast = source.ast;
6461 var sourceMapChain = source.sourceMapChain;
6462
6463 var module = new Module({ id: id, code: code, originalCode: originalCode, ast: ast, sourceMapChain: sourceMapChain, bundle: _this3 });
6464
6465 _this3.modules.push(module);
6466 _this3.moduleById[id] = module;
6467
6468 return _this3.fetchAllDependencies(module).then(function () {
6469 return module;
6470 });
6471 });
6472 };
6473
6474 Bundle.prototype.fetchAllDependencies = function fetchAllDependencies(module) {
6475 var _this4 = this;
6476
6477 var promises = module.dependencies.map(function (source) {
6478 return Promise.resolve(_this4.resolveId(source, module.id)).then(function (resolvedId) {
6479 if (!resolvedId) {
6480 if (! ~_this4.external.indexOf(source)) _this4.onwarn('Treating \'' + source + '\' as external dependency');
6481 module.resolvedIds[source] = source;
6482
6483 if (!_this4.moduleById[source]) {
6484 var _module = new ExternalModule(source);
6485 _this4.externalModules.push(_module);
6486 _this4.moduleById[source] = _module;
6487 }
6488 } else {
6489 if (resolvedId === module.id) {
6490 throw new Error('A module cannot import itself (' + resolvedId + ')');
6491 }
6492
6493 module.resolvedIds[source] = resolvedId;
6494 return _this4.fetchModule(resolvedId, module.id);
6495 }
6496 });
6497 });
6498
6499 return Promise.all(promises);
6500 };
6501
6502 Bundle.prototype.render = function render() {
6503 var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
6504
6505 var format = options.format || 'es6';
6506
6507 // Determine export mode - 'default', 'named', 'none'
6508 var exportMode = getExportMode(this, options.exports);
6509
6510 var magicString = new MagicString.Bundle({ separator: '\n\n' });
6511 var usedModules = [];
6512
6513 this.orderedModules.forEach(function (module) {
6514 var source = module.render(format === 'es6');
6515 if (source.toString().length) {
6516 magicString.addSource(source);
6517 usedModules.push(module);
6518 }
6519 });
6520
6521 var intro = [options.intro].concat(this.plugins.map(function (plugin) {
6522 return plugin.intro && plugin.intro();
6523 })).filter(Boolean).join('\n\n');
6524
6525 if (intro) magicString.prepend(intro + '\n');
6526 if (options.outro) magicString.append('\n' + options.outro);
6527
6528 var indentString = getIndentString(magicString, options);
6529
6530 var finalise = finalisers[format];
6531 if (!finalise) throw new Error('You must specify an output type - valid options are ' + keys(finalisers).join(', '));
6532
6533 magicString = finalise(this, magicString.trim(), { exportMode: exportMode, indentString: indentString }, options);
6534
6535 var banner = [options.banner].concat(this.plugins.map(function (plugin) {
6536 return plugin.banner;
6537 })).map(callIfFunction).filter(Boolean).join('\n');
6538
6539 var footer = [options.footer].concat(this.plugins.map(function (plugin) {
6540 return plugin.footer;
6541 })).map(callIfFunction).filter(Boolean).join('\n');
6542
6543 if (banner) magicString.prepend(banner + '\n');
6544 if (footer) magicString.append('\n' + footer);
6545
6546 var code = magicString.toString();
6547 var map = null;
6548
6549 if (options.sourceMap) {
6550 var file = options.sourceMapFile || options.dest;
6551 map = magicString.generateMap({
6552 includeContent: true,
6553 file: file
6554 // TODO
6555 });
6556
6557 if (this.transformers.length) map = collapseSourcemaps(map, usedModules);
6558 map.sources = map.sources.map(unixizePath);
6559 }
6560
6561 return { code: code, map: map };
6562 };
6563
6564 Bundle.prototype.sort = function sort() {
6565 var seen = {};
6566 var ordered = [];
6567 var hasCycles = undefined;
6568
6569 var strongDeps = {};
6570 var stronglyDependsOn = {};
6571
6572 function visit(module) {
6573 if (seen[module.id]) return;
6574 seen[module.id] = true;
6575
6576 var _module$consolidateDependencies = module.consolidateDependencies();
6577
6578 var strongDependencies = _module$consolidateDependencies.strongDependencies;
6579 var weakDependencies = _module$consolidateDependencies.weakDependencies;
6580
6581 strongDeps[module.id] = [];
6582 stronglyDependsOn[module.id] = {};
6583
6584 strongDependencies.forEach(function (imported) {
6585 strongDeps[module.id].push(imported);
6586
6587 if (seen[imported.id]) {
6588 // we need to prevent an infinite loop, and note that
6589 // we need to check for strong/weak dependency relationships
6590 hasCycles = true;
6591 return;
6592 }
6593
6594 visit(imported);
6595 });
6596
6597 weakDependencies.forEach(function (imported) {
6598 if (seen[imported.id]) {
6599 // we need to prevent an infinite loop, and note that
6600 // we need to check for strong/weak dependency relationships
6601 hasCycles = true;
6602 return;
6603 }
6604
6605 visit(imported);
6606 });
6607
6608 // add second (and third...) order dependencies
6609 function addStrongDependencies(dependency) {
6610 if (stronglyDependsOn[module.id][dependency.id]) return;
6611
6612 stronglyDependsOn[module.id][dependency.id] = true;
6613 strongDeps[dependency.id].forEach(addStrongDependencies);
6614 }
6615
6616 strongDeps[module.id].forEach(addStrongDependencies);
6617
6618 ordered.push(module);
6619 }
6620
6621 this.modules.forEach(visit);
6622
6623 if (hasCycles) {
6624 var unordered = ordered;
6625 ordered = [];
6626
6627 // unordered is actually semi-ordered, as [ fewer dependencies ... more dependencies ]
6628 unordered.forEach(function (module) {
6629 // ensure strong dependencies of `module` that don't strongly depend on `module` go first
6630 strongDeps[module.id].forEach(place);
6631
6632 function place(dep) {
6633 if (!stronglyDependsOn[dep.id][module.id] && ! ~ordered.indexOf(dep)) {
6634 strongDeps[dep.id].forEach(place);
6635 ordered.push(dep);
6636 }
6637 }
6638
6639 if (! ~ordered.indexOf(module)) {
6640 ordered.push(module);
6641 }
6642 });
6643 }
6644
6645 return ordered;
6646 };
6647
6648 return Bundle;
6649 })();
6650
6651 var VERSION = '0.21.1';
6652
6653 function rollup(options) {
6654 if (!options || !options.entry) {
6655 return Promise.reject(new Error('You must supply options.entry to rollup'));
6656 }
6657
6658 if (options.transform || options.load || options.resolveId || options.resolveExternal) {
6659 return Promise.reject(new Error('The `transform`, `load`, `resolveId` and `resolveExternal` options are deprecated in favour of a unified plugin API. See https://github.com/rollup/rollup/wiki/Plugins for details'));
6660 }
6661
6662 var bundle = new Bundle(options);
6663
6664 return bundle.build().then(function () {
6665 return {
6666 imports: bundle.externalModules.map(function (module) {
6667 return module.id;
6668 }),
6669 exports: keys(bundle.entryModule.exports),
6670 modules: bundle.orderedModules.map(function (module) {
6671 return { id: module.id };
6672 }),
6673
6674 generate: function (options) {
6675 return bundle.render(options);
6676 },
6677 write: function (options) {
6678 if (!options || !options.dest) {
6679 throw new Error('You must supply options.dest to bundle.write');
6680 }
6681
6682 var dest = options.dest;
6683
6684 var _bundle$render = bundle.render(options);
6685
6686 var code = _bundle$render.code;
6687 var map = _bundle$render.map;
6688
6689 var promises = [];
6690
6691 if (options.sourceMap) {
6692 var url = undefined;
6693
6694 if (options.sourceMap === 'inline') {
6695 url = map.toUrl();
6696 } else {
6697 url = _basename(dest) + '.map';
6698 promises.push(writeFile(dest + '.map', map.toString()));
6699 }
6700
6701 code += '\n//# ' + SOURCEMAPPING_URL$1 + '=' + url;
6702 }
6703
6704 promises.push(writeFile(dest, code));
6705 return Promise.all(promises);
6706 }
6707 };
6708 });
6709 }
6710
6711 exports.rollup = rollup;
6712 exports.VERSION = VERSION;
6713
6714}));
6715//# sourceMappingURL=rollup.browser.js.map
\No newline at end of file