UNPKG

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