UNPKG

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