UNPKG

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