UNPKG

229 kBJavaScriptView Raw
1/*
2 Rollup.js v0.20.4
3 Wed Nov 04 2015 15:28:41 GMT-0500 (EST) - commit 6593d5824c550b89bc005c2ec6748839507adf92
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$1 = 0;
46var vertxNext;
47var customSchedulerFn;
48
49var asap = function asap(callback, arg) {
50 queue[len$1] = callback;
51 queue[len$1 + 1] = arg;
52 len$1 += 2;
53 if (len$1 === 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$1; 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$1 = 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$1(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
2210function makePredicate(words) {
2211 words = words.split(" ");
2212 var f = "",
2213 cats = [];
2214 out: for (var i = 0; i < words.length; ++i) {
2215 for (var j = 0; j < cats.length; ++j) {
2216 if (cats[j][0].length == words[i].length) {
2217 cats[j].push(words[i]);
2218 continue out;
2219 }
2220 }cats.push([words[i]]);
2221 }
2222 function compareTo(arr) {
2223 if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
2224 f += "switch(str){";
2225 for (var i = 0; i < arr.length; ++i) {
2226 f += "case " + JSON.stringify(arr[i]) + ":";
2227 }f += "return true}return false;";
2228 }
2229
2230 // When there are more than three length categories, an outer
2231 // switch first dispatches on the lengths, to save on comparisons.
2232
2233 if (cats.length > 3) {
2234 cats.sort(function (a, b) {
2235 return b.length - a.length;
2236 });
2237 f += "switch(str.length){";
2238 for (var i = 0; i < cats.length; ++i) {
2239 var cat = cats[i];
2240 f += "case " + cat[0].length + ":";
2241 compareTo(cat);
2242 }
2243 f += "}";
2244
2245 // Otherwise, simply generate a flat `switch` statement.
2246 } else {
2247 compareTo(words);
2248 }
2249 return new Function("str", f);
2250}
2251
2252// Reserved word lists for various dialects of the language
2253
2254var reservedWords$1 = {
2255 3: makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"),
2256 5: makePredicate("class enum extends super const export import"),
2257 6: makePredicate("enum await"),
2258 strict: makePredicate("implements interface let package private protected public static yield"),
2259 strictBind: makePredicate("eval arguments")
2260};
2261
2262// And the keywords
2263
2264var 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";
2265
2266var keywords = {
2267 5: makePredicate(ecma5AndLessKeywords),
2268 6: makePredicate(ecma5AndLessKeywords + " let const class extends export import yield super")
2269};
2270
2271// ## Character categories
2272
2273// Big ugly regular expressions that match characters in the
2274// whitespace, identifier, and identifier-start categories. These
2275// are only applied when a character is found to actually have a
2276// code point above 128.
2277// Generated by `tools/generate-identifier-regex.js`.
2278
2279var 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";
2280var 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";
2281
2282var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
2283var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
2284
2285nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
2286
2287// These are a run-length and offset encoded representation of the
2288// >0xffff code points that are a valid part of identifiers. The
2289// offset starts at 0x10000, and each pair of numbers represents an
2290// offset to the next range, and then a size of the range. They were
2291// generated by tools/generate-identifier-regex.js
2292var 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];
2293var 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];
2294
2295// This has a complexity linear to the value of the code. The
2296// assumption is that looking up astral identifier characters is
2297// rare.
2298function isInAstralSet(code, set) {
2299 var pos = 0x10000;
2300 for (var i = 0; i < set.length; i += 2) {
2301 pos += set[i];
2302 if (pos > code) return false;
2303 pos += set[i + 1];
2304 if (pos >= code) return true;
2305 }
2306}
2307
2308// Test whether a given character code starts an identifier.
2309
2310function isIdentifierStart(code, astral) {
2311 if (code < 65) return code === 36;
2312 if (code < 91) return true;
2313 if (code < 97) return code === 95;
2314 if (code < 123) return true;
2315 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
2316 if (astral === false) return false;
2317 return isInAstralSet(code, astralIdentifierStartCodes);
2318}
2319
2320// Test whether a given character is part of an identifier.
2321
2322function isIdentifierChar(code, astral) {
2323 if (code < 48) return code === 36;
2324 if (code < 58) return true;
2325 if (code < 65) return false;
2326 if (code < 91) return true;
2327 if (code < 97) return code === 95;
2328 if (code < 123) return true;
2329 if (code <= 0xffff) return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
2330 if (astral === false) return false;
2331 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
2332}
2333
2334// ## Token types
2335
2336// The assignment of fine-grained, information-carrying type objects
2337// allows the tokenizer to store the information it has about a
2338// token in a way that is very cheap for the parser to look up.
2339
2340// All token type variables start with an underscore, to make them
2341// easy to recognize.
2342
2343// The `beforeExpr` property is used to disambiguate between regular
2344// expressions and divisions. It is set on all token types that can
2345// be followed by an expression (thus, a slash after them would be a
2346// regular expression).
2347//
2348// `isLoop` marks a keyword as starting a loop, which is important
2349// to know when parsing a label, in order to allow or disallow
2350// continue jumps to that label.
2351
2352var TokenType = function TokenType(label) {
2353 var conf = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
2354 babelHelpers.classCallCheck(this, TokenType);
2355
2356 this.label = label;
2357 this.keyword = conf.keyword;
2358 this.beforeExpr = !!conf.beforeExpr;
2359 this.startsExpr = !!conf.startsExpr;
2360 this.isLoop = !!conf.isLoop;
2361 this.isAssign = !!conf.isAssign;
2362 this.prefix = !!conf.prefix;
2363 this.postfix = !!conf.postfix;
2364 this.binop = conf.binop || null;
2365 this.updateContext = null;
2366};
2367
2368function binop(name, prec) {
2369 return new TokenType(name, { beforeExpr: true, binop: prec });
2370}
2371var beforeExpr = { beforeExpr: true };
2372var startsExpr = { startsExpr: true };
2373var tt = {
2374 num: new TokenType("num", startsExpr),
2375 regexp: new TokenType("regexp", startsExpr),
2376 string: new TokenType("string", startsExpr),
2377 name: new TokenType("name", startsExpr),
2378 eof: new TokenType("eof"),
2379
2380 // Punctuation token types.
2381 bracketL: new TokenType("[", { beforeExpr: true, startsExpr: true }),
2382 bracketR: new TokenType("]"),
2383 braceL: new TokenType("{", { beforeExpr: true, startsExpr: true }),
2384 braceR: new TokenType("}"),
2385 parenL: new TokenType("(", { beforeExpr: true, startsExpr: true }),
2386 parenR: new TokenType(")"),
2387 comma: new TokenType(",", beforeExpr),
2388 semi: new TokenType(";", beforeExpr),
2389 colon: new TokenType(":", beforeExpr),
2390 dot: new TokenType("."),
2391 question: new TokenType("?", beforeExpr),
2392 arrow: new TokenType("=>", beforeExpr),
2393 template: new TokenType("template"),
2394 ellipsis: new TokenType("...", beforeExpr),
2395 backQuote: new TokenType("`", startsExpr),
2396 dollarBraceL: new TokenType("${", { beforeExpr: true, startsExpr: true }),
2397
2398 // Operators. These carry several kinds of properties to help the
2399 // parser use them properly (the presence of these properties is
2400 // what categorizes them as operators).
2401 //
2402 // `binop`, when present, specifies that this operator is a binary
2403 // operator, and will refer to its precedence.
2404 //
2405 // `prefix` and `postfix` mark the operator as a prefix or postfix
2406 // unary operator.
2407 //
2408 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
2409 // binary operators with a very low precedence, that should result
2410 // in AssignmentExpression nodes.
2411
2412 eq: new TokenType("=", { beforeExpr: true, isAssign: true }),
2413 assign: new TokenType("_=", { beforeExpr: true, isAssign: true }),
2414 incDec: new TokenType("++/--", { prefix: true, postfix: true, startsExpr: true }),
2415 prefix: new TokenType("prefix", { beforeExpr: true, prefix: true, startsExpr: true }),
2416 logicalOR: binop("||", 1),
2417 logicalAND: binop("&&", 2),
2418 bitwiseOR: binop("|", 3),
2419 bitwiseXOR: binop("^", 4),
2420 bitwiseAND: binop("&", 5),
2421 equality: binop("==/!=", 6),
2422 relational: binop("</>", 7),
2423 bitShift: binop("<</>>", 8),
2424 plusMin: new TokenType("+/-", { beforeExpr: true, binop: 9, prefix: true, startsExpr: true }),
2425 modulo: binop("%", 10),
2426 star: binop("*", 10),
2427 slash: binop("/", 10)
2428};
2429
2430// Map keyword names to token types.
2431
2432var keywordTypes = {};
2433
2434// Succinct definitions of keyword token types
2435function kw(name) {
2436 var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
2437
2438 options.keyword = name;
2439 keywordTypes[name] = tt["_" + name] = new TokenType(name, options);
2440}
2441
2442kw("break");
2443kw("case", beforeExpr);
2444kw("catch");
2445kw("continue");
2446kw("debugger");
2447kw("default", beforeExpr);
2448kw("do", { isLoop: true });
2449kw("else", beforeExpr);
2450kw("finally");
2451kw("for", { isLoop: true });
2452kw("function", startsExpr);
2453kw("if");
2454kw("return", beforeExpr);
2455kw("switch");
2456kw("throw", beforeExpr);
2457kw("try");
2458kw("var");
2459kw("let");
2460kw("const");
2461kw("while", { isLoop: true });
2462kw("with");
2463kw("new", { beforeExpr: true, startsExpr: true });
2464kw("this", startsExpr);
2465kw("super", startsExpr);
2466kw("class");
2467kw("extends", beforeExpr);
2468kw("export");
2469kw("import");
2470kw("yield", { beforeExpr: true, startsExpr: true });
2471kw("null", startsExpr);
2472kw("true", startsExpr);
2473kw("false", startsExpr);
2474kw("in", { beforeExpr: true, binop: 7 });
2475kw("instanceof", { beforeExpr: true, binop: 7 });
2476kw("typeof", { beforeExpr: true, prefix: true, startsExpr: true });
2477kw("void", { beforeExpr: true, prefix: true, startsExpr: true });
2478kw("delete", { beforeExpr: true, prefix: true, startsExpr: true });
2479
2480// Matches a whole line break (where CRLF is considered a single
2481// line break). Used to count lines.
2482
2483var lineBreak = /\r\n?|\n|\u2028|\u2029/;
2484var lineBreakG = new RegExp(lineBreak.source, "g");
2485
2486function isNewLine(code) {
2487 return code === 10 || code === 13 || code === 0x2028 || code == 0x2029;
2488}
2489
2490var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
2491
2492function isArray$2(obj) {
2493 return Object.prototype.toString.call(obj) === "[object Array]";
2494}
2495
2496// Checks if an object has a property.
2497
2498function has(obj, propName) {
2499 return Object.prototype.hasOwnProperty.call(obj, propName);
2500}
2501
2502// These are used when `options.locations` is on, for the
2503// `startLoc` and `endLoc` properties.
2504
2505var Position = (function () {
2506 function Position(line, col) {
2507 babelHelpers.classCallCheck(this, Position);
2508
2509 this.line = line;
2510 this.column = col;
2511 }
2512
2513 Position.prototype.offset = function offset(n) {
2514 return new Position(this.line, this.column + n);
2515 };
2516
2517 return Position;
2518})();
2519
2520var SourceLocation = function SourceLocation(p, start, end) {
2521 babelHelpers.classCallCheck(this, SourceLocation);
2522
2523 this.start = start;
2524 this.end = end;
2525 if (p.sourceFile !== null) this.source = p.sourceFile;
2526}
2527
2528// The `getLineInfo` function is mostly useful when the
2529// `locations` option is off (for performance reasons) and you
2530// want to find the line/column position for a given character
2531// offset. `input` should be the code string that the offset refers
2532// into.
2533
2534;
2535
2536function getLineInfo(input, offset) {
2537 for (var line = 1, cur = 0;;) {
2538 lineBreakG.lastIndex = cur;
2539 var match = lineBreakG.exec(input);
2540 if (match && match.index < offset) {
2541 ++line;
2542 cur = match.index + match[0].length;
2543 } else {
2544 return new Position(line, offset - cur);
2545 }
2546 }
2547}
2548
2549// A second optional argument can be given to further configure
2550// the parser process. These options are recognized:
2551
2552var defaultOptions = {
2553 // `ecmaVersion` indicates the ECMAScript version to parse. Must
2554 // be either 3, or 5, or 6. This influences support for strict
2555 // mode, the set of reserved words, support for getters and
2556 // setters and other features.
2557 ecmaVersion: 5,
2558 // Source type ("script" or "module") for different semantics
2559 sourceType: "script",
2560 // `onInsertedSemicolon` can be a callback that will be called
2561 // when a semicolon is automatically inserted. It will be passed
2562 // th position of the comma as an offset, and if `locations` is
2563 // enabled, it is given the location as a `{line, column}` object
2564 // as second argument.
2565 onInsertedSemicolon: null,
2566 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
2567 // trailing commas.
2568 onTrailingComma: null,
2569 // By default, reserved words are not enforced. Disable
2570 // `allowReserved` to enforce them. When this option has the
2571 // value "never", reserved words and keywords can also not be
2572 // used as property names.
2573 allowReserved: true,
2574 // When enabled, a return at the top level is not considered an
2575 // error.
2576 allowReturnOutsideFunction: false,
2577 // When enabled, import/export statements are not constrained to
2578 // appearing at the top of the program.
2579 allowImportExportEverywhere: false,
2580 // When enabled, hashbang directive in the beginning of file
2581 // is allowed and treated as a line comment.
2582 allowHashBang: false,
2583 // When `locations` is on, `loc` properties holding objects with
2584 // `start` and `end` properties in `{line, column}` form (with
2585 // line being 1-based and column 0-based) will be attached to the
2586 // nodes.
2587 locations: false,
2588 // A function can be passed as `onToken` option, which will
2589 // cause Acorn to call that function with object in the same
2590 // format as tokenize() returns. Note that you are not
2591 // allowed to call the parser from the callback—that will
2592 // corrupt its internal state.
2593 onToken: null,
2594 // A function can be passed as `onComment` option, which will
2595 // cause Acorn to call that function with `(block, text, start,
2596 // end)` parameters whenever a comment is skipped. `block` is a
2597 // boolean indicating whether this is a block (`/* */`) comment,
2598 // `text` is the content of the comment, and `start` and `end` are
2599 // character offsets that denote the start and end of the comment.
2600 // When the `locations` option is on, two more parameters are
2601 // passed, the full `{line, column}` locations of the start and
2602 // end of the comments. Note that you are not allowed to call the
2603 // parser from the callback—that will corrupt its internal state.
2604 onComment: null,
2605 // Nodes have their start and end characters offsets recorded in
2606 // `start` and `end` properties (directly on the node, rather than
2607 // the `loc` object, which holds line/column data. To also add a
2608 // [semi-standardized][range] `range` property holding a `[start,
2609 // end]` array with the same numbers, set the `ranges` option to
2610 // `true`.
2611 //
2612 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
2613 ranges: false,
2614 // It is possible to parse multiple files into a single AST by
2615 // passing the tree produced by parsing the first file as
2616 // `program` option in subsequent parses. This will add the
2617 // toplevel forms of the parsed file to the `Program` (top) node
2618 // of an existing parse tree.
2619 program: null,
2620 // When `locations` is on, you can pass this to record the source
2621 // file in every node's `loc` object.
2622 sourceFile: null,
2623 // This value, if given, is stored in every node, whether
2624 // `locations` is on or off.
2625 directSourceFile: null,
2626 // When enabled, parenthesized expressions are represented by
2627 // (non-standard) ParenthesizedExpression nodes
2628 preserveParens: false,
2629 plugins: {}
2630};
2631
2632// Interpret and default an options object
2633
2634function getOptions(opts) {
2635 var options = {};
2636 for (var opt in defaultOptions) {
2637 options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt];
2638 }if (isArray$2(options.onToken)) {
2639 (function () {
2640 var tokens = options.onToken;
2641 options.onToken = function (token) {
2642 return tokens.push(token);
2643 };
2644 })();
2645 }
2646 if (isArray$2(options.onComment)) options.onComment = pushComment(options, options.onComment);
2647
2648 return options;
2649}
2650
2651function pushComment(options, array) {
2652 return function (block, text, start, end, startLoc, endLoc) {
2653 var comment = {
2654 type: block ? 'Block' : 'Line',
2655 value: text,
2656 start: start,
2657 end: end
2658 };
2659 if (options.locations) comment.loc = new SourceLocation(this, startLoc, endLoc);
2660 if (options.ranges) comment.range = [start, end];
2661 array.push(comment);
2662 };
2663}
2664
2665// Registered plugins
2666var plugins = {};
2667
2668var Parser = (function () {
2669 function Parser(options, input, startPos) {
2670 babelHelpers.classCallCheck(this, Parser);
2671
2672 this.options = getOptions(options);
2673 this.sourceFile = this.options.sourceFile;
2674 this.isKeyword = keywords[this.options.ecmaVersion >= 6 ? 6 : 5];
2675 this.isReservedWord = reservedWords$1[this.options.ecmaVersion];
2676 this.input = String(input);
2677
2678 // Used to signal to callers of `readWord1` whether the word
2679 // contained any escape sequences. This is needed because words with
2680 // escape sequences must not be interpreted as keywords.
2681 this.containsEsc = false;
2682
2683 // Load plugins
2684 this.loadPlugins(this.options.plugins);
2685
2686 // Set up token state
2687
2688 // The current position of the tokenizer in the input.
2689 if (startPos) {
2690 this.pos = startPos;
2691 this.lineStart = Math.max(0, this.input.lastIndexOf("\n", startPos));
2692 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
2693 } else {
2694 this.pos = this.lineStart = 0;
2695 this.curLine = 1;
2696 }
2697
2698 // Properties of the current token:
2699 // Its type
2700 this.type = tt.eof;
2701 // For tokens that include more information than their type, the value
2702 this.value = null;
2703 // Its start and end offset
2704 this.start = this.end = this.pos;
2705 // And, if locations are used, the {line, column} object
2706 // corresponding to those offsets
2707 this.startLoc = this.endLoc = this.curPosition();
2708
2709 // Position information for the previous token
2710 this.lastTokEndLoc = this.lastTokStartLoc = null;
2711 this.lastTokStart = this.lastTokEnd = this.pos;
2712
2713 // The context stack is used to superficially track syntactic
2714 // context to predict whether a regular expression is allowed in a
2715 // given position.
2716 this.context = this.initialContext();
2717 this.exprAllowed = true;
2718
2719 // Figure out if it's a module code.
2720 this.strict = this.inModule = this.options.sourceType === "module";
2721
2722 // Used to signify the start of a potential arrow function
2723 this.potentialArrowAt = -1;
2724
2725 // Flags to track whether we are in a function, a generator.
2726 this.inFunction = this.inGenerator = false;
2727 // Labels in scope.
2728 this.labels = [];
2729
2730 // If enabled, skip leading hashbang line.
2731 if (this.pos === 0 && this.options.allowHashBang && this.input.slice(0, 2) === '#!') this.skipLineComment(2);
2732 }
2733
2734 Parser.prototype.extend = function extend(name, f) {
2735 this[name] = f(this[name]);
2736 };
2737
2738 Parser.prototype.loadPlugins = function loadPlugins(pluginConfigs) {
2739 for (var _name in pluginConfigs) {
2740 var plugin = plugins[_name];
2741 if (!plugin) throw new Error("Plugin '" + _name + "' not found");
2742 plugin(this, pluginConfigs[_name]);
2743 }
2744 };
2745
2746 Parser.prototype.parse = function parse() {
2747 var node = this.options.program || this.startNode();
2748 this.nextToken();
2749 return this.parseTopLevel(node);
2750 };
2751
2752 return Parser;
2753})();
2754
2755var pp = Parser.prototype;
2756
2757// ## Parser utilities
2758
2759// Test whether a statement node is the string literal `"use strict"`.
2760
2761pp.isUseStrict = function (stmt) {
2762 return this.options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" && stmt.expression.type === "Literal" && stmt.expression.raw.slice(1, -1) === "use strict";
2763};
2764
2765// Predicate that tests whether the next token is of the given
2766// type, and if yes, consumes it as a side effect.
2767
2768pp.eat = function (type) {
2769 if (this.type === type) {
2770 this.next();
2771 return true;
2772 } else {
2773 return false;
2774 }
2775};
2776
2777// Tests whether parsed token is a contextual keyword.
2778
2779pp.isContextual = function (name) {
2780 return this.type === tt.name && this.value === name;
2781};
2782
2783// Consumes contextual keyword if possible.
2784
2785pp.eatContextual = function (name) {
2786 return this.value === name && this.eat(tt.name);
2787};
2788
2789// Asserts that following token is given contextual keyword.
2790
2791pp.expectContextual = function (name) {
2792 if (!this.eatContextual(name)) this.unexpected();
2793};
2794
2795// Test whether a semicolon can be inserted at the current position.
2796
2797pp.canInsertSemicolon = function () {
2798 return this.type === tt.eof || this.type === tt.braceR || lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
2799};
2800
2801pp.insertSemicolon = function () {
2802 if (this.canInsertSemicolon()) {
2803 if (this.options.onInsertedSemicolon) this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc);
2804 return true;
2805 }
2806};
2807
2808// Consume a semicolon, or, failing that, see if we are allowed to
2809// pretend that there is a semicolon at this position.
2810
2811pp.semicolon = function () {
2812 if (!this.eat(tt.semi) && !this.insertSemicolon()) this.unexpected();
2813};
2814
2815pp.afterTrailingComma = function (tokType) {
2816 if (this.type == tokType) {
2817 if (this.options.onTrailingComma) this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc);
2818 this.next();
2819 return true;
2820 }
2821};
2822
2823// Expect a token of a given type. If found, consume it, otherwise,
2824// raise an unexpected token error.
2825
2826pp.expect = function (type) {
2827 this.eat(type) || this.unexpected();
2828};
2829
2830// Raise an unexpected token error.
2831
2832pp.unexpected = function (pos) {
2833 this.raise(pos != null ? pos : this.start, "Unexpected token");
2834};
2835
2836var pp$1 = Parser.prototype;
2837
2838// ### Statement parsing
2839
2840// Parse a program. Initializes the parser, reads any number of
2841// statements, and wraps them in a Program node. Optionally takes a
2842// `program` argument. If present, the statements will be appended
2843// to its body instead of creating a new node.
2844
2845pp$1.parseTopLevel = function (node) {
2846 var first = true;
2847 if (!node.body) node.body = [];
2848 while (this.type !== tt.eof) {
2849 var stmt = this.parseStatement(true, true);
2850 node.body.push(stmt);
2851 if (first) {
2852 if (this.isUseStrict(stmt)) this.setStrict(true);
2853 first = false;
2854 }
2855 }
2856 this.next();
2857 if (this.options.ecmaVersion >= 6) {
2858 node.sourceType = this.options.sourceType;
2859 }
2860 return this.finishNode(node, "Program");
2861};
2862
2863var loopLabel = { kind: "loop" };
2864var switchLabel = { kind: "switch" };
2865// Parse a single statement.
2866//
2867// If expecting a statement and finding a slash operator, parse a
2868// regular expression literal. This is to handle cases like
2869// `if (foo) /blah/.exec(foo)`, where looking at the previous token
2870// does not help.
2871
2872pp$1.parseStatement = function (declaration, topLevel) {
2873 var starttype = this.type,
2874 node = this.startNode();
2875
2876 // Most types of statements are recognized by the keyword they
2877 // start with. Many are trivial to parse, some require a bit of
2878 // complexity.
2879
2880 switch (starttype) {
2881 case tt._break:case tt._continue:
2882 return this.parseBreakContinueStatement(node, starttype.keyword);
2883 case tt._debugger:
2884 return this.parseDebuggerStatement(node);
2885 case tt._do:
2886 return this.parseDoStatement(node);
2887 case tt._for:
2888 return this.parseForStatement(node);
2889 case tt._function:
2890 if (!declaration && this.options.ecmaVersion >= 6) this.unexpected();
2891 return this.parseFunctionStatement(node);
2892 case tt._class:
2893 if (!declaration) this.unexpected();
2894 return this.parseClass(node, true);
2895 case tt._if:
2896 return this.parseIfStatement(node);
2897 case tt._return:
2898 return this.parseReturnStatement(node);
2899 case tt._switch:
2900 return this.parseSwitchStatement(node);
2901 case tt._throw:
2902 return this.parseThrowStatement(node);
2903 case tt._try:
2904 return this.parseTryStatement(node);
2905 case tt._let:case tt._const:
2906 if (!declaration) this.unexpected(); // NOTE: falls through to _var
2907 case tt._var:
2908 return this.parseVarStatement(node, starttype);
2909 case tt._while:
2910 return this.parseWhileStatement(node);
2911 case tt._with:
2912 return this.parseWithStatement(node);
2913 case tt.braceL:
2914 return this.parseBlock();
2915 case tt.semi:
2916 return this.parseEmptyStatement(node);
2917 case tt._export:
2918 case tt._import:
2919 if (!this.options.allowImportExportEverywhere) {
2920 if (!topLevel) this.raise(this.start, "'import' and 'export' may only appear at the top level");
2921 if (!this.inModule) this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
2922 }
2923 return starttype === tt._import ? this.parseImport(node) : this.parseExport(node);
2924
2925 // If the statement does not start with a statement keyword or a
2926 // brace, it's an ExpressionStatement or LabeledStatement. We
2927 // simply start parsing an expression, and afterwards, if the
2928 // next token is a colon and the expression was a simple
2929 // Identifier node, we switch to interpreting it as a label.
2930 default:
2931 var maybeName = this.value,
2932 expr = this.parseExpression();
2933 if (starttype === tt.name && expr.type === "Identifier" && this.eat(tt.colon)) return this.parseLabeledStatement(node, maybeName, expr);else return this.parseExpressionStatement(node, expr);
2934 }
2935};
2936
2937pp$1.parseBreakContinueStatement = function (node, keyword) {
2938 var isBreak = keyword == "break";
2939 this.next();
2940 if (this.eat(tt.semi) || this.insertSemicolon()) node.label = null;else if (this.type !== tt.name) this.unexpected();else {
2941 node.label = this.parseIdent();
2942 this.semicolon();
2943 }
2944
2945 // Verify that there is an actual destination to break or
2946 // continue to.
2947 for (var i = 0; i < this.labels.length; ++i) {
2948 var lab = this.labels[i];
2949 if (node.label == null || lab.name === node.label.name) {
2950 if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
2951 if (node.label && isBreak) break;
2952 }
2953 }
2954 if (i === this.labels.length) this.raise(node.start, "Unsyntactic " + keyword);
2955 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
2956};
2957
2958pp$1.parseDebuggerStatement = function (node) {
2959 this.next();
2960 this.semicolon();
2961 return this.finishNode(node, "DebuggerStatement");
2962};
2963
2964pp$1.parseDoStatement = function (node) {
2965 this.next();
2966 this.labels.push(loopLabel);
2967 node.body = this.parseStatement(false);
2968 this.labels.pop();
2969 this.expect(tt._while);
2970 node.test = this.parseParenExpression();
2971 if (this.options.ecmaVersion >= 6) this.eat(tt.semi);else this.semicolon();
2972 return this.finishNode(node, "DoWhileStatement");
2973};
2974
2975// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
2976// loop is non-trivial. Basically, we have to parse the init `var`
2977// statement or expression, disallowing the `in` operator (see
2978// the second parameter to `parseExpression`), and then check
2979// whether the next token is `in` or `of`. When there is no init
2980// part (semicolon immediately after the opening parenthesis), it
2981// is a regular `for` loop.
2982
2983pp$1.parseForStatement = function (node) {
2984 this.next();
2985 this.labels.push(loopLabel);
2986 this.expect(tt.parenL);
2987 if (this.type === tt.semi) return this.parseFor(node, null);
2988 if (this.type === tt._var || this.type === tt._let || this.type === tt._const) {
2989 var _init = this.startNode(),
2990 varKind = this.type;
2991 this.next();
2992 this.parseVar(_init, true, varKind);
2993 this.finishNode(_init, "VariableDeclaration");
2994 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);
2995 return this.parseFor(node, _init);
2996 }
2997 var refShorthandDefaultPos = { start: 0 };
2998 var init = this.parseExpression(true, refShorthandDefaultPos);
2999 if (this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of")) {
3000 this.toAssignable(init);
3001 this.checkLVal(init);
3002 return this.parseForIn(node, init);
3003 } else if (refShorthandDefaultPos.start) {
3004 this.unexpected(refShorthandDefaultPos.start);
3005 }
3006 return this.parseFor(node, init);
3007};
3008
3009pp$1.parseFunctionStatement = function (node) {
3010 this.next();
3011 return this.parseFunction(node, true);
3012};
3013
3014pp$1.parseIfStatement = function (node) {
3015 this.next();
3016 node.test = this.parseParenExpression();
3017 node.consequent = this.parseStatement(false);
3018 node.alternate = this.eat(tt._else) ? this.parseStatement(false) : null;
3019 return this.finishNode(node, "IfStatement");
3020};
3021
3022pp$1.parseReturnStatement = function (node) {
3023 if (!this.inFunction && !this.options.allowReturnOutsideFunction) this.raise(this.start, "'return' outside of function");
3024 this.next();
3025
3026 // In `return` (and `break`/`continue`), the keywords with
3027 // optional arguments, we eagerly look for a semicolon or the
3028 // possibility to insert one.
3029
3030 if (this.eat(tt.semi) || this.insertSemicolon()) node.argument = null;else {
3031 node.argument = this.parseExpression();this.semicolon();
3032 }
3033 return this.finishNode(node, "ReturnStatement");
3034};
3035
3036pp$1.parseSwitchStatement = function (node) {
3037 this.next();
3038 node.discriminant = this.parseParenExpression();
3039 node.cases = [];
3040 this.expect(tt.braceL);
3041 this.labels.push(switchLabel);
3042
3043 // Statements under must be grouped (by label) in SwitchCase
3044 // nodes. `cur` is used to keep the node that we are currently
3045 // adding statements to.
3046
3047 for (var cur, sawDefault = false; this.type != tt.braceR;) {
3048 if (this.type === tt._case || this.type === tt._default) {
3049 var isCase = this.type === tt._case;
3050 if (cur) this.finishNode(cur, "SwitchCase");
3051 node.cases.push(cur = this.startNode());
3052 cur.consequent = [];
3053 this.next();
3054 if (isCase) {
3055 cur.test = this.parseExpression();
3056 } else {
3057 if (sawDefault) this.raise(this.lastTokStart, "Multiple default clauses");
3058 sawDefault = true;
3059 cur.test = null;
3060 }
3061 this.expect(tt.colon);
3062 } else {
3063 if (!cur) this.unexpected();
3064 cur.consequent.push(this.parseStatement(true));
3065 }
3066 }
3067 if (cur) this.finishNode(cur, "SwitchCase");
3068 this.next(); // Closing brace
3069 this.labels.pop();
3070 return this.finishNode(node, "SwitchStatement");
3071};
3072
3073pp$1.parseThrowStatement = function (node) {
3074 this.next();
3075 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) this.raise(this.lastTokEnd, "Illegal newline after throw");
3076 node.argument = this.parseExpression();
3077 this.semicolon();
3078 return this.finishNode(node, "ThrowStatement");
3079};
3080
3081// Reused empty array added for node fields that are always empty.
3082
3083var empty = [];
3084
3085pp$1.parseTryStatement = function (node) {
3086 this.next();
3087 node.block = this.parseBlock();
3088 node.handler = null;
3089 if (this.type === tt._catch) {
3090 var clause = this.startNode();
3091 this.next();
3092 this.expect(tt.parenL);
3093 clause.param = this.parseBindingAtom();
3094 this.checkLVal(clause.param, true);
3095 this.expect(tt.parenR);
3096 clause.guard = null;
3097 clause.body = this.parseBlock();
3098 node.handler = this.finishNode(clause, "CatchClause");
3099 }
3100 node.guardedHandlers = empty;
3101 node.finalizer = this.eat(tt._finally) ? this.parseBlock() : null;
3102 if (!node.handler && !node.finalizer) this.raise(node.start, "Missing catch or finally clause");
3103 return this.finishNode(node, "TryStatement");
3104};
3105
3106pp$1.parseVarStatement = function (node, kind) {
3107 this.next();
3108 this.parseVar(node, false, kind);
3109 this.semicolon();
3110 return this.finishNode(node, "VariableDeclaration");
3111};
3112
3113pp$1.parseWhileStatement = function (node) {
3114 this.next();
3115 node.test = this.parseParenExpression();
3116 this.labels.push(loopLabel);
3117 node.body = this.parseStatement(false);
3118 this.labels.pop();
3119 return this.finishNode(node, "WhileStatement");
3120};
3121
3122pp$1.parseWithStatement = function (node) {
3123 if (this.strict) this.raise(this.start, "'with' in strict mode");
3124 this.next();
3125 node.object = this.parseParenExpression();
3126 node.body = this.parseStatement(false);
3127 return this.finishNode(node, "WithStatement");
3128};
3129
3130pp$1.parseEmptyStatement = function (node) {
3131 this.next();
3132 return this.finishNode(node, "EmptyStatement");
3133};
3134
3135pp$1.parseLabeledStatement = function (node, maybeName, expr) {
3136 for (var i = 0; i < this.labels.length; ++i) {
3137 if (this.labels[i].name === maybeName) this.raise(expr.start, "Label '" + maybeName + "' is already declared");
3138 }var kind = this.type.isLoop ? "loop" : this.type === tt._switch ? "switch" : null;
3139 for (var i = this.labels.length - 1; i >= 0; i--) {
3140 var label = this.labels[i];
3141 if (label.statementStart == node.start) {
3142 label.statementStart = this.start;
3143 label.kind = kind;
3144 } else break;
3145 }
3146 this.labels.push({ name: maybeName, kind: kind, statementStart: this.start });
3147 node.body = this.parseStatement(true);
3148 this.labels.pop();
3149 node.label = expr;
3150 return this.finishNode(node, "LabeledStatement");
3151};
3152
3153pp$1.parseExpressionStatement = function (node, expr) {
3154 node.expression = expr;
3155 this.semicolon();
3156 return this.finishNode(node, "ExpressionStatement");
3157};
3158
3159// Parse a semicolon-enclosed block of statements, handling `"use
3160// strict"` declarations when `allowStrict` is true (used for
3161// function bodies).
3162
3163pp$1.parseBlock = function (allowStrict) {
3164 var node = this.startNode(),
3165 first = true,
3166 oldStrict = undefined;
3167 node.body = [];
3168 this.expect(tt.braceL);
3169 while (!this.eat(tt.braceR)) {
3170 var stmt = this.parseStatement(true);
3171 node.body.push(stmt);
3172 if (first && allowStrict && this.isUseStrict(stmt)) {
3173 oldStrict = this.strict;
3174 this.setStrict(this.strict = true);
3175 }
3176 first = false;
3177 }
3178 if (oldStrict === false) this.setStrict(false);
3179 return this.finishNode(node, "BlockStatement");
3180};
3181
3182// Parse a regular `for` loop. The disambiguation code in
3183// `parseStatement` will already have parsed the init statement or
3184// expression.
3185
3186pp$1.parseFor = function (node, init) {
3187 node.init = init;
3188 this.expect(tt.semi);
3189 node.test = this.type === tt.semi ? null : this.parseExpression();
3190 this.expect(tt.semi);
3191 node.update = this.type === tt.parenR ? null : this.parseExpression();
3192 this.expect(tt.parenR);
3193 node.body = this.parseStatement(false);
3194 this.labels.pop();
3195 return this.finishNode(node, "ForStatement");
3196};
3197
3198// Parse a `for`/`in` and `for`/`of` loop, which are almost
3199// same from parser's perspective.
3200
3201pp$1.parseForIn = function (node, init) {
3202 var type = this.type === tt._in ? "ForInStatement" : "ForOfStatement";
3203 this.next();
3204 node.left = init;
3205 node.right = this.parseExpression();
3206 this.expect(tt.parenR);
3207 node.body = this.parseStatement(false);
3208 this.labels.pop();
3209 return this.finishNode(node, type);
3210};
3211
3212// Parse a list of variable declarations.
3213
3214pp$1.parseVar = function (node, isFor, kind) {
3215 node.declarations = [];
3216 node.kind = kind.keyword;
3217 for (;;) {
3218 var decl = this.startNode();
3219 this.parseVarId(decl);
3220 if (this.eat(tt.eq)) {
3221 decl.init = this.parseMaybeAssign(isFor);
3222 } else if (kind === tt._const && !(this.type === tt._in || this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
3223 this.unexpected();
3224 } else if (decl.id.type != "Identifier" && !(isFor && (this.type === tt._in || this.isContextual("of")))) {
3225 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
3226 } else {
3227 decl.init = null;
3228 }
3229 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
3230 if (!this.eat(tt.comma)) break;
3231 }
3232 return node;
3233};
3234
3235pp$1.parseVarId = function (decl) {
3236 decl.id = this.parseBindingAtom();
3237 this.checkLVal(decl.id, true);
3238};
3239
3240// Parse a function declaration or literal (depending on the
3241// `isStatement` parameter).
3242
3243pp$1.parseFunction = function (node, isStatement, allowExpressionBody) {
3244 this.initFunction(node);
3245 if (this.options.ecmaVersion >= 6) node.generator = this.eat(tt.star);
3246 if (isStatement || this.type === tt.name) node.id = this.parseIdent();
3247 this.parseFunctionParams(node);
3248 this.parseFunctionBody(node, allowExpressionBody);
3249 return this.finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
3250};
3251
3252pp$1.parseFunctionParams = function (node) {
3253 this.expect(tt.parenL);
3254 node.params = this.parseBindingList(tt.parenR, false, false);
3255};
3256
3257// Parse a class declaration or literal (depending on the
3258// `isStatement` parameter).
3259
3260pp$1.parseClass = function (node, isStatement) {
3261 this.next();
3262 this.parseClassId(node, isStatement);
3263 this.parseClassSuper(node);
3264 var classBody = this.startNode();
3265 var hadConstructor = false;
3266 classBody.body = [];
3267 this.expect(tt.braceL);
3268 while (!this.eat(tt.braceR)) {
3269 if (this.eat(tt.semi)) continue;
3270 var method = this.startNode();
3271 var isGenerator = this.eat(tt.star);
3272 var isMaybeStatic = this.type === tt.name && this.value === "static";
3273 this.parsePropertyName(method);
3274 method.static = isMaybeStatic && this.type !== tt.parenL;
3275 if (method.static) {
3276 if (isGenerator) this.unexpected();
3277 isGenerator = this.eat(tt.star);
3278 this.parsePropertyName(method);
3279 }
3280 method.kind = "method";
3281 var isGetSet = false;
3282 if (!method.computed) {
3283 var key = method.key;
3284
3285 if (!isGenerator && key.type === "Identifier" && this.type !== tt.parenL && (key.name === "get" || key.name === "set")) {
3286 isGetSet = true;
3287 method.kind = key.name;
3288 key = this.parsePropertyName(method);
3289 }
3290 if (!method.static && (key.type === "Identifier" && key.name === "constructor" || key.type === "Literal" && key.value === "constructor")) {
3291 if (hadConstructor) this.raise(key.start, "Duplicate constructor in the same class");
3292 if (isGetSet) this.raise(key.start, "Constructor can't have get/set modifier");
3293 if (isGenerator) this.raise(key.start, "Constructor can't be a generator");
3294 method.kind = "constructor";
3295 hadConstructor = true;
3296 }
3297 }
3298 this.parseClassMethod(classBody, method, isGenerator);
3299 if (isGetSet) {
3300 var paramCount = method.kind === "get" ? 0 : 1;
3301 if (method.value.params.length !== paramCount) {
3302 var start = method.value.start;
3303 if (method.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
3304 }
3305 }
3306 }
3307 node.body = this.finishNode(classBody, "ClassBody");
3308 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression");
3309};
3310
3311pp$1.parseClassMethod = function (classBody, method, isGenerator) {
3312 method.value = this.parseMethod(isGenerator);
3313 classBody.body.push(this.finishNode(method, "MethodDefinition"));
3314};
3315
3316pp$1.parseClassId = function (node, isStatement) {
3317 node.id = this.type === tt.name ? this.parseIdent() : isStatement ? this.unexpected() : null;
3318};
3319
3320pp$1.parseClassSuper = function (node) {
3321 node.superClass = this.eat(tt._extends) ? this.parseExprSubscripts() : null;
3322};
3323
3324// Parses module export declaration.
3325
3326pp$1.parseExport = function (node) {
3327 this.next();
3328 // export * from '...'
3329 if (this.eat(tt.star)) {
3330 this.expectContextual("from");
3331 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
3332 this.semicolon();
3333 return this.finishNode(node, "ExportAllDeclaration");
3334 }
3335 if (this.eat(tt._default)) {
3336 // export default ...
3337 var expr = this.parseMaybeAssign();
3338 var needsSemi = true;
3339 if (expr.type == "FunctionExpression" || expr.type == "ClassExpression") {
3340 needsSemi = false;
3341 if (expr.id) {
3342 expr.type = expr.type == "FunctionExpression" ? "FunctionDeclaration" : "ClassDeclaration";
3343 }
3344 }
3345 node.declaration = expr;
3346 if (needsSemi) this.semicolon();
3347 return this.finishNode(node, "ExportDefaultDeclaration");
3348 }
3349 // export var|const|let|function|class ...
3350 if (this.shouldParseExportStatement()) {
3351 node.declaration = this.parseStatement(true);
3352 node.specifiers = [];
3353 node.source = null;
3354 } else {
3355 // export { x, y as z } [from '...']
3356 node.declaration = null;
3357 node.specifiers = this.parseExportSpecifiers();
3358 if (this.eatContextual("from")) {
3359 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
3360 } else {
3361 node.source = null;
3362 }
3363 this.semicolon();
3364 }
3365 return this.finishNode(node, "ExportNamedDeclaration");
3366};
3367
3368pp$1.shouldParseExportStatement = function () {
3369 return this.type.keyword;
3370};
3371
3372// Parses a comma-separated list of module exports.
3373
3374pp$1.parseExportSpecifiers = function () {
3375 var nodes = [],
3376 first = true;
3377 // export { x, y as z } [from '...']
3378 this.expect(tt.braceL);
3379 while (!this.eat(tt.braceR)) {
3380 if (!first) {
3381 this.expect(tt.comma);
3382 if (this.afterTrailingComma(tt.braceR)) break;
3383 } else first = false;
3384
3385 var node = this.startNode();
3386 node.local = this.parseIdent(this.type === tt._default);
3387 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
3388 nodes.push(this.finishNode(node, "ExportSpecifier"));
3389 }
3390 return nodes;
3391};
3392
3393// Parses import declaration.
3394
3395pp$1.parseImport = function (node) {
3396 this.next();
3397 // import '...'
3398 if (this.type === tt.string) {
3399 node.specifiers = empty;
3400 node.source = this.parseExprAtom();
3401 } else {
3402 node.specifiers = this.parseImportSpecifiers();
3403 this.expectContextual("from");
3404 node.source = this.type === tt.string ? this.parseExprAtom() : this.unexpected();
3405 }
3406 this.semicolon();
3407 return this.finishNode(node, "ImportDeclaration");
3408};
3409
3410// Parses a comma-separated list of module imports.
3411
3412pp$1.parseImportSpecifiers = function () {
3413 var nodes = [],
3414 first = true;
3415 if (this.type === tt.name) {
3416 // import defaultObj, { x, y as z } from '...'
3417 var node = this.startNode();
3418 node.local = this.parseIdent();
3419 this.checkLVal(node.local, true);
3420 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
3421 if (!this.eat(tt.comma)) return nodes;
3422 }
3423 if (this.type === tt.star) {
3424 var node = this.startNode();
3425 this.next();
3426 this.expectContextual("as");
3427 node.local = this.parseIdent();
3428 this.checkLVal(node.local, true);
3429 nodes.push(this.finishNode(node, "ImportNamespaceSpecifier"));
3430 return nodes;
3431 }
3432 this.expect(tt.braceL);
3433 while (!this.eat(tt.braceR)) {
3434 if (!first) {
3435 this.expect(tt.comma);
3436 if (this.afterTrailingComma(tt.braceR)) break;
3437 } else first = false;
3438
3439 var node = this.startNode();
3440 node.imported = this.parseIdent(true);
3441 node.local = this.eatContextual("as") ? this.parseIdent() : node.imported;
3442 this.checkLVal(node.local, true);
3443 nodes.push(this.finishNode(node, "ImportSpecifier"));
3444 }
3445 return nodes;
3446};
3447
3448var pp$2 = Parser.prototype;
3449
3450// Convert existing expression atom to assignable pattern
3451// if possible.
3452
3453pp$2.toAssignable = function (node, isBinding) {
3454 if (this.options.ecmaVersion >= 6 && node) {
3455 switch (node.type) {
3456 case "Identifier":
3457 case "ObjectPattern":
3458 case "ArrayPattern":
3459 case "AssignmentPattern":
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 } else {
3481 this.raise(node.left.end, "Only '=' operator can be used for specifying default value.");
3482 }
3483 break;
3484
3485 case "ParenthesizedExpression":
3486 node.expression = this.toAssignable(node.expression, isBinding);
3487 break;
3488
3489 case "MemberExpression":
3490 if (!isBinding) break;
3491
3492 default:
3493 this.raise(node.start, "Assigning to rvalue");
3494 }
3495 }
3496 return node;
3497};
3498
3499// Convert list of expression atoms to binding list.
3500
3501pp$2.toAssignableList = function (exprList, isBinding) {
3502 var end = exprList.length;
3503 if (end) {
3504 var last = exprList[end - 1];
3505 if (last && last.type == "RestElement") {
3506 --end;
3507 } else if (last && last.type == "SpreadElement") {
3508 last.type = "RestElement";
3509 var arg = last.argument;
3510 this.toAssignable(arg, isBinding);
3511 if (arg.type !== "Identifier" && arg.type !== "MemberExpression" && arg.type !== "ArrayPattern") this.unexpected(arg.start);
3512 --end;
3513 }
3514 }
3515 for (var i = 0; i < end; i++) {
3516 var elt = exprList[i];
3517 if (elt) this.toAssignable(elt, isBinding);
3518 }
3519 return exprList;
3520};
3521
3522// Parses spread element.
3523
3524pp$2.parseSpread = function (refShorthandDefaultPos) {
3525 var node = this.startNode();
3526 this.next();
3527 node.argument = this.parseMaybeAssign(refShorthandDefaultPos);
3528 return this.finishNode(node, "SpreadElement");
3529};
3530
3531pp$2.parseRest = function () {
3532 var node = this.startNode();
3533 this.next();
3534 node.argument = this.type === tt.name || this.type === tt.bracketL ? this.parseBindingAtom() : this.unexpected();
3535 return this.finishNode(node, "RestElement");
3536};
3537
3538// Parses lvalue (assignable) atom.
3539
3540pp$2.parseBindingAtom = function () {
3541 if (this.options.ecmaVersion < 6) return this.parseIdent();
3542 switch (this.type) {
3543 case tt.name:
3544 return this.parseIdent();
3545
3546 case tt.bracketL:
3547 var node = this.startNode();
3548 this.next();
3549 node.elements = this.parseBindingList(tt.bracketR, true, true);
3550 return this.finishNode(node, "ArrayPattern");
3551
3552 case tt.braceL:
3553 return this.parseObj(true);
3554
3555 default:
3556 this.unexpected();
3557 }
3558};
3559
3560pp$2.parseBindingList = function (close, allowEmpty, allowTrailingComma) {
3561 var elts = [],
3562 first = true;
3563 while (!this.eat(close)) {
3564 if (first) first = false;else this.expect(tt.comma);
3565 if (allowEmpty && this.type === tt.comma) {
3566 elts.push(null);
3567 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
3568 break;
3569 } else if (this.type === tt.ellipsis) {
3570 var rest = this.parseRest();
3571 this.parseBindingListItem(rest);
3572 elts.push(rest);
3573 this.expect(close);
3574 break;
3575 } else {
3576 var elem = this.parseMaybeDefault(this.start, this.startLoc);
3577 this.parseBindingListItem(elem);
3578 elts.push(elem);
3579 }
3580 }
3581 return elts;
3582};
3583
3584pp$2.parseBindingListItem = function (param) {
3585 return param;
3586};
3587
3588// Parses assignment pattern around given atom if possible.
3589
3590pp$2.parseMaybeDefault = function (startPos, startLoc, left) {
3591 left = left || this.parseBindingAtom();
3592 if (this.options.ecmaVersion < 6 || !this.eat(tt.eq)) return left;
3593 var node = this.startNodeAt(startPos, startLoc);
3594 node.left = left;
3595 node.right = this.parseMaybeAssign();
3596 return this.finishNode(node, "AssignmentPattern");
3597};
3598
3599// Verify that a node is an lval — something that can be assigned
3600// to.
3601
3602pp$2.checkLVal = function (expr, isBinding, checkClashes) {
3603 switch (expr.type) {
3604 case "Identifier":
3605 if (this.strict && (reservedWords$1.strictBind(expr.name) || reservedWords$1.strict(expr.name))) this.raise(expr.start, (isBinding ? "Binding " : "Assigning to ") + expr.name + " in strict mode");
3606 if (checkClashes) {
3607 if (has(checkClashes, expr.name)) this.raise(expr.start, "Argument name clash in strict mode");
3608 checkClashes[expr.name] = true;
3609 }
3610 break;
3611
3612 case "MemberExpression":
3613 if (isBinding) this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " member expression");
3614 break;
3615
3616 case "ObjectPattern":
3617 for (var i = 0; i < expr.properties.length; i++) {
3618 this.checkLVal(expr.properties[i].value, isBinding, checkClashes);
3619 }break;
3620
3621 case "ArrayPattern":
3622 for (var i = 0; i < expr.elements.length; i++) {
3623 var elem = expr.elements[i];
3624 if (elem) this.checkLVal(elem, isBinding, checkClashes);
3625 }
3626 break;
3627
3628 case "AssignmentPattern":
3629 this.checkLVal(expr.left, isBinding, checkClashes);
3630 break;
3631
3632 case "RestElement":
3633 this.checkLVal(expr.argument, isBinding, checkClashes);
3634 break;
3635
3636 case "ParenthesizedExpression":
3637 this.checkLVal(expr.expression, isBinding, checkClashes);
3638 break;
3639
3640 default:
3641 this.raise(expr.start, (isBinding ? "Binding" : "Assigning to") + " rvalue");
3642 }
3643};
3644
3645var pp$3 = Parser.prototype;
3646
3647// Check if property name clashes with already added.
3648// Object/class getters and setters are not allowed to clash —
3649// either with each other or with an init property — and in
3650// strict mode, init properties are also not allowed to be repeated.
3651
3652pp$3.checkPropClash = function (prop, propHash) {
3653 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand)) return;
3654 var key = prop.key,
3655 name = undefined;
3656 switch (key.type) {
3657 case "Identifier":
3658 name = key.name;break;
3659 case "Literal":
3660 name = String(key.value);break;
3661 default:
3662 return;
3663 }
3664 var kind = prop.kind;
3665 if (this.options.ecmaVersion >= 6) {
3666 if (name === "__proto__" && kind === "init") {
3667 if (propHash.proto) this.raise(key.start, "Redefinition of __proto__ property");
3668 propHash.proto = true;
3669 }
3670 return;
3671 }
3672 var other = undefined;
3673 if (has(propHash, name)) {
3674 other = propHash[name];
3675 var isGetSet = kind !== "init";
3676 if ((this.strict || isGetSet) && other[kind] || !(isGetSet ^ other.init)) this.raise(key.start, "Redefinition of property");
3677 } else {
3678 other = propHash[name] = {
3679 init: false,
3680 get: false,
3681 set: false
3682 };
3683 }
3684 other[kind] = true;
3685};
3686
3687// ### Expression parsing
3688
3689// These nest, from the most general expression type at the top to
3690// 'atomic', nondivisible expression types at the bottom. Most of
3691// the functions will simply let the function(s) below them parse,
3692// and, *if* the syntactic construct they handle is present, wrap
3693// the AST node that the inner parser gave them in another node.
3694
3695// Parse a full expression. The optional arguments are used to
3696// forbid the `in` operator (in for loops initalization expressions)
3697// and provide reference for storing '=' operator inside shorthand
3698// property assignment in contexts where both object expression
3699// and object pattern might appear (so it's possible to raise
3700// delayed syntax error at correct position).
3701
3702pp$3.parseExpression = function (noIn, refShorthandDefaultPos) {
3703 var startPos = this.start,
3704 startLoc = this.startLoc;
3705 var expr = this.parseMaybeAssign(noIn, refShorthandDefaultPos);
3706 if (this.type === tt.comma) {
3707 var node = this.startNodeAt(startPos, startLoc);
3708 node.expressions = [expr];
3709 while (this.eat(tt.comma)) node.expressions.push(this.parseMaybeAssign(noIn, refShorthandDefaultPos));
3710 return this.finishNode(node, "SequenceExpression");
3711 }
3712 return expr;
3713};
3714
3715// Parse an assignment expression. This includes applications of
3716// operators like `+=`.
3717
3718pp$3.parseMaybeAssign = function (noIn, refShorthandDefaultPos, afterLeftParse) {
3719 if (this.type == tt._yield && this.inGenerator) return this.parseYield();
3720
3721 var failOnShorthandAssign = undefined;
3722 if (!refShorthandDefaultPos) {
3723 refShorthandDefaultPos = { start: 0 };
3724 failOnShorthandAssign = true;
3725 } else {
3726 failOnShorthandAssign = false;
3727 }
3728 var startPos = this.start,
3729 startLoc = this.startLoc;
3730 if (this.type == tt.parenL || this.type == tt.name) this.potentialArrowAt = this.start;
3731 var left = this.parseMaybeConditional(noIn, refShorthandDefaultPos);
3732 if (afterLeftParse) left = afterLeftParse.call(this, left, startPos, startLoc);
3733 if (this.type.isAssign) {
3734 var node = this.startNodeAt(startPos, startLoc);
3735 node.operator = this.value;
3736 node.left = this.type === tt.eq ? this.toAssignable(left) : left;
3737 refShorthandDefaultPos.start = 0; // reset because shorthand default was used correctly
3738 this.checkLVal(left);
3739 this.next();
3740 node.right = this.parseMaybeAssign(noIn);
3741 return this.finishNode(node, "AssignmentExpression");
3742 } else if (failOnShorthandAssign && refShorthandDefaultPos.start) {
3743 this.unexpected(refShorthandDefaultPos.start);
3744 }
3745 return left;
3746};
3747
3748// Parse a ternary conditional (`?:`) operator.
3749
3750pp$3.parseMaybeConditional = function (noIn, refShorthandDefaultPos) {
3751 var startPos = this.start,
3752 startLoc = this.startLoc;
3753 var expr = this.parseExprOps(noIn, refShorthandDefaultPos);
3754 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
3755 if (this.eat(tt.question)) {
3756 var node = this.startNodeAt(startPos, startLoc);
3757 node.test = expr;
3758 node.consequent = this.parseMaybeAssign();
3759 this.expect(tt.colon);
3760 node.alternate = this.parseMaybeAssign(noIn);
3761 return this.finishNode(node, "ConditionalExpression");
3762 }
3763 return expr;
3764};
3765
3766// Start the precedence parser.
3767
3768pp$3.parseExprOps = function (noIn, refShorthandDefaultPos) {
3769 var startPos = this.start,
3770 startLoc = this.startLoc;
3771 var expr = this.parseMaybeUnary(refShorthandDefaultPos);
3772 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
3773 return this.parseExprOp(expr, startPos, startLoc, -1, noIn);
3774};
3775
3776// Parse binary operators with the operator precedence parsing
3777// algorithm. `left` is the left-hand side of the operator.
3778// `minPrec` provides context that allows the function to stop and
3779// defer further parser to one of its callers when it encounters an
3780// operator that has a lower precedence than the set it is parsing.
3781
3782pp$3.parseExprOp = function (left, leftStartPos, leftStartLoc, minPrec, noIn) {
3783 var prec = this.type.binop;
3784 if (prec != null && (!noIn || this.type !== tt._in)) {
3785 if (prec > minPrec) {
3786 var node = this.startNodeAt(leftStartPos, leftStartLoc);
3787 node.left = left;
3788 node.operator = this.value;
3789 var op = this.type;
3790 this.next();
3791 var startPos = this.start,
3792 startLoc = this.startLoc;
3793 node.right = this.parseExprOp(this.parseMaybeUnary(), startPos, startLoc, prec, noIn);
3794 this.finishNode(node, op === tt.logicalOR || op === tt.logicalAND ? "LogicalExpression" : "BinaryExpression");
3795 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn);
3796 }
3797 }
3798 return left;
3799};
3800
3801// Parse unary operators, both prefix and postfix.
3802
3803pp$3.parseMaybeUnary = function (refShorthandDefaultPos) {
3804 if (this.type.prefix) {
3805 var node = this.startNode(),
3806 update = this.type === tt.incDec;
3807 node.operator = this.value;
3808 node.prefix = true;
3809 this.next();
3810 node.argument = this.parseMaybeUnary();
3811 if (refShorthandDefaultPos && refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
3812 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");
3813 return this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
3814 }
3815 var startPos = this.start,
3816 startLoc = this.startLoc;
3817 var expr = this.parseExprSubscripts(refShorthandDefaultPos);
3818 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
3819 while (this.type.postfix && !this.canInsertSemicolon()) {
3820 var node = this.startNodeAt(startPos, startLoc);
3821 node.operator = this.value;
3822 node.prefix = false;
3823 node.argument = expr;
3824 this.checkLVal(expr);
3825 this.next();
3826 expr = this.finishNode(node, "UpdateExpression");
3827 }
3828 return expr;
3829};
3830
3831// Parse call, dot, and `[]`-subscript expressions.
3832
3833pp$3.parseExprSubscripts = function (refShorthandDefaultPos) {
3834 var startPos = this.start,
3835 startLoc = this.startLoc;
3836 var expr = this.parseExprAtom(refShorthandDefaultPos);
3837 if (refShorthandDefaultPos && refShorthandDefaultPos.start) return expr;
3838 return this.parseSubscripts(expr, startPos, startLoc);
3839};
3840
3841pp$3.parseSubscripts = function (base, startPos, startLoc, noCalls) {
3842 for (;;) {
3843 if (this.eat(tt.dot)) {
3844 var node = this.startNodeAt(startPos, startLoc);
3845 node.object = base;
3846 node.property = this.parseIdent(true);
3847 node.computed = false;
3848 base = this.finishNode(node, "MemberExpression");
3849 } else if (this.eat(tt.bracketL)) {
3850 var node = this.startNodeAt(startPos, startLoc);
3851 node.object = base;
3852 node.property = this.parseExpression();
3853 node.computed = true;
3854 this.expect(tt.bracketR);
3855 base = this.finishNode(node, "MemberExpression");
3856 } else if (!noCalls && this.eat(tt.parenL)) {
3857 var node = this.startNodeAt(startPos, startLoc);
3858 node.callee = base;
3859 node.arguments = this.parseExprList(tt.parenR, false);
3860 base = this.finishNode(node, "CallExpression");
3861 } else if (this.type === tt.backQuote) {
3862 var node = this.startNodeAt(startPos, startLoc);
3863 node.tag = base;
3864 node.quasi = this.parseTemplate();
3865 base = this.finishNode(node, "TaggedTemplateExpression");
3866 } else {
3867 return base;
3868 }
3869 }
3870};
3871
3872// Parse an atomic expression — either a single token that is an
3873// expression, an expression started by a keyword like `function` or
3874// `new`, or an expression wrapped in punctuation like `()`, `[]`,
3875// or `{}`.
3876
3877pp$3.parseExprAtom = function (refShorthandDefaultPos) {
3878 var node = undefined,
3879 canBeArrow = this.potentialArrowAt == this.start;
3880 switch (this.type) {
3881 case tt._super:
3882 if (!this.inFunction) this.raise(this.start, "'super' outside of function or class");
3883 case tt._this:
3884 var type = this.type === tt._this ? "ThisExpression" : "Super";
3885 node = this.startNode();
3886 this.next();
3887 return this.finishNode(node, type);
3888
3889 case tt._yield:
3890 if (this.inGenerator) this.unexpected();
3891
3892 case tt.name:
3893 var startPos = this.start,
3894 startLoc = this.startLoc;
3895 var id = this.parseIdent(this.type !== tt.name);
3896 if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id]);
3897 return id;
3898
3899 case tt.regexp:
3900 var value = this.value;
3901 node = this.parseLiteral(value.value);
3902 node.regex = { pattern: value.pattern, flags: value.flags };
3903 return node;
3904
3905 case tt.num:case tt.string:
3906 return this.parseLiteral(this.value);
3907
3908 case tt._null:case tt._true:case tt._false:
3909 node = this.startNode();
3910 node.value = this.type === tt._null ? null : this.type === tt._true;
3911 node.raw = this.type.keyword;
3912 this.next();
3913 return this.finishNode(node, "Literal");
3914
3915 case tt.parenL:
3916 return this.parseParenAndDistinguishExpression(canBeArrow);
3917
3918 case tt.bracketL:
3919 node = this.startNode();
3920 this.next();
3921 // check whether this is array comprehension or regular array
3922 if (this.options.ecmaVersion >= 7 && this.type === tt._for) {
3923 return this.parseComprehension(node, false);
3924 }
3925 node.elements = this.parseExprList(tt.bracketR, true, true, refShorthandDefaultPos);
3926 return this.finishNode(node, "ArrayExpression");
3927
3928 case tt.braceL:
3929 return this.parseObj(false, refShorthandDefaultPos);
3930
3931 case tt._function:
3932 node = this.startNode();
3933 this.next();
3934 return this.parseFunction(node, false);
3935
3936 case tt._class:
3937 return this.parseClass(this.startNode(), false);
3938
3939 case tt._new:
3940 return this.parseNew();
3941
3942 case tt.backQuote:
3943 return this.parseTemplate();
3944
3945 default:
3946 this.unexpected();
3947 }
3948};
3949
3950pp$3.parseLiteral = function (value) {
3951 var node = this.startNode();
3952 node.value = value;
3953 node.raw = this.input.slice(this.start, this.end);
3954 this.next();
3955 return this.finishNode(node, "Literal");
3956};
3957
3958pp$3.parseParenExpression = function () {
3959 this.expect(tt.parenL);
3960 var val = this.parseExpression();
3961 this.expect(tt.parenR);
3962 return val;
3963};
3964
3965pp$3.parseParenAndDistinguishExpression = function (canBeArrow) {
3966 var startPos = this.start,
3967 startLoc = this.startLoc,
3968 val = undefined;
3969 if (this.options.ecmaVersion >= 6) {
3970 this.next();
3971
3972 if (this.options.ecmaVersion >= 7 && this.type === tt._for) {
3973 return this.parseComprehension(this.startNodeAt(startPos, startLoc), true);
3974 }
3975
3976 var innerStartPos = this.start,
3977 innerStartLoc = this.startLoc;
3978 var exprList = [],
3979 first = true;
3980 var refShorthandDefaultPos = { start: 0 },
3981 spreadStart = undefined,
3982 innerParenStart = undefined;
3983 while (this.type !== tt.parenR) {
3984 first ? first = false : this.expect(tt.comma);
3985 if (this.type === tt.ellipsis) {
3986 spreadStart = this.start;
3987 exprList.push(this.parseParenItem(this.parseRest()));
3988 break;
3989 } else {
3990 if (this.type === tt.parenL && !innerParenStart) {
3991 innerParenStart = this.start;
3992 }
3993 exprList.push(this.parseMaybeAssign(false, refShorthandDefaultPos, this.parseParenItem));
3994 }
3995 }
3996 var innerEndPos = this.start,
3997 innerEndLoc = this.startLoc;
3998 this.expect(tt.parenR);
3999
4000 if (canBeArrow && !this.canInsertSemicolon() && this.eat(tt.arrow)) {
4001 if (innerParenStart) this.unexpected(innerParenStart);
4002 return this.parseParenArrowList(startPos, startLoc, exprList);
4003 }
4004
4005 if (!exprList.length) this.unexpected(this.lastTokStart);
4006 if (spreadStart) this.unexpected(spreadStart);
4007 if (refShorthandDefaultPos.start) this.unexpected(refShorthandDefaultPos.start);
4008
4009 if (exprList.length > 1) {
4010 val = this.startNodeAt(innerStartPos, innerStartLoc);
4011 val.expressions = exprList;
4012 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
4013 } else {
4014 val = exprList[0];
4015 }
4016 } else {
4017 val = this.parseParenExpression();
4018 }
4019
4020 if (this.options.preserveParens) {
4021 var par = this.startNodeAt(startPos, startLoc);
4022 par.expression = val;
4023 return this.finishNode(par, "ParenthesizedExpression");
4024 } else {
4025 return val;
4026 }
4027};
4028
4029pp$3.parseParenItem = function (item) {
4030 return item;
4031};
4032
4033pp$3.parseParenArrowList = function (startPos, startLoc, exprList) {
4034 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList);
4035};
4036
4037// New's precedence is slightly tricky. It must allow its argument
4038// to be a `[]` or dot subscript expression, but not a call — at
4039// least, not without wrapping it in parentheses. Thus, it uses the
4040
4041var empty$1 = [];
4042
4043pp$3.parseNew = function () {
4044 var node = this.startNode();
4045 var meta = this.parseIdent(true);
4046 if (this.options.ecmaVersion >= 6 && this.eat(tt.dot)) {
4047 node.meta = meta;
4048 node.property = this.parseIdent(true);
4049 if (node.property.name !== "target") this.raise(node.property.start, "The only valid meta property for new is new.target");
4050 return this.finishNode(node, "MetaProperty");
4051 }
4052 var startPos = this.start,
4053 startLoc = this.startLoc;
4054 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
4055 if (this.eat(tt.parenL)) node.arguments = this.parseExprList(tt.parenR, false);else node.arguments = empty$1;
4056 return this.finishNode(node, "NewExpression");
4057};
4058
4059// Parse template expression.
4060
4061pp$3.parseTemplateElement = function () {
4062 var elem = this.startNode();
4063 elem.value = {
4064 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, '\n'),
4065 cooked: this.value
4066 };
4067 this.next();
4068 elem.tail = this.type === tt.backQuote;
4069 return this.finishNode(elem, "TemplateElement");
4070};
4071
4072pp$3.parseTemplate = function () {
4073 var node = this.startNode();
4074 this.next();
4075 node.expressions = [];
4076 var curElt = this.parseTemplateElement();
4077 node.quasis = [curElt];
4078 while (!curElt.tail) {
4079 this.expect(tt.dollarBraceL);
4080 node.expressions.push(this.parseExpression());
4081 this.expect(tt.braceR);
4082 node.quasis.push(curElt = this.parseTemplateElement());
4083 }
4084 this.next();
4085 return this.finishNode(node, "TemplateLiteral");
4086};
4087
4088// Parse an object literal or binding pattern.
4089
4090pp$3.parseObj = function (isPattern, refShorthandDefaultPos) {
4091 var node = this.startNode(),
4092 first = true,
4093 propHash = {};
4094 node.properties = [];
4095 this.next();
4096 while (!this.eat(tt.braceR)) {
4097 if (!first) {
4098 this.expect(tt.comma);
4099 if (this.afterTrailingComma(tt.braceR)) break;
4100 } else first = false;
4101
4102 var prop = this.startNode(),
4103 isGenerator = undefined,
4104 startPos = undefined,
4105 startLoc = undefined;
4106 if (this.options.ecmaVersion >= 6) {
4107 prop.method = false;
4108 prop.shorthand = false;
4109 if (isPattern || refShorthandDefaultPos) {
4110 startPos = this.start;
4111 startLoc = this.startLoc;
4112 }
4113 if (!isPattern) isGenerator = this.eat(tt.star);
4114 }
4115 this.parsePropertyName(prop);
4116 this.parsePropertyValue(prop, isPattern, isGenerator, startPos, startLoc, refShorthandDefaultPos);
4117 this.checkPropClash(prop, propHash);
4118 node.properties.push(this.finishNode(prop, "Property"));
4119 }
4120 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression");
4121};
4122
4123pp$3.parsePropertyValue = function (prop, isPattern, isGenerator, startPos, startLoc, refShorthandDefaultPos) {
4124 if (this.eat(tt.colon)) {
4125 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refShorthandDefaultPos);
4126 prop.kind = "init";
4127 } else if (this.options.ecmaVersion >= 6 && this.type === tt.parenL) {
4128 if (isPattern) this.unexpected();
4129 prop.kind = "init";
4130 prop.method = true;
4131 prop.value = this.parseMethod(isGenerator);
4132 } 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)) {
4133 if (isGenerator || isPattern) this.unexpected();
4134 prop.kind = prop.key.name;
4135 this.parsePropertyName(prop);
4136 prop.value = this.parseMethod(false);
4137 var paramCount = prop.kind === "get" ? 0 : 1;
4138 if (prop.value.params.length !== paramCount) {
4139 var start = prop.value.start;
4140 if (prop.kind === "get") this.raise(start, "getter should have no params");else this.raise(start, "setter should have exactly one param");
4141 }
4142 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
4143 prop.kind = "init";
4144 if (isPattern) {
4145 if (this.isKeyword(prop.key.name) || this.strict && (reservedWords$1.strictBind(prop.key.name) || reservedWords$1.strict(prop.key.name)) || !this.options.allowReserved && this.isReservedWord(prop.key.name)) this.raise(prop.key.start, "Binding " + prop.key.name);
4146 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
4147 } else if (this.type === tt.eq && refShorthandDefaultPos) {
4148 if (!refShorthandDefaultPos.start) refShorthandDefaultPos.start = this.start;
4149 prop.value = this.parseMaybeDefault(startPos, startLoc, prop.key);
4150 } else {
4151 prop.value = prop.key;
4152 }
4153 prop.shorthand = true;
4154 } else this.unexpected();
4155};
4156
4157pp$3.parsePropertyName = function (prop) {
4158 if (this.options.ecmaVersion >= 6) {
4159 if (this.eat(tt.bracketL)) {
4160 prop.computed = true;
4161 prop.key = this.parseMaybeAssign();
4162 this.expect(tt.bracketR);
4163 return prop.key;
4164 } else {
4165 prop.computed = false;
4166 }
4167 }
4168 return prop.key = this.type === tt.num || this.type === tt.string ? this.parseExprAtom() : this.parseIdent(true);
4169};
4170
4171// Initialize empty function node.
4172
4173pp$3.initFunction = function (node) {
4174 node.id = null;
4175 if (this.options.ecmaVersion >= 6) {
4176 node.generator = false;
4177 node.expression = false;
4178 }
4179};
4180
4181// Parse object or class method.
4182
4183pp$3.parseMethod = function (isGenerator) {
4184 var node = this.startNode();
4185 this.initFunction(node);
4186 this.expect(tt.parenL);
4187 node.params = this.parseBindingList(tt.parenR, false, false);
4188 var allowExpressionBody = undefined;
4189 if (this.options.ecmaVersion >= 6) {
4190 node.generator = isGenerator;
4191 }
4192 this.parseFunctionBody(node, false);
4193 return this.finishNode(node, "FunctionExpression");
4194};
4195
4196// Parse arrow function expression with given parameters.
4197
4198pp$3.parseArrowExpression = function (node, params) {
4199 this.initFunction(node);
4200 node.params = this.toAssignableList(params, true);
4201 this.parseFunctionBody(node, true);
4202 return this.finishNode(node, "ArrowFunctionExpression");
4203};
4204
4205// Parse function body and check parameters.
4206
4207pp$3.parseFunctionBody = function (node, allowExpression) {
4208 var isExpression = allowExpression && this.type !== tt.braceL;
4209
4210 if (isExpression) {
4211 node.body = this.parseMaybeAssign();
4212 node.expression = true;
4213 } else {
4214 // Start a new scope with regard to labels and the `inFunction`
4215 // flag (restore them to their old value afterwards).
4216 var oldInFunc = this.inFunction,
4217 oldInGen = this.inGenerator,
4218 oldLabels = this.labels;
4219 this.inFunction = true;this.inGenerator = node.generator;this.labels = [];
4220 node.body = this.parseBlock(true);
4221 node.expression = false;
4222 this.inFunction = oldInFunc;this.inGenerator = oldInGen;this.labels = oldLabels;
4223 }
4224
4225 // If this is a strict mode function, verify that argument names
4226 // are not repeated, and it does not try to bind the words `eval`
4227 // or `arguments`.
4228 if (this.strict || !isExpression && node.body.body.length && this.isUseStrict(node.body.body[0])) {
4229 var nameHash = {},
4230 oldStrict = this.strict;
4231 this.strict = true;
4232 if (node.id) this.checkLVal(node.id, true);
4233 for (var i = 0; i < node.params.length; i++) {
4234 this.checkLVal(node.params[i], true, nameHash);
4235 }this.strict = oldStrict;
4236 }
4237};
4238
4239// Parses a comma-separated list of expressions, and returns them as
4240// an array. `close` is the token type that ends the list, and
4241// `allowEmpty` can be turned on to allow subsequent commas with
4242// nothing in between them to be parsed as `null` (which is needed
4243// for array literals).
4244
4245pp$3.parseExprList = function (close, allowTrailingComma, allowEmpty, refShorthandDefaultPos) {
4246 var elts = [],
4247 first = true;
4248 while (!this.eat(close)) {
4249 if (!first) {
4250 this.expect(tt.comma);
4251 if (allowTrailingComma && this.afterTrailingComma(close)) break;
4252 } else first = false;
4253
4254 var elt = undefined;
4255 if (allowEmpty && this.type === tt.comma) elt = null;else if (this.type === tt.ellipsis) elt = this.parseSpread(refShorthandDefaultPos);else elt = this.parseMaybeAssign(false, refShorthandDefaultPos);
4256 elts.push(elt);
4257 }
4258 return elts;
4259};
4260
4261// Parse the next token as an identifier. If `liberal` is true (used
4262// when parsing properties), it will also convert keywords into
4263// identifiers.
4264
4265pp$3.parseIdent = function (liberal) {
4266 var node = this.startNode();
4267 if (liberal && this.options.allowReserved == "never") liberal = false;
4268 if (this.type === tt.name) {
4269 if (!liberal && (!this.options.allowReserved && this.isReservedWord(this.value) || this.strict && reservedWords$1.strict(this.value) && (this.options.ecmaVersion >= 6 || this.input.slice(this.start, this.end).indexOf("\\") == -1))) this.raise(this.start, "The keyword '" + this.value + "' is reserved");
4270 node.name = this.value;
4271 } else if (liberal && this.type.keyword) {
4272 node.name = this.type.keyword;
4273 } else {
4274 this.unexpected();
4275 }
4276 this.next();
4277 return this.finishNode(node, "Identifier");
4278};
4279
4280// Parses yield expression inside generator.
4281
4282pp$3.parseYield = function () {
4283 var node = this.startNode();
4284 this.next();
4285 if (this.type == tt.semi || this.canInsertSemicolon() || this.type != tt.star && !this.type.startsExpr) {
4286 node.delegate = false;
4287 node.argument = null;
4288 } else {
4289 node.delegate = this.eat(tt.star);
4290 node.argument = this.parseMaybeAssign();
4291 }
4292 return this.finishNode(node, "YieldExpression");
4293};
4294
4295// Parses array and generator comprehensions.
4296
4297pp$3.parseComprehension = function (node, isGenerator) {
4298 node.blocks = [];
4299 while (this.type === tt._for) {
4300 var block = this.startNode();
4301 this.next();
4302 this.expect(tt.parenL);
4303 block.left = this.parseBindingAtom();
4304 this.checkLVal(block.left, true);
4305 this.expectContextual("of");
4306 block.right = this.parseExpression();
4307 this.expect(tt.parenR);
4308 node.blocks.push(this.finishNode(block, "ComprehensionBlock"));
4309 }
4310 node.filter = this.eat(tt._if) ? this.parseParenExpression() : null;
4311 node.body = this.parseExpression();
4312 this.expect(isGenerator ? tt.parenR : tt.bracketR);
4313 node.generator = isGenerator;
4314 return this.finishNode(node, "ComprehensionExpression");
4315};
4316
4317var pp$4 = Parser.prototype;
4318
4319// This function is used to raise exceptions on parse errors. It
4320// takes an offset integer (into the current `input`) to indicate
4321// the location of the error, attaches the position to the end
4322// of the error message, and then raises a `SyntaxError` with that
4323// message.
4324
4325pp$4.raise = function (pos, message) {
4326 var loc = getLineInfo(this.input, pos);
4327 message += " (" + loc.line + ":" + loc.column + ")";
4328 var err = new SyntaxError(message);
4329 err.pos = pos;err.loc = loc;err.raisedAt = this.pos;
4330 throw err;
4331};
4332
4333pp$4.curPosition = function () {
4334 if (this.options.locations) {
4335 return new Position(this.curLine, this.pos - this.lineStart);
4336 }
4337};
4338
4339var Node = function Node(parser, pos, loc) {
4340 babelHelpers.classCallCheck(this, Node);
4341
4342 this.type = "";
4343 this.start = pos;
4344 this.end = 0;
4345 if (parser.options.locations) this.loc = new SourceLocation(parser, loc);
4346 if (parser.options.directSourceFile) this.sourceFile = parser.options.directSourceFile;
4347 if (parser.options.ranges) this.range = [pos, 0];
4348}
4349
4350// Start an AST node, attaching a start offset.
4351
4352;
4353
4354var pp$5 = Parser.prototype;
4355
4356pp$5.startNode = function () {
4357 return new Node(this, this.start, this.startLoc);
4358};
4359
4360pp$5.startNodeAt = function (pos, loc) {
4361 return new Node(this, pos, loc);
4362};
4363
4364// Finish an AST node, adding `type` and `end` properties.
4365
4366function finishNodeAt(node, type, pos, loc) {
4367 node.type = type;
4368 node.end = pos;
4369 if (this.options.locations) node.loc.end = loc;
4370 if (this.options.ranges) node.range[1] = pos;
4371 return node;
4372}
4373
4374pp$5.finishNode = function (node, type) {
4375 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc);
4376};
4377
4378// Finish node at given position
4379
4380pp$5.finishNodeAt = function (node, type, pos, loc) {
4381 return finishNodeAt.call(this, node, type, pos, loc);
4382};
4383
4384var TokContext = function TokContext(token, isExpr, preserveSpace, override) {
4385 babelHelpers.classCallCheck(this, TokContext);
4386
4387 this.token = token;
4388 this.isExpr = !!isExpr;
4389 this.preserveSpace = !!preserveSpace;
4390 this.override = override;
4391};
4392
4393var types = {
4394 b_stat: new TokContext("{", false),
4395 b_expr: new TokContext("{", true),
4396 b_tmpl: new TokContext("${", true),
4397 p_stat: new TokContext("(", false),
4398 p_expr: new TokContext("(", true),
4399 q_tmpl: new TokContext("`", true, true, function (p) {
4400 return p.readTmplToken();
4401 }),
4402 f_expr: new TokContext("function", true)
4403};
4404
4405var pp$6 = Parser.prototype;
4406
4407pp$6.initialContext = function () {
4408 return [types.b_stat];
4409};
4410
4411pp$6.braceIsBlock = function (prevType) {
4412 if (prevType === tt.colon) {
4413 var _parent = this.curContext();
4414 if (_parent === types.b_stat || _parent === types.b_expr) return !_parent.isExpr;
4415 }
4416 if (prevType === tt._return) return lineBreak.test(this.input.slice(this.lastTokEnd, this.start));
4417 if (prevType === tt._else || prevType === tt.semi || prevType === tt.eof || prevType === tt.parenR) return true;
4418 if (prevType == tt.braceL) return this.curContext() === types.b_stat;
4419 return !this.exprAllowed;
4420};
4421
4422pp$6.updateContext = function (prevType) {
4423 var update = undefined,
4424 type = this.type;
4425 if (type.keyword && prevType == tt.dot) this.exprAllowed = false;else if (update = type.updateContext) update.call(this, prevType);else this.exprAllowed = type.beforeExpr;
4426};
4427
4428// Token-specific context update code
4429
4430tt.parenR.updateContext = tt.braceR.updateContext = function () {
4431 if (this.context.length == 1) {
4432 this.exprAllowed = true;
4433 return;
4434 }
4435 var out = this.context.pop();
4436 if (out === types.b_stat && this.curContext() === types.f_expr) {
4437 this.context.pop();
4438 this.exprAllowed = false;
4439 } else if (out === types.b_tmpl) {
4440 this.exprAllowed = true;
4441 } else {
4442 this.exprAllowed = !out.isExpr;
4443 }
4444};
4445
4446tt.braceL.updateContext = function (prevType) {
4447 this.context.push(this.braceIsBlock(prevType) ? types.b_stat : types.b_expr);
4448 this.exprAllowed = true;
4449};
4450
4451tt.dollarBraceL.updateContext = function () {
4452 this.context.push(types.b_tmpl);
4453 this.exprAllowed = true;
4454};
4455
4456tt.parenL.updateContext = function (prevType) {
4457 var statementParens = prevType === tt._if || prevType === tt._for || prevType === tt._with || prevType === tt._while;
4458 this.context.push(statementParens ? types.p_stat : types.p_expr);
4459 this.exprAllowed = true;
4460};
4461
4462tt.incDec.updateContext = function () {
4463 // tokExprAllowed stays unchanged
4464};
4465
4466tt._function.updateContext = function () {
4467 if (this.curContext() !== types.b_stat) this.context.push(types.f_expr);
4468 this.exprAllowed = false;
4469};
4470
4471tt.backQuote.updateContext = function () {
4472 if (this.curContext() === types.q_tmpl) this.context.pop();else this.context.push(types.q_tmpl);
4473 this.exprAllowed = false;
4474};
4475
4476// Object type used to represent tokens. Note that normally, tokens
4477// simply exist as properties on the parser object. This is only
4478// used for the onToken callback and the external tokenizer.
4479
4480var Token = function Token(p) {
4481 babelHelpers.classCallCheck(this, Token);
4482
4483 this.type = p.type;
4484 this.value = p.value;
4485 this.start = p.start;
4486 this.end = p.end;
4487 if (p.options.locations) this.loc = new SourceLocation(p, p.startLoc, p.endLoc);
4488 if (p.options.ranges) this.range = [p.start, p.end];
4489}
4490
4491// ## Tokenizer
4492
4493;
4494
4495var pp$7 = Parser.prototype;
4496
4497// Are we running under Rhino?
4498var isRhino = typeof Packages == "object" && Object.prototype.toString.call(Packages) == "[object JavaPackage]";
4499
4500// Move to the next token
4501
4502pp$7.next = function () {
4503 if (this.options.onToken) this.options.onToken(new Token(this));
4504
4505 this.lastTokEnd = this.end;
4506 this.lastTokStart = this.start;
4507 this.lastTokEndLoc = this.endLoc;
4508 this.lastTokStartLoc = this.startLoc;
4509 this.nextToken();
4510};
4511
4512pp$7.getToken = function () {
4513 this.next();
4514 return new Token(this);
4515};
4516
4517// If we're in an ES6 environment, make parsers iterable
4518if (typeof Symbol !== "undefined") pp$7[Symbol.iterator] = function () {
4519 var self = this;
4520 return { next: function () {
4521 var token = self.getToken();
4522 return {
4523 done: token.type === tt.eof,
4524 value: token
4525 };
4526 } };
4527};
4528
4529// Toggle strict mode. Re-reads the next number or string to please
4530// pedantic tests (`"use strict"; 010;` should fail).
4531
4532pp$7.setStrict = function (strict) {
4533 this.strict = strict;
4534 if (this.type !== tt.num && this.type !== tt.string) return;
4535 this.pos = this.start;
4536 if (this.options.locations) {
4537 while (this.pos < this.lineStart) {
4538 this.lineStart = this.input.lastIndexOf("\n", this.lineStart - 2) + 1;
4539 --this.curLine;
4540 }
4541 }
4542 this.nextToken();
4543};
4544
4545pp$7.curContext = function () {
4546 return this.context[this.context.length - 1];
4547};
4548
4549// Read a single token, updating the parser object's token-related
4550// properties.
4551
4552pp$7.nextToken = function () {
4553 var curContext = this.curContext();
4554 if (!curContext || !curContext.preserveSpace) this.skipSpace();
4555
4556 this.start = this.pos;
4557 if (this.options.locations) this.startLoc = this.curPosition();
4558 if (this.pos >= this.input.length) return this.finishToken(tt.eof);
4559
4560 if (curContext.override) return curContext.override(this);else this.readToken(this.fullCharCodeAtPos());
4561};
4562
4563pp$7.readToken = function (code) {
4564 // Identifier or keyword. '\uXXXX' sequences are allowed in
4565 // identifiers, so '\' also dispatches to that.
4566 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */) return this.readWord();
4567
4568 return this.getTokenFromCode(code);
4569};
4570
4571pp$7.fullCharCodeAtPos = function () {
4572 var code = this.input.charCodeAt(this.pos);
4573 if (code <= 0xd7ff || code >= 0xe000) return code;
4574 var next = this.input.charCodeAt(this.pos + 1);
4575 return (code << 10) + next - 0x35fdc00;
4576};
4577
4578pp$7.skipBlockComment = function () {
4579 var startLoc = this.options.onComment && this.curPosition();
4580 var start = this.pos,
4581 end = this.input.indexOf("*/", this.pos += 2);
4582 if (end === -1) this.raise(this.pos - 2, "Unterminated comment");
4583 this.pos = end + 2;
4584 if (this.options.locations) {
4585 lineBreakG.lastIndex = start;
4586 var match = undefined;
4587 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
4588 ++this.curLine;
4589 this.lineStart = match.index + match[0].length;
4590 }
4591 }
4592 if (this.options.onComment) this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos, startLoc, this.curPosition());
4593};
4594
4595pp$7.skipLineComment = function (startSkip) {
4596 var start = this.pos;
4597 var startLoc = this.options.onComment && this.curPosition();
4598 var ch = this.input.charCodeAt(this.pos += startSkip);
4599 while (this.pos < this.input.length && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
4600 ++this.pos;
4601 ch = this.input.charCodeAt(this.pos);
4602 }
4603 if (this.options.onComment) this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos, startLoc, this.curPosition());
4604};
4605
4606// Called at the start of the parse and after every token. Skips
4607// whitespace and comments, and.
4608
4609pp$7.skipSpace = function () {
4610 loop: while (this.pos < this.input.length) {
4611 var ch = this.input.charCodeAt(this.pos);
4612 switch (ch) {
4613 case 32:case 160:
4614 // ' '
4615 ++this.pos;
4616 break;
4617 case 13:
4618 if (this.input.charCodeAt(this.pos + 1) === 10) {
4619 ++this.pos;
4620 }
4621 case 10:case 8232:case 8233:
4622 ++this.pos;
4623 if (this.options.locations) {
4624 ++this.curLine;
4625 this.lineStart = this.pos;
4626 }
4627 break;
4628 case 47:
4629 // '/'
4630 switch (this.input.charCodeAt(this.pos + 1)) {
4631 case 42:
4632 // '*'
4633 this.skipBlockComment();
4634 break;
4635 case 47:
4636 this.skipLineComment(2);
4637 break;
4638 default:
4639 break loop;
4640 }
4641 break;
4642 default:
4643 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
4644 ++this.pos;
4645 } else {
4646 break loop;
4647 }
4648 }
4649 }
4650};
4651
4652// Called at the end of every token. Sets `end`, `val`, and
4653// maintains `context` and `exprAllowed`, and skips the space after
4654// the token, so that the next one's `start` will point at the
4655// right position.
4656
4657pp$7.finishToken = function (type, val) {
4658 this.end = this.pos;
4659 if (this.options.locations) this.endLoc = this.curPosition();
4660 var prevType = this.type;
4661 this.type = type;
4662 this.value = val;
4663
4664 this.updateContext(prevType);
4665};
4666
4667// ### Token reading
4668
4669// This is the function that is called to fetch the next token. It
4670// is somewhat obscure, because it works in character codes rather
4671// than characters, and because operator parsing has been inlined
4672// into it.
4673//
4674// All in the name of speed.
4675//
4676pp$7.readToken_dot = function () {
4677 var next = this.input.charCodeAt(this.pos + 1);
4678 if (next >= 48 && next <= 57) return this.readNumber(true);
4679 var next2 = this.input.charCodeAt(this.pos + 2);
4680 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) {
4681 // 46 = dot '.'
4682 this.pos += 3;
4683 return this.finishToken(tt.ellipsis);
4684 } else {
4685 ++this.pos;
4686 return this.finishToken(tt.dot);
4687 }
4688};
4689
4690pp$7.readToken_slash = function () {
4691 // '/'
4692 var next = this.input.charCodeAt(this.pos + 1);
4693 if (this.exprAllowed) {
4694 ++this.pos;return this.readRegexp();
4695 }
4696 if (next === 61) return this.finishOp(tt.assign, 2);
4697 return this.finishOp(tt.slash, 1);
4698};
4699
4700pp$7.readToken_mult_modulo = function (code) {
4701 // '%*'
4702 var next = this.input.charCodeAt(this.pos + 1);
4703 if (next === 61) return this.finishOp(tt.assign, 2);
4704 return this.finishOp(code === 42 ? tt.star : tt.modulo, 1);
4705};
4706
4707pp$7.readToken_pipe_amp = function (code) {
4708 // '|&'
4709 var next = this.input.charCodeAt(this.pos + 1);
4710 if (next === code) return this.finishOp(code === 124 ? tt.logicalOR : tt.logicalAND, 2);
4711 if (next === 61) return this.finishOp(tt.assign, 2);
4712 return this.finishOp(code === 124 ? tt.bitwiseOR : tt.bitwiseAND, 1);
4713};
4714
4715pp$7.readToken_caret = function () {
4716 // '^'
4717 var next = this.input.charCodeAt(this.pos + 1);
4718 if (next === 61) return this.finishOp(tt.assign, 2);
4719 return this.finishOp(tt.bitwiseXOR, 1);
4720};
4721
4722pp$7.readToken_plus_min = function (code) {
4723 // '+-'
4724 var next = this.input.charCodeAt(this.pos + 1);
4725 if (next === code) {
4726 if (next == 45 && this.input.charCodeAt(this.pos + 2) == 62 && lineBreak.test(this.input.slice(this.lastTokEnd, this.pos))) {
4727 // A `-->` line comment
4728 this.skipLineComment(3);
4729 this.skipSpace();
4730 return this.nextToken();
4731 }
4732 return this.finishOp(tt.incDec, 2);
4733 }
4734 if (next === 61) return this.finishOp(tt.assign, 2);
4735 return this.finishOp(tt.plusMin, 1);
4736};
4737
4738pp$7.readToken_lt_gt = function (code) {
4739 // '<>'
4740 var next = this.input.charCodeAt(this.pos + 1);
4741 var size = 1;
4742 if (next === code) {
4743 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
4744 if (this.input.charCodeAt(this.pos + size) === 61) return this.finishOp(tt.assign, size + 1);
4745 return this.finishOp(tt.bitShift, size);
4746 }
4747 if (next == 33 && code == 60 && this.input.charCodeAt(this.pos + 2) == 45 && this.input.charCodeAt(this.pos + 3) == 45) {
4748 if (this.inModule) this.unexpected();
4749 // `<!--`, an XML-style comment that should be interpreted as a line comment
4750 this.skipLineComment(4);
4751 this.skipSpace();
4752 return this.nextToken();
4753 }
4754 if (next === 61) size = this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2;
4755 return this.finishOp(tt.relational, size);
4756};
4757
4758pp$7.readToken_eq_excl = function (code) {
4759 // '=!'
4760 var next = this.input.charCodeAt(this.pos + 1);
4761 if (next === 61) return this.finishOp(tt.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2);
4762 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) {
4763 // '=>'
4764 this.pos += 2;
4765 return this.finishToken(tt.arrow);
4766 }
4767 return this.finishOp(code === 61 ? tt.eq : tt.prefix, 1);
4768};
4769
4770pp$7.getTokenFromCode = function (code) {
4771 switch (code) {
4772 // The interpretation of a dot depends on whether it is followed
4773 // by a digit or another two dots.
4774 case 46:
4775 // '.'
4776 return this.readToken_dot();
4777
4778 // Punctuation tokens.
4779 case 40:
4780 ++this.pos;return this.finishToken(tt.parenL);
4781 case 41:
4782 ++this.pos;return this.finishToken(tt.parenR);
4783 case 59:
4784 ++this.pos;return this.finishToken(tt.semi);
4785 case 44:
4786 ++this.pos;return this.finishToken(tt.comma);
4787 case 91:
4788 ++this.pos;return this.finishToken(tt.bracketL);
4789 case 93:
4790 ++this.pos;return this.finishToken(tt.bracketR);
4791 case 123:
4792 ++this.pos;return this.finishToken(tt.braceL);
4793 case 125:
4794 ++this.pos;return this.finishToken(tt.braceR);
4795 case 58:
4796 ++this.pos;return this.finishToken(tt.colon);
4797 case 63:
4798 ++this.pos;return this.finishToken(tt.question);
4799
4800 case 96:
4801 // '`'
4802 if (this.options.ecmaVersion < 6) break;
4803 ++this.pos;
4804 return this.finishToken(tt.backQuote);
4805
4806 case 48:
4807 // '0'
4808 var next = this.input.charCodeAt(this.pos + 1);
4809 if (next === 120 || next === 88) return this.readRadixNumber(16); // '0x', '0X' - hex number
4810 if (this.options.ecmaVersion >= 6) {
4811 if (next === 111 || next === 79) return this.readRadixNumber(8); // '0o', '0O' - octal number
4812 if (next === 98 || next === 66) return this.readRadixNumber(2); // '0b', '0B' - binary number
4813 }
4814 // Anything else beginning with a digit is an integer, octal
4815 // number, or float.
4816 case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:
4817 // 1-9
4818 return this.readNumber(false);
4819
4820 // Quotes produce strings.
4821 case 34:case 39:
4822 // '"', "'"
4823 return this.readString(code);
4824
4825 // Operators are parsed inline in tiny state machines. '=' (61) is
4826 // often referred to. `finishOp` simply skips the amount of
4827 // characters it is given as second argument, and returns a token
4828 // of the type given by its first argument.
4829
4830 case 47:
4831 // '/'
4832 return this.readToken_slash();
4833
4834 case 37:case 42:
4835 // '%*'
4836 return this.readToken_mult_modulo(code);
4837
4838 case 124:case 38:
4839 // '|&'
4840 return this.readToken_pipe_amp(code);
4841
4842 case 94:
4843 // '^'
4844 return this.readToken_caret();
4845
4846 case 43:case 45:
4847 // '+-'
4848 return this.readToken_plus_min(code);
4849
4850 case 60:case 62:
4851 // '<>'
4852 return this.readToken_lt_gt(code);
4853
4854 case 61:case 33:
4855 // '=!'
4856 return this.readToken_eq_excl(code);
4857
4858 case 126:
4859 // '~'
4860 return this.finishOp(tt.prefix, 1);
4861 }
4862
4863 this.raise(this.pos, "Unexpected character '" + codePointToString(code) + "'");
4864};
4865
4866pp$7.finishOp = function (type, size) {
4867 var str = this.input.slice(this.pos, this.pos + size);
4868 this.pos += size;
4869 return this.finishToken(type, str);
4870};
4871
4872// Parse a regular expression. Some context-awareness is necessary,
4873// since a '/' inside a '[]' set does not end the expression.
4874
4875function tryCreateRegexp(src, flags, throwErrorAt) {
4876 try {
4877 return new RegExp(src, flags);
4878 } catch (e) {
4879 if (throwErrorAt !== undefined) {
4880 if (e instanceof SyntaxError) this.raise(throwErrorAt, "Error parsing regular expression: " + e.message);
4881 this.raise(e);
4882 }
4883 }
4884}
4885
4886var regexpUnicodeSupport = !!tryCreateRegexp("\uffff", "u");
4887
4888pp$7.readRegexp = function () {
4889 var _this = this;
4890
4891 var escaped = undefined,
4892 inClass = undefined,
4893 start = this.pos;
4894 for (;;) {
4895 if (this.pos >= this.input.length) this.raise(start, "Unterminated regular expression");
4896 var ch = this.input.charAt(this.pos);
4897 if (lineBreak.test(ch)) this.raise(start, "Unterminated regular expression");
4898 if (!escaped) {
4899 if (ch === "[") inClass = true;else if (ch === "]" && inClass) inClass = false;else if (ch === "/" && !inClass) break;
4900 escaped = ch === "\\";
4901 } else escaped = false;
4902 ++this.pos;
4903 }
4904 var content = this.input.slice(start, this.pos);
4905 ++this.pos;
4906 // Need to use `readWord1` because '\uXXXX' sequences are allowed
4907 // here (don't ask).
4908 var mods = this.readWord1();
4909 var tmp = content;
4910 if (mods) {
4911 var validFlags = /^[gmsiy]*$/;
4912 if (this.options.ecmaVersion >= 6) validFlags = /^[gmsiyu]*$/;
4913 if (!validFlags.test(mods)) this.raise(start, "Invalid regular expression flag");
4914 if (mods.indexOf('u') >= 0 && !regexpUnicodeSupport) {
4915 // Replace each astral symbol and every Unicode escape sequence that
4916 // possibly represents an astral symbol or a paired surrogate with a
4917 // single ASCII symbol to avoid throwing on regular expressions that
4918 // are only valid in combination with the `/u` flag.
4919 // Note: replacing with the ASCII symbol `x` might cause false
4920 // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a
4921 // perfectly valid pattern that is equivalent to `[a-b]`, but it would
4922 // be replaced by `[x-b]` which throws an error.
4923 tmp = tmp.replace(/\\u\{([0-9a-fA-F]+)\}/g, function (match, code, offset) {
4924 code = Number("0x" + code);
4925 if (code > 0x10FFFF) _this.raise(start + offset + 3, "Code point out of bounds");
4926 return "x";
4927 });
4928 tmp = tmp.replace(/\\u([a-fA-F0-9]{4})|[\uD800-\uDBFF][\uDC00-\uDFFF]/g, "x");
4929 }
4930 }
4931 // Detect invalid regular expressions.
4932 var value = null;
4933 // Rhino's regular expression parser is flaky and throws uncatchable exceptions,
4934 // so don't do detection if we are running under Rhino
4935 if (!isRhino) {
4936 tryCreateRegexp(tmp, undefined, start);
4937 // Get a regular expression object for this pattern-flag pair, or `null` in
4938 // case the current environment doesn't support the flags it uses.
4939 value = tryCreateRegexp(content, mods);
4940 }
4941 return this.finishToken(tt.regexp, { pattern: content, flags: mods, value: value });
4942};
4943
4944// Read an integer in the given radix. Return null if zero digits
4945// were read, the integer value otherwise. When `len` is given, this
4946// will return `null` unless the integer has exactly `len` digits.
4947
4948pp$7.readInt = function (radix, len) {
4949 var start = this.pos,
4950 total = 0;
4951 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
4952 var code = this.input.charCodeAt(this.pos),
4953 val = undefined;
4954 if (code >= 97) val = code - 97 + 10; // a
4955 else if (code >= 65) val = code - 65 + 10; // A
4956 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
4957 else val = Infinity;
4958 if (val >= radix) break;
4959 ++this.pos;
4960 total = total * radix + val;
4961 }
4962 if (this.pos === start || len != null && this.pos - start !== len) return null;
4963
4964 return total;
4965};
4966
4967pp$7.readRadixNumber = function (radix) {
4968 this.pos += 2; // 0x
4969 var val = this.readInt(radix);
4970 if (val == null) this.raise(this.start + 2, "Expected number in radix " + radix);
4971 if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
4972 return this.finishToken(tt.num, val);
4973};
4974
4975// Read an integer, octal integer, or floating-point number.
4976
4977pp$7.readNumber = function (startsWithDot) {
4978 var start = this.pos,
4979 isFloat = false,
4980 octal = this.input.charCodeAt(this.pos) === 48;
4981 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
4982 var next = this.input.charCodeAt(this.pos);
4983 if (next === 46) {
4984 // '.'
4985 ++this.pos;
4986 this.readInt(10);
4987 isFloat = true;
4988 next = this.input.charCodeAt(this.pos);
4989 }
4990 if (next === 69 || next === 101) {
4991 // 'eE'
4992 next = this.input.charCodeAt(++this.pos);
4993 if (next === 43 || next === 45) ++this.pos; // '+-'
4994 if (this.readInt(10) === null) this.raise(start, "Invalid number");
4995 isFloat = true;
4996 }
4997 if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
4998
4999 var str = this.input.slice(start, this.pos),
5000 val = undefined;
5001 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);
5002 return this.finishToken(tt.num, val);
5003};
5004
5005// Read a string value, interpreting backslash-escapes.
5006
5007pp$7.readCodePoint = function () {
5008 var ch = this.input.charCodeAt(this.pos),
5009 code = undefined;
5010
5011 if (ch === 123) {
5012 if (this.options.ecmaVersion < 6) this.unexpected();
5013 var codePos = ++this.pos;
5014 code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos);
5015 ++this.pos;
5016 if (code > 0x10FFFF) this.raise(codePos, "Code point out of bounds");
5017 } else {
5018 code = this.readHexChar(4);
5019 }
5020 return code;
5021};
5022
5023function codePointToString(code) {
5024 // UTF-16 Decoding
5025 if (code <= 0xFFFF) return String.fromCharCode(code);
5026 code -= 0x10000;
5027 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00);
5028}
5029
5030pp$7.readString = function (quote) {
5031 var out = "",
5032 chunkStart = ++this.pos;
5033 for (;;) {
5034 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated string constant");
5035 var ch = this.input.charCodeAt(this.pos);
5036 if (ch === quote) break;
5037 if (ch === 92) {
5038 // '\'
5039 out += this.input.slice(chunkStart, this.pos);
5040 out += this.readEscapedChar(false);
5041 chunkStart = this.pos;
5042 } else {
5043 if (isNewLine(ch)) this.raise(this.start, "Unterminated string constant");
5044 ++this.pos;
5045 }
5046 }
5047 out += this.input.slice(chunkStart, this.pos++);
5048 return this.finishToken(tt.string, out);
5049};
5050
5051// Reads template string tokens.
5052
5053pp$7.readTmplToken = function () {
5054 var out = "",
5055 chunkStart = this.pos;
5056 for (;;) {
5057 if (this.pos >= this.input.length) this.raise(this.start, "Unterminated template");
5058 var ch = this.input.charCodeAt(this.pos);
5059 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) {
5060 // '`', '${'
5061 if (this.pos === this.start && this.type === tt.template) {
5062 if (ch === 36) {
5063 this.pos += 2;
5064 return this.finishToken(tt.dollarBraceL);
5065 } else {
5066 ++this.pos;
5067 return this.finishToken(tt.backQuote);
5068 }
5069 }
5070 out += this.input.slice(chunkStart, this.pos);
5071 return this.finishToken(tt.template, out);
5072 }
5073 if (ch === 92) {
5074 // '\'
5075 out += this.input.slice(chunkStart, this.pos);
5076 out += this.readEscapedChar(true);
5077 chunkStart = this.pos;
5078 } else if (isNewLine(ch)) {
5079 out += this.input.slice(chunkStart, this.pos);
5080 ++this.pos;
5081 switch (ch) {
5082 case 13:
5083 if (this.input.charCodeAt(this.pos) === 10) ++this.pos;
5084 case 10:
5085 out += "\n";
5086 break;
5087 default:
5088 out += String.fromCharCode(ch);
5089 break;
5090 }
5091 if (this.options.locations) {
5092 ++this.curLine;
5093 this.lineStart = this.pos;
5094 }
5095 chunkStart = this.pos;
5096 } else {
5097 ++this.pos;
5098 }
5099 }
5100};
5101
5102// Used to read escaped characters
5103
5104pp$7.readEscapedChar = function (inTemplate) {
5105 var ch = this.input.charCodeAt(++this.pos);
5106 ++this.pos;
5107 switch (ch) {
5108 case 110:
5109 return "\n"; // 'n' -> '\n'
5110 case 114:
5111 return "\r"; // 'r' -> '\r'
5112 case 120:
5113 return String.fromCharCode(this.readHexChar(2)); // 'x'
5114 case 117:
5115 return codePointToString(this.readCodePoint()); // 'u'
5116 case 116:
5117 return "\t"; // 't' -> '\t'
5118 case 98:
5119 return "\b"; // 'b' -> '\b'
5120 case 118:
5121 return "\u000b"; // 'v' -> '\u000b'
5122 case 102:
5123 return "\f"; // 'f' -> '\f'
5124 case 13:
5125 if (this.input.charCodeAt(this.pos) === 10) ++this.pos; // '\r\n'
5126 case 10:
5127 // ' \n'
5128 if (this.options.locations) {
5129 this.lineStart = this.pos;++this.curLine;
5130 }
5131 return "";
5132 default:
5133 if (ch >= 48 && ch <= 55) {
5134 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
5135 var octal = parseInt(octalStr, 8);
5136 if (octal > 255) {
5137 octalStr = octalStr.slice(0, -1);
5138 octal = parseInt(octalStr, 8);
5139 }
5140 if (octal > 0 && (this.strict || inTemplate)) {
5141 this.raise(this.pos - 2, "Octal literal in strict mode");
5142 }
5143 this.pos += octalStr.length - 1;
5144 return String.fromCharCode(octal);
5145 }
5146 return String.fromCharCode(ch);
5147 }
5148};
5149
5150// Used to read character escape sequences ('\x', '\u', '\U').
5151
5152pp$7.readHexChar = function (len) {
5153 var codePos = this.pos;
5154 var n = this.readInt(16, len);
5155 if (n === null) this.raise(codePos, "Bad character escape sequence");
5156 return n;
5157};
5158
5159// Read an identifier, and return it as a string. Sets `this.containsEsc`
5160// to whether the word contained a '\u' escape.
5161//
5162// Incrementally adds only escaped chars, adding other chunks as-is
5163// as a micro-optimization.
5164
5165pp$7.readWord1 = function () {
5166 this.containsEsc = false;
5167 var word = "",
5168 first = true,
5169 chunkStart = this.pos;
5170 var astral = this.options.ecmaVersion >= 6;
5171 while (this.pos < this.input.length) {
5172 var ch = this.fullCharCodeAtPos();
5173 if (isIdentifierChar(ch, astral)) {
5174 this.pos += ch <= 0xffff ? 1 : 2;
5175 } else if (ch === 92) {
5176 // "\"
5177 this.containsEsc = true;
5178 word += this.input.slice(chunkStart, this.pos);
5179 var escStart = this.pos;
5180 if (this.input.charCodeAt(++this.pos) != 117) // "u"
5181 this.raise(this.pos, "Expecting Unicode escape sequence \\uXXXX");
5182 ++this.pos;
5183 var esc = this.readCodePoint();
5184 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral)) this.raise(escStart, "Invalid Unicode escape");
5185 word += codePointToString(esc);
5186 chunkStart = this.pos;
5187 } else {
5188 break;
5189 }
5190 first = false;
5191 }
5192 return word + this.input.slice(chunkStart, this.pos);
5193};
5194
5195// Read an identifier or keyword token. Will check for reserved
5196// words when necessary.
5197
5198pp$7.readWord = function () {
5199 var word = this.readWord1();
5200 var type = tt.name;
5201 if ((this.options.ecmaVersion >= 6 || !this.containsEsc) && this.isKeyword(word)) type = keywordTypes[word];
5202 return this.finishToken(type, word);
5203};
5204
5205// The main exported interface (under `self.acorn` when in the
5206// browser) is a `parse` function that takes a code string and
5207// returns an abstract syntax tree as specified by [Mozilla parser
5208// API][api].
5209//
5210// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
5211
5212function parse(input, options) {
5213 return new Parser(options, input).parse();
5214}
5215
5216function walk(ast, _ref) {
5217 var enter = _ref.enter;
5218 var leave = _ref.leave;
5219
5220 visit(ast, null, enter, leave);
5221}
5222
5223var context = {
5224 skip: function skip() {
5225 return context.shouldSkip = true;
5226 }
5227};
5228
5229var childKeys = {};
5230
5231var toString$1 = Object.prototype.toString;
5232
5233function isArray$1(thing) {
5234 return toString$1.call(thing) === '[object Array]';
5235}
5236
5237function visit(node, parent, enter, leave, prop, index) {
5238 if (!node) return;
5239
5240 if (enter) {
5241 context.shouldSkip = false;
5242 enter.call(context, node, parent, prop, index);
5243 if (context.shouldSkip) return;
5244 }
5245
5246 var keys = childKeys[node.type] || (childKeys[node.type] = Object.keys(node).filter(function (prop) {
5247 return typeof node[prop] === 'object';
5248 }));
5249
5250 var key = undefined,
5251 value = undefined,
5252 i = undefined,
5253 j = undefined;
5254
5255 i = keys.length;
5256 while (i--) {
5257 key = keys[i];
5258 value = node[key];
5259
5260 if (isArray$1(value)) {
5261 j = value.length;
5262 while (j--) {
5263 visit(value[j], node, enter, leave, key, j);
5264 }
5265 } else if (value && value.type) {
5266 visit(value, node, enter, leave, key, null);
5267 }
5268 }
5269
5270 if (leave) {
5271 leave(node, parent, prop, index);
5272 }
5273}
5274
5275var extractors = {
5276 Identifier: function (names, param) {
5277 names.push(param.name);
5278 },
5279
5280 ObjectPattern: function (names, param) {
5281 param.properties.forEach(function (prop) {
5282 extractors[prop.key.type](names, prop.key);
5283 });
5284 },
5285
5286 ArrayPattern: function (names, param) {
5287 param.elements.forEach(function (element) {
5288 if (element) extractors[element.type](names, element);
5289 });
5290 },
5291
5292 RestElement: function (names, param) {
5293 extractors[param.argument.type](names, param.argument);
5294 },
5295
5296 AssignmentPattern: function (names, param) {
5297 return extractors[param.left.type](names, param.left);
5298 }
5299};
5300
5301function extractNames(param) {
5302 var names = [];
5303
5304 extractors[param.type](names, param);
5305 return names;
5306}
5307
5308var Declaration = (function () {
5309 function Declaration() {
5310 babelHelpers.classCallCheck(this, Declaration);
5311
5312 this.statement = null;
5313 this.name = null;
5314
5315 this.isReassigned = false;
5316 this.aliases = [];
5317 }
5318
5319 Declaration.prototype.addAlias = function addAlias(declaration) {
5320 this.aliases.push(declaration);
5321 };
5322
5323 Declaration.prototype.addReference = function addReference(reference) {
5324 reference.declaration = this;
5325 this.name = reference.name; // TODO handle differences of opinion
5326
5327 if (reference.isReassignment) this.isReassigned = true;
5328 };
5329
5330 Declaration.prototype.render = function render(es6) {
5331 if (es6) return this.name;
5332 if (!this.isReassigned || !this.isExported) return this.name;
5333
5334 return 'exports.' + this.name;
5335 };
5336
5337 Declaration.prototype.use = function use() {
5338 this.isUsed = true;
5339 if (this.statement) this.statement.mark();
5340
5341 this.aliases.forEach(function (alias) {
5342 return alias.use();
5343 });
5344 };
5345
5346 return Declaration;
5347})();
5348
5349var Scope = (function () {
5350 function Scope(options) {
5351 var _this = this;
5352
5353 babelHelpers.classCallCheck(this, Scope);
5354
5355 options = options || {};
5356
5357 this.parent = options.parent;
5358 this.isBlockScope = !!options.block;
5359
5360 this.declarations = blank();
5361
5362 if (options.params) {
5363 options.params.forEach(function (param) {
5364 extractNames(param).forEach(function (name) {
5365 _this.declarations[name] = new Declaration(name);
5366 });
5367 });
5368 }
5369 }
5370
5371 Scope.prototype.addDeclaration = function addDeclaration(node, isBlockDeclaration, isVar) {
5372 var _this2 = this;
5373
5374 if (!isBlockDeclaration && this.isBlockScope) {
5375 // it's a `var` or function node, and this
5376 // is a block scope, so we need to go up
5377 this.parent.addDeclaration(node, isBlockDeclaration, isVar);
5378 } else {
5379 extractNames(node.id).forEach(function (name) {
5380 _this2.declarations[name] = new Declaration(name);
5381 });
5382 }
5383 };
5384
5385 Scope.prototype.contains = function contains(name) {
5386 return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
5387 };
5388
5389 Scope.prototype.eachDeclaration = function eachDeclaration(fn) {
5390 var _this3 = this;
5391
5392 keys(this.declarations).forEach(function (key) {
5393 fn(key, _this3.declarations[key]);
5394 });
5395 };
5396
5397 Scope.prototype.findDeclaration = function findDeclaration(name) {
5398 return this.declarations[name] || this.parent && this.parent.findDeclaration(name);
5399 };
5400
5401 return Scope;
5402})();
5403
5404var blockDeclarations = {
5405 'const': true,
5406 'let': true
5407};
5408function attachScopes(statement) {
5409 var node = statement.node;
5410 var scope = statement.scope;
5411
5412 walk(node, {
5413 enter: function (node, parent) {
5414 // function foo () {...}
5415 // class Foo {...}
5416 if (/(Function|Class)Declaration/.test(node.type)) {
5417 scope.addDeclaration(node, false, false);
5418 }
5419
5420 // var foo = 1, bar = 2
5421 if (node.type === 'VariableDeclaration') {
5422 (function () {
5423 var isBlockDeclaration = blockDeclarations[node.kind];
5424 node.declarations.forEach(function (declaration) {
5425 return scope.addDeclaration(declaration, isBlockDeclaration, true);
5426 });
5427 })();
5428 }
5429
5430 var newScope = undefined;
5431
5432 // create new function scope
5433 if (/Function/.test(node.type)) {
5434 newScope = new Scope({
5435 parent: scope,
5436 block: false,
5437 params: node.params
5438 });
5439
5440 // named function expressions - the name is considered
5441 // part of the function's scope
5442 if (node.type === 'FunctionExpression' && node.id) {
5443 newScope.addDeclaration(node, false, false);
5444 }
5445 }
5446
5447 // create new block scope
5448 if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
5449 newScope = new Scope({
5450 parent: scope,
5451 block: true
5452 });
5453 }
5454
5455 // catch clause has its own block scope
5456 if (node.type === 'CatchClause') {
5457 newScope = new Scope({
5458 parent: scope,
5459 params: [node.param],
5460 block: true
5461 });
5462 }
5463
5464 if (newScope) {
5465 Object.defineProperty(node, '_scope', {
5466 value: newScope,
5467 configurable: true
5468 });
5469
5470 scope = newScope;
5471 }
5472 },
5473 leave: function (node) {
5474 if (node._scope) {
5475 scope = scope.parent;
5476 }
5477 }
5478 });
5479}
5480
5481function getLocation$1(source, charIndex) {
5482 var lines = source.split('\n');
5483 var len = lines.length;
5484
5485 var lineStart = 0;
5486 var i = undefined;
5487
5488 for (i = 0; i < len; i += 1) {
5489 var line = lines[i];
5490 var lineEnd = lineStart + line.length + 1; // +1 for newline
5491
5492 if (lineEnd > charIndex) {
5493 return { line: i + 1, column: charIndex - lineStart };
5494 }
5495
5496 lineStart = lineEnd;
5497 }
5498
5499 throw new Error('Could not determine location of character');
5500}
5501
5502var modifierNodes = {
5503 AssignmentExpression: 'left',
5504 UpdateExpression: 'argument'
5505};
5506
5507function isIife(node, parent) {
5508 return parent && parent.type === 'CallExpression' && node === parent.callee;
5509}
5510
5511function isReference(node, parent) {
5512 if (node.type === 'MemberExpression') {
5513 return !node.computed && isReference(node.object, node);
5514 }
5515
5516 if (node.type === 'Identifier') {
5517 // TODO is this right?
5518 if (parent.type === 'MemberExpression') return parent.computed || node === parent.object;
5519
5520 // disregard the `bar` in { bar: foo }
5521 if (parent.type === 'Property' && node !== parent.value) return false;
5522
5523 // disregard the `bar` in `class Foo { bar () {...} }`
5524 if (parent.type === 'MethodDefinition') return false;
5525
5526 // disregard the `bar` in `export { foo as bar }`
5527 if (parent.type === 'ExportSpecifier' && node !== parent.local) return;
5528
5529 return true;
5530 }
5531}
5532
5533var Reference = function Reference(node, scope) {
5534 babelHelpers.classCallCheck(this, Reference);
5535
5536 this.node = node;
5537 this.scope = scope;
5538
5539 this.declaration = null; // bound later
5540
5541 this.parts = [];
5542
5543 var root = node;
5544 while (root.type === 'MemberExpression') {
5545 this.parts.unshift(root.property.name);
5546 root = root.object;
5547 }
5548
5549 this.name = root.name;
5550
5551 this.start = node.start;
5552 this.end = node.start + this.name.length; // can be overridden in the case of namespace members
5553 this.rewritten = false;
5554};
5555
5556var Statement = (function () {
5557 function Statement(node, module, start, end) {
5558 babelHelpers.classCallCheck(this, Statement);
5559
5560 this.node = node;
5561 this.module = module;
5562 this.start = start;
5563 this.end = end;
5564 this.next = null; // filled in later
5565
5566 this.scope = new Scope();
5567
5568 this.references = [];
5569 this.stringLiteralRanges = [];
5570
5571 this.isIncluded = false;
5572
5573 this.isImportDeclaration = node.type === 'ImportDeclaration';
5574 this.isExportDeclaration = /^Export/.test(node.type);
5575 this.isReexportDeclaration = this.isExportDeclaration && !!node.source;
5576 }
5577
5578 Statement.prototype.analyse = function analyse() {
5579 var _this = this;
5580
5581 if (this.isImportDeclaration) return; // nothing to analyse
5582
5583 // attach scopes
5584 attachScopes(this);
5585
5586 // attach statement to each top-level declaration,
5587 // so we can mark statements easily
5588 this.scope.eachDeclaration(function (name, declaration) {
5589 declaration.statement = _this;
5590 });
5591
5592 // find references
5593 var module = this.module;
5594 var references = this.references;
5595 var scope = this.scope;
5596 var stringLiteralRanges = this.stringLiteralRanges;
5597
5598 var readDepth = 0;
5599
5600 walk(this.node, {
5601 enter: function (node, parent) {
5602 // warn about eval
5603 if (node.type === 'CallExpression' && node.callee.name === 'eval' && !scope.contains('eval')) {
5604 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');
5605 }
5606
5607 if (node.type === 'TemplateElement') stringLiteralRanges.push([node.start, node.end]);
5608 if (node.type === 'Literal' && typeof node.value === 'string' && /\n/.test(node.raw)) {
5609 stringLiteralRanges.push([node.start + 1, node.end - 1]);
5610 }
5611
5612 if (node._scope) scope = node._scope;
5613 if (/Function/.test(node.type) && !isIife(node, parent)) readDepth += 1;
5614
5615 // special case – shorthand properties. because node.key === node.value,
5616 // we can't differentiate once we've descended into the node
5617 if (node.type === 'Property' && node.shorthand) {
5618 var reference = new Reference(node.key, scope);
5619 reference.isShorthandProperty = true; // TODO feels a bit kludgy
5620 references.push(reference);
5621 return this.skip();
5622 }
5623
5624 var isReassignment = undefined;
5625
5626 if (parent && parent.type in modifierNodes) {
5627 var subject = parent[modifierNodes[parent.type]];
5628 var depth = 0;
5629
5630 while (subject.type === 'MemberExpression') {
5631 subject = subject.object;
5632 depth += 1;
5633 }
5634
5635 var importDeclaration = module.imports[subject.name];
5636
5637 if (!scope.contains(subject.name) && importDeclaration) {
5638 var minDepth = importDeclaration.name === '*' ? 2 : // cannot do e.g. `namespace.foo = bar`
5639 1; // cannot do e.g. `foo = bar`, but `foo.bar = bar` is fine
5640
5641 if (depth < minDepth) {
5642 var err = new Error('Illegal reassignment to import \'' + subject.name + '\'');
5643 err.file = module.id;
5644 err.loc = getLocation$1(module.magicString.toString(), subject.start);
5645 throw err;
5646 }
5647 }
5648
5649 isReassignment = !depth;
5650 }
5651
5652 if (isReference(node, parent)) {
5653 // function declaration IDs are a special case – they're associated
5654 // with the parent scope
5655 var referenceScope = parent.type === 'FunctionDeclaration' && node === parent.id ? scope.parent : scope;
5656
5657 var reference = new Reference(node, referenceScope);
5658 references.push(reference);
5659
5660 reference.isImmediatelyUsed = !readDepth;
5661 reference.isReassignment = isReassignment;
5662
5663 this.skip(); // don't descend from `foo.bar.baz` into `foo.bar`
5664 }
5665 },
5666 leave: function (node, parent) {
5667 if (node._scope) scope = scope.parent;
5668 if (/Function/.test(node.type) && !isIife(node, parent)) readDepth -= 1;
5669 }
5670 });
5671 };
5672
5673 Statement.prototype.mark = function mark() {
5674 if (this.isIncluded) return; // prevent infinite loops
5675 this.isIncluded = true;
5676
5677 this.references.forEach(function (reference) {
5678 if (reference.declaration) reference.declaration.use();
5679 });
5680 };
5681
5682 Statement.prototype.markSideEffect = function markSideEffect() {
5683 if (this.isIncluded) return;
5684
5685 var statement = this;
5686 var hasSideEffect = false;
5687
5688 walk(this.node, {
5689 enter: function (node, parent) {
5690 if (/Function/.test(node.type) && !isIife(node, parent)) return this.skip();
5691
5692 // If this is a top-level call expression, or an assignment to a global,
5693 // this statement will need to be marked
5694 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
5695 hasSideEffect = true;
5696 } else if (node.type in modifierNodes) {
5697 var subject = node[modifierNodes[node.type]];
5698 while (subject.type === 'MemberExpression') subject = subject.object;
5699
5700 var declaration = statement.module.trace(subject.name);
5701
5702 if (!declaration || declaration.isExternal || declaration.statement.isIncluded) {
5703 hasSideEffect = true;
5704 }
5705 }
5706
5707 if (hasSideEffect) this.skip();
5708 }
5709 });
5710
5711 if (hasSideEffect) statement.mark();
5712 return hasSideEffect;
5713 };
5714
5715 Statement.prototype.source = function source() {
5716 return this.module.source.slice(this.start, this.end);
5717 };
5718
5719 Statement.prototype.toString = function toString() {
5720 return this.module.magicString.slice(this.start, this.end);
5721 };
5722
5723 return Statement;
5724})();
5725
5726var 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(' ');
5727var 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(' ');
5728
5729var blacklisted = blank();
5730reservedWords.concat(builtins).forEach(function (word) {
5731 return blacklisted[word] = true;
5732});
5733function makeLegalIdentifier(str) {
5734 str = str.replace(/-(\w)/g, function (_, letter) {
5735 return letter.toUpperCase();
5736 }).replace(/[^$_a-zA-Z0-9]/g, '_');
5737
5738 if (/\d/.test(str[0]) || blacklisted[str]) str = '_' + str;
5739
5740 return str;
5741}
5742
5743var SyntheticDefaultDeclaration = (function () {
5744 function SyntheticDefaultDeclaration(node, statement, name) {
5745 babelHelpers.classCallCheck(this, SyntheticDefaultDeclaration);
5746
5747 this.node = node;
5748 this.statement = statement;
5749 this.name = name;
5750
5751 this.original = null;
5752 this.isExported = false;
5753 this.aliases = [];
5754 }
5755
5756 SyntheticDefaultDeclaration.prototype.addAlias = function addAlias(declaration) {
5757 this.aliases.push(declaration);
5758 };
5759
5760 SyntheticDefaultDeclaration.prototype.addReference = function addReference(reference) {
5761 // Don't change the name to `default`; it's not a valid identifier name.
5762 if (reference.name === 'default') return;
5763
5764 reference.declaration = this;
5765 this.name = reference.name;
5766 };
5767
5768 SyntheticDefaultDeclaration.prototype.bind = function bind(declaration) {
5769 this.original = declaration;
5770 };
5771
5772 SyntheticDefaultDeclaration.prototype.render = function render() {
5773 return !this.original || this.original.isReassigned ? this.name : this.original.render();
5774 };
5775
5776 SyntheticDefaultDeclaration.prototype.use = function use() {
5777 this.isUsed = true;
5778 this.statement.mark();
5779
5780 if (this.original) this.original.use();
5781
5782 this.aliases.forEach(function (alias) {
5783 return alias.use();
5784 });
5785 };
5786
5787 return SyntheticDefaultDeclaration;
5788})();
5789
5790var SyntheticNamespaceDeclaration = (function () {
5791 function SyntheticNamespaceDeclaration(module) {
5792 var _this = this;
5793
5794 babelHelpers.classCallCheck(this, SyntheticNamespaceDeclaration);
5795
5796 this.module = module;
5797 this.name = null;
5798
5799 this.needsNamespaceBlock = false;
5800 this.aliases = [];
5801
5802 this.originals = blank();
5803 module.getExports().forEach(function (name) {
5804 _this.originals[name] = module.traceExport(name);
5805 });
5806 }
5807
5808 SyntheticNamespaceDeclaration.prototype.addAlias = function addAlias(declaration) {
5809 this.aliases.push(declaration);
5810 };
5811
5812 SyntheticNamespaceDeclaration.prototype.addReference = function addReference(reference) {
5813 // if we have e.g. `foo.bar`, we can optimise
5814 // the reference by pointing directly to `bar`
5815 if (reference.parts.length) {
5816 reference.name = reference.parts.shift();
5817
5818 reference.end += reference.name.length + 1; // TODO this is brittle
5819
5820 var original = this.originals[reference.name];
5821
5822 // throw with an informative error message if the reference doesn't exist.
5823 if (!original) {
5824 this.module.bundle.onwarn('Export \'' + reference.name + '\' is not defined by \'' + this.module.id + '\'');
5825 reference.isUndefined = true;
5826 return;
5827 }
5828
5829 original.addReference(reference);
5830 return;
5831 }
5832
5833 // otherwise we're accessing the namespace directly,
5834 // which means we need to mark all of this module's
5835 // exports and render a namespace block in the bundle
5836 if (!this.needsNamespaceBlock) {
5837 this.needsNamespaceBlock = true;
5838 this.module.bundle.internalNamespaces.push(this);
5839 }
5840
5841 reference.declaration = this;
5842 this.name = reference.name;
5843 };
5844
5845 SyntheticNamespaceDeclaration.prototype.renderBlock = function renderBlock(indentString) {
5846 var _this2 = this;
5847
5848 var members = keys(this.originals).map(function (name) {
5849 var original = _this2.originals[name];
5850
5851 if (original.isReassigned) {
5852 return indentString + 'get ' + name + ' () { return ' + original.render() + '; }';
5853 }
5854
5855 return '' + indentString + name + ': ' + original.render();
5856 });
5857
5858 return 'var ' + this.render() + ' = Object.freeze({\n' + members.join(',\n') + '\n});\n\n';
5859 };
5860
5861 SyntheticNamespaceDeclaration.prototype.render = function render() {
5862 return this.name;
5863 };
5864
5865 SyntheticNamespaceDeclaration.prototype.use = function use() {
5866 var _this3 = this;
5867
5868 keys(this.originals).forEach(function (name) {
5869 _this3.originals[name].use();
5870 });
5871
5872 this.aliases.forEach(function (alias) {
5873 return alias.use();
5874 });
5875 };
5876
5877 return SyntheticNamespaceDeclaration;
5878})();
5879
5880var Module = (function () {
5881 function Module(_ref) {
5882 var id = _ref.id;
5883 var code = _ref.code;
5884 var originalCode = _ref.originalCode;
5885 var ast = _ref.ast;
5886 var sourceMapChain = _ref.sourceMapChain;
5887 var bundle = _ref.bundle;
5888 babelHelpers.classCallCheck(this, Module);
5889
5890 this.code = code;
5891 this.originalCode = originalCode;
5892 this.sourceMapChain = sourceMapChain;
5893
5894 this.bundle = bundle;
5895 this.id = id;
5896
5897 // all dependencies
5898 this.dependencies = [];
5899 this.resolvedIds = blank();
5900
5901 // imports and exports, indexed by local name
5902 this.imports = blank();
5903 this.exports = blank();
5904 this.reexports = blank();
5905
5906 this.exportAllSources = [];
5907 this.exportAllModules = null;
5908
5909 // By default, `id` is the filename. Custom resolvers and loaders
5910 // can change that, but it makes sense to use it for the source filename
5911 this.magicString = new MagicString(code, {
5912 filename: id,
5913 indentExclusionRanges: []
5914 });
5915
5916 // remove existing sourceMappingURL comments
5917 var pattern = new RegExp('\\/\\/#\\s+' + SOURCEMAPPING_URL$1 + '=.+\\n?', 'g');
5918 var match = undefined;
5919 while (match = pattern.exec(code)) {
5920 this.magicString.remove(match.index, match.index + match[0].length);
5921 }
5922
5923 this.comments = [];
5924 this.statements = this.parse(ast);
5925
5926 this.declarations = blank();
5927 this.analyse();
5928 }
5929
5930 Module.prototype.addExport = function addExport(statement) {
5931 var _this4 = this;
5932
5933 var node = statement.node;
5934 var source = node.source && node.source.value;
5935
5936 // export { name } from './other.js'
5937 if (source) {
5938 if (! ~this.dependencies.indexOf(source)) this.dependencies.push(source);
5939
5940 if (node.type === 'ExportAllDeclaration') {
5941 // Store `export * from '...'` statements in an array of delegates.
5942 // When an unknown import is encountered, we see if one of them can satisfy it.
5943 this.exportAllSources.push(source);
5944 } else {
5945 node.specifiers.forEach(function (specifier) {
5946 _this4.reexports[specifier.exported.name] = {
5947 source: source,
5948 localName: specifier.local.name,
5949 module: null // filled in later
5950 };
5951 });
5952 }
5953 }
5954
5955 // export default function foo () {}
5956 // export default foo;
5957 // export default 42;
5958 else if (node.type === 'ExportDefaultDeclaration') {
5959 var identifier = node.declaration.id && node.declaration.id.name || node.declaration.name;
5960
5961 this.exports.default = {
5962 localName: 'default',
5963 identifier: identifier
5964 };
5965
5966 // create a synthetic declaration
5967 this.declarations.default = new SyntheticDefaultDeclaration(node, statement, identifier || this.basename());
5968 }
5969
5970 // export { foo, bar, baz }
5971 // export var foo = 42;
5972 // export var a = 1, b = 2, c = 3;
5973 // export function foo () {}
5974 else if (node.type === 'ExportNamedDeclaration') {
5975 if (node.specifiers.length) {
5976 // export { foo, bar, baz }
5977 node.specifiers.forEach(function (specifier) {
5978 var localName = specifier.local.name;
5979 var exportedName = specifier.exported.name;
5980
5981 _this4.exports[exportedName] = { localName: localName };
5982 });
5983 } else {
5984 var declaration = node.declaration;
5985
5986 var _name = undefined;
5987
5988 if (declaration.type === 'VariableDeclaration') {
5989 // export var foo = 42
5990 _name = declaration.declarations[0].id.name;
5991 } else {
5992 // export function foo () {}
5993 _name = declaration.id.name;
5994 }
5995
5996 this.exports[_name] = { localName: _name };
5997 }
5998 }
5999 };
6000
6001 Module.prototype.addImport = function addImport(statement) {
6002 var _this5 = this;
6003
6004 var node = statement.node;
6005 var source = node.source.value;
6006
6007 if (! ~this.dependencies.indexOf(source)) this.dependencies.push(source);
6008
6009 node.specifiers.forEach(function (specifier) {
6010 var localName = specifier.local.name;
6011
6012 if (_this5.imports[localName]) {
6013 var err = new Error('Duplicated import \'' + localName + '\'');
6014 err.file = _this5.id;
6015 err.loc = getLocation$1(_this5.code, specifier.start);
6016 throw err;
6017 }
6018
6019 var isDefault = specifier.type === 'ImportDefaultSpecifier';
6020 var isNamespace = specifier.type === 'ImportNamespaceSpecifier';
6021
6022 var name = isDefault ? 'default' : isNamespace ? '*' : specifier.imported.name;
6023 _this5.imports[localName] = { source: source, name: name, module: null };
6024 });
6025 };
6026
6027 Module.prototype.analyse = function analyse() {
6028 var _this6 = this;
6029
6030 // discover this module's imports and exports
6031 this.statements.forEach(function (statement) {
6032 if (statement.isImportDeclaration) _this6.addImport(statement);else if (statement.isExportDeclaration) _this6.addExport(statement);
6033
6034 statement.analyse();
6035
6036 statement.scope.eachDeclaration(function (name, declaration) {
6037 _this6.declarations[name] = declaration;
6038 });
6039 });
6040 };
6041
6042 Module.prototype.basename = function basename() {
6043 var base = _basename(this.id);
6044 var ext = extname(this.id);
6045
6046 return makeLegalIdentifier(ext ? base.slice(0, -ext.length) : base);
6047 };
6048
6049 Module.prototype.bindAliases = function bindAliases() {
6050 var _this7 = this;
6051
6052 keys(this.declarations).forEach(function (name) {
6053 if (name === '*') return;
6054
6055 var declaration = _this7.declarations[name];
6056 var statement = declaration.statement;
6057
6058 if (statement.node.type !== 'VariableDeclaration') return;
6059
6060 statement.references.forEach(function (reference) {
6061 if (reference.name === name || !reference.isImmediatelyUsed) return;
6062
6063 var otherDeclaration = _this7.trace(reference.name);
6064 if (otherDeclaration) otherDeclaration.addAlias(declaration);
6065 });
6066 });
6067 };
6068
6069 Module.prototype.bindImportSpecifiers = function bindImportSpecifiers() {
6070 var _this8 = this;
6071
6072 [this.imports, this.reexports].forEach(function (specifiers) {
6073 keys(specifiers).forEach(function (name) {
6074 var specifier = specifiers[name];
6075
6076 var id = _this8.resolvedIds[specifier.source];
6077 specifier.module = _this8.bundle.moduleById[id];
6078 });
6079 });
6080
6081 this.exportAllModules = this.exportAllSources.map(function (source) {
6082 var id = _this8.resolvedIds[source];
6083 return _this8.bundle.moduleById[id];
6084 });
6085 };
6086
6087 Module.prototype.bindReferences = function bindReferences() {
6088 var _this9 = this;
6089
6090 if (this.declarations.default) {
6091 if (this.exports.default.identifier) {
6092 var declaration = this.trace(this.exports.default.identifier);
6093 if (declaration) this.declarations.default.bind(declaration);
6094 }
6095 }
6096
6097 this.statements.forEach(function (statement) {
6098 // skip `export { foo, bar, baz }`...
6099 if (statement.node.type === 'ExportNamedDeclaration' && statement.node.specifiers.length) {
6100 // ...unless this is the entry module
6101 if (_this9 !== _this9.bundle.entryModule) return;
6102 }
6103
6104 statement.references.forEach(function (reference) {
6105 var declaration = reference.scope.findDeclaration(reference.name) || _this9.trace(reference.name);
6106
6107 if (declaration) {
6108 declaration.addReference(reference);
6109 } else if (statement.node.type !== 'ExportNamedDeclaration' || !_this9.reexports[reference.name]) {
6110 // TODO handle globals
6111 _this9.bundle.assumedGlobals[reference.name] = true;
6112 }
6113 });
6114 });
6115 };
6116
6117 Module.prototype.consolidateDependencies = function consolidateDependencies() {
6118 var _this10 = this;
6119
6120 var strongDependencies = blank();
6121 var weakDependencies = blank();
6122
6123 // treat all imports as weak dependencies
6124 this.dependencies.forEach(function (source) {
6125 var id = _this10.resolvedIds[source];
6126 var dependency = _this10.bundle.moduleById[id];
6127
6128 if (!dependency.isExternal) {
6129 weakDependencies[dependency.id] = dependency;
6130 }
6131 });
6132
6133 // identify strong dependencies to break ties in case of cycles
6134 this.statements.forEach(function (statement) {
6135 statement.references.forEach(function (reference) {
6136 var declaration = reference.declaration;
6137
6138 if (declaration && declaration.statement) {
6139 var _module = declaration.statement.module;
6140 if (_module === _this10) return;
6141
6142 // TODO disregard function declarations
6143 if (reference.isImmediatelyUsed) {
6144 strongDependencies[_module.id] = _module;
6145 }
6146 }
6147 });
6148 });
6149
6150 return { strongDependencies: strongDependencies, weakDependencies: weakDependencies };
6151 };
6152
6153 Module.prototype.getExports = function getExports() {
6154 var exports = blank();
6155
6156 keys(this.exports).forEach(function (name) {
6157 exports[name] = true;
6158 });
6159
6160 keys(this.reexports).forEach(function (name) {
6161 exports[name] = true;
6162 });
6163
6164 this.exportAllModules.forEach(function (module) {
6165 module.getExports().forEach(function (name) {
6166 if (name !== 'default') exports[name] = true;
6167 });
6168 });
6169
6170 return keys(exports);
6171 };
6172
6173 Module.prototype.markAllSideEffects = function markAllSideEffects() {
6174 var hasSideEffect = false;
6175
6176 this.statements.forEach(function (statement) {
6177 if (statement.markSideEffect()) hasSideEffect = true;
6178 });
6179
6180 return hasSideEffect;
6181 };
6182
6183 Module.prototype.namespace = function namespace() {
6184 if (!this.declarations['*']) {
6185 this.declarations['*'] = new SyntheticNamespaceDeclaration(this);
6186 }
6187
6188 return this.declarations['*'];
6189 };
6190
6191 Module.prototype.parse = function parse$$(ast) {
6192 var _this11 = this;
6193
6194 // The ast can be supplied programmatically (but usually won't be)
6195 if (!ast) {
6196 // Try to extract a list of top-level statements/declarations. If
6197 // the parse fails, attach file info and abort
6198 try {
6199 ast = parse(this.code, {
6200 ecmaVersion: 6,
6201 sourceType: 'module',
6202 onComment: function (block, text, start, end) {
6203 return _this11.comments.push({ block: block, text: text, start: start, end: end });
6204 },
6205 preserveParens: true
6206 });
6207 } catch (err) {
6208 err.code = 'PARSE_ERROR';
6209 err.file = this.id; // see above - not necessarily true, but true enough
6210 err.message += ' in ' + this.id;
6211 throw err;
6212 }
6213 }
6214
6215 walk(ast, {
6216 enter: function (node) {
6217 _this11.magicString.addSourcemapLocation(node.start);
6218 _this11.magicString.addSourcemapLocation(node.end);
6219 }
6220 });
6221
6222 var statements = [];
6223 var lastChar = 0;
6224 var commentIndex = 0;
6225
6226 ast.body.forEach(function (node) {
6227 if (node.type === 'EmptyStatement') return;
6228
6229 if (node.type === 'ExportNamedDeclaration' && node.declaration && node.declaration.type === 'VariableDeclaration' && node.declaration.declarations && node.declaration.declarations.length > 1) {
6230 // push a synthetic export declaration
6231 var syntheticNode = {
6232 type: 'ExportNamedDeclaration',
6233 specifiers: node.declaration.declarations.map(function (declarator) {
6234 var id = { name: declarator.id.name };
6235 return {
6236 local: id,
6237 exported: id
6238 };
6239 }),
6240 isSynthetic: true
6241 };
6242
6243 var statement = new Statement(syntheticNode, _this11, node.start, node.start);
6244 statements.push(statement);
6245
6246 _this11.magicString.remove(node.start, node.declaration.start);
6247 node = node.declaration;
6248 }
6249
6250 // special case - top-level var declarations with multiple declarators
6251 // should be split up. Otherwise, we may end up including code we
6252 // don't need, just because an unwanted declarator is included
6253 if (node.type === 'VariableDeclaration' && node.declarations.length > 1) {
6254 // remove the leading var/let/const... UNLESS the previous node
6255 // was also a synthetic node, in which case it'll get removed anyway
6256 var lastStatement = statements[statements.length - 1];
6257 if (!lastStatement || !lastStatement.node.isSynthetic) {
6258 _this11.magicString.remove(node.start, node.declarations[0].start);
6259 }
6260
6261 node.declarations.forEach(function (declarator) {
6262 var start = declarator.start;
6263 var end = declarator.end;
6264
6265 var syntheticNode = {
6266 type: 'VariableDeclaration',
6267 kind: node.kind,
6268 start: start,
6269 end: end,
6270 declarations: [declarator],
6271 isSynthetic: true
6272 };
6273
6274 var statement = new Statement(syntheticNode, _this11, start, end);
6275 statements.push(statement);
6276 });
6277
6278 lastChar = node.end; // TODO account for trailing line comment
6279 } else {
6280 var comment = undefined;
6281 do {
6282 comment = _this11.comments[commentIndex];
6283 if (!comment) break;
6284 if (comment.start > node.start) break;
6285 commentIndex += 1;
6286 } while (comment.end < lastChar);
6287
6288 var start = comment ? Math.min(comment.start, node.start) : node.start;
6289 var end = node.end; // TODO account for trailing line comment
6290
6291 var statement = new Statement(node, _this11, start, end);
6292 statements.push(statement);
6293
6294 lastChar = end;
6295 }
6296 });
6297
6298 var i = statements.length;
6299 var next = this.code.length;
6300 while (i--) {
6301 statements[i].next = next;
6302 if (!statements[i].isSynthetic) next = statements[i].start;
6303 }
6304
6305 return statements;
6306 };
6307
6308 Module.prototype.render = function render(es6) {
6309 var _this12 = this;
6310
6311 var magicString = this.magicString.clone();
6312
6313 this.statements.forEach(function (statement) {
6314 if (!statement.isIncluded) {
6315 magicString.remove(statement.start, statement.next);
6316 return;
6317 }
6318
6319 statement.stringLiteralRanges.forEach(function (range) {
6320 return magicString.indentExclusionRanges.push(range);
6321 });
6322
6323 // skip `export { foo, bar, baz }`
6324 if (statement.node.type === 'ExportNamedDeclaration') {
6325 if (statement.node.isSynthetic) return;
6326
6327 // skip `export { foo, bar, baz }`
6328 if (statement.node.specifiers.length) {
6329 magicString.remove(statement.start, statement.next);
6330 return;
6331 }
6332 }
6333
6334 // split up/remove var declarations as necessary
6335 if (statement.node.isSynthetic) {
6336 // insert `var/let/const` if necessary
6337 var declaration = _this12.declarations[statement.node.declarations[0].id.name];
6338 if (!(declaration.isExported && declaration.isReassigned)) {
6339 // TODO encapsulate this
6340 magicString.insert(statement.start, statement.node.kind + ' ');
6341 }
6342
6343 magicString.overwrite(statement.end, statement.next, ';\n'); // TODO account for trailing newlines
6344 }
6345
6346 var toDeshadow = blank();
6347
6348 statement.references.forEach(function (reference) {
6349 var start = reference.start;
6350 var end = reference.end;
6351
6352 if (reference.isUndefined) {
6353 magicString.overwrite(start, end, 'undefined', true);
6354 }
6355
6356 var declaration = reference.declaration;
6357
6358 if (declaration) {
6359 var _name2 = declaration.render(es6);
6360
6361 // the second part of this check is necessary because of
6362 // namespace optimisation – name of `foo.bar` could be `bar`
6363 if (reference.name === _name2 && _name2.length === end - start) return;
6364
6365 reference.rewritten = true;
6366
6367 // prevent local variables from shadowing renamed references
6368 var identifier = _name2.match(/[^\.]+/)[0];
6369 if (reference.scope.contains(identifier)) {
6370 toDeshadow[identifier] = identifier + '$$'; // TODO more robust mechanism
6371 }
6372
6373 if (reference.isShorthandProperty) {
6374 magicString.insert(end, ': ' + _name2);
6375 } else {
6376 magicString.overwrite(start, end, _name2, true);
6377 }
6378 }
6379 });
6380
6381 if (keys(toDeshadow).length) {
6382 statement.references.forEach(function (reference) {
6383 if (!reference.rewritten && reference.name in toDeshadow) {
6384 magicString.overwrite(reference.start, reference.end, toDeshadow[reference.name], true);
6385 }
6386 });
6387 }
6388
6389 // modify exports as necessary
6390 if (statement.isExportDeclaration) {
6391 // remove `export` from `export var foo = 42`
6392 if (statement.node.type === 'ExportNamedDeclaration' && statement.node.declaration.type === 'VariableDeclaration') {
6393 var _name3 = statement.node.declaration.declarations[0].id.name;
6394 var declaration = _this12.declarations[_name3];
6395
6396 var end = declaration.isExported && declaration.isReassigned ? statement.node.declaration.declarations[0].start : statement.node.declaration.start;
6397
6398 magicString.remove(statement.node.start, end);
6399 } else if (statement.node.type === 'ExportAllDeclaration') {
6400 // TODO: remove once `export * from 'external'` is supported.
6401 magicString.remove(statement.start, statement.next);
6402 }
6403
6404 // remove `export` from `export class Foo {...}` or `export default Foo`
6405 // TODO default exports need different treatment
6406 else if (statement.node.declaration.id) {
6407 magicString.remove(statement.node.start, statement.node.declaration.start);
6408 } else if (statement.node.type === 'ExportDefaultDeclaration') {
6409 var defaultDeclaration = _this12.declarations.default;
6410
6411 // prevent `var foo = foo`
6412 if (defaultDeclaration.original && !defaultDeclaration.original.isReassigned) {
6413 magicString.remove(statement.start, statement.next);
6414 return;
6415 }
6416
6417 var defaultName = defaultDeclaration.render();
6418
6419 // prevent `var undefined = sideEffectyDefault(foo)`
6420 if (!defaultDeclaration.isExported && !defaultDeclaration.isUsed) {
6421 magicString.remove(statement.start, statement.node.declaration.start);
6422 return;
6423 }
6424
6425 // anonymous functions should be converted into declarations
6426 if (statement.node.declaration.type === 'FunctionExpression') {
6427 magicString.overwrite(statement.node.start, statement.node.declaration.start + 8, 'function ' + defaultName);
6428 } else {
6429 magicString.overwrite(statement.node.start, statement.node.declaration.start, 'var ' + defaultName + ' = ');
6430 }
6431 } else {
6432 throw new Error('Unhandled export');
6433 }
6434 }
6435 });
6436
6437 // add namespace block if necessary
6438 var namespace = this.declarations['*'];
6439 if (namespace && namespace.needsNamespaceBlock) {
6440 magicString.append('\n\n' + namespace.renderBlock(magicString.getIndentString()));
6441 }
6442
6443 return magicString.trim();
6444 };
6445
6446 Module.prototype.trace = function trace(name) {
6447 if (name in this.declarations) return this.declarations[name];
6448 if (name in this.imports) {
6449 var importDeclaration = this.imports[name];
6450 var otherModule = importDeclaration.module;
6451
6452 if (importDeclaration.name === '*' && !otherModule.isExternal) {
6453 return otherModule.namespace();
6454 }
6455
6456 var declaration = otherModule.traceExport(importDeclaration.name);
6457
6458 if (!declaration) throw new Error('Module ' + otherModule.id + ' does not export ' + importDeclaration.name + ' (imported by ' + this.id + ')');
6459 return declaration;
6460 }
6461
6462 return null;
6463 };
6464
6465 Module.prototype.traceExport = function traceExport(name) {
6466 // export { foo } from './other.js'
6467 var reexportDeclaration = this.reexports[name];
6468 if (reexportDeclaration) {
6469 return reexportDeclaration.module.traceExport(reexportDeclaration.localName);
6470 }
6471
6472 var exportDeclaration = this.exports[name];
6473 if (exportDeclaration) {
6474 return this.trace(exportDeclaration.localName);
6475 }
6476
6477 for (var i = 0; i < this.exportAllModules.length; i += 1) {
6478 var _module2 = this.exportAllModules[i];
6479 var declaration = _module2.traceExport(name);
6480
6481 if (declaration) return declaration;
6482 }
6483 };
6484
6485 return Module;
6486})();
6487
6488var ExternalDeclaration = (function () {
6489 function ExternalDeclaration(module, name) {
6490 babelHelpers.classCallCheck(this, ExternalDeclaration);
6491
6492 this.module = module;
6493 this.name = name;
6494 this.isExternal = true;
6495 }
6496
6497 ExternalDeclaration.prototype.addAlias = function addAlias() {
6498 // noop
6499 };
6500
6501 ExternalDeclaration.prototype.addReference = function addReference(reference) {
6502 reference.declaration = this;
6503
6504 if (this.name === 'default' || this.name === '*') {
6505 this.module.suggestName(reference.name);
6506 }
6507 };
6508
6509 ExternalDeclaration.prototype.render = function render(es6) {
6510 if (this.name === '*') {
6511 return this.module.name;
6512 }
6513
6514 if (this.name === 'default') {
6515 return !es6 && this.module.exportsNames ? this.module.name + '__default' : this.module.name;
6516 }
6517
6518 return es6 ? this.name : this.module.name + '.' + this.name;
6519 };
6520
6521 ExternalDeclaration.prototype.use = function use() {
6522 // noop?
6523 };
6524
6525 return ExternalDeclaration;
6526})();
6527
6528var ExternalModule = (function () {
6529 function ExternalModule(id) {
6530 babelHelpers.classCallCheck(this, ExternalModule);
6531
6532 this.id = id;
6533 this.name = makeLegalIdentifier(id);
6534
6535 this.nameSuggestions = blank();
6536 this.mostCommonSuggestion = 0;
6537
6538 this.isExternal = true;
6539 this.declarations = blank();
6540
6541 this.exportsNames = false;
6542 }
6543
6544 ExternalModule.prototype.suggestName = function suggestName(name) {
6545 if (!this.nameSuggestions[name]) this.nameSuggestions[name] = 0;
6546 this.nameSuggestions[name] += 1;
6547
6548 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
6549 this.mostCommonSuggestion = this.nameSuggestions[name];
6550 this.name = name;
6551 }
6552 };
6553
6554 ExternalModule.prototype.traceExport = function traceExport(name) {
6555 if (name !== 'default' && name !== '*') {
6556 this.exportsNames = true;
6557 }
6558
6559 return this.declarations[name] || (this.declarations[name] = new ExternalDeclaration(this, name));
6560 };
6561
6562 return ExternalModule;
6563})();
6564
6565function getName(x) {
6566 return x.name;
6567}
6568
6569function quoteId(x) {
6570 return "'" + x.id + "'";
6571}
6572
6573function req(x) {
6574 return "require('" + x.id + "')";
6575}
6576
6577function getInteropBlock(bundle) {
6578 return bundle.externalModules.map(function (module) {
6579 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;
6580 }).filter(Boolean).join('\n');
6581}
6582
6583function getExportBlock(entryModule, exportMode) {
6584 var mechanism = arguments.length <= 2 || arguments[2] === undefined ? 'return' : arguments[2];
6585
6586 if (exportMode === 'default') {
6587 return mechanism + ' ' + entryModule.declarations.default.render(false) + ';';
6588 }
6589
6590 return entryModule.getExports().map(function (name) {
6591 var prop = name === 'default' ? '[\'default\']' : '.' + name;
6592 var declaration = entryModule.traceExport(name);
6593
6594 var lhs = 'exports' + prop;
6595 var rhs = declaration.render(false);
6596
6597 // prevent `exports.count = exports.count`
6598 if (lhs === rhs) return null;
6599
6600 return lhs + ' = ' + rhs + ';';
6601 }).filter(Boolean).join('\n');
6602}
6603
6604function umd(bundle, magicString, _ref, options) {
6605 var exportMode = _ref.exportMode;
6606 var indentString = _ref.indentString;
6607
6608 if (exportMode !== 'none' && !options.moduleName) {
6609 throw new Error('You must supply options.moduleName for UMD bundles');
6610 }
6611
6612 var globalNames = options.globals || blank();
6613
6614 var amdDeps = bundle.externalModules.map(quoteId);
6615 var cjsDeps = bundle.externalModules.map(req);
6616 var globalDeps = bundle.externalModules.map(function (module) {
6617 return 'global.' + (globalNames[module.id] || module.name);
6618 });
6619
6620 var args = bundle.externalModules.map(getName);
6621
6622 if (exportMode === 'named') {
6623 amdDeps.unshift('\'exports\'');
6624 cjsDeps.unshift('exports');
6625 globalDeps.unshift('(global.' + options.moduleName + ' = {})');
6626
6627 args.unshift('exports');
6628 }
6629
6630 var amdParams = (options.moduleId ? '\'' + options.moduleId + '\', ' : '') + (amdDeps.length ? '[' + amdDeps.join(', ') + '], ' : '');
6631
6632 var cjsExport = exportMode === 'default' ? 'module.exports = ' : '';
6633 var defaultExport = exportMode === 'default' ? 'global.' + options.moduleName + ' = ' : '';
6634
6635 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
6636
6637 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());
6638
6639 // var foo__default = 'default' in foo ? foo['default'] : foo;
6640 var interopBlock = getInteropBlock(bundle);
6641 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
6642
6643 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
6644 if (exportBlock) magicString.append('\n\n' + exportBlock);
6645
6646 return magicString.trim().indent(indentString).append('\n\n}));').prepend(intro);
6647}
6648
6649function iife(bundle, magicString, _ref, options) {
6650 var exportMode = _ref.exportMode;
6651 var indentString = _ref.indentString;
6652
6653 var globalNames = options.globals || blank();
6654
6655 var dependencies = bundle.externalModules.map(function (module) {
6656 return globalNames[module.id] || module.name;
6657 });
6658
6659 var args = bundle.externalModules.map(getName);
6660
6661 if (exportMode !== 'none' && !options.moduleName) {
6662 throw new Error('You must supply options.moduleName for IIFE bundles');
6663 }
6664
6665 if (exportMode === 'named') {
6666 dependencies.unshift('(this.' + options.moduleName + ' = {})');
6667 args.unshift('exports');
6668 }
6669
6670 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
6671 var intro = '(function (' + args + ') {' + useStrict + '\n\n';
6672 var outro = '\n\n})(' + dependencies + ');';
6673
6674 if (exportMode === 'default') {
6675 intro = 'var ' + options.moduleName + ' = ' + intro;
6676 }
6677
6678 // var foo__default = 'default' in foo ? foo['default'] : foo;
6679 var interopBlock = getInteropBlock(bundle);
6680 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
6681
6682 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
6683 if (exportBlock) magicString.append('\n\n' + exportBlock);
6684
6685 return magicString.indent(indentString).prepend(intro).append(outro);
6686}
6687
6688function notDefault(name) {
6689 return name !== 'default';
6690}
6691function es6(bundle, magicString) {
6692 var importBlock = bundle.externalModules.map(function (module) {
6693 var specifiers = [];
6694 var importedNames = keys(module.declarations).filter(function (name) {
6695 return name !== '*' && name !== 'default';
6696 });
6697
6698 if (module.declarations.default) {
6699 specifiers.push(module.name);
6700 }
6701
6702 if (module.declarations['*']) {
6703 specifiers.push('* as ' + module.name);
6704 }
6705
6706 if (importedNames.length) {
6707 specifiers.push('{ ' + importedNames.join(', ') + ' }');
6708 }
6709
6710 return specifiers.length ? 'import ' + specifiers.join(', ') + ' from \'' + module.id + '\';' : 'import \'' + module.id + '\';';
6711 }).join('\n');
6712
6713 if (importBlock) {
6714 magicString.prepend(importBlock + '\n\n');
6715 }
6716
6717 var module = bundle.entryModule;
6718
6719 var specifiers = module.getExports().filter(notDefault).map(function (name) {
6720 var declaration = module.traceExport(name);
6721
6722 return declaration.name === name ? name : declaration.name + ' as ' + name;
6723 });
6724
6725 var exportBlock = specifiers.length ? 'export { ' + specifiers.join(', ') + ' };' : '';
6726
6727 var defaultExport = module.exports.default || module.reexports.default;
6728 if (defaultExport) {
6729 exportBlock += 'export default ' + module.traceExport('default').name + ';';
6730 }
6731
6732 if (exportBlock) {
6733 magicString.append('\n\n' + exportBlock.trim());
6734 }
6735
6736 return magicString.trim();
6737}
6738
6739function cjs(bundle, magicString, _ref, options) {
6740 var exportMode = _ref.exportMode;
6741
6742 var intro = options.useStrict === false ? '' : '\'use strict\';\n\n';
6743
6744 // TODO handle empty imports, once they're supported
6745 var importBlock = bundle.externalModules.map(function (module) {
6746 var requireStatement = 'var ' + module.name + ' = require(\'' + module.id + '\');';
6747
6748 if (module.declarations.default) {
6749 requireStatement += '\n' + (module.exportsNames ? 'var ' + module.name + '__default = ' : module.name + ' = ') + ('\'default\' in ' + module.name + ' ? ' + module.name + '[\'default\'] : ' + module.name + ';');
6750 }
6751
6752 return requireStatement;
6753 }).join('\n');
6754
6755 if (importBlock) {
6756 intro += importBlock + '\n\n';
6757 }
6758
6759 magicString.prepend(intro);
6760
6761 var exportBlock = getExportBlock(bundle.entryModule, exportMode, 'module.exports =');
6762 if (exportBlock) magicString.append('\n\n' + exportBlock);
6763
6764 return magicString;
6765}
6766
6767function amd(bundle, magicString, _ref, options) {
6768 var exportMode = _ref.exportMode;
6769 var indentString = _ref.indentString;
6770
6771 var deps = bundle.externalModules.map(quoteId);
6772 var args = bundle.externalModules.map(getName);
6773
6774 if (exportMode === 'named') {
6775 args.unshift('exports');
6776 deps.unshift('\'exports\'');
6777 }
6778
6779 var params = (options.moduleId ? '\'' + options.moduleId + '\', ' : '') + (deps.length ? '[' + deps.join(', ') + '], ' : '');
6780
6781 var useStrict = options.useStrict !== false ? ' \'use strict\';' : '';
6782 var intro = 'define(' + params + 'function (' + args.join(', ') + ') {' + useStrict + '\n\n';
6783
6784 // var foo__default = 'default' in foo ? foo['default'] : foo;
6785 var interopBlock = getInteropBlock(bundle);
6786 if (interopBlock) magicString.prepend(interopBlock + '\n\n');
6787
6788 var exportBlock = getExportBlock(bundle.entryModule, exportMode);
6789 if (exportBlock) magicString.append('\n\n' + exportBlock);
6790
6791 return magicString.indent(indentString).append('\n\n});').prepend(intro);
6792}
6793
6794var finalisers = { amd: amd, cjs: cjs, es6: es6, iife: iife, umd: umd };
6795
6796function ensureArray(thing) {
6797 if (Array.isArray(thing)) return thing;
6798 if (thing == undefined) return [];
6799 return [thing];
6800}
6801
6802function load(id) {
6803 return readFileSync(id, 'utf-8');
6804}
6805
6806function addJsExtensionIfNecessary(file) {
6807 if (isFile(file)) return file;
6808
6809 file += '.js';
6810 if (isFile(file)) return file;
6811
6812 return null;
6813}
6814
6815function resolveId(importee, importer) {
6816 // absolute paths are left untouched
6817 if (isAbsolute(importee)) return addJsExtensionIfNecessary(importee);
6818
6819 // if this is the entry point, resolve against cwd
6820 if (importer === undefined) return addJsExtensionIfNecessary(resolve(process.cwd(), importee));
6821
6822 // external modules are skipped at this stage
6823 if (importee[0] !== '.') return null;
6824
6825 return addJsExtensionIfNecessary(resolve(dirname(importer), importee));
6826}
6827
6828function onwarn(msg) {
6829 console.error(msg);
6830}
6831
6832function badExports(option, keys) {
6833 throw new Error('\'' + option + '\' was specified for options.exports, but entry module has following exports: ' + keys.join(', '));
6834}
6835function getExportMode(bundle, exportMode) {
6836 var exportKeys = keys(bundle.entryModule.exports).concat(keys(bundle.entryModule.reexports)).concat(bundle.entryModule.exportAllSources); // not keys, but makes our job easier this way
6837
6838 if (exportMode === 'default') {
6839 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
6840 badExports('default', exportKeys);
6841 }
6842 } else if (exportMode === 'none' && exportKeys.length) {
6843 badExports('none', exportKeys);
6844 }
6845
6846 if (!exportMode || exportMode === 'auto') {
6847 if (exportKeys.length === 0) {
6848 exportMode = 'none';
6849 } else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
6850 exportMode = 'default';
6851 } else {
6852 exportMode = 'named';
6853 }
6854 }
6855
6856 if (!/(?:default|named|none)/.test(exportMode)) {
6857 throw new Error('options.exports must be \'default\', \'named\', \'none\', \'auto\', or left unspecified (defaults to \'auto\')');
6858 }
6859
6860 return exportMode;
6861}
6862
6863function getIndentString(magicString, options) {
6864 if (!('indent' in options) || options.indent === true) {
6865 return magicString.getIndentString();
6866 }
6867
6868 return options.indent || '';
6869}
6870
6871function unixizePath(path) {
6872 return path.split(/[\/\\]/).join('/');
6873}
6874
6875function transform(source, id, transformers) {
6876 var sourceMapChain = [];
6877
6878 if (typeof source === 'string') {
6879 source = {
6880 code: source,
6881 ast: null
6882 };
6883 }
6884
6885 var originalCode = source.code;
6886 var ast = source.ast;
6887
6888 return transformers.reduce(function (promise, transformer) {
6889 return promise.then(function (previous) {
6890 return Promise.resolve(transformer(previous, id)).then(function (result) {
6891 if (result == null) return previous;
6892
6893 if (typeof result === 'string') {
6894 result = {
6895 code: result,
6896 ast: null,
6897 map: null
6898 };
6899 }
6900
6901 sourceMapChain.push(result.map);
6902 ast = result.ast;
6903
6904 return result.code;
6905 });
6906 });
6907 }, Promise.resolve(source.code)).then(function (code) {
6908 return { code: code, originalCode: originalCode, ast: ast, sourceMapChain: sourceMapChain };
6909 });
6910}
6911
6912var charToInteger$1 = {};
6913var integerToChar$1 = {};
6914
6915'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('').forEach(function (char, i) {
6916 charToInteger$1[char] = i;
6917 integerToChar$1[i] = char;
6918});
6919
6920function decode$1(string) {
6921 var result = [],
6922 len = string.length,
6923 i,
6924 hasContinuationBit,
6925 shift = 0,
6926 value = 0,
6927 integer,
6928 shouldNegate;
6929
6930 for (i = 0; i < len; i += 1) {
6931 integer = charToInteger$1[string[i]];
6932
6933 if (integer === undefined) {
6934 throw new Error('Invalid character (' + string[i] + ')');
6935 }
6936
6937 hasContinuationBit = integer & 32;
6938
6939 integer &= 31;
6940 value += integer << shift;
6941
6942 if (hasContinuationBit) {
6943 shift += 5;
6944 } else {
6945 shouldNegate = value & 1;
6946 value >>= 1;
6947
6948 result.push(shouldNegate ? -value : value);
6949
6950 // reset
6951 value = shift = 0;
6952 }
6953 }
6954
6955 return result;
6956}
6957
6958function encode$1(value) {
6959 var result, i;
6960
6961 if (typeof value === 'number') {
6962 result = encodeInteger$1(value);
6963 } else {
6964 result = '';
6965 for (i = 0; i < value.length; i += 1) {
6966 result += encodeInteger$1(value[i]);
6967 }
6968 }
6969
6970 return result;
6971}
6972
6973function encodeInteger$1(num) {
6974 var result = '',
6975 clamped;
6976
6977 if (num < 0) {
6978 num = -num << 1 | 1;
6979 } else {
6980 num <<= 1;
6981 }
6982
6983 do {
6984 clamped = num & 31;
6985 num >>= 5;
6986
6987 if (num > 0) {
6988 clamped |= 32;
6989 }
6990
6991 result += integerToChar$1[clamped];
6992 } while (num > 0);
6993
6994 return result;
6995}
6996
6997function decodeSegments(encodedSegments) {
6998 var i = encodedSegments.length;
6999 var segments = new Array(i);
7000
7001 while (i--) segments[i] = decode$1(encodedSegments[i]);
7002 return segments;
7003}
7004
7005//let _uid = 0;
7006
7007function decode$1$1(mappings) {
7008 var sourceFileIndex = 0; // second field
7009 var sourceCodeLine = 0; // third field
7010 var sourceCodeColumn = 0; // fourth field
7011 var nameIndex = 0; // fifth field
7012
7013 var lines = mappings.split(';');
7014 var numLines = lines.length;
7015 var decoded = new Array(numLines);
7016
7017 var i = undefined;
7018 var j = undefined;
7019 var line = undefined;
7020 var generatedCodeColumn = undefined;
7021 var decodedLine = undefined;
7022 var segments = undefined;
7023 var segment = undefined;
7024 var result = undefined;
7025
7026 for (i = 0; i < numLines; i += 1) {
7027 line = lines[i];
7028
7029 generatedCodeColumn = 0; // first field - reset each time
7030 decodedLine = [];
7031
7032 //if ( _uid++ > 50 ) throw new Error( 'hm' );
7033
7034 segments = decodeSegments(line.split(','));
7035
7036 for (j = 0; j < segments.length; j += 1) {
7037 segment = segments[j];
7038
7039 if (!segment.length) {
7040 break;
7041 }
7042
7043 generatedCodeColumn += segment[0];
7044
7045 result = [generatedCodeColumn];
7046 decodedLine.push(result);
7047
7048 if (segment.length === 1) {
7049 // only one field!
7050 continue;
7051 }
7052
7053 sourceFileIndex += segment[1];
7054 sourceCodeLine += segment[2];
7055 sourceCodeColumn += segment[3];
7056
7057 result.push(sourceFileIndex, sourceCodeLine, sourceCodeColumn);
7058
7059 if (segment.length === 5) {
7060 nameIndex += segment[4];
7061 result.push(nameIndex);
7062 }
7063 }
7064
7065 decoded[i] = decodedLine;
7066 }
7067
7068 return decoded;
7069}
7070
7071function encode$1$1(decoded) {
7072 var offsets = {
7073 generatedCodeColumn: 0,
7074 sourceFileIndex: 0, // second field
7075 sourceCodeLine: 0, // third field
7076 sourceCodeColumn: 0, // fourth field
7077 nameIndex: 0 // fifth field
7078 };
7079
7080 return decoded.map(function (line) {
7081 offsets.generatedCodeColumn = 0; // first field - reset each time
7082 return line.map(encodeSegment).join(',');
7083 }).join(';');
7084
7085 function encodeSegment(segment) {
7086 if (!segment.length) {
7087 return segment;
7088 }
7089
7090 var result = new Array(segment.length);
7091
7092 result[0] = segment[0] - offsets.generatedCodeColumn;
7093 offsets.generatedCodeColumn = segment[0];
7094
7095 if (segment.length === 1) {
7096 // only one field!
7097 return encode$1(result);
7098 }
7099
7100 result[1] = segment[1] - offsets.sourceFileIndex;
7101 result[2] = segment[2] - offsets.sourceCodeLine;
7102 result[3] = segment[3] - offsets.sourceCodeColumn;
7103
7104 offsets.sourceFileIndex = segment[1];
7105 offsets.sourceCodeLine = segment[2];
7106 offsets.sourceCodeColumn = segment[3];
7107
7108 if (segment.length === 5) {
7109 result[4] = segment[4] - offsets.nameIndex;
7110 offsets.nameIndex = segment[4];
7111 }
7112
7113 return encode$1(result);
7114 }
7115}
7116
7117function traceSegment(loc, mappings) {
7118 var line = loc[0];
7119 var column = loc[1];
7120
7121 var segments = mappings[line];
7122
7123 if (!segments) return null;
7124
7125 for (var i = 0; i < segments.length; i += 1) {
7126 var segment = segments[i];
7127
7128 if (segment[0] > column) return null;
7129
7130 if (segment[0] === column) {
7131 if (segment[1] !== 0) {
7132 throw new Error('Bad sourcemap');
7133 }
7134
7135 return [segment[2], segment[3]];
7136 }
7137 }
7138
7139 return null;
7140}
7141function collapseSourcemaps(map, modules) {
7142 var chains = modules.map(function (module) {
7143 return module.sourceMapChain.map(function (map) {
7144 if (!map) throw new Error('Cannot generate a sourcemap if non-sourcemap-generating transformers are used');
7145 return decode$1$1(map.mappings);
7146 });
7147 });
7148
7149 var decodedMappings = decode$1$1(map.mappings);
7150
7151 var tracedMappings = decodedMappings.map(function (line) {
7152 var tracedLine = [];
7153
7154 line.forEach(function (segment) {
7155 var sourceIndex = segment[1];
7156 var sourceCodeLine = segment[2];
7157 var sourceCodeColumn = segment[3];
7158
7159 var chain = chains[sourceIndex];
7160
7161 var i = chain.length;
7162 var traced = [sourceCodeLine, sourceCodeColumn];
7163
7164 while (i-- && traced) {
7165 traced = traceSegment(traced, chain[i]);
7166 }
7167
7168 if (traced) {
7169 tracedLine.push([segment[0], segment[1], traced[0], traced[1]
7170 // TODO name?
7171 ]);
7172 }
7173 });
7174
7175 return tracedLine;
7176 });
7177
7178 map.sourcesContent = modules.map(function (module) {
7179 return module.originalCode;
7180 });
7181 map.mappings = encode$1$1(tracedMappings);
7182 return map;
7183}
7184
7185function callIfFunction(thing) {
7186 return typeof thing === 'function' ? thing() : thing;
7187}
7188
7189var Bundle = (function () {
7190 function Bundle(options) {
7191 var _this = this;
7192
7193 babelHelpers.classCallCheck(this, Bundle);
7194
7195 this.entry = options.entry;
7196 this.entryModule = null;
7197
7198 this.plugins = ensureArray(options.plugins);
7199
7200 this.resolveId = first$1(this.plugins.map(function (plugin) {
7201 return plugin.resolveId;
7202 }).filter(Boolean).concat(resolveId));
7203
7204 this.load = first$1(this.plugins.map(function (plugin) {
7205 return plugin.load;
7206 }).filter(Boolean).concat(load));
7207
7208 this.transformers = this.plugins.map(function (plugin) {
7209 return plugin.transform;
7210 }).filter(Boolean);
7211
7212 this.pending = blank();
7213 this.moduleById = blank();
7214 this.modules = [];
7215
7216 this.externalModules = [];
7217 this.internalNamespaces = [];
7218
7219 this.assumedGlobals = blank();
7220
7221 this.external = options.external || [];
7222 this.onwarn = options.onwarn || onwarn;
7223
7224 // TODO strictly speaking, this only applies with non-ES6, non-default-only bundles
7225 ['module', 'exports'].forEach(function (global) {
7226 return _this.assumedGlobals[global] = true;
7227 });
7228 }
7229
7230 Bundle.prototype.build = function build() {
7231 var _this2 = this;
7232
7233 return Promise.resolve(this.resolveId(this.entry, undefined)).then(function (id) {
7234 return _this2.fetchModule(id, undefined);
7235 }).then(function (entryModule) {
7236 _this2.entryModule = entryModule;
7237
7238 _this2.modules.forEach(function (module) {
7239 return module.bindImportSpecifiers();
7240 });
7241 _this2.modules.forEach(function (module) {
7242 return module.bindAliases();
7243 });
7244 _this2.modules.forEach(function (module) {
7245 return module.bindReferences();
7246 });
7247
7248 // mark all export statements
7249 entryModule.getExports().forEach(function (name) {
7250 var declaration = entryModule.traceExport(name);
7251 declaration.isExported = true;
7252
7253 declaration.use();
7254 });
7255
7256 var settled = false;
7257 while (!settled) {
7258 settled = true;
7259
7260 _this2.modules.forEach(function (module) {
7261 if (module.markAllSideEffects()) settled = false;
7262 });
7263 }
7264
7265 _this2.orderedModules = _this2.sort();
7266 _this2.deconflict();
7267 });
7268 };
7269
7270 Bundle.prototype.deconflict = function deconflict() {
7271 var used = blank();
7272
7273 // ensure no conflicts with globals
7274 keys(this.assumedGlobals).forEach(function (name) {
7275 return used[name] = 1;
7276 });
7277
7278 function getSafeName(name) {
7279 while (used[name]) {
7280 name += '$' + used[name]++;
7281 }
7282
7283 used[name] = 1;
7284 return name;
7285 }
7286
7287 this.externalModules.forEach(function (module) {
7288 module.name = getSafeName(module.name);
7289 });
7290
7291 this.modules.forEach(function (module) {
7292 keys(module.declarations).forEach(function (originalName) {
7293 var declaration = module.declarations[originalName];
7294
7295 if (originalName === 'default') {
7296 if (declaration.original && !declaration.original.isReassigned) return;
7297 }
7298
7299 declaration.name = getSafeName(declaration.name);
7300 });
7301 });
7302 };
7303
7304 Bundle.prototype.fetchModule = function fetchModule(id, importer) {
7305 var _this3 = this;
7306
7307 // short-circuit cycles
7308 if (this.pending[id]) return null;
7309 this.pending[id] = true;
7310
7311 return Promise.resolve(this.load(id)).catch(function (err) {
7312 var msg = 'Could not load ' + id;
7313 if (importer) msg += ' (imported by ' + importer + ')';
7314
7315 msg += ': ' + err.message;
7316 throw new Error(msg);
7317 }).then(function (source) {
7318 return transform(source, id, _this3.transformers);
7319 }).then(function (source) {
7320 var code = source.code;
7321 var originalCode = source.originalCode;
7322 var ast = source.ast;
7323 var sourceMapChain = source.sourceMapChain;
7324
7325 var module = new Module({ id: id, code: code, originalCode: originalCode, ast: ast, sourceMapChain: sourceMapChain, bundle: _this3 });
7326
7327 _this3.modules.push(module);
7328 _this3.moduleById[id] = module;
7329
7330 return _this3.fetchAllDependencies(module).then(function () {
7331 return module;
7332 });
7333 });
7334 };
7335
7336 Bundle.prototype.fetchAllDependencies = function fetchAllDependencies(module) {
7337 var _this4 = this;
7338
7339 var promises = module.dependencies.map(function (source) {
7340 return Promise.resolve(_this4.resolveId(source, module.id)).then(function (resolvedId) {
7341 if (!resolvedId) {
7342 if (! ~_this4.external.indexOf(source)) _this4.onwarn('Treating \'' + source + '\' as external dependency');
7343 module.resolvedIds[source] = source;
7344
7345 if (!_this4.moduleById[source]) {
7346 var _module = new ExternalModule(source);
7347 _this4.externalModules.push(_module);
7348 _this4.moduleById[source] = _module;
7349 }
7350 } else {
7351 if (resolvedId === module.id) {
7352 throw new Error('A module cannot import itself (' + resolvedId + ')');
7353 }
7354
7355 module.resolvedIds[source] = resolvedId;
7356 return _this4.fetchModule(resolvedId, module.id);
7357 }
7358 });
7359 });
7360
7361 return Promise.all(promises);
7362 };
7363
7364 Bundle.prototype.render = function render() {
7365 var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
7366
7367 var format = options.format || 'es6';
7368
7369 // Determine export mode - 'default', 'named', 'none'
7370 var exportMode = getExportMode(this, options.exports);
7371
7372 var magicString = new MagicString.Bundle({ separator: '\n\n' });
7373 var usedModules = [];
7374
7375 this.orderedModules.forEach(function (module) {
7376 var source = module.render(format === 'es6');
7377 if (source.toString().length) {
7378 magicString.addSource(source);
7379 usedModules.push(module);
7380 }
7381 });
7382
7383 var intro = [options.intro].concat(this.plugins.map(function (plugin) {
7384 return plugin.intro && plugin.intro();
7385 })).filter(Boolean).join('\n\n');
7386
7387 if (intro) magicString.prepend(intro + '\n');
7388 if (options.outro) magicString.append('\n' + options.outro);
7389
7390 var indentString = getIndentString(magicString, options);
7391
7392 var finalise = finalisers[format];
7393 if (!finalise) throw new Error('You must specify an output type - valid options are ' + keys(finalisers).join(', '));
7394
7395 magicString = finalise(this, magicString.trim(), { exportMode: exportMode, indentString: indentString }, options);
7396
7397 var banner = [options.banner].concat(this.plugins.map(function (plugin) {
7398 return plugin.banner;
7399 })).map(callIfFunction).filter(Boolean).join('\n');
7400
7401 var footer = [options.footer].concat(this.plugins.map(function (plugin) {
7402 return plugin.footer;
7403 })).map(callIfFunction).filter(Boolean).join('\n');
7404
7405 if (banner) magicString.prepend(banner + '\n');
7406 if (footer) magicString.append('\n' + footer);
7407
7408 var code = magicString.toString();
7409 var map = null;
7410
7411 if (options.sourceMap) {
7412 var file = options.sourceMapFile || options.dest;
7413 map = magicString.generateMap({
7414 includeContent: true,
7415 file: file
7416 // TODO
7417 });
7418
7419 if (this.transformers.length) map = collapseSourcemaps(map, usedModules);
7420 map.sources = map.sources.map(unixizePath);
7421 }
7422
7423 return { code: code, map: map };
7424 };
7425
7426 Bundle.prototype.sort = function sort() {
7427 var seen = {};
7428 var ordered = [];
7429 var hasCycles = undefined;
7430
7431 var strongDeps = {};
7432 var stronglyDependsOn = {};
7433
7434 function visit(module) {
7435 if (seen[module.id]) return;
7436 seen[module.id] = true;
7437
7438 var _module$consolidateDependencies = module.consolidateDependencies();
7439
7440 var strongDependencies = _module$consolidateDependencies.strongDependencies;
7441 var weakDependencies = _module$consolidateDependencies.weakDependencies;
7442
7443 strongDeps[module.id] = [];
7444 stronglyDependsOn[module.id] = {};
7445
7446 keys(strongDependencies).forEach(function (id) {
7447 var imported = strongDependencies[id];
7448
7449 strongDeps[module.id].push(imported);
7450
7451 if (seen[id]) {
7452 // we need to prevent an infinite loop, and note that
7453 // we need to check for strong/weak dependency relationships
7454 hasCycles = true;
7455 return;
7456 }
7457
7458 visit(imported);
7459 });
7460
7461 keys(weakDependencies).forEach(function (id) {
7462 var imported = weakDependencies[id];
7463
7464 if (seen[id]) {
7465 // we need to prevent an infinite loop, and note that
7466 // we need to check for strong/weak dependency relationships
7467 hasCycles = true;
7468 return;
7469 }
7470
7471 visit(imported);
7472 });
7473
7474 // add second (and third...) order dependencies
7475 function addStrongDependencies(dependency) {
7476 if (stronglyDependsOn[module.id][dependency.id]) return;
7477
7478 stronglyDependsOn[module.id][dependency.id] = true;
7479 strongDeps[dependency.id].forEach(addStrongDependencies);
7480 }
7481
7482 strongDeps[module.id].forEach(addStrongDependencies);
7483
7484 ordered.push(module);
7485 }
7486
7487 this.modules.forEach(visit);
7488
7489 if (hasCycles) {
7490 var unordered = ordered;
7491 ordered = [];
7492
7493 // unordered is actually semi-ordered, as [ fewer dependencies ... more dependencies ]
7494 unordered.forEach(function (module) {
7495 // ensure strong dependencies of `module` that don't strongly depend on `module` go first
7496 strongDeps[module.id].forEach(place);
7497
7498 function place(dep) {
7499 if (!stronglyDependsOn[dep.id][module.id] && ! ~ordered.indexOf(dep)) {
7500 strongDeps[dep.id].forEach(place);
7501 ordered.push(dep);
7502 }
7503 }
7504
7505 if (! ~ordered.indexOf(module)) {
7506 ordered.push(module);
7507 }
7508 });
7509 }
7510
7511 return ordered;
7512 };
7513
7514 return Bundle;
7515})();
7516
7517var VERSION = '0.20.4';
7518
7519function rollup(options) {
7520 if (!options || !options.entry) {
7521 throw new Error('You must supply options.entry to rollup');
7522 }
7523
7524 if (options.transform || options.load || options.resolveId || options.resolveExternal) {
7525 throw new Error('The `transform`, `load`, `resolveId` and `resolveExternal` options are deprecated in favour of a unified plugin API. See https://github.com/rollup/rollup/wiki/Plugins for details');
7526 }
7527
7528 var bundle = new Bundle(options);
7529
7530 return bundle.build().then(function () {
7531 return {
7532 imports: bundle.externalModules.map(function (module) {
7533 return module.id;
7534 }),
7535 exports: keys(bundle.entryModule.exports),
7536 modules: bundle.orderedModules.map(function (module) {
7537 return { id: module.id };
7538 }),
7539
7540 generate: function (options) {
7541 return bundle.render(options);
7542 },
7543 write: function (options) {
7544 if (!options || !options.dest) {
7545 throw new Error('You must supply options.dest to bundle.write');
7546 }
7547
7548 var dest = options.dest;
7549
7550 var _bundle$render = bundle.render(options);
7551
7552 var code = _bundle$render.code;
7553 var map = _bundle$render.map;
7554
7555 var promises = [];
7556
7557 if (options.sourceMap) {
7558 var url = undefined;
7559
7560 if (options.sourceMap === 'inline') {
7561 url = map.toUrl();
7562 } else {
7563 url = _basename(dest) + '.map';
7564 promises.push(writeFile(dest + '.map', map.toString()));
7565 }
7566
7567 code += '\n//# ' + SOURCEMAPPING_URL$1 + '=' + url;
7568 }
7569
7570 promises.push(writeFile(dest, code));
7571 return Promise.all(promises);
7572 }
7573 };
7574 });
7575}
7576
7577exports.rollup = rollup;
7578exports.VERSION = VERSION;
7579//# sourceMappingURL=rollup.js.map
\No newline at end of file