UNPKG

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