UNPKG

746 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v2.29.0
4 Thu, 08 Oct 2020 04:24:04 GMT - commit 0b02e52bc7816c473784794670a2c3047ac62a07
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11'use strict';
12
13var fs = require('fs');
14var sysPath = require('path');
15var crypto = require('crypto');
16var require$$0$1 = require('events');
17
18function _interopNamespaceDefaultOnly(e) {
19 return {__proto__: null, 'default': e};
20}
21
22var version = "2.29.0";
23
24function ensureArray(items) {
25 if (Array.isArray(items)) {
26 return items.filter(Boolean);
27 }
28 if (items) {
29 return [items];
30 }
31 return [];
32}
33
34const defaultOnWarn = warning => console.warn(warning.message || warning);
35function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
36 const validOptionSet = new Set(validOptions);
37 const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
38 if (unknownOptions.length > 0) {
39 warn({
40 code: 'UNKNOWN_OPTION',
41 message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
42 ...validOptionSet
43 ]
44 .sort()
45 .join(', ')}`
46 });
47 }
48}
49
50const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
51const relativePath = /^\.?\.\//;
52function isAbsolute(path) {
53 return absolutePath.test(path);
54}
55function isRelative(path) {
56 return relativePath.test(path);
57}
58function normalize(path) {
59 if (path.indexOf('\\') == -1)
60 return path;
61 return path.replace(/\\/g, '/');
62}
63
64function sanitizeFileName(name) {
65 return name.replace(/[\0?*]/g, '_');
66}
67
68function getAliasName(id) {
69 const base = sysPath.basename(id);
70 return base.substr(0, base.length - sysPath.extname(id).length);
71}
72function relativeId(id) {
73 if (typeof process === 'undefined' || !isAbsolute(id))
74 return id;
75 return sysPath.relative(process.cwd(), id);
76}
77function isPlainPathFragment(name) {
78 // not starting with "/", "./", "../"
79 return (name[0] !== '/' &&
80 !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) &&
81 sanitizeFileName(name) === name &&
82 !isAbsolute(name));
83}
84
85let fsEvents;
86let fsEventsImportError;
87function loadFsEvents() {
88 return Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespaceDefaultOnly(require('fsevents')); })
89 .then(namespace => {
90 fsEvents = namespace.default;
91 })
92 .catch(err => {
93 fsEventsImportError = err;
94 });
95}
96// A call to this function will be injected into the chokidar code
97function getFsEvents() {
98 if (fsEventsImportError)
99 throw fsEventsImportError;
100 return fsEvents;
101}
102
103var fseventsImporter = {
104 __proto__: null,
105 loadFsEvents: loadFsEvents,
106 getFsEvents: getFsEvents
107};
108
109var charToInteger = {};
110var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
111for (var i = 0; i < chars.length; i++) {
112 charToInteger[chars.charCodeAt(i)] = i;
113}
114function decode(mappings) {
115 var decoded = [];
116 var line = [];
117 var segment = [
118 0,
119 0,
120 0,
121 0,
122 0,
123 ];
124 var j = 0;
125 for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
126 var c = mappings.charCodeAt(i);
127 if (c === 44) { // ","
128 segmentify(line, segment, j);
129 j = 0;
130 }
131 else if (c === 59) { // ";"
132 segmentify(line, segment, j);
133 j = 0;
134 decoded.push(line);
135 line = [];
136 segment[0] = 0;
137 }
138 else {
139 var integer = charToInteger[c];
140 if (integer === undefined) {
141 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
142 }
143 var hasContinuationBit = integer & 32;
144 integer &= 31;
145 value += integer << shift;
146 if (hasContinuationBit) {
147 shift += 5;
148 }
149 else {
150 var shouldNegate = value & 1;
151 value >>>= 1;
152 if (shouldNegate) {
153 value = value === 0 ? -0x80000000 : -value;
154 }
155 segment[j] += value;
156 j++;
157 value = shift = 0; // reset
158 }
159 }
160 }
161 segmentify(line, segment, j);
162 decoded.push(line);
163 return decoded;
164}
165function segmentify(line, segment, j) {
166 // This looks ugly, but we're creating specialized arrays with a specific
167 // length. This is much faster than creating a new array (which v8 expands to
168 // a capacity of 17 after pushing the first item), or slicing out a subarray
169 // (which is slow). Length 4 is assumed to be the most frequent, followed by
170 // length 5 (since not everything will have an associated name), followed by
171 // length 1 (it's probably rare for a source substring to not have an
172 // associated segment data).
173 if (j === 4)
174 line.push([segment[0], segment[1], segment[2], segment[3]]);
175 else if (j === 5)
176 line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
177 else if (j === 1)
178 line.push([segment[0]]);
179}
180function encode(decoded) {
181 var sourceFileIndex = 0; // second field
182 var sourceCodeLine = 0; // third field
183 var sourceCodeColumn = 0; // fourth field
184 var nameIndex = 0; // fifth field
185 var mappings = '';
186 for (var i = 0; i < decoded.length; i++) {
187 var line = decoded[i];
188 if (i > 0)
189 mappings += ';';
190 if (line.length === 0)
191 continue;
192 var generatedCodeColumn = 0; // first field
193 var lineMappings = [];
194 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
195 var segment = line_1[_i];
196 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
197 generatedCodeColumn = segment[0];
198 if (segment.length > 1) {
199 segmentMappings +=
200 encodeInteger(segment[1] - sourceFileIndex) +
201 encodeInteger(segment[2] - sourceCodeLine) +
202 encodeInteger(segment[3] - sourceCodeColumn);
203 sourceFileIndex = segment[1];
204 sourceCodeLine = segment[2];
205 sourceCodeColumn = segment[3];
206 }
207 if (segment.length === 5) {
208 segmentMappings += encodeInteger(segment[4] - nameIndex);
209 nameIndex = segment[4];
210 }
211 lineMappings.push(segmentMappings);
212 }
213 mappings += lineMappings.join(',');
214 }
215 return mappings;
216}
217function encodeInteger(num) {
218 var result = '';
219 num = num < 0 ? (-num << 1) | 1 : num << 1;
220 do {
221 var clamped = num & 31;
222 num >>>= 5;
223 if (num > 0) {
224 clamped |= 32;
225 }
226 result += chars[clamped];
227 } while (num > 0);
228 return result;
229}
230
231var BitSet = function BitSet(arg) {
232 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
233};
234
235BitSet.prototype.add = function add (n) {
236 this.bits[n >> 5] |= 1 << (n & 31);
237};
238
239BitSet.prototype.has = function has (n) {
240 return !!(this.bits[n >> 5] & (1 << (n & 31)));
241};
242
243var Chunk = function Chunk(start, end, content) {
244 this.start = start;
245 this.end = end;
246 this.original = content;
247
248 this.intro = '';
249 this.outro = '';
250
251 this.content = content;
252 this.storeName = false;
253 this.edited = false;
254
255 // we make these non-enumerable, for sanity while debugging
256 Object.defineProperties(this, {
257 previous: { writable: true, value: null },
258 next: { writable: true, value: null }
259 });
260};
261
262Chunk.prototype.appendLeft = function appendLeft (content) {
263 this.outro += content;
264};
265
266Chunk.prototype.appendRight = function appendRight (content) {
267 this.intro = this.intro + content;
268};
269
270Chunk.prototype.clone = function clone () {
271 var chunk = new Chunk(this.start, this.end, this.original);
272
273 chunk.intro = this.intro;
274 chunk.outro = this.outro;
275 chunk.content = this.content;
276 chunk.storeName = this.storeName;
277 chunk.edited = this.edited;
278
279 return chunk;
280};
281
282Chunk.prototype.contains = function contains (index) {
283 return this.start < index && index < this.end;
284};
285
286Chunk.prototype.eachNext = function eachNext (fn) {
287 var chunk = this;
288 while (chunk) {
289 fn(chunk);
290 chunk = chunk.next;
291 }
292};
293
294Chunk.prototype.eachPrevious = function eachPrevious (fn) {
295 var chunk = this;
296 while (chunk) {
297 fn(chunk);
298 chunk = chunk.previous;
299 }
300};
301
302Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
303 this.content = content;
304 if (!contentOnly) {
305 this.intro = '';
306 this.outro = '';
307 }
308 this.storeName = storeName;
309
310 this.edited = true;
311
312 return this;
313};
314
315Chunk.prototype.prependLeft = function prependLeft (content) {
316 this.outro = content + this.outro;
317};
318
319Chunk.prototype.prependRight = function prependRight (content) {
320 this.intro = content + this.intro;
321};
322
323Chunk.prototype.split = function split (index) {
324 var sliceIndex = index - this.start;
325
326 var originalBefore = this.original.slice(0, sliceIndex);
327 var originalAfter = this.original.slice(sliceIndex);
328
329 this.original = originalBefore;
330
331 var newChunk = new Chunk(index, this.end, originalAfter);
332 newChunk.outro = this.outro;
333 this.outro = '';
334
335 this.end = index;
336
337 if (this.edited) {
338 // TODO is this block necessary?...
339 newChunk.edit('', false);
340 this.content = '';
341 } else {
342 this.content = originalBefore;
343 }
344
345 newChunk.next = this.next;
346 if (newChunk.next) { newChunk.next.previous = newChunk; }
347 newChunk.previous = this;
348 this.next = newChunk;
349
350 return newChunk;
351};
352
353Chunk.prototype.toString = function toString () {
354 return this.intro + this.content + this.outro;
355};
356
357Chunk.prototype.trimEnd = function trimEnd (rx) {
358 this.outro = this.outro.replace(rx, '');
359 if (this.outro.length) { return true; }
360
361 var trimmed = this.content.replace(rx, '');
362
363 if (trimmed.length) {
364 if (trimmed !== this.content) {
365 this.split(this.start + trimmed.length).edit('', undefined, true);
366 }
367 return true;
368
369 } else {
370 this.edit('', undefined, true);
371
372 this.intro = this.intro.replace(rx, '');
373 if (this.intro.length) { return true; }
374 }
375};
376
377Chunk.prototype.trimStart = function trimStart (rx) {
378 this.intro = this.intro.replace(rx, '');
379 if (this.intro.length) { return true; }
380
381 var trimmed = this.content.replace(rx, '');
382
383 if (trimmed.length) {
384 if (trimmed !== this.content) {
385 this.split(this.end - trimmed.length);
386 this.edit('', undefined, true);
387 }
388 return true;
389
390 } else {
391 this.edit('', undefined, true);
392
393 this.outro = this.outro.replace(rx, '');
394 if (this.outro.length) { return true; }
395 }
396};
397
398var btoa = function () {
399 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
400};
401if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
402 btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
403} else if (typeof Buffer === 'function') {
404 btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
405}
406
407var SourceMap = function SourceMap(properties) {
408 this.version = 3;
409 this.file = properties.file;
410 this.sources = properties.sources;
411 this.sourcesContent = properties.sourcesContent;
412 this.names = properties.names;
413 this.mappings = encode(properties.mappings);
414};
415
416SourceMap.prototype.toString = function toString () {
417 return JSON.stringify(this);
418};
419
420SourceMap.prototype.toUrl = function toUrl () {
421 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
422};
423
424function guessIndent(code) {
425 var lines = code.split('\n');
426
427 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
428 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
429
430 if (tabbed.length === 0 && spaced.length === 0) {
431 return null;
432 }
433
434 // More lines tabbed than spaced? Assume tabs, and
435 // default to tabs in the case of a tie (or nothing
436 // to go on)
437 if (tabbed.length >= spaced.length) {
438 return '\t';
439 }
440
441 // Otherwise, we need to guess the multiple
442 var min = spaced.reduce(function (previous, current) {
443 var numSpaces = /^ +/.exec(current)[0].length;
444 return Math.min(numSpaces, previous);
445 }, Infinity);
446
447 return new Array(min + 1).join(' ');
448}
449
450function getRelativePath(from, to) {
451 var fromParts = from.split(/[/\\]/);
452 var toParts = to.split(/[/\\]/);
453
454 fromParts.pop(); // get dirname
455
456 while (fromParts[0] === toParts[0]) {
457 fromParts.shift();
458 toParts.shift();
459 }
460
461 if (fromParts.length) {
462 var i = fromParts.length;
463 while (i--) { fromParts[i] = '..'; }
464 }
465
466 return fromParts.concat(toParts).join('/');
467}
468
469var toString = Object.prototype.toString;
470
471function isObject(thing) {
472 return toString.call(thing) === '[object Object]';
473}
474
475function getLocator(source) {
476 var originalLines = source.split('\n');
477 var lineOffsets = [];
478
479 for (var i = 0, pos = 0; i < originalLines.length; i++) {
480 lineOffsets.push(pos);
481 pos += originalLines[i].length + 1;
482 }
483
484 return function locate(index) {
485 var i = 0;
486 var j = lineOffsets.length;
487 while (i < j) {
488 var m = (i + j) >> 1;
489 if (index < lineOffsets[m]) {
490 j = m;
491 } else {
492 i = m + 1;
493 }
494 }
495 var line = i - 1;
496 var column = index - lineOffsets[line];
497 return { line: line, column: column };
498 };
499}
500
501var Mappings = function Mappings(hires) {
502 this.hires = hires;
503 this.generatedCodeLine = 0;
504 this.generatedCodeColumn = 0;
505 this.raw = [];
506 this.rawSegments = this.raw[this.generatedCodeLine] = [];
507 this.pending = null;
508};
509
510Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
511 if (content.length) {
512 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
513 if (nameIndex >= 0) {
514 segment.push(nameIndex);
515 }
516 this.rawSegments.push(segment);
517 } else if (this.pending) {
518 this.rawSegments.push(this.pending);
519 }
520
521 this.advance(content);
522 this.pending = null;
523};
524
525Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
526 var originalCharIndex = chunk.start;
527 var first = true;
528
529 while (originalCharIndex < chunk.end) {
530 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
531 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
532 }
533
534 if (original[originalCharIndex] === '\n') {
535 loc.line += 1;
536 loc.column = 0;
537 this.generatedCodeLine += 1;
538 this.raw[this.generatedCodeLine] = this.rawSegments = [];
539 this.generatedCodeColumn = 0;
540 first = true;
541 } else {
542 loc.column += 1;
543 this.generatedCodeColumn += 1;
544 first = false;
545 }
546
547 originalCharIndex += 1;
548 }
549
550 this.pending = null;
551};
552
553Mappings.prototype.advance = function advance (str) {
554 if (!str) { return; }
555
556 var lines = str.split('\n');
557
558 if (lines.length > 1) {
559 for (var i = 0; i < lines.length - 1; i++) {
560 this.generatedCodeLine++;
561 this.raw[this.generatedCodeLine] = this.rawSegments = [];
562 }
563 this.generatedCodeColumn = 0;
564 }
565
566 this.generatedCodeColumn += lines[lines.length - 1].length;
567};
568
569var n = '\n';
570
571var warned = {
572 insertLeft: false,
573 insertRight: false,
574 storeName: false
575};
576
577var MagicString = function MagicString(string, options) {
578 if ( options === void 0 ) options = {};
579
580 var chunk = new Chunk(0, string.length, string);
581
582 Object.defineProperties(this, {
583 original: { writable: true, value: string },
584 outro: { writable: true, value: '' },
585 intro: { writable: true, value: '' },
586 firstChunk: { writable: true, value: chunk },
587 lastChunk: { writable: true, value: chunk },
588 lastSearchedChunk: { writable: true, value: chunk },
589 byStart: { writable: true, value: {} },
590 byEnd: { writable: true, value: {} },
591 filename: { writable: true, value: options.filename },
592 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
593 sourcemapLocations: { writable: true, value: new BitSet() },
594 storedNames: { writable: true, value: {} },
595 indentStr: { writable: true, value: guessIndent(string) }
596 });
597
598 this.byStart[0] = chunk;
599 this.byEnd[string.length] = chunk;
600};
601
602MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
603 this.sourcemapLocations.add(char);
604};
605
606MagicString.prototype.append = function append (content) {
607 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
608
609 this.outro += content;
610 return this;
611};
612
613MagicString.prototype.appendLeft = function appendLeft (index, content) {
614 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
615
616 this._split(index);
617
618 var chunk = this.byEnd[index];
619
620 if (chunk) {
621 chunk.appendLeft(content);
622 } else {
623 this.intro += content;
624 }
625 return this;
626};
627
628MagicString.prototype.appendRight = function appendRight (index, content) {
629 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
630
631 this._split(index);
632
633 var chunk = this.byStart[index];
634
635 if (chunk) {
636 chunk.appendRight(content);
637 } else {
638 this.outro += content;
639 }
640 return this;
641};
642
643MagicString.prototype.clone = function clone () {
644 var cloned = new MagicString(this.original, { filename: this.filename });
645
646 var originalChunk = this.firstChunk;
647 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
648
649 while (originalChunk) {
650 cloned.byStart[clonedChunk.start] = clonedChunk;
651 cloned.byEnd[clonedChunk.end] = clonedChunk;
652
653 var nextOriginalChunk = originalChunk.next;
654 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
655
656 if (nextClonedChunk) {
657 clonedChunk.next = nextClonedChunk;
658 nextClonedChunk.previous = clonedChunk;
659
660 clonedChunk = nextClonedChunk;
661 }
662
663 originalChunk = nextOriginalChunk;
664 }
665
666 cloned.lastChunk = clonedChunk;
667
668 if (this.indentExclusionRanges) {
669 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
670 }
671
672 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
673
674 cloned.intro = this.intro;
675 cloned.outro = this.outro;
676
677 return cloned;
678};
679
680MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
681 var this$1 = this;
682
683 options = options || {};
684
685 var sourceIndex = 0;
686 var names = Object.keys(this.storedNames);
687 var mappings = new Mappings(options.hires);
688
689 var locate = getLocator(this.original);
690
691 if (this.intro) {
692 mappings.advance(this.intro);
693 }
694
695 this.firstChunk.eachNext(function (chunk) {
696 var loc = locate(chunk.start);
697
698 if (chunk.intro.length) { mappings.advance(chunk.intro); }
699
700 if (chunk.edited) {
701 mappings.addEdit(
702 sourceIndex,
703 chunk.content,
704 loc,
705 chunk.storeName ? names.indexOf(chunk.original) : -1
706 );
707 } else {
708 mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
709 }
710
711 if (chunk.outro.length) { mappings.advance(chunk.outro); }
712 });
713
714 return {
715 file: options.file ? options.file.split(/[/\\]/).pop() : null,
716 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
717 sourcesContent: options.includeContent ? [this.original] : [null],
718 names: names,
719 mappings: mappings.raw
720 };
721};
722
723MagicString.prototype.generateMap = function generateMap (options) {
724 return new SourceMap(this.generateDecodedMap(options));
725};
726
727MagicString.prototype.getIndentString = function getIndentString () {
728 return this.indentStr === null ? '\t' : this.indentStr;
729};
730
731MagicString.prototype.indent = function indent (indentStr, options) {
732 var pattern = /^[^\r\n]/gm;
733
734 if (isObject(indentStr)) {
735 options = indentStr;
736 indentStr = undefined;
737 }
738
739 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
740
741 if (indentStr === '') { return this; } // noop
742
743 options = options || {};
744
745 // Process exclusion ranges
746 var isExcluded = {};
747
748 if (options.exclude) {
749 var exclusions =
750 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
751 exclusions.forEach(function (exclusion) {
752 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
753 isExcluded[i] = true;
754 }
755 });
756 }
757
758 var shouldIndentNextCharacter = options.indentStart !== false;
759 var replacer = function (match) {
760 if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
761 shouldIndentNextCharacter = true;
762 return match;
763 };
764
765 this.intro = this.intro.replace(pattern, replacer);
766
767 var charIndex = 0;
768 var chunk = this.firstChunk;
769
770 while (chunk) {
771 var end = chunk.end;
772
773 if (chunk.edited) {
774 if (!isExcluded[charIndex]) {
775 chunk.content = chunk.content.replace(pattern, replacer);
776
777 if (chunk.content.length) {
778 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
779 }
780 }
781 } else {
782 charIndex = chunk.start;
783
784 while (charIndex < end) {
785 if (!isExcluded[charIndex]) {
786 var char = this.original[charIndex];
787
788 if (char === '\n') {
789 shouldIndentNextCharacter = true;
790 } else if (char !== '\r' && shouldIndentNextCharacter) {
791 shouldIndentNextCharacter = false;
792
793 if (charIndex === chunk.start) {
794 chunk.prependRight(indentStr);
795 } else {
796 this._splitChunk(chunk, charIndex);
797 chunk = chunk.next;
798 chunk.prependRight(indentStr);
799 }
800 }
801 }
802
803 charIndex += 1;
804 }
805 }
806
807 charIndex = chunk.end;
808 chunk = chunk.next;
809 }
810
811 this.outro = this.outro.replace(pattern, replacer);
812
813 return this;
814};
815
816MagicString.prototype.insert = function insert () {
817 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
818};
819
820MagicString.prototype.insertLeft = function insertLeft (index, content) {
821 if (!warned.insertLeft) {
822 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
823 warned.insertLeft = true;
824 }
825
826 return this.appendLeft(index, content);
827};
828
829MagicString.prototype.insertRight = function insertRight (index, content) {
830 if (!warned.insertRight) {
831 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
832 warned.insertRight = true;
833 }
834
835 return this.prependRight(index, content);
836};
837
838MagicString.prototype.move = function move (start, end, index) {
839 if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
840
841 this._split(start);
842 this._split(end);
843 this._split(index);
844
845 var first = this.byStart[start];
846 var last = this.byEnd[end];
847
848 var oldLeft = first.previous;
849 var oldRight = last.next;
850
851 var newRight = this.byStart[index];
852 if (!newRight && last === this.lastChunk) { return this; }
853 var newLeft = newRight ? newRight.previous : this.lastChunk;
854
855 if (oldLeft) { oldLeft.next = oldRight; }
856 if (oldRight) { oldRight.previous = oldLeft; }
857
858 if (newLeft) { newLeft.next = first; }
859 if (newRight) { newRight.previous = last; }
860
861 if (!first.previous) { this.firstChunk = last.next; }
862 if (!last.next) {
863 this.lastChunk = first.previous;
864 this.lastChunk.next = null;
865 }
866
867 first.previous = newLeft;
868 last.next = newRight || null;
869
870 if (!newLeft) { this.firstChunk = first; }
871 if (!newRight) { this.lastChunk = last; }
872 return this;
873};
874
875MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
876 if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
877
878 while (start < 0) { start += this.original.length; }
879 while (end < 0) { end += this.original.length; }
880
881 if (end > this.original.length) { throw new Error('end is out of bounds'); }
882 if (start === end)
883 { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
884
885 this._split(start);
886 this._split(end);
887
888 if (options === true) {
889 if (!warned.storeName) {
890 console.warn('The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string'); // eslint-disable-line no-console
891 warned.storeName = true;
892 }
893
894 options = { storeName: true };
895 }
896 var storeName = options !== undefined ? options.storeName : false;
897 var contentOnly = options !== undefined ? options.contentOnly : false;
898
899 if (storeName) {
900 var original = this.original.slice(start, end);
901 this.storedNames[original] = true;
902 }
903
904 var first = this.byStart[start];
905 var last = this.byEnd[end];
906
907 if (first) {
908 if (end > first.end && first.next !== this.byStart[first.end]) {
909 throw new Error('Cannot overwrite across a split point');
910 }
911
912 first.edit(content, storeName, contentOnly);
913
914 if (first !== last) {
915 var chunk = first.next;
916 while (chunk !== last) {
917 chunk.edit('', false);
918 chunk = chunk.next;
919 }
920
921 chunk.edit('', false);
922 }
923 } else {
924 // must be inserting at the end
925 var newChunk = new Chunk(start, end, '').edit(content, storeName);
926
927 // TODO last chunk in the array may not be the last chunk, if it's moved...
928 last.next = newChunk;
929 newChunk.previous = last;
930 }
931 return this;
932};
933
934MagicString.prototype.prepend = function prepend (content) {
935 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
936
937 this.intro = content + this.intro;
938 return this;
939};
940
941MagicString.prototype.prependLeft = function prependLeft (index, content) {
942 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
943
944 this._split(index);
945
946 var chunk = this.byEnd[index];
947
948 if (chunk) {
949 chunk.prependLeft(content);
950 } else {
951 this.intro = content + this.intro;
952 }
953 return this;
954};
955
956MagicString.prototype.prependRight = function prependRight (index, content) {
957 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
958
959 this._split(index);
960
961 var chunk = this.byStart[index];
962
963 if (chunk) {
964 chunk.prependRight(content);
965 } else {
966 this.outro = content + this.outro;
967 }
968 return this;
969};
970
971MagicString.prototype.remove = function remove (start, end) {
972 while (start < 0) { start += this.original.length; }
973 while (end < 0) { end += this.original.length; }
974
975 if (start === end) { return this; }
976
977 if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
978 if (start > end) { throw new Error('end must be greater than start'); }
979
980 this._split(start);
981 this._split(end);
982
983 var chunk = this.byStart[start];
984
985 while (chunk) {
986 chunk.intro = '';
987 chunk.outro = '';
988 chunk.edit('');
989
990 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
991 }
992 return this;
993};
994
995MagicString.prototype.lastChar = function lastChar () {
996 if (this.outro.length)
997 { return this.outro[this.outro.length - 1]; }
998 var chunk = this.lastChunk;
999 do {
1000 if (chunk.outro.length)
1001 { return chunk.outro[chunk.outro.length - 1]; }
1002 if (chunk.content.length)
1003 { return chunk.content[chunk.content.length - 1]; }
1004 if (chunk.intro.length)
1005 { return chunk.intro[chunk.intro.length - 1]; }
1006 } while (chunk = chunk.previous);
1007 if (this.intro.length)
1008 { return this.intro[this.intro.length - 1]; }
1009 return '';
1010};
1011
1012MagicString.prototype.lastLine = function lastLine () {
1013 var lineIndex = this.outro.lastIndexOf(n);
1014 if (lineIndex !== -1)
1015 { return this.outro.substr(lineIndex + 1); }
1016 var lineStr = this.outro;
1017 var chunk = this.lastChunk;
1018 do {
1019 if (chunk.outro.length > 0) {
1020 lineIndex = chunk.outro.lastIndexOf(n);
1021 if (lineIndex !== -1)
1022 { return chunk.outro.substr(lineIndex + 1) + lineStr; }
1023 lineStr = chunk.outro + lineStr;
1024 }
1025
1026 if (chunk.content.length > 0) {
1027 lineIndex = chunk.content.lastIndexOf(n);
1028 if (lineIndex !== -1)
1029 { return chunk.content.substr(lineIndex + 1) + lineStr; }
1030 lineStr = chunk.content + lineStr;
1031 }
1032
1033 if (chunk.intro.length > 0) {
1034 lineIndex = chunk.intro.lastIndexOf(n);
1035 if (lineIndex !== -1)
1036 { return chunk.intro.substr(lineIndex + 1) + lineStr; }
1037 lineStr = chunk.intro + lineStr;
1038 }
1039 } while (chunk = chunk.previous);
1040 lineIndex = this.intro.lastIndexOf(n);
1041 if (lineIndex !== -1)
1042 { return this.intro.substr(lineIndex + 1) + lineStr; }
1043 return this.intro + lineStr;
1044};
1045
1046MagicString.prototype.slice = function slice (start, end) {
1047 if ( start === void 0 ) start = 0;
1048 if ( end === void 0 ) end = this.original.length;
1049
1050 while (start < 0) { start += this.original.length; }
1051 while (end < 0) { end += this.original.length; }
1052
1053 var result = '';
1054
1055 // find start chunk
1056 var chunk = this.firstChunk;
1057 while (chunk && (chunk.start > start || chunk.end <= start)) {
1058 // found end chunk before start
1059 if (chunk.start < end && chunk.end >= end) {
1060 return result;
1061 }
1062
1063 chunk = chunk.next;
1064 }
1065
1066 if (chunk && chunk.edited && chunk.start !== start)
1067 { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
1068
1069 var startChunk = chunk;
1070 while (chunk) {
1071 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1072 result += chunk.intro;
1073 }
1074
1075 var containsEnd = chunk.start < end && chunk.end >= end;
1076 if (containsEnd && chunk.edited && chunk.end !== end)
1077 { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
1078
1079 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1080 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1081
1082 result += chunk.content.slice(sliceStart, sliceEnd);
1083
1084 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1085 result += chunk.outro;
1086 }
1087
1088 if (containsEnd) {
1089 break;
1090 }
1091
1092 chunk = chunk.next;
1093 }
1094
1095 return result;
1096};
1097
1098// TODO deprecate this? not really very useful
1099MagicString.prototype.snip = function snip (start, end) {
1100 var clone = this.clone();
1101 clone.remove(0, start);
1102 clone.remove(end, clone.original.length);
1103
1104 return clone;
1105};
1106
1107MagicString.prototype._split = function _split (index) {
1108 if (this.byStart[index] || this.byEnd[index]) { return; }
1109
1110 var chunk = this.lastSearchedChunk;
1111 var searchForward = index > chunk.end;
1112
1113 while (chunk) {
1114 if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
1115
1116 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1117 }
1118};
1119
1120MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
1121 if (chunk.edited && chunk.content.length) {
1122 // zero-length edited chunks are a special case (overlapping replacements)
1123 var loc = getLocator(this.original)(index);
1124 throw new Error(
1125 ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
1126 );
1127 }
1128
1129 var newChunk = chunk.split(index);
1130
1131 this.byEnd[index] = chunk;
1132 this.byStart[index] = newChunk;
1133 this.byEnd[newChunk.end] = newChunk;
1134
1135 if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
1136
1137 this.lastSearchedChunk = chunk;
1138 return true;
1139};
1140
1141MagicString.prototype.toString = function toString () {
1142 var str = this.intro;
1143
1144 var chunk = this.firstChunk;
1145 while (chunk) {
1146 str += chunk.toString();
1147 chunk = chunk.next;
1148 }
1149
1150 return str + this.outro;
1151};
1152
1153MagicString.prototype.isEmpty = function isEmpty () {
1154 var chunk = this.firstChunk;
1155 do {
1156 if (chunk.intro.length && chunk.intro.trim() ||
1157 chunk.content.length && chunk.content.trim() ||
1158 chunk.outro.length && chunk.outro.trim())
1159 { return false; }
1160 } while (chunk = chunk.next);
1161 return true;
1162};
1163
1164MagicString.prototype.length = function length () {
1165 var chunk = this.firstChunk;
1166 var length = 0;
1167 do {
1168 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1169 } while (chunk = chunk.next);
1170 return length;
1171};
1172
1173MagicString.prototype.trimLines = function trimLines () {
1174 return this.trim('[\\r\\n]');
1175};
1176
1177MagicString.prototype.trim = function trim (charType) {
1178 return this.trimStart(charType).trimEnd(charType);
1179};
1180
1181MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
1182 var rx = new RegExp((charType || '\\s') + '+$');
1183
1184 this.outro = this.outro.replace(rx, '');
1185 if (this.outro.length) { return true; }
1186
1187 var chunk = this.lastChunk;
1188
1189 do {
1190 var end = chunk.end;
1191 var aborted = chunk.trimEnd(rx);
1192
1193 // if chunk was trimmed, we have a new lastChunk
1194 if (chunk.end !== end) {
1195 if (this.lastChunk === chunk) {
1196 this.lastChunk = chunk.next;
1197 }
1198
1199 this.byEnd[chunk.end] = chunk;
1200 this.byStart[chunk.next.start] = chunk.next;
1201 this.byEnd[chunk.next.end] = chunk.next;
1202 }
1203
1204 if (aborted) { return true; }
1205 chunk = chunk.previous;
1206 } while (chunk);
1207
1208 return false;
1209};
1210
1211MagicString.prototype.trimEnd = function trimEnd (charType) {
1212 this.trimEndAborted(charType);
1213 return this;
1214};
1215MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
1216 var rx = new RegExp('^' + (charType || '\\s') + '+');
1217
1218 this.intro = this.intro.replace(rx, '');
1219 if (this.intro.length) { return true; }
1220
1221 var chunk = this.firstChunk;
1222
1223 do {
1224 var end = chunk.end;
1225 var aborted = chunk.trimStart(rx);
1226
1227 if (chunk.end !== end) {
1228 // special case...
1229 if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
1230
1231 this.byEnd[chunk.end] = chunk;
1232 this.byStart[chunk.next.start] = chunk.next;
1233 this.byEnd[chunk.next.end] = chunk.next;
1234 }
1235
1236 if (aborted) { return true; }
1237 chunk = chunk.next;
1238 } while (chunk);
1239
1240 return false;
1241};
1242
1243MagicString.prototype.trimStart = function trimStart (charType) {
1244 this.trimStartAborted(charType);
1245 return this;
1246};
1247
1248var hasOwnProp = Object.prototype.hasOwnProperty;
1249
1250var Bundle = function Bundle(options) {
1251 if ( options === void 0 ) options = {};
1252
1253 this.intro = options.intro || '';
1254 this.separator = options.separator !== undefined ? options.separator : '\n';
1255 this.sources = [];
1256 this.uniqueSources = [];
1257 this.uniqueSourceIndexByFilename = {};
1258};
1259
1260Bundle.prototype.addSource = function addSource (source) {
1261 if (source instanceof MagicString) {
1262 return this.addSource({
1263 content: source,
1264 filename: source.filename,
1265 separator: this.separator
1266 });
1267 }
1268
1269 if (!isObject(source) || !source.content) {
1270 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
1271 }
1272
1273 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
1274 if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
1275 });
1276
1277 if (source.separator === undefined) {
1278 // TODO there's a bunch of this sort of thing, needs cleaning up
1279 source.separator = this.separator;
1280 }
1281
1282 if (source.filename) {
1283 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1284 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1285 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1286 } else {
1287 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1288 if (source.content.original !== uniqueSource.content) {
1289 throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
1290 }
1291 }
1292 }
1293
1294 this.sources.push(source);
1295 return this;
1296};
1297
1298Bundle.prototype.append = function append (str, options) {
1299 this.addSource({
1300 content: new MagicString(str),
1301 separator: (options && options.separator) || ''
1302 });
1303
1304 return this;
1305};
1306
1307Bundle.prototype.clone = function clone () {
1308 var bundle = new Bundle({
1309 intro: this.intro,
1310 separator: this.separator
1311 });
1312
1313 this.sources.forEach(function (source) {
1314 bundle.addSource({
1315 filename: source.filename,
1316 content: source.content.clone(),
1317 separator: source.separator
1318 });
1319 });
1320
1321 return bundle;
1322};
1323
1324Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
1325 var this$1 = this;
1326 if ( options === void 0 ) options = {};
1327
1328 var names = [];
1329 this.sources.forEach(function (source) {
1330 Object.keys(source.content.storedNames).forEach(function (name) {
1331 if (!~names.indexOf(name)) { names.push(name); }
1332 });
1333 });
1334
1335 var mappings = new Mappings(options.hires);
1336
1337 if (this.intro) {
1338 mappings.advance(this.intro);
1339 }
1340
1341 this.sources.forEach(function (source, i) {
1342 if (i > 0) {
1343 mappings.advance(this$1.separator);
1344 }
1345
1346 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
1347 var magicString = source.content;
1348 var locate = getLocator(magicString.original);
1349
1350 if (magicString.intro) {
1351 mappings.advance(magicString.intro);
1352 }
1353
1354 magicString.firstChunk.eachNext(function (chunk) {
1355 var loc = locate(chunk.start);
1356
1357 if (chunk.intro.length) { mappings.advance(chunk.intro); }
1358
1359 if (source.filename) {
1360 if (chunk.edited) {
1361 mappings.addEdit(
1362 sourceIndex,
1363 chunk.content,
1364 loc,
1365 chunk.storeName ? names.indexOf(chunk.original) : -1
1366 );
1367 } else {
1368 mappings.addUneditedChunk(
1369 sourceIndex,
1370 chunk,
1371 magicString.original,
1372 loc,
1373 magicString.sourcemapLocations
1374 );
1375 }
1376 } else {
1377 mappings.advance(chunk.content);
1378 }
1379
1380 if (chunk.outro.length) { mappings.advance(chunk.outro); }
1381 });
1382
1383 if (magicString.outro) {
1384 mappings.advance(magicString.outro);
1385 }
1386 });
1387
1388 return {
1389 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1390 sources: this.uniqueSources.map(function (source) {
1391 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
1392 }),
1393 sourcesContent: this.uniqueSources.map(function (source) {
1394 return options.includeContent ? source.content : null;
1395 }),
1396 names: names,
1397 mappings: mappings.raw
1398 };
1399};
1400
1401Bundle.prototype.generateMap = function generateMap (options) {
1402 return new SourceMap(this.generateDecodedMap(options));
1403};
1404
1405Bundle.prototype.getIndentString = function getIndentString () {
1406 var indentStringCounts = {};
1407
1408 this.sources.forEach(function (source) {
1409 var indentStr = source.content.indentStr;
1410
1411 if (indentStr === null) { return; }
1412
1413 if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
1414 indentStringCounts[indentStr] += 1;
1415 });
1416
1417 return (
1418 Object.keys(indentStringCounts).sort(function (a, b) {
1419 return indentStringCounts[a] - indentStringCounts[b];
1420 })[0] || '\t'
1421 );
1422};
1423
1424Bundle.prototype.indent = function indent (indentStr) {
1425 var this$1 = this;
1426
1427 if (!arguments.length) {
1428 indentStr = this.getIndentString();
1429 }
1430
1431 if (indentStr === '') { return this; } // noop
1432
1433 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
1434
1435 this.sources.forEach(function (source, i) {
1436 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1437 var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
1438
1439 source.content.indent(indentStr, {
1440 exclude: source.indentExclusionRanges,
1441 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1442 });
1443
1444 trailingNewline = source.content.lastChar() === '\n';
1445 });
1446
1447 if (this.intro) {
1448 this.intro =
1449 indentStr +
1450 this.intro.replace(/^[^\n]/gm, function (match, index) {
1451 return index > 0 ? indentStr + match : match;
1452 });
1453 }
1454
1455 return this;
1456};
1457
1458Bundle.prototype.prepend = function prepend (str) {
1459 this.intro = str + this.intro;
1460 return this;
1461};
1462
1463Bundle.prototype.toString = function toString () {
1464 var this$1 = this;
1465
1466 var body = this.sources
1467 .map(function (source, i) {
1468 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1469 var str = (i > 0 ? separator : '') + source.content.toString();
1470
1471 return str;
1472 })
1473 .join('');
1474
1475 return this.intro + body;
1476};
1477
1478Bundle.prototype.isEmpty = function isEmpty () {
1479 if (this.intro.length && this.intro.trim())
1480 { return false; }
1481 if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
1482 { return false; }
1483 return true;
1484};
1485
1486Bundle.prototype.length = function length () {
1487 return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
1488};
1489
1490Bundle.prototype.trimLines = function trimLines () {
1491 return this.trim('[\\r\\n]');
1492};
1493
1494Bundle.prototype.trim = function trim (charType) {
1495 return this.trimStart(charType).trimEnd(charType);
1496};
1497
1498Bundle.prototype.trimStart = function trimStart (charType) {
1499 var rx = new RegExp('^' + (charType || '\\s') + '+');
1500 this.intro = this.intro.replace(rx, '');
1501
1502 if (!this.intro) {
1503 var source;
1504 var i = 0;
1505
1506 do {
1507 source = this.sources[i++];
1508 if (!source) {
1509 break;
1510 }
1511 } while (!source.content.trimStartAborted(charType));
1512 }
1513
1514 return this;
1515};
1516
1517Bundle.prototype.trimEnd = function trimEnd (charType) {
1518 var rx = new RegExp((charType || '\\s') + '+$');
1519
1520 var source;
1521 var i = this.sources.length - 1;
1522
1523 do {
1524 source = this.sources[i--];
1525 if (!source) {
1526 this.intro = this.intro.replace(rx, '');
1527 break;
1528 }
1529 } while (!source.content.trimEndAborted(charType));
1530
1531 return this;
1532};
1533
1534function relative(from, to) {
1535 const fromParts = from.split(/[/\\]/).filter(Boolean);
1536 const toParts = to.split(/[/\\]/).filter(Boolean);
1537 if (fromParts[0] === '.')
1538 fromParts.shift();
1539 if (toParts[0] === '.')
1540 toParts.shift();
1541 while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
1542 fromParts.shift();
1543 toParts.shift();
1544 }
1545 while (toParts[0] === '..' && fromParts.length > 0) {
1546 toParts.shift();
1547 fromParts.pop();
1548 }
1549 while (fromParts.pop()) {
1550 toParts.unshift('..');
1551 }
1552 return toParts.join('/');
1553}
1554
1555const ArrowFunctionExpression = 'ArrowFunctionExpression';
1556const BlockStatement = 'BlockStatement';
1557const CallExpression = 'CallExpression';
1558const ExpressionStatement = 'ExpressionStatement';
1559const FunctionExpression = 'FunctionExpression';
1560const Identifier = 'Identifier';
1561const ImportDefaultSpecifier = 'ImportDefaultSpecifier';
1562const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
1563const Program = 'Program';
1564const Property = 'Property';
1565const ReturnStatement = 'ReturnStatement';
1566
1567function treeshakeNode(node, code, start, end) {
1568 code.remove(start, end);
1569 if (node.annotations) {
1570 for (const annotation of node.annotations) {
1571 if (annotation.start < start) {
1572 code.remove(annotation.start, annotation.end);
1573 }
1574 else {
1575 return;
1576 }
1577 }
1578 }
1579}
1580function removeAnnotations(node, code) {
1581 if (!node.annotations && node.parent.type === ExpressionStatement) {
1582 node = node.parent;
1583 }
1584 if (node.annotations) {
1585 for (const annotation of node.annotations) {
1586 code.remove(annotation.start, annotation.end);
1587 }
1588 }
1589}
1590
1591const NO_SEMICOLON = { isNoStatement: true };
1592// This assumes there are only white-space and comments between start and the string we are looking for
1593function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
1594 let searchPos, charCodeAfterSlash;
1595 searchPos = code.indexOf(searchString, start);
1596 while (true) {
1597 start = code.indexOf('/', start);
1598 if (start === -1 || start >= searchPos)
1599 return searchPos;
1600 charCodeAfterSlash = code.charCodeAt(++start);
1601 ++start;
1602 // With our assumption, '/' always starts a comment. Determine comment type:
1603 start =
1604 charCodeAfterSlash === 47 /*"/"*/
1605 ? code.indexOf('\n', start) + 1
1606 : code.indexOf('*/', start) + 2;
1607 if (start > searchPos) {
1608 searchPos = code.indexOf(searchString, start);
1609 }
1610 }
1611}
1612const WHITESPACE = /\s/;
1613function findNonWhiteSpace(code, index) {
1614 while (index < code.length && WHITESPACE.test(code[index]))
1615 index++;
1616 return index;
1617}
1618// This assumes "code" only contains white-space and comments
1619// Returns position of line-comment if applicable
1620function findFirstLineBreakOutsideComment(code) {
1621 let lineBreakPos, charCodeAfterSlash, start = 0;
1622 lineBreakPos = code.indexOf('\n', start);
1623 while (true) {
1624 start = code.indexOf('/', start);
1625 if (start === -1 || start > lineBreakPos)
1626 return [lineBreakPos, lineBreakPos + 1];
1627 // With our assumption, '/' always starts a comment. Determine comment type:
1628 charCodeAfterSlash = code.charCodeAt(start + 1);
1629 if (charCodeAfterSlash === 47 /*"/"*/)
1630 return [start, lineBreakPos + 1];
1631 start = code.indexOf('*/', start + 3) + 2;
1632 if (start > lineBreakPos) {
1633 lineBreakPos = code.indexOf('\n', start);
1634 }
1635 }
1636}
1637function renderStatementList(statements, code, start, end, options) {
1638 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
1639 let nextNode = statements[0];
1640 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
1641 if (nextNodeNeedsBoundaries) {
1642 nextNodeStart =
1643 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
1644 }
1645 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
1646 currentNode = nextNode;
1647 currentNodeStart = nextNodeStart;
1648 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
1649 nextNode = statements[nextIndex];
1650 nextNodeNeedsBoundaries =
1651 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
1652 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
1653 nextNodeStart =
1654 currentNode.end +
1655 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
1656 if (currentNode.included) {
1657 currentNodeNeedsBoundaries
1658 ? currentNode.render(code, options, {
1659 end: nextNodeStart,
1660 start: currentNodeStart
1661 })
1662 : currentNode.render(code, options);
1663 }
1664 else {
1665 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
1666 }
1667 }
1668 else {
1669 currentNode.render(code, options);
1670 }
1671 }
1672}
1673// This assumes that the first character is not part of the first node
1674function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
1675 const splitUpNodes = [];
1676 let node, nextNode, nextNodeStart, contentEnd, char;
1677 let separator = start - 1;
1678 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
1679 nextNode = nodes[nextIndex];
1680 if (node !== undefined) {
1681 separator =
1682 node.end +
1683 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
1684 }
1685 nextNodeStart = contentEnd =
1686 separator +
1687 1 +
1688 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
1689 while (((char = code.original.charCodeAt(nextNodeStart)),
1690 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
1691 nextNodeStart++;
1692 if (node !== undefined) {
1693 splitUpNodes.push({
1694 contentEnd,
1695 end: nextNodeStart,
1696 node,
1697 separator,
1698 start
1699 });
1700 }
1701 node = nextNode;
1702 start = nextNodeStart;
1703 }
1704 splitUpNodes.push({
1705 contentEnd: end,
1706 end,
1707 node: node,
1708 separator: null,
1709 start
1710 });
1711 return splitUpNodes;
1712}
1713// This assumes there are only white-space and comments between start and end
1714function removeLineBreaks(code, start, end) {
1715 while (true) {
1716 const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
1717 if (removeStart === -1) {
1718 break;
1719 }
1720 code.remove(start + removeStart, (start += removeEnd));
1721 }
1722}
1723
1724function getSystemExportStatement(exportedVariables, options) {
1725 const _ = options.compact ? '' : ' ';
1726 if (exportedVariables.length === 1 &&
1727 options.exportNamesByVariable.get(exportedVariables[0]).length === 1) {
1728 const variable = exportedVariables[0];
1729 return `exports('${options.exportNamesByVariable.get(variable)}',${_}${variable.getName()})`;
1730 }
1731 else {
1732 return `exports({${_}${exportedVariables
1733 .map(variable => {
1734 return options.exportNamesByVariable
1735 .get(variable)
1736 .map(exportName => `${exportName}:${_}${variable.getName()}`)
1737 .join(`,${_}`);
1738 })
1739 .join(`,${_}`)}${_}})`;
1740 }
1741}
1742function getSystemExportFunctionLeft(exportedVariables, setFromExpression, options) {
1743 const _ = options.compact ? '' : ' ';
1744 const s = options.compact ? '' : ';';
1745 return `function${_}(v)${_}{${_}return exports({${_}${exportedVariables
1746 .map(variable => {
1747 return options.exportNamesByVariable
1748 .get(variable)
1749 .map(exportName => `${exportName}:${_}${setFromExpression ? variable.getName() : 'v'}`)
1750 .join(`,${_}`);
1751 })
1752 .join(`,${_}`)}${_}}),${_}v${s}${_}}(`;
1753}
1754
1755const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
1756const base = 64;
1757function toBase64(num) {
1758 let outStr = '';
1759 do {
1760 const curDigit = num % base;
1761 num = Math.floor(num / base);
1762 outStr = chars$1[curDigit] + outStr;
1763 } while (num !== 0);
1764 return outStr;
1765}
1766
1767const RESERVED_NAMES = {
1768 // @ts-ignore
1769 __proto__: null,
1770 await: true,
1771 break: true,
1772 case: true,
1773 catch: true,
1774 class: true,
1775 const: true,
1776 continue: true,
1777 debugger: true,
1778 default: true,
1779 delete: true,
1780 do: true,
1781 else: true,
1782 enum: true,
1783 eval: true,
1784 export: true,
1785 extends: true,
1786 false: true,
1787 finally: true,
1788 for: true,
1789 function: true,
1790 if: true,
1791 implements: true,
1792 import: true,
1793 in: true,
1794 instanceof: true,
1795 interface: true,
1796 let: true,
1797 new: true,
1798 null: true,
1799 package: true,
1800 private: true,
1801 protected: true,
1802 public: true,
1803 return: true,
1804 static: true,
1805 super: true,
1806 switch: true,
1807 this: true,
1808 throw: true,
1809 true: true,
1810 try: true,
1811 typeof: true,
1812 undefined: true,
1813 var: true,
1814 void: true,
1815 while: true,
1816 with: true,
1817 yield: true
1818};
1819
1820function getSafeName(baseName, usedNames) {
1821 let safeName = baseName;
1822 let count = 1;
1823 while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
1824 safeName = `${baseName}$${toBase64(count++)}`;
1825 }
1826 usedNames.add(safeName);
1827 return safeName;
1828}
1829
1830const NO_ARGS = [];
1831
1832function getOrCreate(map, key, init) {
1833 const existing = map.get(key);
1834 if (existing) {
1835 return existing;
1836 }
1837 const value = init();
1838 map.set(key, value);
1839 return value;
1840}
1841
1842const UnknownKey = Symbol('Unknown Key');
1843const EMPTY_PATH = [];
1844const UNKNOWN_PATH = [UnknownKey];
1845const EntitiesKey = Symbol('Entities');
1846class PathTracker {
1847 constructor() {
1848 this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } });
1849 }
1850 getEntities(path) {
1851 let currentPaths = this.entityPaths;
1852 for (const pathSegment of path) {
1853 currentPaths = currentPaths[pathSegment] =
1854 currentPaths[pathSegment] ||
1855 Object.create(null, { [EntitiesKey]: { value: new Set() } });
1856 }
1857 return currentPaths[EntitiesKey];
1858 }
1859}
1860const SHARED_RECURSION_TRACKER = new PathTracker();
1861class DiscriminatedPathTracker {
1862 constructor() {
1863 this.entityPaths = Object.create(null, {
1864 [EntitiesKey]: { value: new Map() }
1865 });
1866 }
1867 getEntities(path, discriminator) {
1868 let currentPaths = this.entityPaths;
1869 for (const pathSegment of path) {
1870 currentPaths = currentPaths[pathSegment] =
1871 currentPaths[pathSegment] ||
1872 Object.create(null, { [EntitiesKey]: { value: new Map() } });
1873 }
1874 return getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
1875 }
1876}
1877
1878function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
1879 return Object.create(inheritedDescriptions, memberDescriptions);
1880}
1881const UnknownValue = Symbol('Unknown Value');
1882const UNKNOWN_EXPRESSION = {
1883 deoptimizePath: () => { },
1884 getLiteralValueAtPath: () => UnknownValue,
1885 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
1886 hasEffectsWhenAccessedAtPath: path => path.length > 0,
1887 hasEffectsWhenAssignedAtPath: path => path.length > 0,
1888 hasEffectsWhenCalledAtPath: () => true,
1889 include: () => { },
1890 includeCallArguments(context, args) {
1891 for (const arg of args) {
1892 arg.include(context, false);
1893 }
1894 },
1895 included: true,
1896 toString: () => '[[UNKNOWN]]'
1897};
1898const UNDEFINED_EXPRESSION = {
1899 deoptimizePath: () => { },
1900 getLiteralValueAtPath: () => undefined,
1901 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
1902 hasEffectsWhenAccessedAtPath: path => path.length > 0,
1903 hasEffectsWhenAssignedAtPath: path => path.length > 0,
1904 hasEffectsWhenCalledAtPath: () => true,
1905 include: () => { },
1906 includeCallArguments() { },
1907 included: true,
1908 toString: () => 'undefined'
1909};
1910const returnsUnknown = {
1911 value: {
1912 callsArgs: null,
1913 mutatesSelf: false,
1914 returns: null,
1915 returnsPrimitive: UNKNOWN_EXPRESSION
1916 }
1917};
1918const mutatesSelfReturnsUnknown = {
1919 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
1920};
1921const callsArgReturnsUnknown = {
1922 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
1923};
1924class UnknownArrayExpression {
1925 constructor() {
1926 this.included = false;
1927 }
1928 deoptimizePath() { }
1929 getLiteralValueAtPath() {
1930 return UnknownValue;
1931 }
1932 getReturnExpressionWhenCalledAtPath(path) {
1933 if (path.length === 1) {
1934 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
1935 }
1936 return UNKNOWN_EXPRESSION;
1937 }
1938 hasEffectsWhenAccessedAtPath(path) {
1939 return path.length > 1;
1940 }
1941 hasEffectsWhenAssignedAtPath(path) {
1942 return path.length > 1;
1943 }
1944 hasEffectsWhenCalledAtPath(path, callOptions, context) {
1945 if (path.length === 1) {
1946 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
1947 }
1948 return true;
1949 }
1950 include() {
1951 this.included = true;
1952 }
1953 includeCallArguments(context, args) {
1954 for (const arg of args) {
1955 arg.include(context, false);
1956 }
1957 }
1958 toString() {
1959 return '[[UNKNOWN ARRAY]]';
1960 }
1961}
1962const returnsArray = {
1963 value: {
1964 callsArgs: null,
1965 mutatesSelf: false,
1966 returns: UnknownArrayExpression,
1967 returnsPrimitive: null
1968 }
1969};
1970const mutatesSelfReturnsArray = {
1971 value: {
1972 callsArgs: null,
1973 mutatesSelf: true,
1974 returns: UnknownArrayExpression,
1975 returnsPrimitive: null
1976 }
1977};
1978const callsArgReturnsArray = {
1979 value: {
1980 callsArgs: [0],
1981 mutatesSelf: false,
1982 returns: UnknownArrayExpression,
1983 returnsPrimitive: null
1984 }
1985};
1986const callsArgMutatesSelfReturnsArray = {
1987 value: {
1988 callsArgs: [0],
1989 mutatesSelf: true,
1990 returns: UnknownArrayExpression,
1991 returnsPrimitive: null
1992 }
1993};
1994const UNKNOWN_LITERAL_BOOLEAN = {
1995 deoptimizePath: () => { },
1996 getLiteralValueAtPath: () => UnknownValue,
1997 getReturnExpressionWhenCalledAtPath: path => {
1998 if (path.length === 1) {
1999 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
2000 }
2001 return UNKNOWN_EXPRESSION;
2002 },
2003 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2004 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2005 hasEffectsWhenCalledAtPath: path => {
2006 if (path.length === 1) {
2007 const subPath = path[0];
2008 return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
2009 }
2010 return true;
2011 },
2012 include: () => { },
2013 includeCallArguments(context, args) {
2014 for (const arg of args) {
2015 arg.include(context, false);
2016 }
2017 },
2018 included: true,
2019 toString: () => '[[UNKNOWN BOOLEAN]]'
2020};
2021const returnsBoolean = {
2022 value: {
2023 callsArgs: null,
2024 mutatesSelf: false,
2025 returns: null,
2026 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2027 }
2028};
2029const callsArgReturnsBoolean = {
2030 value: {
2031 callsArgs: [0],
2032 mutatesSelf: false,
2033 returns: null,
2034 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2035 }
2036};
2037const UNKNOWN_LITERAL_NUMBER = {
2038 deoptimizePath: () => { },
2039 getLiteralValueAtPath: () => UnknownValue,
2040 getReturnExpressionWhenCalledAtPath: path => {
2041 if (path.length === 1) {
2042 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
2043 }
2044 return UNKNOWN_EXPRESSION;
2045 },
2046 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2047 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2048 hasEffectsWhenCalledAtPath: path => {
2049 if (path.length === 1) {
2050 const subPath = path[0];
2051 return typeof subPath !== 'string' || !literalNumberMembers[subPath];
2052 }
2053 return true;
2054 },
2055 include: () => { },
2056 includeCallArguments(context, args) {
2057 for (const arg of args) {
2058 arg.include(context, false);
2059 }
2060 },
2061 included: true,
2062 toString: () => '[[UNKNOWN NUMBER]]'
2063};
2064const returnsNumber = {
2065 value: {
2066 callsArgs: null,
2067 mutatesSelf: false,
2068 returns: null,
2069 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2070 }
2071};
2072const mutatesSelfReturnsNumber = {
2073 value: {
2074 callsArgs: null,
2075 mutatesSelf: true,
2076 returns: null,
2077 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2078 }
2079};
2080const callsArgReturnsNumber = {
2081 value: {
2082 callsArgs: [0],
2083 mutatesSelf: false,
2084 returns: null,
2085 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2086 }
2087};
2088const UNKNOWN_LITERAL_STRING = {
2089 deoptimizePath: () => { },
2090 getLiteralValueAtPath: () => UnknownValue,
2091 getReturnExpressionWhenCalledAtPath: path => {
2092 if (path.length === 1) {
2093 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
2094 }
2095 return UNKNOWN_EXPRESSION;
2096 },
2097 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2098 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2099 hasEffectsWhenCalledAtPath: (path, callOptions, context) => {
2100 if (path.length === 1) {
2101 return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context);
2102 }
2103 return true;
2104 },
2105 include: () => { },
2106 includeCallArguments(context, args) {
2107 for (const arg of args) {
2108 arg.include(context, false);
2109 }
2110 },
2111 included: true,
2112 toString: () => '[[UNKNOWN STRING]]'
2113};
2114const returnsString = {
2115 value: {
2116 callsArgs: null,
2117 mutatesSelf: false,
2118 returns: null,
2119 returnsPrimitive: UNKNOWN_LITERAL_STRING
2120 }
2121};
2122class UnknownObjectExpression {
2123 constructor() {
2124 this.included = false;
2125 }
2126 deoptimizePath() { }
2127 getLiteralValueAtPath() {
2128 return UnknownValue;
2129 }
2130 getReturnExpressionWhenCalledAtPath(path) {
2131 if (path.length === 1) {
2132 return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
2133 }
2134 return UNKNOWN_EXPRESSION;
2135 }
2136 hasEffectsWhenAccessedAtPath(path) {
2137 return path.length > 1;
2138 }
2139 hasEffectsWhenAssignedAtPath(path) {
2140 return path.length > 1;
2141 }
2142 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2143 if (path.length === 1) {
2144 return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context);
2145 }
2146 return true;
2147 }
2148 include() {
2149 this.included = true;
2150 }
2151 includeCallArguments(context, args) {
2152 for (const arg of args) {
2153 arg.include(context, false);
2154 }
2155 }
2156 toString() {
2157 return '[[UNKNOWN OBJECT]]';
2158 }
2159}
2160const objectMembers = assembleMemberDescriptions({
2161 hasOwnProperty: returnsBoolean,
2162 isPrototypeOf: returnsBoolean,
2163 propertyIsEnumerable: returnsBoolean,
2164 toLocaleString: returnsString,
2165 toString: returnsString,
2166 valueOf: returnsUnknown
2167});
2168const arrayMembers = assembleMemberDescriptions({
2169 concat: returnsArray,
2170 copyWithin: mutatesSelfReturnsArray,
2171 every: callsArgReturnsBoolean,
2172 fill: mutatesSelfReturnsArray,
2173 filter: callsArgReturnsArray,
2174 find: callsArgReturnsUnknown,
2175 findIndex: callsArgReturnsNumber,
2176 forEach: callsArgReturnsUnknown,
2177 includes: returnsBoolean,
2178 indexOf: returnsNumber,
2179 join: returnsString,
2180 lastIndexOf: returnsNumber,
2181 map: callsArgReturnsArray,
2182 pop: mutatesSelfReturnsUnknown,
2183 push: mutatesSelfReturnsNumber,
2184 reduce: callsArgReturnsUnknown,
2185 reduceRight: callsArgReturnsUnknown,
2186 reverse: mutatesSelfReturnsArray,
2187 shift: mutatesSelfReturnsUnknown,
2188 slice: returnsArray,
2189 some: callsArgReturnsBoolean,
2190 sort: callsArgMutatesSelfReturnsArray,
2191 splice: mutatesSelfReturnsArray,
2192 unshift: mutatesSelfReturnsNumber
2193}, objectMembers);
2194const literalBooleanMembers = assembleMemberDescriptions({
2195 valueOf: returnsBoolean
2196}, objectMembers);
2197const literalNumberMembers = assembleMemberDescriptions({
2198 toExponential: returnsString,
2199 toFixed: returnsString,
2200 toLocaleString: returnsString,
2201 toPrecision: returnsString,
2202 valueOf: returnsNumber
2203}, objectMembers);
2204const literalStringMembers = assembleMemberDescriptions({
2205 charAt: returnsString,
2206 charCodeAt: returnsNumber,
2207 codePointAt: returnsNumber,
2208 concat: returnsString,
2209 endsWith: returnsBoolean,
2210 includes: returnsBoolean,
2211 indexOf: returnsNumber,
2212 lastIndexOf: returnsNumber,
2213 localeCompare: returnsNumber,
2214 match: returnsBoolean,
2215 normalize: returnsString,
2216 padEnd: returnsString,
2217 padStart: returnsString,
2218 repeat: returnsString,
2219 replace: {
2220 value: {
2221 callsArgs: [1],
2222 mutatesSelf: false,
2223 returns: null,
2224 returnsPrimitive: UNKNOWN_LITERAL_STRING
2225 }
2226 },
2227 search: returnsNumber,
2228 slice: returnsString,
2229 split: returnsArray,
2230 startsWith: returnsBoolean,
2231 substr: returnsString,
2232 substring: returnsString,
2233 toLocaleLowerCase: returnsString,
2234 toLocaleUpperCase: returnsString,
2235 toLowerCase: returnsString,
2236 toUpperCase: returnsString,
2237 trim: returnsString,
2238 valueOf: returnsString
2239}, objectMembers);
2240function getLiteralMembersForValue(value) {
2241 switch (typeof value) {
2242 case 'boolean':
2243 return literalBooleanMembers;
2244 case 'number':
2245 return literalNumberMembers;
2246 case 'string':
2247 return literalStringMembers;
2248 default:
2249 return Object.create(null);
2250 }
2251}
2252function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) {
2253 if (typeof memberName !== 'string' ||
2254 !members[memberName] ||
2255 (members[memberName].mutatesSelf && parentIncluded))
2256 return true;
2257 if (!members[memberName].callsArgs)
2258 return false;
2259 for (const argIndex of members[memberName].callsArgs) {
2260 if (callOptions.args[argIndex] &&
2261 callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
2262 args: NO_ARGS,
2263 withNew: false
2264 }, context))
2265 return true;
2266 }
2267 return false;
2268}
2269function getMemberReturnExpressionWhenCalled(members, memberName) {
2270 if (typeof memberName !== 'string' || !members[memberName])
2271 return UNKNOWN_EXPRESSION;
2272 return members[memberName].returnsPrimitive !== null
2273 ? members[memberName].returnsPrimitive
2274 : new members[memberName].returns();
2275}
2276
2277class Variable {
2278 constructor(name) {
2279 this.alwaysRendered = false;
2280 this.included = false;
2281 this.isId = false;
2282 this.isReassigned = false;
2283 this.renderBaseName = null;
2284 this.renderName = null;
2285 this.name = name;
2286 }
2287 /**
2288 * Binds identifiers that reference this variable to this variable.
2289 * Necessary to be able to change variable names.
2290 */
2291 addReference(_identifier) { }
2292 deoptimizePath(_path) { }
2293 getBaseVariableName() {
2294 return this.renderBaseName || this.renderName || this.name;
2295 }
2296 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2297 return UnknownValue;
2298 }
2299 getName() {
2300 const name = this.renderName || this.name;
2301 return this.renderBaseName
2302 ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
2303 : name;
2304 }
2305 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
2306 return UNKNOWN_EXPRESSION;
2307 }
2308 hasEffectsWhenAccessedAtPath(path, _context) {
2309 return path.length > 0;
2310 }
2311 hasEffectsWhenAssignedAtPath(_path, _context) {
2312 return true;
2313 }
2314 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
2315 return true;
2316 }
2317 /**
2318 * Marks this variable as being part of the bundle, which is usually the case when one of
2319 * its identifiers becomes part of the bundle. Returns true if it has not been included
2320 * previously.
2321 * Once a variable is included, it should take care all its declarations are included.
2322 */
2323 include() {
2324 this.included = true;
2325 }
2326 includeCallArguments(context, args) {
2327 for (const arg of args) {
2328 arg.include(context, false);
2329 }
2330 }
2331 markCalledFromTryStatement() { }
2332 setRenderNames(baseName, name) {
2333 this.renderBaseName = baseName;
2334 this.renderName = name;
2335 }
2336}
2337
2338class ExternalVariable extends Variable {
2339 constructor(module, name) {
2340 super(name);
2341 this.module = module;
2342 this.isNamespace = name === '*';
2343 this.referenced = false;
2344 }
2345 addReference(identifier) {
2346 this.referenced = true;
2347 if (this.name === 'default' || this.name === '*') {
2348 this.module.suggestName(identifier.name);
2349 }
2350 }
2351 include() {
2352 if (!this.included) {
2353 this.included = true;
2354 this.module.used = true;
2355 }
2356 }
2357}
2358
2359const 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(' ');
2360const 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(' ');
2361const blacklisted = new Set(reservedWords.concat(builtins));
2362const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2363const startsWithDigit = (str) => /\d/.test(str[0]);
2364function isLegal(str) {
2365 if (startsWithDigit(str) || blacklisted.has(str)) {
2366 return false;
2367 }
2368 return !illegalCharacters.test(str);
2369}
2370function makeLegal(str) {
2371 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2372 if (startsWithDigit(str) || blacklisted.has(str))
2373 str = `_${str}`;
2374 return str || '_';
2375}
2376
2377class ExternalModule {
2378 constructor(options, id, moduleSideEffects, meta) {
2379 this.options = options;
2380 this.id = id;
2381 this.moduleSideEffects = moduleSideEffects;
2382 this.meta = meta;
2383 this.defaultVariableName = '';
2384 this.dynamicImporters = [];
2385 this.importers = [];
2386 this.mostCommonSuggestion = 0;
2387 this.namespaceVariableName = '';
2388 this.reexported = false;
2389 this.renderPath = undefined;
2390 this.renormalizeRenderPath = false;
2391 this.used = false;
2392 this.variableName = '';
2393 this.id = id;
2394 this.execIndex = Infinity;
2395 this.moduleSideEffects = moduleSideEffects;
2396 const parts = id.split(/[\\/]/);
2397 this.suggestedVariableName = makeLegal(parts.pop());
2398 this.nameSuggestions = Object.create(null);
2399 this.declarations = Object.create(null);
2400 this.exportedVariables = new Map();
2401 }
2402 getVariableForExportName(name) {
2403 let declaration = this.declarations[name];
2404 if (declaration)
2405 return declaration;
2406 this.declarations[name] = declaration = new ExternalVariable(this, name);
2407 this.exportedVariables.set(declaration, name);
2408 return declaration;
2409 }
2410 setRenderPath(options, inputBase) {
2411 this.renderPath =
2412 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2413 if (!this.renderPath) {
2414 if (!isAbsolute(this.id)) {
2415 this.renderPath = this.id;
2416 }
2417 else {
2418 this.renderPath = normalize(sysPath.relative(inputBase, this.id));
2419 this.renormalizeRenderPath = true;
2420 }
2421 }
2422 return this.renderPath;
2423 }
2424 suggestName(name) {
2425 if (!this.nameSuggestions[name])
2426 this.nameSuggestions[name] = 0;
2427 this.nameSuggestions[name] += 1;
2428 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
2429 this.mostCommonSuggestion = this.nameSuggestions[name];
2430 this.suggestedVariableName = name;
2431 }
2432 }
2433 warnUnusedImports() {
2434 const unused = Object.keys(this.declarations).filter(name => {
2435 if (name === '*')
2436 return false;
2437 const declaration = this.declarations[name];
2438 return !declaration.included && !this.reexported && !declaration.referenced;
2439 });
2440 if (unused.length === 0)
2441 return;
2442 const names = unused.length === 1
2443 ? `'${unused[0]}' is`
2444 : `${unused
2445 .slice(0, -1)
2446 .map(name => `'${name}'`)
2447 .join(', ')} and '${unused.slice(-1)}' are`;
2448 this.options.onwarn({
2449 code: 'UNUSED_EXTERNAL_IMPORT',
2450 message: `${names} imported from external module '${this.id}' but never used`,
2451 names: unused,
2452 source: this.id
2453 });
2454 }
2455}
2456
2457function markModuleAndImpureDependenciesAsExecuted(baseModule) {
2458 baseModule.isExecuted = true;
2459 const modules = [baseModule];
2460 const visitedModules = new Set();
2461 for (const module of modules) {
2462 for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
2463 if (!(dependency instanceof ExternalModule) &&
2464 !dependency.isExecuted &&
2465 (dependency.moduleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
2466 !visitedModules.has(dependency.id)) {
2467 dependency.isExecuted = true;
2468 visitedModules.add(dependency.id);
2469 modules.push(dependency);
2470 }
2471 }
2472 }
2473}
2474
2475const BROKEN_FLOW_NONE = 0;
2476const BROKEN_FLOW_BREAK_CONTINUE = 1;
2477const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
2478function createInclusionContext() {
2479 return {
2480 brokenFlow: BROKEN_FLOW_NONE,
2481 includedCallArguments: new Set(),
2482 includedLabels: new Set()
2483 };
2484}
2485function createHasEffectsContext() {
2486 return {
2487 accessed: new PathTracker(),
2488 assigned: new PathTracker(),
2489 brokenFlow: BROKEN_FLOW_NONE,
2490 called: new DiscriminatedPathTracker(),
2491 ignore: {
2492 breaks: false,
2493 continues: false,
2494 labels: new Set(),
2495 returnAwaitYield: false
2496 },
2497 includedLabels: new Set(),
2498 instantiated: new DiscriminatedPathTracker(),
2499 replacedVariableInits: new Map()
2500 };
2501}
2502
2503// To avoid infinite recursions
2504const MAX_PATH_DEPTH = 7;
2505class LocalVariable extends Variable {
2506 constructor(name, declarator, init, context) {
2507 super(name);
2508 this.additionalInitializers = null;
2509 this.calledFromTryStatement = false;
2510 this.expressionsToBeDeoptimized = [];
2511 this.declarations = declarator ? [declarator] : [];
2512 this.init = init;
2513 this.deoptimizationTracker = context.deoptimizationTracker;
2514 this.module = context.module;
2515 }
2516 addDeclaration(identifier, init) {
2517 this.declarations.push(identifier);
2518 if (this.additionalInitializers === null) {
2519 this.additionalInitializers = this.init === null ? [] : [this.init];
2520 this.init = UNKNOWN_EXPRESSION;
2521 this.isReassigned = true;
2522 }
2523 if (init !== null) {
2524 this.additionalInitializers.push(init);
2525 }
2526 }
2527 consolidateInitializers() {
2528 if (this.additionalInitializers !== null) {
2529 for (const initializer of this.additionalInitializers) {
2530 initializer.deoptimizePath(UNKNOWN_PATH);
2531 }
2532 this.additionalInitializers = null;
2533 }
2534 }
2535 deoptimizePath(path) {
2536 if (path.length > MAX_PATH_DEPTH || this.isReassigned)
2537 return;
2538 const trackedEntities = this.deoptimizationTracker.getEntities(path);
2539 if (trackedEntities.has(this))
2540 return;
2541 trackedEntities.add(this);
2542 if (path.length === 0) {
2543 if (!this.isReassigned) {
2544 this.isReassigned = true;
2545 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
2546 this.expressionsToBeDeoptimized = [];
2547 for (const expression of expressionsToBeDeoptimized) {
2548 expression.deoptimizeCache();
2549 }
2550 if (this.init) {
2551 this.init.deoptimizePath(UNKNOWN_PATH);
2552 }
2553 }
2554 }
2555 else if (this.init) {
2556 this.init.deoptimizePath(path);
2557 }
2558 }
2559 getLiteralValueAtPath(path, recursionTracker, origin) {
2560 if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
2561 return UnknownValue;
2562 }
2563 const trackedEntities = recursionTracker.getEntities(path);
2564 if (trackedEntities.has(this.init)) {
2565 return UnknownValue;
2566 }
2567 this.expressionsToBeDeoptimized.push(origin);
2568 trackedEntities.add(this.init);
2569 const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
2570 trackedEntities.delete(this.init);
2571 return value;
2572 }
2573 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
2574 if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
2575 return UNKNOWN_EXPRESSION;
2576 }
2577 const trackedEntities = recursionTracker.getEntities(path);
2578 if (trackedEntities.has(this.init)) {
2579 return UNKNOWN_EXPRESSION;
2580 }
2581 this.expressionsToBeDeoptimized.push(origin);
2582 trackedEntities.add(this.init);
2583 const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
2584 trackedEntities.delete(this.init);
2585 return value;
2586 }
2587 hasEffectsWhenAccessedAtPath(path, context) {
2588 if (path.length === 0)
2589 return false;
2590 if (this.isReassigned || path.length > MAX_PATH_DEPTH)
2591 return true;
2592 const trackedExpressions = context.accessed.getEntities(path);
2593 if (trackedExpressions.has(this))
2594 return false;
2595 trackedExpressions.add(this);
2596 return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
2597 }
2598 hasEffectsWhenAssignedAtPath(path, context) {
2599 if (this.included || path.length > MAX_PATH_DEPTH)
2600 return true;
2601 if (path.length === 0)
2602 return false;
2603 if (this.isReassigned)
2604 return true;
2605 const trackedExpressions = context.assigned.getEntities(path);
2606 if (trackedExpressions.has(this))
2607 return false;
2608 trackedExpressions.add(this);
2609 return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
2610 }
2611 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2612 if (path.length > MAX_PATH_DEPTH || this.isReassigned)
2613 return true;
2614 const trackedExpressions = (callOptions.withNew
2615 ? context.instantiated
2616 : context.called).getEntities(path, callOptions);
2617 if (trackedExpressions.has(this))
2618 return false;
2619 trackedExpressions.add(this);
2620 return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
2621 }
2622 include() {
2623 if (!this.included) {
2624 this.included = true;
2625 if (!this.module.isExecuted) {
2626 markModuleAndImpureDependenciesAsExecuted(this.module);
2627 }
2628 for (const declaration of this.declarations) {
2629 // If node is a default export, it can save a tree-shaking run to include the full declaration now
2630 if (!declaration.included)
2631 declaration.include(createInclusionContext(), false);
2632 let node = declaration.parent;
2633 while (!node.included) {
2634 // We do not want to properly include parents in case they are part of a dead branch
2635 // in which case .include() might pull in more dead code
2636 node.included = true;
2637 if (node.type === Program)
2638 break;
2639 node = node.parent;
2640 }
2641 }
2642 }
2643 }
2644 includeCallArguments(context, args) {
2645 if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
2646 for (const arg of args) {
2647 arg.include(context, false);
2648 }
2649 }
2650 else if (this.init) {
2651 context.includedCallArguments.add(this.init);
2652 this.init.includeCallArguments(context, args);
2653 context.includedCallArguments.delete(this.init);
2654 }
2655 }
2656 markCalledFromTryStatement() {
2657 this.calledFromTryStatement = true;
2658 }
2659}
2660
2661class Scope {
2662 constructor() {
2663 this.children = [];
2664 this.variables = new Map();
2665 }
2666 addDeclaration(identifier, context, init, _isHoisted) {
2667 const name = identifier.name;
2668 let variable = this.variables.get(name);
2669 if (variable) {
2670 variable.addDeclaration(identifier, init);
2671 }
2672 else {
2673 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
2674 this.variables.set(name, variable);
2675 }
2676 return variable;
2677 }
2678 contains(name) {
2679 return this.variables.has(name);
2680 }
2681 findVariable(_name) {
2682 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
2683 }
2684}
2685
2686class ChildScope extends Scope {
2687 constructor(parent) {
2688 super();
2689 this.accessedOutsideVariables = new Map();
2690 this.parent = parent;
2691 parent.children.push(this);
2692 }
2693 addAccessedDynamicImport(importExpression) {
2694 (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
2695 if (this.parent instanceof ChildScope) {
2696 this.parent.addAccessedDynamicImport(importExpression);
2697 }
2698 }
2699 addAccessedGlobals(globals, accessedGlobalsByScope) {
2700 const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
2701 for (const name of globals) {
2702 accessedGlobals.add(name);
2703 }
2704 accessedGlobalsByScope.set(this, accessedGlobals);
2705 if (this.parent instanceof ChildScope) {
2706 this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
2707 }
2708 }
2709 addNamespaceMemberAccess(name, variable) {
2710 this.accessedOutsideVariables.set(name, variable);
2711 this.parent.addNamespaceMemberAccess(name, variable);
2712 }
2713 addReturnExpression(expression) {
2714 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
2715 }
2716 addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
2717 for (const variable of this.accessedOutsideVariables.values()) {
2718 if (variable.included) {
2719 usedNames.add(variable.getBaseVariableName());
2720 if (format === 'system' && exportNamesByVariable.has(variable)) {
2721 usedNames.add('exports');
2722 }
2723 }
2724 }
2725 const accessedGlobals = accessedGlobalsByScope.get(this);
2726 if (accessedGlobals) {
2727 for (const name of accessedGlobals) {
2728 usedNames.add(name);
2729 }
2730 }
2731 }
2732 contains(name) {
2733 return this.variables.has(name) || this.parent.contains(name);
2734 }
2735 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
2736 const usedNames = new Set();
2737 this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
2738 if (this.accessedDynamicImports) {
2739 for (const importExpression of this.accessedDynamicImports) {
2740 if (importExpression.inlineNamespace) {
2741 usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
2742 }
2743 }
2744 }
2745 for (const [name, variable] of this.variables) {
2746 if (variable.included || variable.alwaysRendered) {
2747 variable.setRenderNames(null, getSafeName(name, usedNames));
2748 }
2749 }
2750 for (const scope of this.children) {
2751 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
2752 }
2753 }
2754 findLexicalBoundary() {
2755 return this.parent.findLexicalBoundary();
2756 }
2757 findVariable(name) {
2758 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
2759 if (knownVariable) {
2760 return knownVariable;
2761 }
2762 const variable = this.parent.findVariable(name);
2763 this.accessedOutsideVariables.set(name, variable);
2764 return variable;
2765 }
2766}
2767
2768function getLocator$1(source, options) {
2769 if (options === void 0) { options = {}; }
2770 var offsetLine = options.offsetLine || 0;
2771 var offsetColumn = options.offsetColumn || 0;
2772 var originalLines = source.split('\n');
2773 var start = 0;
2774 var lineRanges = originalLines.map(function (line, i) {
2775 var end = start + line.length + 1;
2776 var range = { start: start, end: end, line: i };
2777 start = end;
2778 return range;
2779 });
2780 var i = 0;
2781 function rangeContains(range, index) {
2782 return range.start <= index && index < range.end;
2783 }
2784 function getLocation(range, index) {
2785 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
2786 }
2787 function locate(search, startIndex) {
2788 if (typeof search === 'string') {
2789 search = source.indexOf(search, startIndex || 0);
2790 }
2791 var range = lineRanges[i];
2792 var d = search >= range.end ? 1 : -1;
2793 while (range) {
2794 if (rangeContains(range, search))
2795 return getLocation(range, search);
2796 i += d;
2797 range = lineRanges[i];
2798 }
2799 }
2800 return locate;
2801}
2802function locate(source, search, options) {
2803 if (typeof options === 'number') {
2804 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
2805 }
2806 return getLocator$1(source, options)(search, options && options.startIndex);
2807}
2808
2809const keys = {
2810 Literal: [],
2811 Program: ['body']
2812};
2813function getAndCreateKeys(esTreeNode) {
2814 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
2815 return keys[esTreeNode.type];
2816}
2817
2818const INCLUDE_PARAMETERS = 'variables';
2819class NodeBase {
2820 constructor(esTreeNode, parent, parentScope) {
2821 this.included = false;
2822 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
2823 this.parent = parent;
2824 this.context = parent.context;
2825 this.createScope(parentScope);
2826 this.parseNode(esTreeNode);
2827 this.initialise();
2828 this.context.magicString.addSourcemapLocation(this.start);
2829 this.context.magicString.addSourcemapLocation(this.end);
2830 }
2831 /**
2832 * Override this to bind assignments to variables and do any initialisations that
2833 * require the scopes to be populated with variables.
2834 */
2835 bind() {
2836 for (const key of this.keys) {
2837 const value = this[key];
2838 if (value === null || key === 'annotations')
2839 continue;
2840 if (Array.isArray(value)) {
2841 for (const child of value) {
2842 if (child !== null)
2843 child.bind();
2844 }
2845 }
2846 else {
2847 value.bind();
2848 }
2849 }
2850 }
2851 /**
2852 * Override if this node should receive a different scope than the parent scope.
2853 */
2854 createScope(parentScope) {
2855 this.scope = parentScope;
2856 }
2857 declare(_kind, _init) {
2858 return [];
2859 }
2860 deoptimizePath(_path) { }
2861 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2862 return UnknownValue;
2863 }
2864 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
2865 return UNKNOWN_EXPRESSION;
2866 }
2867 hasEffects(context) {
2868 for (const key of this.keys) {
2869 const value = this[key];
2870 if (value === null || key === 'annotations')
2871 continue;
2872 if (Array.isArray(value)) {
2873 for (const child of value) {
2874 if (child !== null && child.hasEffects(context))
2875 return true;
2876 }
2877 }
2878 else if (value.hasEffects(context))
2879 return true;
2880 }
2881 return false;
2882 }
2883 hasEffectsWhenAccessedAtPath(path, _context) {
2884 return path.length > 0;
2885 }
2886 hasEffectsWhenAssignedAtPath(_path, _context) {
2887 return true;
2888 }
2889 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
2890 return true;
2891 }
2892 include(context, includeChildrenRecursively) {
2893 this.included = true;
2894 for (const key of this.keys) {
2895 const value = this[key];
2896 if (value === null || key === 'annotations')
2897 continue;
2898 if (Array.isArray(value)) {
2899 for (const child of value) {
2900 if (child !== null)
2901 child.include(context, includeChildrenRecursively);
2902 }
2903 }
2904 else {
2905 value.include(context, includeChildrenRecursively);
2906 }
2907 }
2908 }
2909 includeCallArguments(context, args) {
2910 for (const arg of args) {
2911 arg.include(context, false);
2912 }
2913 }
2914 includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
2915 this.include(context, includeChildrenRecursively);
2916 }
2917 /**
2918 * Override to perform special initialisation steps after the scope is initialised
2919 */
2920 initialise() { }
2921 insertSemicolon(code) {
2922 if (code.original[this.end - 1] !== ';') {
2923 code.appendLeft(this.end, ';');
2924 }
2925 }
2926 parseNode(esTreeNode) {
2927 for (const key of Object.keys(esTreeNode)) {
2928 // That way, we can override this function to add custom initialisation and then call super.parseNode
2929 if (this.hasOwnProperty(key))
2930 continue;
2931 const value = esTreeNode[key];
2932 if (typeof value !== 'object' || value === null || key === 'annotations') {
2933 this[key] = value;
2934 }
2935 else if (Array.isArray(value)) {
2936 this[key] = [];
2937 for (const child of value) {
2938 this[key].push(child === null
2939 ? null
2940 : new (this.context.nodeConstructors[child.type] ||
2941 this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
2942 }
2943 }
2944 else {
2945 this[key] = new (this.context.nodeConstructors[value.type] ||
2946 this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
2947 }
2948 }
2949 }
2950 render(code, options) {
2951 for (const key of this.keys) {
2952 const value = this[key];
2953 if (value === null || key === 'annotations')
2954 continue;
2955 if (Array.isArray(value)) {
2956 for (const child of value) {
2957 if (child !== null)
2958 child.render(code, options);
2959 }
2960 }
2961 else {
2962 value.render(code, options);
2963 }
2964 }
2965 }
2966 shouldBeIncluded(context) {
2967 return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
2968 }
2969 toString() {
2970 return this.context.code.slice(this.start, this.end);
2971 }
2972}
2973
2974class ClassNode extends NodeBase {
2975 createScope(parentScope) {
2976 this.scope = new ChildScope(parentScope);
2977 }
2978 hasEffectsWhenAccessedAtPath(path) {
2979 if (path.length <= 1)
2980 return false;
2981 return path.length > 2 || path[0] !== 'prototype';
2982 }
2983 hasEffectsWhenAssignedAtPath(path) {
2984 if (path.length <= 1)
2985 return false;
2986 return path.length > 2 || path[0] !== 'prototype';
2987 }
2988 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2989 if (!callOptions.withNew)
2990 return true;
2991 return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
2992 (this.superClass !== null &&
2993 this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
2994 }
2995 initialise() {
2996 if (this.id !== null) {
2997 this.id.declare('class', this);
2998 }
2999 }
3000}
3001
3002class ClassDeclaration extends ClassNode {
3003 initialise() {
3004 super.initialise();
3005 if (this.id !== null) {
3006 this.id.variable.isId = true;
3007 }
3008 }
3009 parseNode(esTreeNode) {
3010 if (esTreeNode.id !== null) {
3011 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
3012 }
3013 super.parseNode(esTreeNode);
3014 }
3015 render(code, options) {
3016 if (options.format === 'system' &&
3017 this.id &&
3018 options.exportNamesByVariable.has(this.id.variable)) {
3019 code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
3020 }
3021 super.render(code, options);
3022 }
3023}
3024
3025class ArgumentsVariable extends LocalVariable {
3026 constructor(context) {
3027 super('arguments', null, UNKNOWN_EXPRESSION, context);
3028 }
3029 hasEffectsWhenAccessedAtPath(path) {
3030 return path.length > 1;
3031 }
3032 hasEffectsWhenAssignedAtPath() {
3033 return true;
3034 }
3035 hasEffectsWhenCalledAtPath() {
3036 return true;
3037 }
3038}
3039
3040class ThisVariable extends LocalVariable {
3041 constructor(context) {
3042 super('this', null, null, context);
3043 }
3044 getLiteralValueAtPath() {
3045 return UnknownValue;
3046 }
3047 hasEffectsWhenAccessedAtPath(path, context) {
3048 return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
3049 super.hasEffectsWhenAccessedAtPath(path, context));
3050 }
3051 hasEffectsWhenAssignedAtPath(path, context) {
3052 return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
3053 super.hasEffectsWhenAssignedAtPath(path, context));
3054 }
3055 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3056 return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
3057 super.hasEffectsWhenCalledAtPath(path, callOptions, context));
3058 }
3059 getInit(context) {
3060 return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
3061 }
3062}
3063
3064class SpreadElement extends NodeBase {
3065 bind() {
3066 super.bind();
3067 // Only properties of properties of the argument could become subject to reassignment
3068 // This will also reassign the return values of iterators
3069 this.argument.deoptimizePath([UnknownKey, UnknownKey]);
3070 }
3071}
3072
3073class ParameterScope extends ChildScope {
3074 constructor(parent, context) {
3075 super(parent);
3076 this.parameters = [];
3077 this.hasRest = false;
3078 this.context = context;
3079 this.hoistedBodyVarScope = new ChildScope(this);
3080 }
3081 /**
3082 * Adds a parameter to this scope. Parameters must be added in the correct
3083 * order, e.g. from left to right.
3084 */
3085 addParameterDeclaration(identifier) {
3086 const name = identifier.name;
3087 let variable = this.hoistedBodyVarScope.variables.get(name);
3088 if (variable) {
3089 variable.addDeclaration(identifier, null);
3090 }
3091 else {
3092 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
3093 }
3094 this.variables.set(name, variable);
3095 return variable;
3096 }
3097 addParameterVariables(parameters, hasRest) {
3098 this.parameters = parameters;
3099 for (const parameterList of parameters) {
3100 for (const parameter of parameterList) {
3101 parameter.alwaysRendered = true;
3102 }
3103 }
3104 this.hasRest = hasRest;
3105 }
3106 includeCallArguments(context, args) {
3107 let calledFromTryStatement = false;
3108 let argIncluded = false;
3109 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
3110 for (const checkedArg of args) {
3111 if (checkedArg instanceof SpreadElement) {
3112 for (const arg of args) {
3113 arg.include(context, false);
3114 }
3115 break;
3116 }
3117 }
3118 for (let index = args.length - 1; index >= 0; index--) {
3119 const paramVars = this.parameters[index] || restParam;
3120 const arg = args[index];
3121 if (paramVars) {
3122 calledFromTryStatement = false;
3123 for (const variable of paramVars) {
3124 if (variable.included) {
3125 argIncluded = true;
3126 }
3127 if (variable.calledFromTryStatement) {
3128 calledFromTryStatement = true;
3129 }
3130 }
3131 }
3132 if (!argIncluded && arg.shouldBeIncluded(context)) {
3133 argIncluded = true;
3134 }
3135 if (argIncluded) {
3136 arg.include(context, calledFromTryStatement);
3137 }
3138 }
3139 }
3140}
3141
3142class ReturnValueScope extends ParameterScope {
3143 constructor() {
3144 super(...arguments);
3145 this.returnExpression = null;
3146 this.returnExpressions = [];
3147 }
3148 addReturnExpression(expression) {
3149 this.returnExpressions.push(expression);
3150 }
3151 getReturnExpression() {
3152 if (this.returnExpression === null)
3153 this.updateReturnExpression();
3154 return this.returnExpression;
3155 }
3156 updateReturnExpression() {
3157 if (this.returnExpressions.length === 1) {
3158 this.returnExpression = this.returnExpressions[0];
3159 }
3160 else {
3161 this.returnExpression = UNKNOWN_EXPRESSION;
3162 for (const expression of this.returnExpressions) {
3163 expression.deoptimizePath(UNKNOWN_PATH);
3164 }
3165 }
3166 }
3167}
3168
3169class FunctionScope extends ReturnValueScope {
3170 constructor(parent, context) {
3171 super(parent, context);
3172 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
3173 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
3174 }
3175 findLexicalBoundary() {
3176 return this;
3177 }
3178 includeCallArguments(context, args) {
3179 super.includeCallArguments(context, args);
3180 if (this.argumentsVariable.included) {
3181 for (const arg of args) {
3182 if (!arg.included) {
3183 arg.include(context, false);
3184 }
3185 }
3186 }
3187 }
3188}
3189
3190function isReference(node, parent) {
3191 if (node.type === 'MemberExpression') {
3192 return !node.computed && isReference(node.object, node);
3193 }
3194 if (node.type === 'Identifier') {
3195 if (!parent)
3196 return true;
3197 switch (parent.type) {
3198 // disregard `bar` in `foo.bar`
3199 case 'MemberExpression': return parent.computed || node === parent.object;
3200 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
3201 case 'MethodDefinition': return parent.computed;
3202 // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
3203 case 'FieldDefinition': return parent.computed || node === parent.value;
3204 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
3205 case 'Property': return parent.computed || node === parent.value;
3206 // disregard the `bar` in `export { foo as bar }` or
3207 // the foo in `import { foo as bar }`
3208 case 'ExportSpecifier':
3209 case 'ImportSpecifier': return node === parent.local;
3210 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
3211 case 'LabeledStatement':
3212 case 'BreakStatement':
3213 case 'ContinueStatement': return false;
3214 default: return true;
3215 }
3216 }
3217 return false;
3218}
3219
3220const BLANK = Object.freeze(Object.create(null));
3221const EMPTY_OBJECT = Object.freeze({});
3222const EMPTY_ARRAY = Object.freeze([]);
3223
3224const ValueProperties = Symbol('Value Properties');
3225const PURE = { pure: true };
3226const IMPURE = { pure: false };
3227// We use shortened variables to reduce file size here
3228/* OBJECT */
3229const O = {
3230 // @ts-ignore
3231 __proto__: null,
3232 [ValueProperties]: IMPURE
3233};
3234/* PURE FUNCTION */
3235const PF = {
3236 // @ts-ignore
3237 __proto__: null,
3238 [ValueProperties]: PURE
3239};
3240/* CONSTRUCTOR */
3241const C = {
3242 // @ts-ignore
3243 __proto__: null,
3244 [ValueProperties]: IMPURE,
3245 prototype: O
3246};
3247/* PURE CONSTRUCTOR */
3248const PC = {
3249 // @ts-ignore
3250 __proto__: null,
3251 [ValueProperties]: PURE,
3252 prototype: O
3253};
3254const ARRAY_TYPE = {
3255 // @ts-ignore
3256 __proto__: null,
3257 [ValueProperties]: PURE,
3258 from: PF,
3259 of: PF,
3260 prototype: O
3261};
3262const INTL_MEMBER = {
3263 // @ts-ignore
3264 __proto__: null,
3265 [ValueProperties]: PURE,
3266 supportedLocalesOf: PC
3267};
3268const knownGlobals = {
3269 // Placeholders for global objects to avoid shape mutations
3270 global: O,
3271 globalThis: O,
3272 self: O,
3273 window: O,
3274 // Common globals
3275 // @ts-ignore
3276 __proto__: null,
3277 [ValueProperties]: IMPURE,
3278 Array: {
3279 // @ts-ignore
3280 __proto__: null,
3281 [ValueProperties]: IMPURE,
3282 from: O,
3283 isArray: PF,
3284 of: PF,
3285 prototype: O
3286 },
3287 ArrayBuffer: {
3288 // @ts-ignore
3289 __proto__: null,
3290 [ValueProperties]: PURE,
3291 isView: PF,
3292 prototype: O
3293 },
3294 Atomics: O,
3295 BigInt: C,
3296 BigInt64Array: C,
3297 BigUint64Array: C,
3298 Boolean: PC,
3299 // @ts-ignore
3300 constructor: C,
3301 DataView: PC,
3302 Date: {
3303 // @ts-ignore
3304 __proto__: null,
3305 [ValueProperties]: PURE,
3306 now: PF,
3307 parse: PF,
3308 prototype: O,
3309 UTC: PF
3310 },
3311 decodeURI: PF,
3312 decodeURIComponent: PF,
3313 encodeURI: PF,
3314 encodeURIComponent: PF,
3315 Error: PC,
3316 escape: PF,
3317 eval: O,
3318 EvalError: PC,
3319 Float32Array: ARRAY_TYPE,
3320 Float64Array: ARRAY_TYPE,
3321 Function: C,
3322 // @ts-ignore
3323 hasOwnProperty: O,
3324 Infinity: O,
3325 Int16Array: ARRAY_TYPE,
3326 Int32Array: ARRAY_TYPE,
3327 Int8Array: ARRAY_TYPE,
3328 isFinite: PF,
3329 isNaN: PF,
3330 // @ts-ignore
3331 isPrototypeOf: O,
3332 JSON: O,
3333 Map: PC,
3334 Math: {
3335 // @ts-ignore
3336 __proto__: null,
3337 [ValueProperties]: IMPURE,
3338 abs: PF,
3339 acos: PF,
3340 acosh: PF,
3341 asin: PF,
3342 asinh: PF,
3343 atan: PF,
3344 atan2: PF,
3345 atanh: PF,
3346 cbrt: PF,
3347 ceil: PF,
3348 clz32: PF,
3349 cos: PF,
3350 cosh: PF,
3351 exp: PF,
3352 expm1: PF,
3353 floor: PF,
3354 fround: PF,
3355 hypot: PF,
3356 imul: PF,
3357 log: PF,
3358 log10: PF,
3359 log1p: PF,
3360 log2: PF,
3361 max: PF,
3362 min: PF,
3363 pow: PF,
3364 random: PF,
3365 round: PF,
3366 sign: PF,
3367 sin: PF,
3368 sinh: PF,
3369 sqrt: PF,
3370 tan: PF,
3371 tanh: PF,
3372 trunc: PF
3373 },
3374 NaN: O,
3375 Number: {
3376 // @ts-ignore
3377 __proto__: null,
3378 [ValueProperties]: PURE,
3379 isFinite: PF,
3380 isInteger: PF,
3381 isNaN: PF,
3382 isSafeInteger: PF,
3383 parseFloat: PF,
3384 parseInt: PF,
3385 prototype: O
3386 },
3387 Object: {
3388 // @ts-ignore
3389 __proto__: null,
3390 [ValueProperties]: PURE,
3391 create: PF,
3392 getNotifier: PF,
3393 getOwn: PF,
3394 getOwnPropertyDescriptor: PF,
3395 getOwnPropertyNames: PF,
3396 getOwnPropertySymbols: PF,
3397 getPrototypeOf: PF,
3398 is: PF,
3399 isExtensible: PF,
3400 isFrozen: PF,
3401 isSealed: PF,
3402 keys: PF,
3403 prototype: O
3404 },
3405 parseFloat: PF,
3406 parseInt: PF,
3407 Promise: {
3408 // @ts-ignore
3409 __proto__: null,
3410 [ValueProperties]: IMPURE,
3411 all: PF,
3412 prototype: O,
3413 race: PF,
3414 resolve: PF
3415 },
3416 // @ts-ignore
3417 propertyIsEnumerable: O,
3418 Proxy: O,
3419 RangeError: PC,
3420 ReferenceError: PC,
3421 Reflect: O,
3422 RegExp: PC,
3423 Set: PC,
3424 SharedArrayBuffer: C,
3425 String: {
3426 // @ts-ignore
3427 __proto__: null,
3428 [ValueProperties]: PURE,
3429 fromCharCode: PF,
3430 fromCodePoint: PF,
3431 prototype: O,
3432 raw: PF
3433 },
3434 Symbol: {
3435 // @ts-ignore
3436 __proto__: null,
3437 [ValueProperties]: PURE,
3438 for: PF,
3439 keyFor: PF,
3440 prototype: O
3441 },
3442 SyntaxError: PC,
3443 // @ts-ignore
3444 toLocaleString: O,
3445 // @ts-ignore
3446 toString: O,
3447 TypeError: PC,
3448 Uint16Array: ARRAY_TYPE,
3449 Uint32Array: ARRAY_TYPE,
3450 Uint8Array: ARRAY_TYPE,
3451 Uint8ClampedArray: ARRAY_TYPE,
3452 // Technically, this is a global, but it needs special handling
3453 // undefined: ?,
3454 unescape: PF,
3455 URIError: PC,
3456 // @ts-ignore
3457 valueOf: O,
3458 WeakMap: PC,
3459 WeakSet: PC,
3460 // Additional globals shared by Node and Browser that are not strictly part of the language
3461 clearInterval: C,
3462 clearTimeout: C,
3463 console: O,
3464 Intl: {
3465 // @ts-ignore
3466 __proto__: null,
3467 [ValueProperties]: IMPURE,
3468 Collator: INTL_MEMBER,
3469 DateTimeFormat: INTL_MEMBER,
3470 ListFormat: INTL_MEMBER,
3471 NumberFormat: INTL_MEMBER,
3472 PluralRules: INTL_MEMBER,
3473 RelativeTimeFormat: INTL_MEMBER
3474 },
3475 setInterval: C,
3476 setTimeout: C,
3477 TextDecoder: C,
3478 TextEncoder: C,
3479 URL: C,
3480 URLSearchParams: C,
3481 // Browser specific globals
3482 AbortController: C,
3483 AbortSignal: C,
3484 addEventListener: O,
3485 alert: O,
3486 AnalyserNode: C,
3487 Animation: C,
3488 AnimationEvent: C,
3489 applicationCache: O,
3490 ApplicationCache: C,
3491 ApplicationCacheErrorEvent: C,
3492 atob: O,
3493 Attr: C,
3494 Audio: C,
3495 AudioBuffer: C,
3496 AudioBufferSourceNode: C,
3497 AudioContext: C,
3498 AudioDestinationNode: C,
3499 AudioListener: C,
3500 AudioNode: C,
3501 AudioParam: C,
3502 AudioProcessingEvent: C,
3503 AudioScheduledSourceNode: C,
3504 AudioWorkletNode: C,
3505 BarProp: C,
3506 BaseAudioContext: C,
3507 BatteryManager: C,
3508 BeforeUnloadEvent: C,
3509 BiquadFilterNode: C,
3510 Blob: C,
3511 BlobEvent: C,
3512 blur: O,
3513 BroadcastChannel: C,
3514 btoa: O,
3515 ByteLengthQueuingStrategy: C,
3516 Cache: C,
3517 caches: O,
3518 CacheStorage: C,
3519 cancelAnimationFrame: O,
3520 cancelIdleCallback: O,
3521 CanvasCaptureMediaStreamTrack: C,
3522 CanvasGradient: C,
3523 CanvasPattern: C,
3524 CanvasRenderingContext2D: C,
3525 ChannelMergerNode: C,
3526 ChannelSplitterNode: C,
3527 CharacterData: C,
3528 clientInformation: O,
3529 ClipboardEvent: C,
3530 close: O,
3531 closed: O,
3532 CloseEvent: C,
3533 Comment: C,
3534 CompositionEvent: C,
3535 confirm: O,
3536 ConstantSourceNode: C,
3537 ConvolverNode: C,
3538 CountQueuingStrategy: C,
3539 createImageBitmap: O,
3540 Credential: C,
3541 CredentialsContainer: C,
3542 crypto: O,
3543 Crypto: C,
3544 CryptoKey: C,
3545 CSS: C,
3546 CSSConditionRule: C,
3547 CSSFontFaceRule: C,
3548 CSSGroupingRule: C,
3549 CSSImportRule: C,
3550 CSSKeyframeRule: C,
3551 CSSKeyframesRule: C,
3552 CSSMediaRule: C,
3553 CSSNamespaceRule: C,
3554 CSSPageRule: C,
3555 CSSRule: C,
3556 CSSRuleList: C,
3557 CSSStyleDeclaration: C,
3558 CSSStyleRule: C,
3559 CSSStyleSheet: C,
3560 CSSSupportsRule: C,
3561 CustomElementRegistry: C,
3562 customElements: O,
3563 CustomEvent: C,
3564 DataTransfer: C,
3565 DataTransferItem: C,
3566 DataTransferItemList: C,
3567 defaultstatus: O,
3568 defaultStatus: O,
3569 DelayNode: C,
3570 DeviceMotionEvent: C,
3571 DeviceOrientationEvent: C,
3572 devicePixelRatio: O,
3573 dispatchEvent: O,
3574 document: O,
3575 Document: C,
3576 DocumentFragment: C,
3577 DocumentType: C,
3578 DOMError: C,
3579 DOMException: C,
3580 DOMImplementation: C,
3581 DOMMatrix: C,
3582 DOMMatrixReadOnly: C,
3583 DOMParser: C,
3584 DOMPoint: C,
3585 DOMPointReadOnly: C,
3586 DOMQuad: C,
3587 DOMRect: C,
3588 DOMRectReadOnly: C,
3589 DOMStringList: C,
3590 DOMStringMap: C,
3591 DOMTokenList: C,
3592 DragEvent: C,
3593 DynamicsCompressorNode: C,
3594 Element: C,
3595 ErrorEvent: C,
3596 Event: C,
3597 EventSource: C,
3598 EventTarget: C,
3599 external: O,
3600 fetch: O,
3601 File: C,
3602 FileList: C,
3603 FileReader: C,
3604 find: O,
3605 focus: O,
3606 FocusEvent: C,
3607 FontFace: C,
3608 FontFaceSetLoadEvent: C,
3609 FormData: C,
3610 frames: O,
3611 GainNode: C,
3612 Gamepad: C,
3613 GamepadButton: C,
3614 GamepadEvent: C,
3615 getComputedStyle: O,
3616 getSelection: O,
3617 HashChangeEvent: C,
3618 Headers: C,
3619 history: O,
3620 History: C,
3621 HTMLAllCollection: C,
3622 HTMLAnchorElement: C,
3623 HTMLAreaElement: C,
3624 HTMLAudioElement: C,
3625 HTMLBaseElement: C,
3626 HTMLBodyElement: C,
3627 HTMLBRElement: C,
3628 HTMLButtonElement: C,
3629 HTMLCanvasElement: C,
3630 HTMLCollection: C,
3631 HTMLContentElement: C,
3632 HTMLDataElement: C,
3633 HTMLDataListElement: C,
3634 HTMLDetailsElement: C,
3635 HTMLDialogElement: C,
3636 HTMLDirectoryElement: C,
3637 HTMLDivElement: C,
3638 HTMLDListElement: C,
3639 HTMLDocument: C,
3640 HTMLElement: C,
3641 HTMLEmbedElement: C,
3642 HTMLFieldSetElement: C,
3643 HTMLFontElement: C,
3644 HTMLFormControlsCollection: C,
3645 HTMLFormElement: C,
3646 HTMLFrameElement: C,
3647 HTMLFrameSetElement: C,
3648 HTMLHeadElement: C,
3649 HTMLHeadingElement: C,
3650 HTMLHRElement: C,
3651 HTMLHtmlElement: C,
3652 HTMLIFrameElement: C,
3653 HTMLImageElement: C,
3654 HTMLInputElement: C,
3655 HTMLLabelElement: C,
3656 HTMLLegendElement: C,
3657 HTMLLIElement: C,
3658 HTMLLinkElement: C,
3659 HTMLMapElement: C,
3660 HTMLMarqueeElement: C,
3661 HTMLMediaElement: C,
3662 HTMLMenuElement: C,
3663 HTMLMetaElement: C,
3664 HTMLMeterElement: C,
3665 HTMLModElement: C,
3666 HTMLObjectElement: C,
3667 HTMLOListElement: C,
3668 HTMLOptGroupElement: C,
3669 HTMLOptionElement: C,
3670 HTMLOptionsCollection: C,
3671 HTMLOutputElement: C,
3672 HTMLParagraphElement: C,
3673 HTMLParamElement: C,
3674 HTMLPictureElement: C,
3675 HTMLPreElement: C,
3676 HTMLProgressElement: C,
3677 HTMLQuoteElement: C,
3678 HTMLScriptElement: C,
3679 HTMLSelectElement: C,
3680 HTMLShadowElement: C,
3681 HTMLSlotElement: C,
3682 HTMLSourceElement: C,
3683 HTMLSpanElement: C,
3684 HTMLStyleElement: C,
3685 HTMLTableCaptionElement: C,
3686 HTMLTableCellElement: C,
3687 HTMLTableColElement: C,
3688 HTMLTableElement: C,
3689 HTMLTableRowElement: C,
3690 HTMLTableSectionElement: C,
3691 HTMLTemplateElement: C,
3692 HTMLTextAreaElement: C,
3693 HTMLTimeElement: C,
3694 HTMLTitleElement: C,
3695 HTMLTrackElement: C,
3696 HTMLUListElement: C,
3697 HTMLUnknownElement: C,
3698 HTMLVideoElement: C,
3699 IDBCursor: C,
3700 IDBCursorWithValue: C,
3701 IDBDatabase: C,
3702 IDBFactory: C,
3703 IDBIndex: C,
3704 IDBKeyRange: C,
3705 IDBObjectStore: C,
3706 IDBOpenDBRequest: C,
3707 IDBRequest: C,
3708 IDBTransaction: C,
3709 IDBVersionChangeEvent: C,
3710 IdleDeadline: C,
3711 IIRFilterNode: C,
3712 Image: C,
3713 ImageBitmap: C,
3714 ImageBitmapRenderingContext: C,
3715 ImageCapture: C,
3716 ImageData: C,
3717 indexedDB: O,
3718 innerHeight: O,
3719 innerWidth: O,
3720 InputEvent: C,
3721 IntersectionObserver: C,
3722 IntersectionObserverEntry: C,
3723 isSecureContext: O,
3724 KeyboardEvent: C,
3725 KeyframeEffect: C,
3726 length: O,
3727 localStorage: O,
3728 location: O,
3729 Location: C,
3730 locationbar: O,
3731 matchMedia: O,
3732 MediaDeviceInfo: C,
3733 MediaDevices: C,
3734 MediaElementAudioSourceNode: C,
3735 MediaEncryptedEvent: C,
3736 MediaError: C,
3737 MediaKeyMessageEvent: C,
3738 MediaKeySession: C,
3739 MediaKeyStatusMap: C,
3740 MediaKeySystemAccess: C,
3741 MediaList: C,
3742 MediaQueryList: C,
3743 MediaQueryListEvent: C,
3744 MediaRecorder: C,
3745 MediaSettingsRange: C,
3746 MediaSource: C,
3747 MediaStream: C,
3748 MediaStreamAudioDestinationNode: C,
3749 MediaStreamAudioSourceNode: C,
3750 MediaStreamEvent: C,
3751 MediaStreamTrack: C,
3752 MediaStreamTrackEvent: C,
3753 menubar: O,
3754 MessageChannel: C,
3755 MessageEvent: C,
3756 MessagePort: C,
3757 MIDIAccess: C,
3758 MIDIConnectionEvent: C,
3759 MIDIInput: C,
3760 MIDIInputMap: C,
3761 MIDIMessageEvent: C,
3762 MIDIOutput: C,
3763 MIDIOutputMap: C,
3764 MIDIPort: C,
3765 MimeType: C,
3766 MimeTypeArray: C,
3767 MouseEvent: C,
3768 moveBy: O,
3769 moveTo: O,
3770 MutationEvent: C,
3771 MutationObserver: C,
3772 MutationRecord: C,
3773 name: O,
3774 NamedNodeMap: C,
3775 NavigationPreloadManager: C,
3776 navigator: O,
3777 Navigator: C,
3778 NetworkInformation: C,
3779 Node: C,
3780 NodeFilter: O,
3781 NodeIterator: C,
3782 NodeList: C,
3783 Notification: C,
3784 OfflineAudioCompletionEvent: C,
3785 OfflineAudioContext: C,
3786 offscreenBuffering: O,
3787 OffscreenCanvas: C,
3788 open: O,
3789 openDatabase: O,
3790 Option: C,
3791 origin: O,
3792 OscillatorNode: C,
3793 outerHeight: O,
3794 outerWidth: O,
3795 PageTransitionEvent: C,
3796 pageXOffset: O,
3797 pageYOffset: O,
3798 PannerNode: C,
3799 parent: O,
3800 Path2D: C,
3801 PaymentAddress: C,
3802 PaymentRequest: C,
3803 PaymentRequestUpdateEvent: C,
3804 PaymentResponse: C,
3805 performance: O,
3806 Performance: C,
3807 PerformanceEntry: C,
3808 PerformanceLongTaskTiming: C,
3809 PerformanceMark: C,
3810 PerformanceMeasure: C,
3811 PerformanceNavigation: C,
3812 PerformanceNavigationTiming: C,
3813 PerformanceObserver: C,
3814 PerformanceObserverEntryList: C,
3815 PerformancePaintTiming: C,
3816 PerformanceResourceTiming: C,
3817 PerformanceTiming: C,
3818 PeriodicWave: C,
3819 Permissions: C,
3820 PermissionStatus: C,
3821 personalbar: O,
3822 PhotoCapabilities: C,
3823 Plugin: C,
3824 PluginArray: C,
3825 PointerEvent: C,
3826 PopStateEvent: C,
3827 postMessage: O,
3828 Presentation: C,
3829 PresentationAvailability: C,
3830 PresentationConnection: C,
3831 PresentationConnectionAvailableEvent: C,
3832 PresentationConnectionCloseEvent: C,
3833 PresentationConnectionList: C,
3834 PresentationReceiver: C,
3835 PresentationRequest: C,
3836 print: O,
3837 ProcessingInstruction: C,
3838 ProgressEvent: C,
3839 PromiseRejectionEvent: C,
3840 prompt: O,
3841 PushManager: C,
3842 PushSubscription: C,
3843 PushSubscriptionOptions: C,
3844 queueMicrotask: O,
3845 RadioNodeList: C,
3846 Range: C,
3847 ReadableStream: C,
3848 RemotePlayback: C,
3849 removeEventListener: O,
3850 Request: C,
3851 requestAnimationFrame: O,
3852 requestIdleCallback: O,
3853 resizeBy: O,
3854 ResizeObserver: C,
3855 ResizeObserverEntry: C,
3856 resizeTo: O,
3857 Response: C,
3858 RTCCertificate: C,
3859 RTCDataChannel: C,
3860 RTCDataChannelEvent: C,
3861 RTCDtlsTransport: C,
3862 RTCIceCandidate: C,
3863 RTCIceTransport: C,
3864 RTCPeerConnection: C,
3865 RTCPeerConnectionIceEvent: C,
3866 RTCRtpReceiver: C,
3867 RTCRtpSender: C,
3868 RTCSctpTransport: C,
3869 RTCSessionDescription: C,
3870 RTCStatsReport: C,
3871 RTCTrackEvent: C,
3872 screen: O,
3873 Screen: C,
3874 screenLeft: O,
3875 ScreenOrientation: C,
3876 screenTop: O,
3877 screenX: O,
3878 screenY: O,
3879 ScriptProcessorNode: C,
3880 scroll: O,
3881 scrollbars: O,
3882 scrollBy: O,
3883 scrollTo: O,
3884 scrollX: O,
3885 scrollY: O,
3886 SecurityPolicyViolationEvent: C,
3887 Selection: C,
3888 ServiceWorker: C,
3889 ServiceWorkerContainer: C,
3890 ServiceWorkerRegistration: C,
3891 sessionStorage: O,
3892 ShadowRoot: C,
3893 SharedWorker: C,
3894 SourceBuffer: C,
3895 SourceBufferList: C,
3896 speechSynthesis: O,
3897 SpeechSynthesisEvent: C,
3898 SpeechSynthesisUtterance: C,
3899 StaticRange: C,
3900 status: O,
3901 statusbar: O,
3902 StereoPannerNode: C,
3903 stop: O,
3904 Storage: C,
3905 StorageEvent: C,
3906 StorageManager: C,
3907 styleMedia: O,
3908 StyleSheet: C,
3909 StyleSheetList: C,
3910 SubtleCrypto: C,
3911 SVGAElement: C,
3912 SVGAngle: C,
3913 SVGAnimatedAngle: C,
3914 SVGAnimatedBoolean: C,
3915 SVGAnimatedEnumeration: C,
3916 SVGAnimatedInteger: C,
3917 SVGAnimatedLength: C,
3918 SVGAnimatedLengthList: C,
3919 SVGAnimatedNumber: C,
3920 SVGAnimatedNumberList: C,
3921 SVGAnimatedPreserveAspectRatio: C,
3922 SVGAnimatedRect: C,
3923 SVGAnimatedString: C,
3924 SVGAnimatedTransformList: C,
3925 SVGAnimateElement: C,
3926 SVGAnimateMotionElement: C,
3927 SVGAnimateTransformElement: C,
3928 SVGAnimationElement: C,
3929 SVGCircleElement: C,
3930 SVGClipPathElement: C,
3931 SVGComponentTransferFunctionElement: C,
3932 SVGDefsElement: C,
3933 SVGDescElement: C,
3934 SVGDiscardElement: C,
3935 SVGElement: C,
3936 SVGEllipseElement: C,
3937 SVGFEBlendElement: C,
3938 SVGFEColorMatrixElement: C,
3939 SVGFEComponentTransferElement: C,
3940 SVGFECompositeElement: C,
3941 SVGFEConvolveMatrixElement: C,
3942 SVGFEDiffuseLightingElement: C,
3943 SVGFEDisplacementMapElement: C,
3944 SVGFEDistantLightElement: C,
3945 SVGFEDropShadowElement: C,
3946 SVGFEFloodElement: C,
3947 SVGFEFuncAElement: C,
3948 SVGFEFuncBElement: C,
3949 SVGFEFuncGElement: C,
3950 SVGFEFuncRElement: C,
3951 SVGFEGaussianBlurElement: C,
3952 SVGFEImageElement: C,
3953 SVGFEMergeElement: C,
3954 SVGFEMergeNodeElement: C,
3955 SVGFEMorphologyElement: C,
3956 SVGFEOffsetElement: C,
3957 SVGFEPointLightElement: C,
3958 SVGFESpecularLightingElement: C,
3959 SVGFESpotLightElement: C,
3960 SVGFETileElement: C,
3961 SVGFETurbulenceElement: C,
3962 SVGFilterElement: C,
3963 SVGForeignObjectElement: C,
3964 SVGGElement: C,
3965 SVGGeometryElement: C,
3966 SVGGradientElement: C,
3967 SVGGraphicsElement: C,
3968 SVGImageElement: C,
3969 SVGLength: C,
3970 SVGLengthList: C,
3971 SVGLinearGradientElement: C,
3972 SVGLineElement: C,
3973 SVGMarkerElement: C,
3974 SVGMaskElement: C,
3975 SVGMatrix: C,
3976 SVGMetadataElement: C,
3977 SVGMPathElement: C,
3978 SVGNumber: C,
3979 SVGNumberList: C,
3980 SVGPathElement: C,
3981 SVGPatternElement: C,
3982 SVGPoint: C,
3983 SVGPointList: C,
3984 SVGPolygonElement: C,
3985 SVGPolylineElement: C,
3986 SVGPreserveAspectRatio: C,
3987 SVGRadialGradientElement: C,
3988 SVGRect: C,
3989 SVGRectElement: C,
3990 SVGScriptElement: C,
3991 SVGSetElement: C,
3992 SVGStopElement: C,
3993 SVGStringList: C,
3994 SVGStyleElement: C,
3995 SVGSVGElement: C,
3996 SVGSwitchElement: C,
3997 SVGSymbolElement: C,
3998 SVGTextContentElement: C,
3999 SVGTextElement: C,
4000 SVGTextPathElement: C,
4001 SVGTextPositioningElement: C,
4002 SVGTitleElement: C,
4003 SVGTransform: C,
4004 SVGTransformList: C,
4005 SVGTSpanElement: C,
4006 SVGUnitTypes: C,
4007 SVGUseElement: C,
4008 SVGViewElement: C,
4009 TaskAttributionTiming: C,
4010 Text: C,
4011 TextEvent: C,
4012 TextMetrics: C,
4013 TextTrack: C,
4014 TextTrackCue: C,
4015 TextTrackCueList: C,
4016 TextTrackList: C,
4017 TimeRanges: C,
4018 toolbar: O,
4019 top: O,
4020 Touch: C,
4021 TouchEvent: C,
4022 TouchList: C,
4023 TrackEvent: C,
4024 TransitionEvent: C,
4025 TreeWalker: C,
4026 UIEvent: C,
4027 ValidityState: C,
4028 visualViewport: O,
4029 VisualViewport: C,
4030 VTTCue: C,
4031 WaveShaperNode: C,
4032 WebAssembly: O,
4033 WebGL2RenderingContext: C,
4034 WebGLActiveInfo: C,
4035 WebGLBuffer: C,
4036 WebGLContextEvent: C,
4037 WebGLFramebuffer: C,
4038 WebGLProgram: C,
4039 WebGLQuery: C,
4040 WebGLRenderbuffer: C,
4041 WebGLRenderingContext: C,
4042 WebGLSampler: C,
4043 WebGLShader: C,
4044 WebGLShaderPrecisionFormat: C,
4045 WebGLSync: C,
4046 WebGLTexture: C,
4047 WebGLTransformFeedback: C,
4048 WebGLUniformLocation: C,
4049 WebGLVertexArrayObject: C,
4050 WebSocket: C,
4051 WheelEvent: C,
4052 Window: C,
4053 Worker: C,
4054 WritableStream: C,
4055 XMLDocument: C,
4056 XMLHttpRequest: C,
4057 XMLHttpRequestEventTarget: C,
4058 XMLHttpRequestUpload: C,
4059 XMLSerializer: C,
4060 XPathEvaluator: C,
4061 XPathExpression: C,
4062 XPathResult: C,
4063 XSLTProcessor: C
4064};
4065for (const global of ['window', 'global', 'self', 'globalThis']) {
4066 knownGlobals[global] = knownGlobals;
4067}
4068function getGlobalAtPath(path) {
4069 let currentGlobal = knownGlobals;
4070 for (const pathSegment of path) {
4071 if (typeof pathSegment !== 'string') {
4072 return null;
4073 }
4074 currentGlobal = currentGlobal[pathSegment];
4075 if (!currentGlobal) {
4076 return null;
4077 }
4078 }
4079 return currentGlobal[ValueProperties];
4080}
4081function isPureGlobal(path) {
4082 const globalAtPath = getGlobalAtPath(path);
4083 return globalAtPath !== null && globalAtPath.pure;
4084}
4085function isGlobalMember(path) {
4086 if (path.length === 1) {
4087 return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
4088 }
4089 return getGlobalAtPath(path.slice(0, -1)) !== null;
4090}
4091
4092class GlobalVariable extends Variable {
4093 constructor() {
4094 super(...arguments);
4095 this.isReassigned = true;
4096 }
4097 hasEffectsWhenAccessedAtPath(path) {
4098 return !isGlobalMember([this.name, ...path]);
4099 }
4100 hasEffectsWhenCalledAtPath(path) {
4101 return !isPureGlobal([this.name, ...path]);
4102 }
4103}
4104
4105class Identifier$1 extends NodeBase {
4106 constructor() {
4107 super(...arguments);
4108 this.variable = null;
4109 this.bound = false;
4110 }
4111 addExportedVariables(variables, exportNamesByVariable) {
4112 if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
4113 variables.push(this.variable);
4114 }
4115 }
4116 bind() {
4117 if (this.bound)
4118 return;
4119 this.bound = true;
4120 if (this.variable === null && isReference(this, this.parent)) {
4121 this.variable = this.scope.findVariable(this.name);
4122 this.variable.addReference(this);
4123 }
4124 if (this.variable !== null &&
4125 this.variable instanceof LocalVariable &&
4126 this.variable.additionalInitializers !== null) {
4127 this.variable.consolidateInitializers();
4128 }
4129 }
4130 declare(kind, init) {
4131 let variable;
4132 switch (kind) {
4133 case 'var':
4134 variable = this.scope.addDeclaration(this, this.context, init, true);
4135 break;
4136 case 'function':
4137 // in strict mode, functions are only hoisted within a scope but not across block scopes
4138 variable = this.scope.addDeclaration(this, this.context, init, false);
4139 break;
4140 case 'let':
4141 case 'const':
4142 case 'class':
4143 variable = this.scope.addDeclaration(this, this.context, init, false);
4144 break;
4145 case 'parameter':
4146 variable = this.scope.addParameterDeclaration(this);
4147 break;
4148 /* istanbul ignore next */
4149 default:
4150 /* istanbul ignore next */
4151 throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
4152 }
4153 return [(this.variable = variable)];
4154 }
4155 deoptimizePath(path) {
4156 if (!this.bound)
4157 this.bind();
4158 if (path.length === 0 && !this.scope.contains(this.name)) {
4159 this.disallowImportReassignment();
4160 }
4161 this.variable.deoptimizePath(path);
4162 }
4163 getLiteralValueAtPath(path, recursionTracker, origin) {
4164 if (!this.bound)
4165 this.bind();
4166 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
4167 }
4168 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
4169 if (!this.bound)
4170 this.bind();
4171 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
4172 }
4173 hasEffects() {
4174 return (this.context.options.treeshake.unknownGlobalSideEffects &&
4175 this.variable instanceof GlobalVariable &&
4176 this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
4177 }
4178 hasEffectsWhenAccessedAtPath(path, context) {
4179 return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
4180 }
4181 hasEffectsWhenAssignedAtPath(path, context) {
4182 return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
4183 }
4184 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4185 return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
4186 }
4187 include() {
4188 if (!this.included) {
4189 this.included = true;
4190 if (this.variable !== null) {
4191 this.context.includeVariable(this.variable);
4192 }
4193 }
4194 }
4195 includeCallArguments(context, args) {
4196 this.variable.includeCallArguments(context, args);
4197 }
4198 render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
4199 if (this.variable) {
4200 const name = this.variable.getName();
4201 if (name !== this.name) {
4202 code.overwrite(this.start, this.end, name, {
4203 contentOnly: true,
4204 storeName: true
4205 });
4206 if (isShorthandProperty) {
4207 code.prependRight(this.start, `${this.name}: `);
4208 }
4209 }
4210 // In strict mode, any variable named "eval" must be the actual "eval" function
4211 if (name === 'eval' &&
4212 renderedParentType === CallExpression &&
4213 isCalleeOfRenderedParent) {
4214 code.appendRight(this.start, '0, ');
4215 }
4216 }
4217 }
4218 disallowImportReassignment() {
4219 return this.context.error({
4220 code: 'ILLEGAL_REASSIGNMENT',
4221 message: `Illegal reassignment to import '${this.name}'`
4222 }, this.start);
4223 }
4224}
4225
4226class RestElement extends NodeBase {
4227 constructor() {
4228 super(...arguments);
4229 this.declarationInit = null;
4230 }
4231 addExportedVariables(variables, exportNamesByVariable) {
4232 this.argument.addExportedVariables(variables, exportNamesByVariable);
4233 }
4234 bind() {
4235 super.bind();
4236 if (this.declarationInit !== null) {
4237 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
4238 }
4239 }
4240 declare(kind, init) {
4241 this.declarationInit = init;
4242 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
4243 }
4244 deoptimizePath(path) {
4245 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
4246 }
4247 hasEffectsWhenAssignedAtPath(path, context) {
4248 return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
4249 }
4250}
4251
4252class FunctionNode extends NodeBase {
4253 constructor() {
4254 super(...arguments);
4255 this.isPrototypeDeoptimized = false;
4256 }
4257 createScope(parentScope) {
4258 this.scope = new FunctionScope(parentScope, this.context);
4259 }
4260 deoptimizePath(path) {
4261 if (path.length === 1) {
4262 if (path[0] === 'prototype') {
4263 this.isPrototypeDeoptimized = true;
4264 }
4265 else if (path[0] === UnknownKey) {
4266 this.isPrototypeDeoptimized = true;
4267 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
4268 // which means the return expression needs to be reassigned as well
4269 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
4270 }
4271 }
4272 }
4273 getReturnExpressionWhenCalledAtPath(path) {
4274 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
4275 }
4276 hasEffects() {
4277 return this.id !== null && this.id.hasEffects();
4278 }
4279 hasEffectsWhenAccessedAtPath(path) {
4280 if (path.length <= 1)
4281 return false;
4282 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
4283 }
4284 hasEffectsWhenAssignedAtPath(path) {
4285 if (path.length <= 1) {
4286 return false;
4287 }
4288 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
4289 }
4290 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4291 if (path.length > 0)
4292 return true;
4293 for (const param of this.params) {
4294 if (param.hasEffects(context))
4295 return true;
4296 }
4297 const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
4298 context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
4299 const { brokenFlow, ignore } = context;
4300 context.ignore = {
4301 breaks: false,
4302 continues: false,
4303 labels: new Set(),
4304 returnAwaitYield: true
4305 };
4306 if (this.body.hasEffects(context))
4307 return true;
4308 context.brokenFlow = brokenFlow;
4309 if (thisInit) {
4310 context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
4311 }
4312 else {
4313 context.replacedVariableInits.delete(this.scope.thisVariable);
4314 }
4315 context.ignore = ignore;
4316 return false;
4317 }
4318 include(context, includeChildrenRecursively) {
4319 this.included = true;
4320 if (this.id)
4321 this.id.include();
4322 const hasArguments = this.scope.argumentsVariable.included;
4323 for (const param of this.params) {
4324 if (!(param instanceof Identifier$1) || hasArguments) {
4325 param.include(context, includeChildrenRecursively);
4326 }
4327 }
4328 const { brokenFlow } = context;
4329 context.brokenFlow = BROKEN_FLOW_NONE;
4330 this.body.include(context, includeChildrenRecursively);
4331 context.brokenFlow = brokenFlow;
4332 }
4333 includeCallArguments(context, args) {
4334 this.scope.includeCallArguments(context, args);
4335 }
4336 initialise() {
4337 if (this.id !== null) {
4338 this.id.declare('function', this);
4339 }
4340 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
4341 this.body.addImplicitReturnExpressionToScope();
4342 }
4343 parseNode(esTreeNode) {
4344 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
4345 super.parseNode(esTreeNode);
4346 }
4347}
4348FunctionNode.prototype.preventChildBlockScope = true;
4349
4350class FunctionDeclaration extends FunctionNode {
4351 initialise() {
4352 super.initialise();
4353 if (this.id !== null) {
4354 this.id.variable.isId = true;
4355 }
4356 }
4357 parseNode(esTreeNode) {
4358 if (esTreeNode.id !== null) {
4359 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
4360 .parent);
4361 }
4362 super.parseNode(esTreeNode);
4363 }
4364}
4365
4366// The header ends at the first non-white-space after "default"
4367function getDeclarationStart(code, start) {
4368 return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
4369}
4370function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
4371 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
4372 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
4373 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
4374 if (generatorStarPos === -1) {
4375 return declarationEnd;
4376 }
4377 return declarationEnd + generatorStarPos + 1;
4378}
4379class ExportDefaultDeclaration extends NodeBase {
4380 include(context, includeChildrenRecursively) {
4381 super.include(context, includeChildrenRecursively);
4382 if (includeChildrenRecursively) {
4383 this.context.includeVariable(this.variable);
4384 }
4385 }
4386 initialise() {
4387 const declaration = this.declaration;
4388 this.declarationName =
4389 (declaration.id && declaration.id.name) || this.declaration.name;
4390 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
4391 this.context.addExport(this);
4392 }
4393 render(code, options, nodeRenderOptions) {
4394 const { start, end } = nodeRenderOptions;
4395 const declarationStart = getDeclarationStart(code.original, this.start);
4396 if (this.declaration instanceof FunctionDeclaration) {
4397 this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
4398 }
4399 else if (this.declaration instanceof ClassDeclaration) {
4400 this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
4401 }
4402 else if (this.variable.getOriginalVariable() !== this.variable) {
4403 // Remove altogether to prevent re-declaring the same variable
4404 treeshakeNode(this, code, start, end);
4405 return;
4406 }
4407 else if (this.variable.included) {
4408 this.renderVariableDeclaration(code, declarationStart, options);
4409 }
4410 else {
4411 code.remove(this.start, declarationStart);
4412 this.declaration.render(code, options, {
4413 isCalleeOfRenderedParent: false,
4414 renderedParentType: ExpressionStatement
4415 });
4416 if (code.original[this.end - 1] !== ';') {
4417 code.appendLeft(this.end, ';');
4418 }
4419 return;
4420 }
4421 this.declaration.render(code, options);
4422 }
4423 renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
4424 const name = this.variable.getName();
4425 // Remove `export default`
4426 code.remove(this.start, declarationStart);
4427 if (needsId) {
4428 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
4429 }
4430 if (options.format === 'system' &&
4431 this.declaration instanceof ClassDeclaration &&
4432 options.exportNamesByVariable.has(this.variable)) {
4433 code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
4434 }
4435 }
4436 renderVariableDeclaration(code, declarationStart, options) {
4437 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
4438 const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
4439 if (systemExportNames) {
4440 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
4441 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
4442 }
4443 else {
4444 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
4445 if (!hasTrailingSemicolon) {
4446 code.appendLeft(this.end, ';');
4447 }
4448 }
4449 }
4450}
4451ExportDefaultDeclaration.prototype.needsBoundaries = true;
4452
4453class UndefinedVariable extends Variable {
4454 constructor() {
4455 super('undefined');
4456 }
4457 getLiteralValueAtPath() {
4458 return undefined;
4459 }
4460}
4461
4462class ExportDefaultVariable extends LocalVariable {
4463 constructor(name, exportDefaultDeclaration, context) {
4464 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
4465 this.hasId = false;
4466 // Not initialised during construction
4467 this.originalId = null;
4468 this.originalVariableAndDeclarationModules = null;
4469 const declaration = exportDefaultDeclaration.declaration;
4470 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
4471 declaration.id) {
4472 this.hasId = true;
4473 this.originalId = declaration.id;
4474 }
4475 else if (declaration instanceof Identifier$1) {
4476 this.originalId = declaration;
4477 }
4478 }
4479 addReference(identifier) {
4480 if (!this.hasId) {
4481 this.name = identifier.name;
4482 }
4483 }
4484 getAssignedVariableName() {
4485 return (this.originalId && this.originalId.name) || null;
4486 }
4487 getBaseVariableName() {
4488 const original = this.getOriginalVariable();
4489 if (original === this) {
4490 return super.getBaseVariableName();
4491 }
4492 else {
4493 return original.getBaseVariableName();
4494 }
4495 }
4496 getName() {
4497 const original = this.getOriginalVariable();
4498 if (original === this) {
4499 return super.getName();
4500 }
4501 else {
4502 return original.getName();
4503 }
4504 }
4505 getOriginalVariable() {
4506 return this.getOriginalVariableAndDeclarationModules().original;
4507 }
4508 getOriginalVariableAndDeclarationModules() {
4509 if (this.originalVariableAndDeclarationModules === null) {
4510 if (!this.originalId ||
4511 (!this.hasId &&
4512 (this.originalId.variable.isReassigned ||
4513 this.originalId.variable instanceof UndefinedVariable))) {
4514 this.originalVariableAndDeclarationModules = { modules: [], original: this };
4515 }
4516 else {
4517 const assignedOriginal = this.originalId.variable;
4518 if (assignedOriginal instanceof ExportDefaultVariable) {
4519 const { modules, original } = assignedOriginal.getOriginalVariableAndDeclarationModules();
4520 this.originalVariableAndDeclarationModules = {
4521 modules: modules.concat(this.module),
4522 original
4523 };
4524 }
4525 else {
4526 this.originalVariableAndDeclarationModules = {
4527 modules: [this.module],
4528 original: assignedOriginal
4529 };
4530 }
4531 }
4532 }
4533 return this.originalVariableAndDeclarationModules;
4534 }
4535}
4536
4537const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
4538
4539class ExportShimVariable extends Variable {
4540 constructor(module) {
4541 super(MISSING_EXPORT_SHIM_VARIABLE);
4542 this.module = module;
4543 }
4544}
4545
4546class NamespaceVariable extends Variable {
4547 constructor(context, syntheticNamedExports) {
4548 super(context.getModuleName());
4549 this.memberVariables = null;
4550 this.mergedNamespaces = [];
4551 this.referencedEarly = false;
4552 this.references = [];
4553 this.context = context;
4554 this.module = context.module;
4555 this.syntheticNamedExports = syntheticNamedExports;
4556 }
4557 addReference(identifier) {
4558 this.references.push(identifier);
4559 this.name = identifier.name;
4560 }
4561 // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
4562 // build fails due to an illegal namespace reassignment or MemberExpression already forwards
4563 // the reassignment to the right variable. This means we lost track of this variable and thus
4564 // need to reassign all exports.
4565 deoptimizePath() {
4566 const memberVariables = this.getMemberVariables();
4567 for (const key of Object.keys(memberVariables)) {
4568 memberVariables[key].deoptimizePath(UNKNOWN_PATH);
4569 }
4570 }
4571 getMemberVariables() {
4572 if (this.memberVariables) {
4573 return this.memberVariables;
4574 }
4575 const memberVariables = Object.create(null);
4576 for (const name of this.context.getExports().concat(this.context.getReexports())) {
4577 if (name[0] !== '*' && name !== this.module.syntheticNamedExports) {
4578 memberVariables[name] = this.context.traceExport(name);
4579 }
4580 }
4581 return (this.memberVariables = memberVariables);
4582 }
4583 include() {
4584 this.included = true;
4585 this.context.includeAllExports();
4586 }
4587 prepareNamespace(mergedNamespaces) {
4588 this.mergedNamespaces = mergedNamespaces;
4589 const moduleExecIndex = this.context.getModuleExecIndex();
4590 for (const identifier of this.references) {
4591 if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
4592 this.referencedEarly = true;
4593 break;
4594 }
4595 }
4596 }
4597 renderBlock(options) {
4598 const _ = options.compact ? '' : ' ';
4599 const n = options.compact ? '' : '\n';
4600 const t = options.indent;
4601 const memberVariables = this.getMemberVariables();
4602 const members = Object.keys(memberVariables).map(name => {
4603 const original = memberVariables[name];
4604 if (this.referencedEarly || original.isReassigned) {
4605 return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
4606 }
4607 const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
4608 return `${t}${safeName}: ${original.getName()}`;
4609 });
4610 if (options.namespaceToStringTag) {
4611 members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
4612 }
4613 const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
4614 if (!needsObjectAssign)
4615 members.unshift(`${t}__proto__:${_}null`);
4616 let output = `{${n}${members.join(`,${n}`)}${n}}`;
4617 if (needsObjectAssign) {
4618 const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
4619 if (this.mergedNamespaces.length > 0) {
4620 assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
4621 }
4622 if (this.syntheticNamedExports) {
4623 assignmentArgs.push(this.module.getSyntheticNamespace().getName());
4624 }
4625 if (members.length > 0) {
4626 assignmentArgs.push(output);
4627 }
4628 output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
4629 }
4630 if (options.freeze) {
4631 output = `/*#__PURE__*/Object.freeze(${output})`;
4632 }
4633 const name = this.getName();
4634 output = `${options.varOrConst} ${name}${_}=${_}${output};`;
4635 if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
4636 output += `${n}${getSystemExportStatement([this], options)};`;
4637 }
4638 return output;
4639 }
4640 renderFirst() {
4641 return this.referencedEarly;
4642 }
4643}
4644NamespaceVariable.prototype.isNamespace = true;
4645
4646class SyntheticNamedExportVariable extends Variable {
4647 constructor(context, name, syntheticNamespace) {
4648 super(name);
4649 this.context = context;
4650 this.module = context.module;
4651 this.syntheticNamespace = syntheticNamespace;
4652 }
4653 getBaseVariable() {
4654 let baseVariable = this.syntheticNamespace;
4655 if (baseVariable instanceof ExportDefaultVariable) {
4656 baseVariable = baseVariable.getOriginalVariable();
4657 }
4658 if (baseVariable instanceof SyntheticNamedExportVariable) {
4659 baseVariable = baseVariable.getBaseVariable();
4660 }
4661 return baseVariable;
4662 }
4663 getBaseVariableName() {
4664 return this.syntheticNamespace.getBaseVariableName();
4665 }
4666 getName() {
4667 const name = this.name;
4668 return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
4669 }
4670 include() {
4671 if (!this.included) {
4672 this.included = true;
4673 this.context.includeVariable(this.syntheticNamespace);
4674 }
4675 }
4676 setRenderNames(baseName, name) {
4677 super.setRenderNames(baseName, name);
4678 }
4679}
4680const getPropertyAccess = (name) => {
4681 return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
4682 ? `.${name}`
4683 : `[${JSON.stringify(name)}]`;
4684};
4685
4686const esModuleExport = `Object.defineProperty(exports, '__esModule', { value: true });`;
4687const compactEsModuleExport = `Object.defineProperty(exports,'__esModule',{value:true});`;
4688
4689const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
4690const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
4691const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
4692const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
4693const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
4694const defaultInteropHelpersByInteropType = {
4695 auto: INTEROP_DEFAULT_VARIABLE,
4696 default: null,
4697 defaultOnly: null,
4698 esModule: null,
4699 false: null,
4700 true: INTEROP_DEFAULT_LEGACY_VARIABLE
4701};
4702function isDefaultAProperty(interopType, externalLiveBindings) {
4703 return (interopType === 'esModule' ||
4704 (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
4705}
4706const namespaceInteropHelpersByInteropType = {
4707 auto: INTEROP_NAMESPACE_VARIABLE,
4708 default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
4709 defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
4710 esModule: null,
4711 false: null,
4712 true: INTEROP_NAMESPACE_VARIABLE
4713};
4714function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
4715 return (isDefaultAProperty(interopType, externalLiveBindings) &&
4716 defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
4717}
4718function getDefaultOnlyHelper() {
4719 return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
4720}
4721function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze) {
4722 return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
4723 ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, usedHelpers)
4724 : '').join('');
4725}
4726const HELPER_GENERATORS = {
4727 [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
4728 `e${_}&&${_}e.__esModule${_}?${_}` +
4729 `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
4730 [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
4731 `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
4732 `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
4733 [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
4734 (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
4735 ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
4736 : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
4737 createNamespaceObject(_, n, t, t, liveBindings, freeze)) +
4738 `}${n}${n}`,
4739 [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
4740 createNamespaceObject(_, n, t, t, liveBindings, freeze) +
4741 `}${n}${n}`,
4742 [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
4743 `${t}return ${getFrozen(`{__proto__: null,${_}'default':${_}e}`, freeze)};${n}` +
4744 `}${n}${n}`
4745};
4746function getDefaultLiveBinding(_) {
4747 return `e${_}:${_}{${_}'default':${_}e${_}}`;
4748}
4749function getDefaultStatic(_) {
4750 return `e['default']${_}:${_}e`;
4751}
4752function createNamespaceObject(_, n, t, i, liveBindings, freeze) {
4753 return (`${i}var n${_}=${_}Object.create(null);${n}` +
4754 `${i}if${_}(e)${_}{${n}` +
4755 `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
4756 (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
4757 `${i}${t}});${n}` +
4758 `${i}}${n}` +
4759 `${i}n['default']${_}=${_}e;${n}` +
4760 `${i}return ${getFrozen('n', freeze)};${n}`);
4761}
4762function copyPropertyLiveBinding(_, n, t, i) {
4763 return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
4764 `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
4765 `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
4766 `${i}${t}${t}enumerable:${_}true,${n}` +
4767 `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
4768 `${i}${t}${t}${t}return e[k];${n}` +
4769 `${i}${t}${t}}${n}` +
4770 `${i}${t}});${n}` +
4771 `${i}}${n}`);
4772}
4773function copyPropertyStatic(_, n, _t, i) {
4774 return `${i}n[k]${_}=${_}e[k];${n}`;
4775}
4776function getFrozen(fragment, freeze) {
4777 return freeze ? `Object.freeze(${fragment})` : fragment;
4778}
4779const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
4780
4781function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
4782 const _ = compact ? '' : ' ';
4783 const n = compact ? '' : '\n';
4784 if (!namedExportsMode) {
4785 return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
4786 }
4787 let exportBlock = '';
4788 // star exports must always output first for precedence
4789 for (const { name, reexports } of dependencies) {
4790 if (reexports && namedExportsMode) {
4791 for (const specifier of reexports) {
4792 if (specifier.reexported === '*') {
4793 if (exportBlock)
4794 exportBlock += n;
4795 if (specifier.needsLiveBinding) {
4796 exportBlock +=
4797 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
4798 `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
4799 `${t}${t}enumerable:${_}true,${n}` +
4800 `${t}${t}get:${_}function${_}()${_}{${n}` +
4801 `${t}${t}${t}return ${name}[k];${n}` +
4802 `${t}${t}}${n}${t}});${n}});`;
4803 }
4804 else {
4805 exportBlock +=
4806 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
4807 `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
4808 }
4809 }
4810 }
4811 }
4812 }
4813 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
4814 if (reexports && namedExportsMode) {
4815 for (const specifier of reexports) {
4816 if (specifier.reexported !== '*') {
4817 const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
4818 if (exportBlock)
4819 exportBlock += n;
4820 exportBlock +=
4821 specifier.imported !== '*' && specifier.needsLiveBinding
4822 ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
4823 `${t}enumerable:${_}true,${n}` +
4824 `${t}get:${_}function${_}()${_}{${n}` +
4825 `${t}${t}return ${importName};${n}${t}}${n}});`
4826 : `exports.${specifier.reexported}${_}=${_}${importName};`;
4827 }
4828 }
4829 }
4830 }
4831 for (const chunkExport of exports) {
4832 const lhs = `exports.${chunkExport.exported}`;
4833 const rhs = chunkExport.local;
4834 if (lhs !== rhs) {
4835 if (exportBlock)
4836 exportBlock += n;
4837 exportBlock += `${lhs}${_}=${_}${rhs};`;
4838 }
4839 }
4840 if (exportBlock) {
4841 return `${n}${n}${exportBlock}`;
4842 }
4843 return '';
4844}
4845function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
4846 if (exports.length > 0) {
4847 return exports[0].local;
4848 }
4849 else {
4850 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
4851 if (reexports) {
4852 return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
4853 }
4854 }
4855 }
4856}
4857function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
4858 if (imported === 'default') {
4859 if (!isChunk) {
4860 const moduleInterop = String(interop(moduleId));
4861 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
4862 ? defaultVariableName
4863 : moduleVariableName;
4864 return isDefaultAProperty(moduleInterop, externalLiveBindings)
4865 ? `${variableName}['default']`
4866 : variableName;
4867 }
4868 return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
4869 }
4870 if (imported === '*') {
4871 return (isChunk
4872 ? !depNamedExportsMode
4873 : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
4874 ? namespaceVariableName
4875 : moduleVariableName;
4876 }
4877 return `${moduleVariableName}.${imported}`;
4878}
4879
4880function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, accessedGlobals, _, n, s, t) {
4881 const neededInteropHelpers = new Set();
4882 const interopStatements = [];
4883 const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
4884 neededInteropHelpers.add(helper);
4885 interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
4886 };
4887 for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
4888 if (isChunk) {
4889 for (const { imported, reexported } of [
4890 ...(imports || []),
4891 ...(reexports || [])
4892 ]) {
4893 if (imported === '*' && reexported !== '*') {
4894 if (!namedExportsMode) {
4895 addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
4896 }
4897 break;
4898 }
4899 }
4900 }
4901 else {
4902 const moduleInterop = String(interop(id));
4903 let hasDefault = false;
4904 let hasNamespace = false;
4905 for (const { imported, reexported } of [
4906 ...(imports || []),
4907 ...(reexports || [])
4908 ]) {
4909 let helper;
4910 let variableName;
4911 if (imported === 'default') {
4912 if (!hasDefault) {
4913 hasDefault = true;
4914 if (defaultVariableName !== namespaceVariableName) {
4915 variableName = defaultVariableName;
4916 helper = defaultInteropHelpersByInteropType[moduleInterop];
4917 }
4918 }
4919 }
4920 else if (imported === '*' && reexported !== '*') {
4921 if (!hasNamespace) {
4922 hasNamespace = true;
4923 helper = namespaceInteropHelpersByInteropType[moduleInterop];
4924 variableName = namespaceVariableName;
4925 }
4926 }
4927 if (helper) {
4928 addInteropStatement(variableName, helper, name);
4929 }
4930 }
4931 }
4932 }
4933 return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
4934}
4935
4936const builtins$1 = {
4937 assert: true,
4938 buffer: true,
4939 console: true,
4940 constants: true,
4941 domain: true,
4942 events: true,
4943 http: true,
4944 https: true,
4945 os: true,
4946 path: true,
4947 process: true,
4948 punycode: true,
4949 querystring: true,
4950 stream: true,
4951 string_decoder: true,
4952 timers: true,
4953 tty: true,
4954 url: true,
4955 util: true,
4956 vm: true,
4957 zlib: true
4958};
4959function warnOnBuiltins(warn, dependencies) {
4960 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins$1);
4961 if (!externalBuiltins.length)
4962 return;
4963 const detail = externalBuiltins.length === 1
4964 ? `module ('${externalBuiltins[0]}')`
4965 : `modules (${externalBuiltins
4966 .slice(0, -1)
4967 .map(name => `'${name}'`)
4968 .join(', ')} and '${externalBuiltins.slice(-1)}')`;
4969 warn({
4970 code: 'MISSING_NODE_BUILTINS',
4971 message: `Creating a browser bundle that depends on Node.js built-in ${detail}. You might need to include https://github.com/ionic-team/rollup-plugin-node-polyfills`,
4972 modules: externalBuiltins
4973 });
4974}
4975
4976// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
4977// The assumption is that this makes sense for all relative ids:
4978// https://requirejs.org/docs/api.html#jsfiles
4979function removeExtensionFromRelativeAmdId(id) {
4980 if (id[0] === '.' && id.endsWith('.js')) {
4981 return id.slice(0, -3);
4982 }
4983 return id;
4984}
4985function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst, warn }, { amd: { define: amdDefine, id: amdId }, compact, esModule, externalLiveBindings, freeze, interop, strict }) {
4986 warnOnBuiltins(warn, dependencies);
4987 const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
4988 const args = dependencies.map(m => m.name);
4989 const n = compact ? '' : '\n';
4990 const s = compact ? '' : ';';
4991 const _ = compact ? '' : ' ';
4992 if (namedExportsMode && hasExports) {
4993 args.unshift(`exports`);
4994 deps.unshift(`'exports'`);
4995 }
4996 if (accessedGlobals.has('require')) {
4997 args.unshift('require');
4998 deps.unshift(`'require'`);
4999 }
5000 if (accessedGlobals.has('module')) {
5001 args.unshift('module');
5002 deps.unshift(`'module'`);
5003 }
5004 const params = (amdId ? `'${amdId}',${_}` : ``) + (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
5005 const useStrict = strict ? `${_}'use strict';` : '';
5006 magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, accessedGlobals, _, n, s, t)}`);
5007 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
5008 if (exportBlock)
5009 magicString.append(exportBlock);
5010 if (namedExportsMode && hasExports && isEntryModuleFacade && esModule)
5011 magicString.append(`${n}${n}${compact ? compactEsModuleExport : esModuleExport}`);
5012 if (outro)
5013 magicString.append(outro);
5014 return magicString
5015 .indent(t)
5016 .prepend(`${amdDefine}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
5017 .append(`${n}${n}});`);
5018}
5019
5020function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, strict }) {
5021 const n = compact ? '' : '\n';
5022 const s = compact ? '' : ';';
5023 const _ = compact ? '' : ' ';
5024 const useStrict = strict ? `'use strict';${n}${n}` : '';
5025 const esModuleProp = namedExportsMode && hasExports && isEntryModuleFacade && esModule
5026 ? `${compact ? compactEsModuleExport : esModuleExport}${n}${n}`
5027 : '';
5028 const importBlock = getImportBlock(dependencies, compact, varOrConst, n, _);
5029 const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, accessedGlobals, _, n, s, t);
5030 magicString.prepend(`${useStrict}${intro}${esModuleProp}${importBlock}${interopBlock}`);
5031 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
5032 return magicString.append(`${exportBlock}${outro}`);
5033}
5034function getImportBlock(dependencies, compact, varOrConst, n, _) {
5035 let importBlock = '';
5036 let definingVariable = false;
5037 for (const { id, name, reexports, imports } of dependencies) {
5038 if (!reexports && !imports) {
5039 if (importBlock) {
5040 importBlock += !compact || definingVariable ? `;${n}` : ',';
5041 }
5042 definingVariable = false;
5043 importBlock += `require('${id}')`;
5044 }
5045 else {
5046 importBlock +=
5047 compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
5048 definingVariable = true;
5049 importBlock += `${name}${_}=${_}require('${id}')`;
5050 }
5051 }
5052 if (importBlock) {
5053 return `${importBlock};${n}${n}`;
5054 }
5055 return '';
5056}
5057
5058function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
5059 const _ = compact ? '' : ' ';
5060 const n = compact ? '' : '\n';
5061 const importBlock = getImportBlock$1(dependencies, _);
5062 if (importBlock.length > 0)
5063 intro += importBlock.join(n) + n + n;
5064 if (intro)
5065 magicString.prepend(intro);
5066 const exportBlock = getExportBlock$1(exports, _, varOrConst);
5067 if (exportBlock.length)
5068 magicString.append(n + n + exportBlock.join(n).trim());
5069 if (outro)
5070 magicString.append(outro);
5071 return magicString.trim();
5072}
5073function getImportBlock$1(dependencies, _) {
5074 const importBlock = [];
5075 for (const { id, reexports, imports, name } of dependencies) {
5076 if (!reexports && !imports) {
5077 importBlock.push(`import${_}'${id}';`);
5078 continue;
5079 }
5080 if (imports) {
5081 let defaultImport = null;
5082 let starImport = null;
5083 const importedNames = [];
5084 for (const specifier of imports) {
5085 if (specifier.imported === 'default') {
5086 defaultImport = specifier;
5087 }
5088 else if (specifier.imported === '*') {
5089 starImport = specifier;
5090 }
5091 else {
5092 importedNames.push(specifier);
5093 }
5094 }
5095 if (starImport) {
5096 importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
5097 }
5098 if (defaultImport && importedNames.length === 0) {
5099 importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
5100 }
5101 else if (importedNames.length > 0) {
5102 importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
5103 .map(specifier => {
5104 if (specifier.imported === specifier.local) {
5105 return specifier.imported;
5106 }
5107 else {
5108 return `${specifier.imported} as ${specifier.local}`;
5109 }
5110 })
5111 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
5112 }
5113 }
5114 if (reexports) {
5115 let starExport = null;
5116 const namespaceReexports = [];
5117 const namedReexports = [];
5118 for (const specifier of reexports) {
5119 if (specifier.reexported === '*') {
5120 starExport = specifier;
5121 }
5122 else if (specifier.imported === '*') {
5123 namespaceReexports.push(specifier);
5124 }
5125 else {
5126 namedReexports.push(specifier);
5127 }
5128 }
5129 if (starExport) {
5130 importBlock.push(`export${_}*${_}from${_}'${id}';`);
5131 }
5132 if (namespaceReexports.length > 0) {
5133 if (!imports ||
5134 !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
5135 importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
5136 }
5137 for (const specifier of namespaceReexports) {
5138 importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
5139 }
5140 }
5141 if (namedReexports.length > 0) {
5142 importBlock.push(`export${_}{${_}${namedReexports
5143 .map(specifier => {
5144 if (specifier.imported === specifier.reexported) {
5145 return specifier.imported;
5146 }
5147 else {
5148 return `${specifier.imported} as ${specifier.reexported}`;
5149 }
5150 })
5151 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
5152 }
5153 }
5154 }
5155 return importBlock;
5156}
5157function getExportBlock$1(exports, _, varOrConst) {
5158 const exportBlock = [];
5159 const exportDeclaration = [];
5160 for (const specifier of exports) {
5161 if (specifier.exported === 'default') {
5162 exportBlock.push(`export default ${specifier.local};`);
5163 }
5164 else {
5165 if (specifier.expression) {
5166 exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
5167 }
5168 exportDeclaration.push(specifier.exported === specifier.local
5169 ? specifier.local
5170 : `${specifier.local} as ${specifier.exported}`);
5171 }
5172 }
5173 if (exportDeclaration.length) {
5174 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
5175 }
5176 return exportBlock;
5177}
5178
5179function spaces(i) {
5180 let result = '';
5181 while (i--)
5182 result += ' ';
5183 return result;
5184}
5185function tabsToSpaces(str) {
5186 return str.replace(/^\t+/, match => match.split('\t').join(' '));
5187}
5188function getCodeFrame(source, line, column) {
5189 let lines = source.split('\n');
5190 const frameStart = Math.max(0, line - 3);
5191 let frameEnd = Math.min(line + 2, lines.length);
5192 lines = lines.slice(frameStart, frameEnd);
5193 while (!/\S/.test(lines[lines.length - 1])) {
5194 lines.pop();
5195 frameEnd -= 1;
5196 }
5197 const digits = String(frameEnd).length;
5198 return lines
5199 .map((str, i) => {
5200 const isErrorLine = frameStart + i + 1 === line;
5201 let lineNum = String(i + frameStart + 1);
5202 while (lineNum.length < digits)
5203 lineNum = ` ${lineNum}`;
5204 if (isErrorLine) {
5205 const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
5206 return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
5207 }
5208 return `${lineNum}: ${tabsToSpaces(str)}`;
5209 })
5210 .join('\n');
5211}
5212
5213function error(base) {
5214 if (!(base instanceof Error))
5215 base = Object.assign(new Error(base.message), base);
5216 throw base;
5217}
5218function augmentCodeLocation(props, pos, source, id) {
5219 if (typeof pos === 'object') {
5220 const { line, column } = pos;
5221 props.loc = { file: id, line, column };
5222 }
5223 else {
5224 props.pos = pos;
5225 const { line, column } = locate(source, pos, { offsetLine: 1 });
5226 props.loc = { file: id, line, column };
5227 }
5228 if (props.frame === undefined) {
5229 const { line, column } = props.loc;
5230 props.frame = getCodeFrame(source, line, column);
5231 }
5232}
5233var Errors;
5234(function (Errors) {
5235 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
5236 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
5237 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
5238 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
5239 Errors["BAD_LOADER"] = "BAD_LOADER";
5240 Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
5241 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
5242 Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
5243 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
5244 Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
5245 Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
5246 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
5247 Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
5248 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
5249 Errors["INVALID_OPTION"] = "INVALID_OPTION";
5250 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
5251 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
5252 Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
5253 Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
5254 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
5255 Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
5256 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
5257 Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
5258 Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
5259 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
5260 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
5261 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
5262 Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
5263 Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
5264})(Errors || (Errors = {}));
5265function errAssetNotFinalisedForFileName(name) {
5266 return {
5267 code: Errors.ASSET_NOT_FINALISED,
5268 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
5269 };
5270}
5271function errCannotEmitFromOptionsHook() {
5272 return {
5273 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
5274 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
5275 };
5276}
5277function errChunkNotGeneratedForFileName(name) {
5278 return {
5279 code: Errors.CHUNK_NOT_GENERATED,
5280 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
5281 };
5282}
5283function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
5284 return {
5285 code: Errors.ASSET_NOT_FOUND,
5286 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
5287 };
5288}
5289function errAssetSourceAlreadySet(name) {
5290 return {
5291 code: Errors.ASSET_SOURCE_ALREADY_SET,
5292 message: `Unable to set the source for asset "${name}", source already set.`
5293 };
5294}
5295function errNoAssetSourceSet(assetName) {
5296 return {
5297 code: Errors.ASSET_SOURCE_MISSING,
5298 message: `Plugin error creating asset "${assetName}" - no asset source set.`
5299 };
5300}
5301function errBadLoader(id) {
5302 return {
5303 code: Errors.BAD_LOADER,
5304 message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
5305 };
5306}
5307function errDeprecation(deprecation) {
5308 return {
5309 code: Errors.DEPRECATED_FEATURE,
5310 ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
5311 };
5312}
5313function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
5314 return {
5315 code: Errors.FILE_NOT_FOUND,
5316 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
5317 };
5318}
5319function errFileNameConflict(fileName) {
5320 return {
5321 code: Errors.FILE_NAME_CONFLICT,
5322 message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
5323 };
5324}
5325function errInputHookInOutputPlugin(pluginName, hookName) {
5326 return {
5327 code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
5328 message: `The "${hookName}" hook used by the output plugin ${pluginName} is a build time hook and will not be run for that plugin. Either this plugin cannot be used as an output plugin, or it should have an option to configure it as an output plugin.`
5329 };
5330}
5331function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
5332 return {
5333 code: Errors.INVALID_CHUNK,
5334 message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
5335 };
5336}
5337function errInvalidExportOptionValue(optionValue) {
5338 return {
5339 code: Errors.INVALID_EXPORT_OPTION,
5340 message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
5341 url: `https://rollupjs.org/guide/en/#outputexports`
5342 };
5343}
5344function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
5345 return {
5346 code: 'INVALID_EXPORT_OPTION',
5347 message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
5348 };
5349}
5350function errInternalIdCannotBeExternal(source, importer) {
5351 return {
5352 code: Errors.INVALID_EXTERNAL_ID,
5353 message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
5354 };
5355}
5356function errInvalidOption(option, explanation) {
5357 return {
5358 code: Errors.INVALID_OPTION,
5359 message: `Invalid value for option "${option}" - ${explanation}.`
5360 };
5361}
5362function errInvalidRollupPhaseForAddWatchFile() {
5363 return {
5364 code: Errors.INVALID_ROLLUP_PHASE,
5365 message: `Cannot call addWatchFile after the build has finished.`
5366 };
5367}
5368function errInvalidRollupPhaseForChunkEmission() {
5369 return {
5370 code: Errors.INVALID_ROLLUP_PHASE,
5371 message: `Cannot emit chunks after module loading has finished.`
5372 };
5373}
5374function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
5375 return {
5376 code: Errors.MISSING_IMPLICIT_DEPENDANT,
5377 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
5378 };
5379}
5380function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
5381 return {
5382 code: Errors.MISSING_IMPLICIT_DEPENDANT,
5383 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
5384 };
5385}
5386function errImplicitDependantIsNotIncluded(module) {
5387 const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
5388 return {
5389 code: Errors.MISSING_IMPLICIT_DEPENDANT,
5390 message: `Module "${relativeId(module.id)}" that should be implicitly loaded before "${implicitDependencies.length === 1
5391 ? implicitDependencies[0]
5392 : `${implicitDependencies.slice(0, -1).join('", "')}" and "${implicitDependencies.slice(-1)[0]}`}" is not included in the module graph. Either it was not imported by an included module or only via a tree-shaken dynamic import, or no imported bindings were used and it had otherwise no side-effects.`
5393 };
5394}
5395function errMixedExport(facadeModuleId, name) {
5396 return {
5397 code: Errors.MIXED_EXPORTS,
5398 id: facadeModuleId,
5399 message: `Entry module "${relativeId(facadeModuleId)}" is using named and default exports together. Consumers of your bundle will have to use \`${name || 'chunk'}["default"]\` to access the default export, which may not be what you want. Use \`output.exports: "named"\` to disable this warning`,
5400 url: `https://rollupjs.org/guide/en/#outputexports`
5401 };
5402}
5403function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
5404 return {
5405 code: Errors.NAMESPACE_CONFLICT,
5406 message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
5407 name,
5408 reexporter: reexportingModule.id,
5409 sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
5410 };
5411}
5412function errNoTransformMapOrAstWithoutCode(pluginName) {
5413 return {
5414 code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
5415 message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
5416 'a "code". This will be ignored.'
5417 };
5418}
5419function errPreferNamedExports(facadeModuleId) {
5420 const file = relativeId(facadeModuleId);
5421 return {
5422 code: Errors.PREFER_NAMED_EXPORTS,
5423 id: facadeModuleId,
5424 message: `Entry module "${file}" is implicitly using "default" export mode, which means for CommonJS output that its default export is assigned to "module.exports". For many tools, such CommonJS output will not be interchangeable with the original ES module. If this is intended, explicitly set "output.exports" to either "auto" or "default", otherwise you might want to consider changing the signature of "${file}" to use named exports only.`,
5425 url: `https://rollupjs.org/guide/en/#outputexports`
5426 };
5427}
5428function errUnexpectedNamedImport(id, imported, isReexport) {
5429 const importType = isReexport ? 'reexport' : 'import';
5430 return {
5431 code: Errors.UNEXPECTED_NAMED_IMPORT,
5432 id,
5433 message: `The named export "${imported}" was ${importType}ed from the external module ${relativeId(id)} even though its interop type is "defaultOnly". Either remove or change this ${importType} or change the value of the "output.interop" option.`,
5434 url: 'https://rollupjs.org/guide/en/#outputinterop'
5435 };
5436}
5437function errUnexpectedNamespaceReexport(id) {
5438 return {
5439 code: Errors.UNEXPECTED_NAMED_IMPORT,
5440 id,
5441 message: `There was a namespace "*" reexport from the external module ${relativeId(id)} even though its interop type is "defaultOnly". This will be ignored as namespace reexports only reexport named exports. If this is not intended, either remove or change this reexport or change the value of the "output.interop" option.`,
5442 url: 'https://rollupjs.org/guide/en/#outputinterop'
5443 };
5444}
5445function errEntryCannotBeExternal(unresolvedId) {
5446 return {
5447 code: Errors.UNRESOLVED_ENTRY,
5448 message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
5449 };
5450}
5451function errUnresolvedEntry(unresolvedId) {
5452 return {
5453 code: Errors.UNRESOLVED_ENTRY,
5454 message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
5455 };
5456}
5457function errUnresolvedImport(source, importer) {
5458 return {
5459 code: Errors.UNRESOLVED_IMPORT,
5460 message: `Could not resolve '${source}' from ${relativeId(importer)}`
5461 };
5462}
5463function errUnresolvedImportTreatedAsExternal(source, importer) {
5464 return {
5465 code: Errors.UNRESOLVED_IMPORT,
5466 importer: relativeId(importer),
5467 message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
5468 source,
5469 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
5470 };
5471}
5472function errExternalSyntheticExports(source, importer) {
5473 return {
5474 code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
5475 importer: relativeId(importer),
5476 message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
5477 source
5478 };
5479}
5480function errFailedValidation(message) {
5481 return {
5482 code: Errors.VALIDATION_ERROR,
5483 message
5484 };
5485}
5486function warnDeprecation(deprecation, activeDeprecation, options) {
5487 warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
5488}
5489function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
5490 if (activeDeprecation || strictDeprecations) {
5491 const warning = errDeprecation(deprecation);
5492 if (strictDeprecations) {
5493 return error(warning);
5494 }
5495 warn(warning);
5496 }
5497}
5498
5499// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
5500// if the property name isn't trivial
5501const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
5502function property(prop) {
5503 return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
5504}
5505function keypath(keypath) {
5506 return keypath
5507 .split('.')
5508 .map(property)
5509 .join('');
5510}
5511
5512function setupNamespace(name, root, globals, compact) {
5513 const _ = compact ? '' : ' ';
5514 const parts = name.split('.');
5515 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
5516 parts.pop();
5517 let acc = root;
5518 return (parts
5519 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
5520 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
5521}
5522function assignToDeepVariable(deepName, root, globals, compact, assignment) {
5523 const _ = compact ? '' : ' ';
5524 const parts = deepName.split('.');
5525 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
5526 const last = parts.pop();
5527 let acc = root;
5528 let deepAssignment = parts
5529 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
5530 .concat(`${acc}${property(last)}`)
5531 .join(`,${_}`)
5532 .concat(`${_}=${_}${assignment}`);
5533 if (parts.length > 0) {
5534 deepAssignment = `(${deepAssignment})`;
5535 }
5536 return deepAssignment;
5537}
5538
5539function trimEmptyImports(dependencies) {
5540 let i = dependencies.length;
5541 while (i--) {
5542 const { imports, reexports } = dependencies[i];
5543 if (imports || reexports) {
5544 return dependencies.slice(0, i + 1);
5545 }
5546 }
5547 return [];
5548}
5549
5550const thisProp = (name) => `this${keypath(name)}`;
5551function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, extend, freeze, externalLiveBindings, globals, interop, name, strict }) {
5552 const _ = compact ? '' : ' ';
5553 const s = compact ? '' : ';';
5554 const n = compact ? '' : '\n';
5555 const isNamespaced = name && name.indexOf('.') !== -1;
5556 const useVariableAssignment = !extend && !isNamespaced;
5557 if (name && useVariableAssignment && !isLegal(name)) {
5558 return error({
5559 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
5560 message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
5561 });
5562 }
5563 warnOnBuiltins(warn, dependencies);
5564 const external = trimEmptyImports(dependencies);
5565 const deps = external.map(dep => dep.globalName || 'null');
5566 const args = external.map(m => m.name);
5567 if (hasExports && !name) {
5568 warn({
5569 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
5570 message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
5571 });
5572 }
5573 if (namedExportsMode && hasExports) {
5574 if (extend) {
5575 deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
5576 args.unshift('exports');
5577 }
5578 else {
5579 deps.unshift('{}');
5580 args.unshift('exports');
5581 }
5582 }
5583 const useStrict = strict ? `${t}'use strict';${n}` : '';
5584 const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, accessedGlobals, _, n, s, t);
5585 magicString.prepend(`${intro}${interopBlock}`);
5586 let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
5587 if (hasExports) {
5588 if (name && !(extend && namedExportsMode)) {
5589 wrapperIntro =
5590 (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
5591 `${_}=${_}${wrapperIntro}`;
5592 }
5593 if (isNamespaced) {
5594 wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
5595 }
5596 }
5597 let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
5598 if (hasExports && !extend && namedExportsMode) {
5599 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
5600 }
5601 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
5602 magicString.append(`${exportBlock}${outro}`);
5603 return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
5604}
5605
5606function getStarExcludes({ dependencies, exports }) {
5607 const starExcludes = new Set(exports.map(expt => expt.exported));
5608 if (!starExcludes.has('default'))
5609 starExcludes.add('default');
5610 // also include reexport names
5611 for (const { reexports } of dependencies) {
5612 if (reexports) {
5613 for (const reexport of reexports) {
5614 if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
5615 starExcludes.add(reexport.reexported);
5616 }
5617 }
5618 }
5619 return starExcludes;
5620}
5621const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
5622 ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
5623 .map(prop => `${prop}:${_}1`)
5624 .join(`,${_}`)}${_}};`
5625 : '';
5626const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
5627function getExportsBlock(exports, _, t, n) {
5628 if (exports.length === 0) {
5629 return '';
5630 }
5631 if (exports.length === 1) {
5632 return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
5633 }
5634 return (`${t}${t}${t}exports({${n}` +
5635 exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
5636 `${n}${t}${t}${t}});${n}${n}`);
5637}
5638const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5639 .filter(expt => expt.hoisted || expt.uninitialized)
5640 .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
5641const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5642 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
5643 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
5644const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5645 .filter(expt => expt.expression)
5646 .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
5647function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
5648 const n = options.compact ? '' : '\n';
5649 const _ = options.compact ? '' : ' ';
5650 const dependencyIds = dependencies.map(m => `'${m.id}'`);
5651 const importBindings = [];
5652 let starExcludes;
5653 const setters = [];
5654 for (const { imports, reexports } of dependencies) {
5655 const setter = [];
5656 if (imports) {
5657 for (const specifier of imports) {
5658 importBindings.push(specifier.local);
5659 if (specifier.imported === '*') {
5660 setter.push(`${specifier.local}${_}=${_}module;`);
5661 }
5662 else {
5663 setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
5664 }
5665 }
5666 }
5667 if (reexports) {
5668 let createdSetter = false;
5669 // bulk-reexport form
5670 if (reexports.length > 1 ||
5671 (reexports.length === 1 &&
5672 (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
5673 // star reexports
5674 for (const specifier of reexports) {
5675 if (specifier.reexported !== '*')
5676 continue;
5677 // need own exports list for deduping in star export case
5678 if (!starExcludes) {
5679 starExcludes = getStarExcludes({ dependencies, exports });
5680 }
5681 if (!createdSetter) {
5682 setter.push(`${varOrConst} _setter${_}=${_}{};`);
5683 createdSetter = true;
5684 }
5685 setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
5686 setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
5687 setter.push('}');
5688 }
5689 // star import reexport
5690 for (const specifier of reexports) {
5691 if (specifier.imported !== '*' || specifier.reexported === '*')
5692 continue;
5693 setter.push(`exports('${specifier.reexported}',${_}module);`);
5694 }
5695 // reexports
5696 for (const specifier of reexports) {
5697 if (specifier.reexported === '*' || specifier.imported === '*')
5698 continue;
5699 if (!createdSetter) {
5700 setter.push(`${varOrConst} _setter${_}=${_}{};`);
5701 createdSetter = true;
5702 }
5703 setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
5704 }
5705 if (createdSetter) {
5706 setter.push('exports(_setter);');
5707 }
5708 }
5709 else {
5710 // single reexport
5711 for (const specifier of reexports) {
5712 setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
5713 }
5714 }
5715 }
5716 setters.push(setter.join(`${n}${t}${t}${t}`));
5717 }
5718 const registeredName = options.name ? `'${options.name}',${_}` : '';
5719 const wrapperParams = accessedGlobals.has('module')
5720 ? `exports,${_}module`
5721 : hasExports
5722 ? 'exports'
5723 : '';
5724 let wrapperStart = `System.register(${registeredName}[` +
5725 dependencyIds.join(`,${_}`) +
5726 `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
5727 getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
5728 getImportBindingsBlock(importBindings, _, t, n) +
5729 `${n}${t}return${_}{${setters.length
5730 ? `${n}${t}${t}setters:${_}[${setters
5731 .map(s => s
5732 ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
5733 : options.systemNullSetters
5734 ? `null`
5735 : `function${_}()${_}{}`)
5736 .join(`,${_}`)}],`
5737 : ''}${n}`;
5738 wrapperStart +=
5739 `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
5740 getHoistedExportsBlock(exports, _, t, n);
5741 const wrapperEnd = `${n}${n}` +
5742 getSyntheticExportsBlock(exports, _, t, n) +
5743 getMissingExportsBlock(exports, _, t, n) +
5744 `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
5745 if (intro)
5746 magicString.prepend(intro);
5747 if (outro)
5748 magicString.append(outro);
5749 return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
5750}
5751
5752function globalProp(name, globalVar) {
5753 if (!name)
5754 return 'null';
5755 return `${globalVar}${keypath(name)}`;
5756}
5757function safeAccess(name, globalVar, _) {
5758 const parts = name.split('.');
5759 let acc = globalVar;
5760 return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
5761}
5762function umd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { amd: { define: amdDefine, id: amdId }, compact, esModule, extend, externalLiveBindings, freeze, interop, name, globals, noConflict, strict }) {
5763 const _ = compact ? '' : ' ';
5764 const n = compact ? '' : '\n';
5765 const s = compact ? '' : ';';
5766 const factoryVar = compact ? 'f' : 'factory';
5767 const globalVar = compact ? 'g' : 'global';
5768 if (hasExports && !name) {
5769 return error({
5770 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
5771 message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
5772 });
5773 }
5774 warnOnBuiltins(warn, dependencies);
5775 const amdDeps = dependencies.map(m => `'${m.id}'`);
5776 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
5777 const trimmedImports = trimEmptyImports(dependencies);
5778 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
5779 const factoryArgs = trimmedImports.map(m => m.name);
5780 if (namedExportsMode && (hasExports || noConflict)) {
5781 amdDeps.unshift(`'exports'`);
5782 cjsDeps.unshift(`exports`);
5783 globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
5784 factoryArgs.unshift('exports');
5785 }
5786 const amdParams = (amdId ? `'${amdId}',${_}` : ``) + (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
5787 const define = amdDefine;
5788 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
5789 const useStrict = strict ? `${_}'use strict';${n}` : ``;
5790 let iifeExport;
5791 if (noConflict) {
5792 const noConflictExportsVar = compact ? 'e' : 'exports';
5793 let factory;
5794 if (!namedExportsMode && hasExports) {
5795 factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
5796 }
5797 else {
5798 const module = globalDeps.shift();
5799 factory =
5800 `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
5801 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
5802 }
5803 iifeExport =
5804 `(function${_}()${_}{${n}` +
5805 `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
5806 `${t}${t}${factory}${n}` +
5807 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
5808 `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
5809 `${t}}())`;
5810 }
5811 else {
5812 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
5813 if (!namedExportsMode && hasExports) {
5814 iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
5815 }
5816 }
5817 const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
5818 const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
5819 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
5820 const iifeStart = iifeNeedsGlobal
5821 ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
5822 : '';
5823 const iifeEnd = iifeNeedsGlobal ? ')' : '';
5824 const cjsIntro = iifeNeedsGlobal
5825 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
5826 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
5827 : '';
5828 // factory function should be wrapped by parentheses to avoid lazy parsing
5829 const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
5830 cjsIntro +
5831 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
5832 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
5833 `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
5834 const wrapperOutro = n + n + '})));';
5835 magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, accessedGlobals, _, n, s, t)}`);
5836 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
5837 if (exportBlock)
5838 magicString.append(exportBlock);
5839 if (namedExportsMode && hasExports && esModule)
5840 magicString.append(n + n + (compact ? compactEsModuleExport : esModuleExport));
5841 if (outro)
5842 magicString.append(outro);
5843 return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
5844}
5845
5846var finalisers = { system, amd, cjs, es, iife, umd };
5847
5848const extractors = {
5849 ArrayPattern(names, param) {
5850 for (const element of param.elements) {
5851 if (element)
5852 extractors[element.type](names, element);
5853 }
5854 },
5855 AssignmentPattern(names, param) {
5856 extractors[param.left.type](names, param.left);
5857 },
5858 Identifier(names, param) {
5859 names.push(param.name);
5860 },
5861 MemberExpression() { },
5862 ObjectPattern(names, param) {
5863 for (const prop of param.properties) {
5864 if (prop.type === 'RestElement') {
5865 extractors.RestElement(names, prop);
5866 }
5867 else {
5868 extractors[prop.value.type](names, prop.value);
5869 }
5870 }
5871 },
5872 RestElement(names, param) {
5873 extractors[param.argument.type](names, param.argument);
5874 }
5875};
5876const extractAssignedNames = function extractAssignedNames(param) {
5877 const names = [];
5878 extractors[param.type](names, param);
5879 return names;
5880};
5881
5882class ExportAllDeclaration extends NodeBase {
5883 hasEffects() {
5884 return false;
5885 }
5886 initialise() {
5887 this.context.addExport(this);
5888 }
5889 render(code, _options, nodeRenderOptions) {
5890 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
5891 }
5892}
5893ExportAllDeclaration.prototype.needsBoundaries = true;
5894
5895class ArrayExpression extends NodeBase {
5896 bind() {
5897 super.bind();
5898 for (const element of this.elements) {
5899 if (element !== null)
5900 element.deoptimizePath(UNKNOWN_PATH);
5901 }
5902 }
5903 getReturnExpressionWhenCalledAtPath(path) {
5904 if (path.length !== 1)
5905 return UNKNOWN_EXPRESSION;
5906 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
5907 }
5908 hasEffectsWhenAccessedAtPath(path) {
5909 return path.length > 1;
5910 }
5911 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5912 if (path.length === 1) {
5913 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
5914 }
5915 return true;
5916 }
5917}
5918
5919class ArrayPattern extends NodeBase {
5920 addExportedVariables(variables, exportNamesByVariable) {
5921 for (const element of this.elements) {
5922 if (element !== null) {
5923 element.addExportedVariables(variables, exportNamesByVariable);
5924 }
5925 }
5926 }
5927 declare(kind) {
5928 const variables = [];
5929 for (const element of this.elements) {
5930 if (element !== null) {
5931 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
5932 }
5933 }
5934 return variables;
5935 }
5936 deoptimizePath(path) {
5937 if (path.length === 0) {
5938 for (const element of this.elements) {
5939 if (element !== null) {
5940 element.deoptimizePath(path);
5941 }
5942 }
5943 }
5944 }
5945 hasEffectsWhenAssignedAtPath(path, context) {
5946 if (path.length > 0)
5947 return true;
5948 for (const element of this.elements) {
5949 if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
5950 return true;
5951 }
5952 return false;
5953 }
5954}
5955
5956class BlockScope extends ChildScope {
5957 addDeclaration(identifier, context, init, isHoisted) {
5958 if (isHoisted) {
5959 return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, isHoisted);
5960 }
5961 else {
5962 return super.addDeclaration(identifier, context, init, false);
5963 }
5964 }
5965}
5966
5967class ExpressionStatement$1 extends NodeBase {
5968 initialise() {
5969 if (this.directive &&
5970 this.directive !== 'use strict' &&
5971 this.parent.type === Program) {
5972 this.context.warn(
5973 // This is necessary, because either way (deleting or not) can lead to errors.
5974 {
5975 code: 'MODULE_LEVEL_DIRECTIVE',
5976 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
5977 }, this.start);
5978 }
5979 }
5980 render(code, options) {
5981 super.render(code, options);
5982 if (this.included)
5983 this.insertSemicolon(code);
5984 }
5985 shouldBeIncluded(context) {
5986 if (this.directive && this.directive !== 'use strict')
5987 return this.parent.type !== Program;
5988 return super.shouldBeIncluded(context);
5989 }
5990}
5991
5992class BlockStatement$1 extends NodeBase {
5993 constructor() {
5994 super(...arguments);
5995 this.directlyIncluded = false;
5996 }
5997 addImplicitReturnExpressionToScope() {
5998 const lastStatement = this.body[this.body.length - 1];
5999 if (!lastStatement || lastStatement.type !== ReturnStatement) {
6000 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
6001 }
6002 }
6003 createScope(parentScope) {
6004 this.scope = this.parent.preventChildBlockScope
6005 ? parentScope
6006 : new BlockScope(parentScope);
6007 }
6008 hasEffects(context) {
6009 if (this.deoptimizeBody)
6010 return true;
6011 for (const node of this.body) {
6012 if (node.hasEffects(context))
6013 return true;
6014 if (context.brokenFlow)
6015 break;
6016 }
6017 return false;
6018 }
6019 include(context, includeChildrenRecursively) {
6020 if (!this.deoptimizeBody || !this.directlyIncluded) {
6021 this.included = true;
6022 this.directlyIncluded = true;
6023 if (this.deoptimizeBody)
6024 includeChildrenRecursively = true;
6025 for (const node of this.body) {
6026 if (includeChildrenRecursively || node.shouldBeIncluded(context))
6027 node.include(context, includeChildrenRecursively);
6028 }
6029 }
6030 }
6031 initialise() {
6032 const firstBodyStatement = this.body[0];
6033 this.deoptimizeBody =
6034 firstBodyStatement instanceof ExpressionStatement$1 &&
6035 firstBodyStatement.directive === 'use asm';
6036 }
6037 render(code, options) {
6038 if (this.body.length) {
6039 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
6040 }
6041 else {
6042 super.render(code, options);
6043 }
6044 }
6045}
6046
6047class ArrowFunctionExpression$1 extends NodeBase {
6048 createScope(parentScope) {
6049 this.scope = new ReturnValueScope(parentScope, this.context);
6050 }
6051 deoptimizePath(path) {
6052 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
6053 // which means the return expression needs to be reassigned
6054 if (path.length === 1 && path[0] === UnknownKey) {
6055 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
6056 }
6057 }
6058 getReturnExpressionWhenCalledAtPath(path) {
6059 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
6060 }
6061 hasEffects() {
6062 return false;
6063 }
6064 hasEffectsWhenAccessedAtPath(path) {
6065 return path.length > 1;
6066 }
6067 hasEffectsWhenAssignedAtPath(path) {
6068 return path.length > 1;
6069 }
6070 hasEffectsWhenCalledAtPath(path, _callOptions, context) {
6071 if (path.length > 0)
6072 return true;
6073 for (const param of this.params) {
6074 if (param.hasEffects(context))
6075 return true;
6076 }
6077 const { ignore, brokenFlow } = context;
6078 context.ignore = {
6079 breaks: false,
6080 continues: false,
6081 labels: new Set(),
6082 returnAwaitYield: true
6083 };
6084 if (this.body.hasEffects(context))
6085 return true;
6086 context.ignore = ignore;
6087 context.brokenFlow = brokenFlow;
6088 return false;
6089 }
6090 include(context, includeChildrenRecursively) {
6091 this.included = true;
6092 for (const param of this.params) {
6093 if (!(param instanceof Identifier$1)) {
6094 param.include(context, includeChildrenRecursively);
6095 }
6096 }
6097 const { brokenFlow } = context;
6098 context.brokenFlow = BROKEN_FLOW_NONE;
6099 this.body.include(context, includeChildrenRecursively);
6100 context.brokenFlow = brokenFlow;
6101 }
6102 includeCallArguments(context, args) {
6103 this.scope.includeCallArguments(context, args);
6104 }
6105 initialise() {
6106 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
6107 if (this.body instanceof BlockStatement$1) {
6108 this.body.addImplicitReturnExpressionToScope();
6109 }
6110 else {
6111 this.scope.addReturnExpression(this.body);
6112 }
6113 }
6114 parseNode(esTreeNode) {
6115 if (esTreeNode.body.type === BlockStatement) {
6116 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
6117 }
6118 super.parseNode(esTreeNode);
6119 }
6120}
6121ArrowFunctionExpression$1.prototype.preventChildBlockScope = true;
6122
6123class AssignmentExpression extends NodeBase {
6124 constructor() {
6125 super(...arguments);
6126 this.deoptimized = false;
6127 }
6128 hasEffects(context) {
6129 if (!this.deoptimized)
6130 this.applyDeoptimizations();
6131 return (this.right.hasEffects(context) ||
6132 this.left.hasEffects(context) ||
6133 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
6134 }
6135 hasEffectsWhenAccessedAtPath(path, context) {
6136 return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
6137 }
6138 include(context, includeChildrenRecursively) {
6139 if (!this.deoptimized)
6140 this.applyDeoptimizations();
6141 this.included = true;
6142 this.left.include(context, includeChildrenRecursively);
6143 this.right.include(context, includeChildrenRecursively);
6144 }
6145 render(code, options) {
6146 this.left.render(code, options);
6147 this.right.render(code, options);
6148 if (options.format === 'system') {
6149 const exportNames = this.left.variable && options.exportNamesByVariable.get(this.left.variable);
6150 if (this.left.type === 'Identifier' && exportNames) {
6151 const _ = options.compact ? '' : ' ';
6152 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
6153 const operation = this.operator.length > 1 ? `${exportNames[0]}${_}${this.operator.slice(0, -1)}${_}` : '';
6154 code.overwrite(operatorPos, findNonWhiteSpace(code.original, operatorPos + this.operator.length), `=${_}${exportNames.length === 1
6155 ? `exports('${exportNames[0]}',${_}`
6156 : getSystemExportFunctionLeft([this.left.variable], false, options)}${operation}`);
6157 code.appendLeft(this.right.end, ')');
6158 }
6159 else {
6160 const systemPatternExports = [];
6161 this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
6162 if (systemPatternExports.length > 0) {
6163 code.prependRight(this.start, getSystemExportFunctionLeft(systemPatternExports, true, options));
6164 code.appendLeft(this.end, ')');
6165 }
6166 }
6167 }
6168 }
6169 applyDeoptimizations() {
6170 this.deoptimized = true;
6171 this.left.deoptimizePath(EMPTY_PATH);
6172 this.right.deoptimizePath(UNKNOWN_PATH);
6173 }
6174}
6175
6176class AssignmentPattern extends NodeBase {
6177 addExportedVariables(variables, exportNamesByVariable) {
6178 this.left.addExportedVariables(variables, exportNamesByVariable);
6179 }
6180 bind() {
6181 super.bind();
6182 this.left.deoptimizePath(EMPTY_PATH);
6183 this.right.deoptimizePath(UNKNOWN_PATH);
6184 }
6185 declare(kind, init) {
6186 return this.left.declare(kind, init);
6187 }
6188 deoptimizePath(path) {
6189 path.length === 0 && this.left.deoptimizePath(path);
6190 }
6191 hasEffectsWhenAssignedAtPath(path, context) {
6192 return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
6193 }
6194 render(code, options, { isShorthandProperty } = BLANK) {
6195 this.left.render(code, options, { isShorthandProperty });
6196 this.right.render(code, options);
6197 }
6198}
6199
6200class AwaitExpression extends NodeBase {
6201 hasEffects(context) {
6202 return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
6203 }
6204 include(context, includeChildrenRecursively) {
6205 if (!this.included) {
6206 this.included = true;
6207 checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
6208 let parent = this.parent;
6209 do {
6210 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression$1)
6211 break checkTopLevelAwait;
6212 } while ((parent = parent.parent));
6213 this.context.usesTopLevelAwait = true;
6214 }
6215 }
6216 this.argument.include(context, includeChildrenRecursively);
6217 }
6218}
6219
6220const binaryOperators = {
6221 '!=': (left, right) => left != right,
6222 '!==': (left, right) => left !== right,
6223 '%': (left, right) => left % right,
6224 '&': (left, right) => left & right,
6225 '*': (left, right) => left * right,
6226 // At the moment, "**" will be transpiled to Math.pow
6227 '**': (left, right) => left ** right,
6228 '+': (left, right) => left + right,
6229 '-': (left, right) => left - right,
6230 '/': (left, right) => left / right,
6231 '<': (left, right) => left < right,
6232 '<<': (left, right) => left << right,
6233 '<=': (left, right) => left <= right,
6234 '==': (left, right) => left == right,
6235 '===': (left, right) => left === right,
6236 '>': (left, right) => left > right,
6237 '>=': (left, right) => left >= right,
6238 '>>': (left, right) => left >> right,
6239 '>>>': (left, right) => left >>> right,
6240 '^': (left, right) => left ^ right,
6241 in: () => UnknownValue,
6242 instanceof: () => UnknownValue,
6243 '|': (left, right) => left | right
6244};
6245class BinaryExpression extends NodeBase {
6246 deoptimizeCache() { }
6247 getLiteralValueAtPath(path, recursionTracker, origin) {
6248 if (path.length > 0)
6249 return UnknownValue;
6250 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6251 if (leftValue === UnknownValue)
6252 return UnknownValue;
6253 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6254 if (rightValue === UnknownValue)
6255 return UnknownValue;
6256 const operatorFn = binaryOperators[this.operator];
6257 if (!operatorFn)
6258 return UnknownValue;
6259 return operatorFn(leftValue, rightValue);
6260 }
6261 hasEffects(context) {
6262 // support some implicit type coercion runtime errors
6263 if (this.operator === '+' &&
6264 this.parent instanceof ExpressionStatement$1 &&
6265 this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
6266 return true;
6267 return super.hasEffects(context);
6268 }
6269 hasEffectsWhenAccessedAtPath(path) {
6270 return path.length > 1;
6271 }
6272}
6273
6274class BreakStatement extends NodeBase {
6275 hasEffects(context) {
6276 if (this.label) {
6277 if (!context.ignore.labels.has(this.label.name))
6278 return true;
6279 context.includedLabels.add(this.label.name);
6280 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
6281 }
6282 else {
6283 if (!context.ignore.breaks)
6284 return true;
6285 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
6286 }
6287 return false;
6288 }
6289 include(context) {
6290 this.included = true;
6291 if (this.label) {
6292 this.label.include();
6293 context.includedLabels.add(this.label.name);
6294 }
6295 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
6296 }
6297}
6298
6299class Literal extends NodeBase {
6300 getLiteralValueAtPath(path) {
6301 if (path.length > 0 ||
6302 // unknown literals can also be null but do not start with an "n"
6303 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
6304 typeof this.value === 'bigint' ||
6305 // to support shims for regular expressions
6306 this.context.code.charCodeAt(this.start) === 47) {
6307 return UnknownValue;
6308 }
6309 return this.value;
6310 }
6311 getReturnExpressionWhenCalledAtPath(path) {
6312 if (path.length !== 1)
6313 return UNKNOWN_EXPRESSION;
6314 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
6315 }
6316 hasEffectsWhenAccessedAtPath(path) {
6317 if (this.value === null) {
6318 return path.length > 0;
6319 }
6320 return path.length > 1;
6321 }
6322 hasEffectsWhenAssignedAtPath(path) {
6323 return path.length > 0;
6324 }
6325 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6326 if (path.length === 1) {
6327 return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
6328 }
6329 return true;
6330 }
6331 initialise() {
6332 this.members = getLiteralMembersForValue(this.value);
6333 }
6334 parseNode(esTreeNode) {
6335 this.value = esTreeNode.value;
6336 this.regex = esTreeNode.regex;
6337 super.parseNode(esTreeNode);
6338 }
6339 render(code) {
6340 if (typeof this.value === 'string') {
6341 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
6342 }
6343 }
6344}
6345
6346function getResolvablePropertyKey(memberExpression) {
6347 return memberExpression.computed
6348 ? getResolvableComputedPropertyKey(memberExpression.property)
6349 : memberExpression.property.name;
6350}
6351function getResolvableComputedPropertyKey(propertyKey) {
6352 if (propertyKey instanceof Literal) {
6353 return String(propertyKey.value);
6354 }
6355 return null;
6356}
6357function getPathIfNotComputed(memberExpression) {
6358 const nextPathKey = memberExpression.propertyKey;
6359 const object = memberExpression.object;
6360 if (typeof nextPathKey === 'string') {
6361 if (object instanceof Identifier$1) {
6362 return [
6363 { key: object.name, pos: object.start },
6364 { key: nextPathKey, pos: memberExpression.property.start }
6365 ];
6366 }
6367 if (object instanceof MemberExpression) {
6368 const parentPath = getPathIfNotComputed(object);
6369 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
6370 }
6371 }
6372 return null;
6373}
6374function getStringFromPath(path) {
6375 let pathString = path[0].key;
6376 for (let index = 1; index < path.length; index++) {
6377 pathString += '.' + path[index].key;
6378 }
6379 return pathString;
6380}
6381class MemberExpression extends NodeBase {
6382 constructor() {
6383 super(...arguments);
6384 this.variable = null;
6385 this.bound = false;
6386 this.expressionsToBeDeoptimized = [];
6387 this.replacement = null;
6388 this.wasPathDeoptimizedWhileOptimized = false;
6389 }
6390 addExportedVariables() { }
6391 bind() {
6392 if (this.bound)
6393 return;
6394 this.bound = true;
6395 const path = getPathIfNotComputed(this);
6396 const baseVariable = path && this.scope.findVariable(path[0].key);
6397 if (baseVariable && baseVariable.isNamespace) {
6398 const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
6399 if (!resolvedVariable) {
6400 super.bind();
6401 }
6402 else if (typeof resolvedVariable === 'string') {
6403 this.replacement = resolvedVariable;
6404 }
6405 else {
6406 if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
6407 resolvedVariable.module.suggestName(path[0].key);
6408 }
6409 this.variable = resolvedVariable;
6410 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
6411 }
6412 }
6413 else {
6414 super.bind();
6415 // ensure the propertyKey is set for the tree-shaking passes
6416 this.getPropertyKey();
6417 }
6418 }
6419 deoptimizeCache() {
6420 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6421 this.expressionsToBeDeoptimized = [];
6422 this.propertyKey = UnknownKey;
6423 if (this.wasPathDeoptimizedWhileOptimized) {
6424 this.object.deoptimizePath(UNKNOWN_PATH);
6425 }
6426 for (const expression of expressionsToBeDeoptimized) {
6427 expression.deoptimizeCache();
6428 }
6429 }
6430 deoptimizePath(path) {
6431 if (!this.bound)
6432 this.bind();
6433 if (path.length === 0)
6434 this.disallowNamespaceReassignment();
6435 if (this.variable) {
6436 this.variable.deoptimizePath(path);
6437 }
6438 else {
6439 const propertyKey = this.getPropertyKey();
6440 if (propertyKey === UnknownKey) {
6441 this.object.deoptimizePath(UNKNOWN_PATH);
6442 }
6443 else {
6444 this.wasPathDeoptimizedWhileOptimized = true;
6445 this.object.deoptimizePath([propertyKey, ...path]);
6446 }
6447 }
6448 }
6449 getLiteralValueAtPath(path, recursionTracker, origin) {
6450 if (!this.bound)
6451 this.bind();
6452 if (this.variable !== null) {
6453 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
6454 }
6455 this.expressionsToBeDeoptimized.push(origin);
6456 return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
6457 }
6458 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6459 if (!this.bound)
6460 this.bind();
6461 if (this.variable !== null) {
6462 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6463 }
6464 this.expressionsToBeDeoptimized.push(origin);
6465 return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
6466 }
6467 hasEffects(context) {
6468 return (this.property.hasEffects(context) ||
6469 this.object.hasEffects(context) ||
6470 (this.context.options.treeshake.propertyReadSideEffects &&
6471 this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
6472 }
6473 hasEffectsWhenAccessedAtPath(path, context) {
6474 if (path.length === 0)
6475 return false;
6476 if (this.variable !== null) {
6477 return this.variable.hasEffectsWhenAccessedAtPath(path, context);
6478 }
6479 return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
6480 }
6481 hasEffectsWhenAssignedAtPath(path, context) {
6482 if (this.variable !== null) {
6483 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
6484 }
6485 return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
6486 }
6487 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6488 if (this.variable !== null) {
6489 return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
6490 }
6491 return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
6492 }
6493 include(context, includeChildrenRecursively) {
6494 if (!this.included) {
6495 this.included = true;
6496 if (this.variable !== null) {
6497 this.context.includeVariable(this.variable);
6498 }
6499 }
6500 this.object.include(context, includeChildrenRecursively);
6501 this.property.include(context, includeChildrenRecursively);
6502 }
6503 includeCallArguments(context, args) {
6504 if (this.variable) {
6505 this.variable.includeCallArguments(context, args);
6506 }
6507 else {
6508 super.includeCallArguments(context, args);
6509 }
6510 }
6511 initialise() {
6512 this.propertyKey = getResolvablePropertyKey(this);
6513 }
6514 render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
6515 const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
6516 if (this.variable || this.replacement) {
6517 let replacement = this.variable ? this.variable.getName() : this.replacement;
6518 if (isCalleeOfDifferentParent)
6519 replacement = '0, ' + replacement;
6520 code.overwrite(this.start, this.end, replacement, {
6521 contentOnly: true,
6522 storeName: true
6523 });
6524 }
6525 else {
6526 if (isCalleeOfDifferentParent) {
6527 code.appendRight(this.start, '0, ');
6528 }
6529 super.render(code, options);
6530 }
6531 }
6532 disallowNamespaceReassignment() {
6533 if (this.object instanceof Identifier$1) {
6534 const variable = this.scope.findVariable(this.object.name);
6535 if (variable.isNamespace) {
6536 if (this.variable) {
6537 this.context.includeVariable(this.variable);
6538 }
6539 this.context.warn({
6540 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
6541 message: `Illegal reassignment to import '${this.object.name}'`
6542 }, this.start);
6543 }
6544 }
6545 }
6546 getPropertyKey() {
6547 if (this.propertyKey === null) {
6548 this.propertyKey = UnknownKey;
6549 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
6550 return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
6551 }
6552 return this.propertyKey;
6553 }
6554 resolveNamespaceVariables(baseVariable, path) {
6555 if (path.length === 0)
6556 return baseVariable;
6557 if (!baseVariable.isNamespace)
6558 return null;
6559 const exportName = path[0].key;
6560 const variable = baseVariable instanceof ExternalVariable
6561 ? baseVariable.module.getVariableForExportName(exportName)
6562 : baseVariable.context.traceExport(exportName);
6563 if (!variable) {
6564 const fileName = baseVariable instanceof ExternalVariable
6565 ? baseVariable.module.id
6566 : baseVariable.context.fileName;
6567 this.context.warn({
6568 code: 'MISSING_EXPORT',
6569 exporter: relativeId(fileName),
6570 importer: relativeId(this.context.fileName),
6571 message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
6572 missing: exportName,
6573 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
6574 }, path[0].pos);
6575 return 'undefined';
6576 }
6577 return this.resolveNamespaceVariables(variable, path.slice(1));
6578 }
6579}
6580
6581class CallExpression$1 extends NodeBase {
6582 constructor() {
6583 super(...arguments);
6584 this.expressionsToBeDeoptimized = [];
6585 this.returnExpression = null;
6586 this.wasPathDeoptmizedWhileOptimized = false;
6587 }
6588 bind() {
6589 super.bind();
6590 if (this.callee instanceof Identifier$1) {
6591 const variable = this.scope.findVariable(this.callee.name);
6592 if (variable.isNamespace) {
6593 this.context.warn({
6594 code: 'CANNOT_CALL_NAMESPACE',
6595 message: `Cannot call a namespace ('${this.callee.name}')`
6596 }, this.start);
6597 }
6598 if (this.callee.name === 'eval') {
6599 this.context.warn({
6600 code: 'EVAL',
6601 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
6602 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
6603 }, this.start);
6604 }
6605 }
6606 // ensure the returnExpression is set for the tree-shaking passes
6607 this.getReturnExpression(SHARED_RECURSION_TRACKER);
6608 // This deoptimizes "this" for non-namespace calls until we have a better solution
6609 if (this.callee instanceof MemberExpression && !this.callee.variable) {
6610 this.callee.object.deoptimizePath(UNKNOWN_PATH);
6611 }
6612 for (const argument of this.arguments) {
6613 // This will make sure all properties of parameters behave as "unknown"
6614 argument.deoptimizePath(UNKNOWN_PATH);
6615 }
6616 }
6617 deoptimizeCache() {
6618 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
6619 this.returnExpression = null;
6620 const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
6621 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6622 if (returnExpression !== UNKNOWN_EXPRESSION) {
6623 // We need to replace here because is possible new expressions are added
6624 // while we are deoptimizing the old ones
6625 this.expressionsToBeDeoptimized = [];
6626 if (this.wasPathDeoptmizedWhileOptimized) {
6627 returnExpression.deoptimizePath(UNKNOWN_PATH);
6628 this.wasPathDeoptmizedWhileOptimized = false;
6629 }
6630 }
6631 for (const expression of expressionsToBeDeoptimized) {
6632 expression.deoptimizeCache();
6633 }
6634 }
6635 }
6636 deoptimizePath(path) {
6637 if (path.length === 0)
6638 return;
6639 const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
6640 if (trackedEntities.has(this))
6641 return;
6642 trackedEntities.add(this);
6643 const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
6644 if (returnExpression !== UNKNOWN_EXPRESSION) {
6645 this.wasPathDeoptmizedWhileOptimized = true;
6646 returnExpression.deoptimizePath(path);
6647 }
6648 }
6649 getLiteralValueAtPath(path, recursionTracker, origin) {
6650 const returnExpression = this.getReturnExpression(recursionTracker);
6651 if (returnExpression === UNKNOWN_EXPRESSION) {
6652 return UnknownValue;
6653 }
6654 const trackedEntities = recursionTracker.getEntities(path);
6655 if (trackedEntities.has(returnExpression)) {
6656 return UnknownValue;
6657 }
6658 this.expressionsToBeDeoptimized.push(origin);
6659 trackedEntities.add(returnExpression);
6660 const value = returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
6661 trackedEntities.delete(returnExpression);
6662 return value;
6663 }
6664 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6665 const returnExpression = this.getReturnExpression(recursionTracker);
6666 if (this.returnExpression === UNKNOWN_EXPRESSION) {
6667 return UNKNOWN_EXPRESSION;
6668 }
6669 const trackedEntities = recursionTracker.getEntities(path);
6670 if (trackedEntities.has(returnExpression)) {
6671 return UNKNOWN_EXPRESSION;
6672 }
6673 this.expressionsToBeDeoptimized.push(origin);
6674 trackedEntities.add(returnExpression);
6675 const value = returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6676 trackedEntities.delete(returnExpression);
6677 return value;
6678 }
6679 hasEffects(context) {
6680 for (const argument of this.arguments) {
6681 if (argument.hasEffects(context))
6682 return true;
6683 }
6684 if (this.context.options.treeshake.annotations &&
6685 this.annotatedPure)
6686 return false;
6687 return (this.callee.hasEffects(context) ||
6688 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
6689 }
6690 hasEffectsWhenAccessedAtPath(path, context) {
6691 if (path.length === 0)
6692 return false;
6693 const trackedExpressions = context.accessed.getEntities(path);
6694 if (trackedExpressions.has(this))
6695 return false;
6696 trackedExpressions.add(this);
6697 return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
6698 }
6699 hasEffectsWhenAssignedAtPath(path, context) {
6700 if (path.length === 0)
6701 return true;
6702 const trackedExpressions = context.assigned.getEntities(path);
6703 if (trackedExpressions.has(this))
6704 return false;
6705 trackedExpressions.add(this);
6706 return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
6707 }
6708 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6709 const trackedExpressions = (callOptions.withNew
6710 ? context.instantiated
6711 : context.called).getEntities(path, callOptions);
6712 if (trackedExpressions.has(this))
6713 return false;
6714 trackedExpressions.add(this);
6715 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
6716 }
6717 include(context, includeChildrenRecursively) {
6718 if (includeChildrenRecursively) {
6719 super.include(context, includeChildrenRecursively);
6720 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
6721 this.callee instanceof Identifier$1 &&
6722 this.callee.variable) {
6723 this.callee.variable.markCalledFromTryStatement();
6724 }
6725 }
6726 else {
6727 this.included = true;
6728 this.callee.include(context, false);
6729 }
6730 this.callee.includeCallArguments(context, this.arguments);
6731 if (!this.returnExpression.included) {
6732 this.returnExpression.include(context, false);
6733 }
6734 }
6735 initialise() {
6736 this.callOptions = {
6737 args: this.arguments,
6738 withNew: false
6739 };
6740 }
6741 render(code, options, { renderedParentType } = BLANK) {
6742 this.callee.render(code, options);
6743 if (this.arguments.length > 0) {
6744 if (this.arguments[this.arguments.length - 1].included) {
6745 for (const arg of this.arguments) {
6746 arg.render(code, options);
6747 }
6748 }
6749 else {
6750 let lastIncludedIndex = this.arguments.length - 2;
6751 while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
6752 lastIncludedIndex--;
6753 }
6754 if (lastIncludedIndex >= 0) {
6755 for (let index = 0; index <= lastIncludedIndex; index++) {
6756 this.arguments[index].render(code, options);
6757 }
6758 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
6759 }
6760 else {
6761 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
6762 }
6763 }
6764 }
6765 if (renderedParentType === ExpressionStatement &&
6766 this.callee.type === FunctionExpression) {
6767 code.appendRight(this.start, '(');
6768 code.prependLeft(this.end, ')');
6769 }
6770 }
6771 getReturnExpression(recursionTracker) {
6772 if (this.returnExpression === null) {
6773 this.returnExpression = UNKNOWN_EXPRESSION;
6774 return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this));
6775 }
6776 return this.returnExpression;
6777 }
6778}
6779
6780class CatchScope extends ParameterScope {
6781 addDeclaration(identifier, context, init, isHoisted) {
6782 if (isHoisted) {
6783 return this.parent.addDeclaration(identifier, context, init, isHoisted);
6784 }
6785 else {
6786 return super.addDeclaration(identifier, context, init, false);
6787 }
6788 }
6789}
6790
6791class CatchClause extends NodeBase {
6792 createScope(parentScope) {
6793 this.scope = new CatchScope(parentScope, this.context);
6794 }
6795 initialise() {
6796 if (this.param) {
6797 this.param.declare('parameter', UNKNOWN_EXPRESSION);
6798 }
6799 }
6800 parseNode(esTreeNode) {
6801 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
6802 super.parseNode(esTreeNode);
6803 }
6804}
6805CatchClause.prototype.preventChildBlockScope = true;
6806
6807class ChainExpression extends NodeBase {
6808}
6809
6810class ClassBodyScope extends ChildScope {
6811 findLexicalBoundary() {
6812 return this;
6813 }
6814}
6815
6816class MethodDefinition extends NodeBase {
6817 hasEffects(context) {
6818 return this.key.hasEffects(context);
6819 }
6820 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6821 return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
6822 }
6823}
6824
6825class ClassBody extends NodeBase {
6826 createScope(parentScope) {
6827 this.scope = new ClassBodyScope(parentScope);
6828 }
6829 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6830 if (path.length > 0)
6831 return true;
6832 return (this.classConstructor !== null &&
6833 this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
6834 }
6835 initialise() {
6836 for (const method of this.body) {
6837 if (method instanceof MethodDefinition && method.kind === 'constructor') {
6838 this.classConstructor = method;
6839 return;
6840 }
6841 }
6842 this.classConstructor = null;
6843 }
6844}
6845
6846class ClassExpression extends ClassNode {
6847}
6848
6849class MultiExpression {
6850 constructor(expressions) {
6851 this.included = false;
6852 this.expressions = expressions;
6853 }
6854 deoptimizePath(path) {
6855 for (const expression of this.expressions) {
6856 expression.deoptimizePath(path);
6857 }
6858 }
6859 getLiteralValueAtPath() {
6860 return UnknownValue;
6861 }
6862 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6863 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
6864 }
6865 hasEffectsWhenAccessedAtPath(path, context) {
6866 for (const expression of this.expressions) {
6867 if (expression.hasEffectsWhenAccessedAtPath(path, context))
6868 return true;
6869 }
6870 return false;
6871 }
6872 hasEffectsWhenAssignedAtPath(path, context) {
6873 for (const expression of this.expressions) {
6874 if (expression.hasEffectsWhenAssignedAtPath(path, context))
6875 return true;
6876 }
6877 return false;
6878 }
6879 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6880 for (const expression of this.expressions) {
6881 if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
6882 return true;
6883 }
6884 return false;
6885 }
6886 include(context, includeChildrenRecursively) {
6887 // This is only relevant to include values that do not have an AST representation,
6888 // such as UnknownArrayExpression. Thus we only need to include them once.
6889 for (const expression of this.expressions) {
6890 if (!expression.included) {
6891 expression.include(context, includeChildrenRecursively);
6892 }
6893 }
6894 }
6895 includeCallArguments() { }
6896}
6897
6898class ConditionalExpression extends NodeBase {
6899 constructor() {
6900 super(...arguments);
6901 this.expressionsToBeDeoptimized = [];
6902 this.isBranchResolutionAnalysed = false;
6903 this.usedBranch = null;
6904 this.wasPathDeoptimizedWhileOptimized = false;
6905 }
6906 bind() {
6907 super.bind();
6908 // ensure the usedBranch is set for the tree-shaking passes
6909 this.getUsedBranch();
6910 }
6911 deoptimizeCache() {
6912 if (this.usedBranch !== null) {
6913 const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
6914 this.usedBranch = null;
6915 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6916 this.expressionsToBeDeoptimized = [];
6917 if (this.wasPathDeoptimizedWhileOptimized) {
6918 unusedBranch.deoptimizePath(UNKNOWN_PATH);
6919 }
6920 for (const expression of expressionsToBeDeoptimized) {
6921 expression.deoptimizeCache();
6922 }
6923 }
6924 }
6925 deoptimizePath(path) {
6926 if (path.length > 0) {
6927 const usedBranch = this.getUsedBranch();
6928 if (usedBranch === null) {
6929 this.consequent.deoptimizePath(path);
6930 this.alternate.deoptimizePath(path);
6931 }
6932 else {
6933 this.wasPathDeoptimizedWhileOptimized = true;
6934 usedBranch.deoptimizePath(path);
6935 }
6936 }
6937 }
6938 getLiteralValueAtPath(path, recursionTracker, origin) {
6939 const usedBranch = this.getUsedBranch();
6940 if (usedBranch === null)
6941 return UnknownValue;
6942 this.expressionsToBeDeoptimized.push(origin);
6943 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
6944 }
6945 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6946 const usedBranch = this.getUsedBranch();
6947 if (usedBranch === null)
6948 return new MultiExpression([
6949 this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
6950 this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
6951 ]);
6952 this.expressionsToBeDeoptimized.push(origin);
6953 return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6954 }
6955 hasEffects(context) {
6956 if (this.test.hasEffects(context))
6957 return true;
6958 if (this.usedBranch === null) {
6959 return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
6960 }
6961 return this.usedBranch.hasEffects(context);
6962 }
6963 hasEffectsWhenAccessedAtPath(path, context) {
6964 if (path.length === 0)
6965 return false;
6966 if (this.usedBranch === null) {
6967 return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
6968 this.alternate.hasEffectsWhenAccessedAtPath(path, context));
6969 }
6970 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
6971 }
6972 hasEffectsWhenAssignedAtPath(path, context) {
6973 if (path.length === 0)
6974 return true;
6975 if (this.usedBranch === null) {
6976 return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
6977 this.alternate.hasEffectsWhenAssignedAtPath(path, context));
6978 }
6979 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
6980 }
6981 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6982 if (this.usedBranch === null) {
6983 return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
6984 this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
6985 }
6986 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
6987 }
6988 include(context, includeChildrenRecursively) {
6989 this.included = true;
6990 if (includeChildrenRecursively ||
6991 this.test.shouldBeIncluded(context) ||
6992 this.usedBranch === null) {
6993 this.test.include(context, includeChildrenRecursively);
6994 this.consequent.include(context, includeChildrenRecursively);
6995 this.alternate.include(context, includeChildrenRecursively);
6996 }
6997 else {
6998 this.usedBranch.include(context, includeChildrenRecursively);
6999 }
7000 }
7001 includeCallArguments(context, args) {
7002 if (this.usedBranch === null) {
7003 this.consequent.includeCallArguments(context, args);
7004 this.alternate.includeCallArguments(context, args);
7005 }
7006 else {
7007 this.usedBranch.includeCallArguments(context, args);
7008 }
7009 }
7010 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
7011 if (!this.test.included) {
7012 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
7013 const inclusionStart = (this.consequent.included
7014 ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
7015 : colonPos) + 1;
7016 if (preventASI) {
7017 removeLineBreaks(code, inclusionStart, this.usedBranch.start);
7018 }
7019 code.remove(this.start, inclusionStart);
7020 if (this.consequent.included) {
7021 code.remove(colonPos, this.end);
7022 }
7023 removeAnnotations(this, code);
7024 this.usedBranch.render(code, options, {
7025 isCalleeOfRenderedParent: renderedParentType
7026 ? isCalleeOfRenderedParent
7027 : this.parent.callee === this,
7028 preventASI: true,
7029 renderedParentType: renderedParentType || this.parent.type
7030 });
7031 }
7032 else {
7033 super.render(code, options);
7034 }
7035 }
7036 getUsedBranch() {
7037 if (this.isBranchResolutionAnalysed) {
7038 return this.usedBranch;
7039 }
7040 this.isBranchResolutionAnalysed = true;
7041 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
7042 return testValue === UnknownValue
7043 ? null
7044 : (this.usedBranch = testValue ? this.consequent : this.alternate);
7045 }
7046}
7047
7048class ContinueStatement extends NodeBase {
7049 hasEffects(context) {
7050 if (this.label) {
7051 if (!context.ignore.labels.has(this.label.name))
7052 return true;
7053 context.includedLabels.add(this.label.name);
7054 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
7055 }
7056 else {
7057 if (!context.ignore.continues)
7058 return true;
7059 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
7060 }
7061 return false;
7062 }
7063 include(context) {
7064 this.included = true;
7065 if (this.label) {
7066 this.label.include();
7067 context.includedLabels.add(this.label.name);
7068 }
7069 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
7070 }
7071}
7072
7073class DoWhileStatement extends NodeBase {
7074 hasEffects(context) {
7075 if (this.test.hasEffects(context))
7076 return true;
7077 const { brokenFlow, ignore: { breaks, continues } } = context;
7078 context.ignore.breaks = true;
7079 context.ignore.continues = true;
7080 if (this.body.hasEffects(context))
7081 return true;
7082 context.ignore.breaks = breaks;
7083 context.ignore.continues = continues;
7084 context.brokenFlow = brokenFlow;
7085 return false;
7086 }
7087 include(context, includeChildrenRecursively) {
7088 this.included = true;
7089 this.test.include(context, includeChildrenRecursively);
7090 const { brokenFlow } = context;
7091 this.body.include(context, includeChildrenRecursively);
7092 context.brokenFlow = brokenFlow;
7093 }
7094}
7095
7096class EmptyStatement extends NodeBase {
7097 hasEffects() {
7098 return false;
7099 }
7100}
7101
7102class ExportNamedDeclaration extends NodeBase {
7103 bind() {
7104 // Do not bind specifiers
7105 if (this.declaration !== null)
7106 this.declaration.bind();
7107 }
7108 hasEffects(context) {
7109 return this.declaration !== null && this.declaration.hasEffects(context);
7110 }
7111 initialise() {
7112 this.context.addExport(this);
7113 }
7114 render(code, options, nodeRenderOptions) {
7115 const { start, end } = nodeRenderOptions;
7116 if (this.declaration === null) {
7117 code.remove(start, end);
7118 }
7119 else {
7120 code.remove(this.start, this.declaration.start);
7121 this.declaration.render(code, options, { start, end });
7122 }
7123 }
7124}
7125ExportNamedDeclaration.prototype.needsBoundaries = true;
7126
7127class ExportSpecifier extends NodeBase {
7128}
7129
7130class FieldDefinition extends NodeBase {
7131 hasEffects(context) {
7132 return (this.key.hasEffects(context) ||
7133 (this.static && this.value !== null && this.value.hasEffects(context)));
7134 }
7135}
7136
7137class ForInStatement extends NodeBase {
7138 bind() {
7139 this.left.bind();
7140 this.left.deoptimizePath(EMPTY_PATH);
7141 this.right.bind();
7142 this.body.bind();
7143 }
7144 createScope(parentScope) {
7145 this.scope = new BlockScope(parentScope);
7146 }
7147 hasEffects(context) {
7148 if ((this.left &&
7149 (this.left.hasEffects(context) ||
7150 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
7151 (this.right && this.right.hasEffects(context)))
7152 return true;
7153 const { brokenFlow, ignore: { breaks, continues } } = context;
7154 context.ignore.breaks = true;
7155 context.ignore.continues = true;
7156 if (this.body.hasEffects(context))
7157 return true;
7158 context.ignore.breaks = breaks;
7159 context.ignore.continues = continues;
7160 context.brokenFlow = brokenFlow;
7161 return false;
7162 }
7163 include(context, includeChildrenRecursively) {
7164 this.included = true;
7165 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
7166 this.left.deoptimizePath(EMPTY_PATH);
7167 this.right.include(context, includeChildrenRecursively);
7168 const { brokenFlow } = context;
7169 this.body.include(context, includeChildrenRecursively);
7170 context.brokenFlow = brokenFlow;
7171 }
7172 render(code, options) {
7173 this.left.render(code, options, NO_SEMICOLON);
7174 this.right.render(code, options, NO_SEMICOLON);
7175 // handle no space between "in" and the right side
7176 if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
7177 code.prependLeft(this.right.start, ' ');
7178 }
7179 this.body.render(code, options);
7180 }
7181}
7182
7183class ForOfStatement extends NodeBase {
7184 bind() {
7185 this.left.bind();
7186 this.left.deoptimizePath(EMPTY_PATH);
7187 this.right.bind();
7188 this.body.bind();
7189 }
7190 createScope(parentScope) {
7191 this.scope = new BlockScope(parentScope);
7192 }
7193 hasEffects() {
7194 // Placeholder until proper Symbol.Iterator support
7195 return true;
7196 }
7197 include(context, includeChildrenRecursively) {
7198 this.included = true;
7199 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
7200 this.left.deoptimizePath(EMPTY_PATH);
7201 this.right.include(context, includeChildrenRecursively);
7202 const { brokenFlow } = context;
7203 this.body.include(context, includeChildrenRecursively);
7204 context.brokenFlow = brokenFlow;
7205 }
7206 render(code, options) {
7207 this.left.render(code, options, NO_SEMICOLON);
7208 this.right.render(code, options, NO_SEMICOLON);
7209 // handle no space between "of" and the right side
7210 if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
7211 code.prependLeft(this.right.start, ' ');
7212 }
7213 this.body.render(code, options);
7214 }
7215}
7216
7217class ForStatement extends NodeBase {
7218 createScope(parentScope) {
7219 this.scope = new BlockScope(parentScope);
7220 }
7221 hasEffects(context) {
7222 if ((this.init && this.init.hasEffects(context)) ||
7223 (this.test && this.test.hasEffects(context)) ||
7224 (this.update && this.update.hasEffects(context)))
7225 return true;
7226 const { brokenFlow, ignore: { breaks, continues } } = context;
7227 context.ignore.breaks = true;
7228 context.ignore.continues = true;
7229 if (this.body.hasEffects(context))
7230 return true;
7231 context.ignore.breaks = breaks;
7232 context.ignore.continues = continues;
7233 context.brokenFlow = brokenFlow;
7234 return false;
7235 }
7236 include(context, includeChildrenRecursively) {
7237 this.included = true;
7238 if (this.init)
7239 this.init.include(context, includeChildrenRecursively);
7240 if (this.test)
7241 this.test.include(context, includeChildrenRecursively);
7242 const { brokenFlow } = context;
7243 if (this.update)
7244 this.update.include(context, includeChildrenRecursively);
7245 this.body.include(context, includeChildrenRecursively);
7246 context.brokenFlow = brokenFlow;
7247 }
7248 render(code, options) {
7249 if (this.init)
7250 this.init.render(code, options, NO_SEMICOLON);
7251 if (this.test)
7252 this.test.render(code, options, NO_SEMICOLON);
7253 if (this.update)
7254 this.update.render(code, options, NO_SEMICOLON);
7255 this.body.render(code, options);
7256 }
7257}
7258
7259class FunctionExpression$1 extends FunctionNode {
7260}
7261
7262class TrackingScope extends BlockScope {
7263 constructor() {
7264 super(...arguments);
7265 this.hoistedDeclarations = [];
7266 }
7267 addDeclaration(identifier, context, init, isHoisted) {
7268 this.hoistedDeclarations.push(identifier);
7269 return this.parent.addDeclaration(identifier, context, init, isHoisted);
7270 }
7271}
7272
7273const unset = Symbol('unset');
7274class IfStatement extends NodeBase {
7275 constructor() {
7276 super(...arguments);
7277 this.testValue = unset;
7278 }
7279 deoptimizeCache() {
7280 this.testValue = UnknownValue;
7281 }
7282 hasEffects(context) {
7283 if (this.test.hasEffects(context)) {
7284 return true;
7285 }
7286 const testValue = this.getTestValue();
7287 if (testValue === UnknownValue) {
7288 const { brokenFlow } = context;
7289 if (this.consequent.hasEffects(context))
7290 return true;
7291 const consequentBrokenFlow = context.brokenFlow;
7292 context.brokenFlow = brokenFlow;
7293 if (this.alternate === null)
7294 return false;
7295 if (this.alternate.hasEffects(context))
7296 return true;
7297 context.brokenFlow =
7298 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
7299 return false;
7300 }
7301 return testValue
7302 ? this.consequent.hasEffects(context)
7303 : this.alternate !== null && this.alternate.hasEffects(context);
7304 }
7305 include(context, includeChildrenRecursively) {
7306 this.included = true;
7307 if (includeChildrenRecursively) {
7308 this.includeRecursively(includeChildrenRecursively, context);
7309 }
7310 else {
7311 const testValue = this.getTestValue();
7312 if (testValue === UnknownValue) {
7313 this.includeUnknownTest(context);
7314 }
7315 else {
7316 this.includeKnownTest(context, testValue);
7317 }
7318 }
7319 }
7320 parseNode(esTreeNode) {
7321 this.consequentScope = new TrackingScope(this.scope);
7322 this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
7323 this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
7324 if (esTreeNode.alternate) {
7325 this.alternateScope = new TrackingScope(this.scope);
7326 this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
7327 this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
7328 }
7329 super.parseNode(esTreeNode);
7330 }
7331 render(code, options) {
7332 // Note that unknown test values are always included
7333 const testValue = this.getTestValue();
7334 const hoistedDeclarations = [];
7335 const includesIfElse = this.test.included;
7336 const noTreeshake = !this.context.options.treeshake;
7337 if (includesIfElse) {
7338 this.test.render(code, options);
7339 }
7340 else {
7341 removeAnnotations(this, code);
7342 code.remove(this.start, this.consequent.start);
7343 }
7344 if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
7345 this.consequent.render(code, options);
7346 }
7347 else {
7348 code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
7349 hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
7350 }
7351 if (this.alternate) {
7352 if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
7353 if (includesIfElse) {
7354 if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
7355 code.prependLeft(this.alternate.start, ' ');
7356 }
7357 }
7358 else {
7359 code.remove(this.consequent.end, this.alternate.start);
7360 }
7361 this.alternate.render(code, options);
7362 }
7363 else {
7364 if (includesIfElse && this.shouldKeepAlternateBranch()) {
7365 code.overwrite(this.alternate.start, this.end, ';');
7366 }
7367 else {
7368 code.remove(this.consequent.end, this.end);
7369 }
7370 hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
7371 }
7372 }
7373 this.renderHoistedDeclarations(hoistedDeclarations, code);
7374 }
7375 getTestValue() {
7376 if (this.testValue === unset) {
7377 return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
7378 }
7379 return this.testValue;
7380 }
7381 includeKnownTest(context, testValue) {
7382 if (this.test.shouldBeIncluded(context)) {
7383 this.test.include(context, false);
7384 }
7385 if (testValue && this.consequent.shouldBeIncluded(context)) {
7386 this.consequent.include(context, false);
7387 }
7388 if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
7389 this.alternate.include(context, false);
7390 }
7391 }
7392 includeRecursively(includeChildrenRecursively, context) {
7393 this.test.include(context, includeChildrenRecursively);
7394 this.consequent.include(context, includeChildrenRecursively);
7395 if (this.alternate !== null) {
7396 this.alternate.include(context, includeChildrenRecursively);
7397 }
7398 }
7399 includeUnknownTest(context) {
7400 this.test.include(context, false);
7401 const { brokenFlow } = context;
7402 let consequentBrokenFlow = BROKEN_FLOW_NONE;
7403 if (this.consequent.shouldBeIncluded(context)) {
7404 this.consequent.include(context, false);
7405 consequentBrokenFlow = context.brokenFlow;
7406 context.brokenFlow = brokenFlow;
7407 }
7408 if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
7409 this.alternate.include(context, false);
7410 context.brokenFlow =
7411 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
7412 }
7413 }
7414 renderHoistedDeclarations(hoistedDeclarations, code) {
7415 const hoistedVars = [
7416 ...new Set(hoistedDeclarations.map(identifier => {
7417 const variable = identifier.variable;
7418 return variable.included ? variable.getName() : '';
7419 }))
7420 ]
7421 .filter(Boolean)
7422 .join(', ');
7423 if (hoistedVars) {
7424 const parentType = this.parent.type;
7425 const needsBraces = parentType !== Program && parentType !== BlockStatement;
7426 code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
7427 if (needsBraces) {
7428 code.appendLeft(this.end, ` }`);
7429 }
7430 }
7431 }
7432 shouldKeepAlternateBranch() {
7433 let currentParent = this.parent;
7434 do {
7435 if (currentParent instanceof IfStatement && currentParent.alternate) {
7436 return true;
7437 }
7438 if (currentParent instanceof BlockStatement$1) {
7439 return false;
7440 }
7441 currentParent = currentParent.parent;
7442 } while (currentParent);
7443 return false;
7444 }
7445}
7446
7447class ImportDeclaration extends NodeBase {
7448 bind() { }
7449 hasEffects() {
7450 return false;
7451 }
7452 initialise() {
7453 this.context.addImport(this);
7454 }
7455 render(code, _options, nodeRenderOptions) {
7456 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
7457 }
7458}
7459ImportDeclaration.prototype.needsBoundaries = true;
7460
7461class ImportDefaultSpecifier$1 extends NodeBase {
7462}
7463
7464class ImportExpression extends NodeBase {
7465 constructor() {
7466 super(...arguments);
7467 this.inlineNamespace = null;
7468 this.mechanism = null;
7469 this.resolution = null;
7470 }
7471 hasEffects() {
7472 return true;
7473 }
7474 include(context, includeChildrenRecursively) {
7475 if (!this.included) {
7476 this.included = true;
7477 this.context.includeDynamicImport(this);
7478 this.scope.addAccessedDynamicImport(this);
7479 }
7480 this.source.include(context, includeChildrenRecursively);
7481 }
7482 initialise() {
7483 this.context.addDynamicImport(this);
7484 }
7485 render(code, options) {
7486 if (this.inlineNamespace) {
7487 const _ = options.compact ? '' : ' ';
7488 const s = options.compact ? '' : ';';
7489 code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
7490 return;
7491 }
7492 if (this.mechanism) {
7493 code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
7494 code.overwrite(this.end - 1, this.end, this.mechanism.right);
7495 }
7496 this.source.render(code, options);
7497 }
7498 renderFinalResolution(code, resolution, namespaceExportName, options) {
7499 code.overwrite(this.source.start, this.source.end, resolution);
7500 if (namespaceExportName) {
7501 const _ = options.compact ? '' : ' ';
7502 const s = options.compact ? '' : ';';
7503 code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
7504 }
7505 }
7506 setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
7507 this.resolution = resolution;
7508 const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
7509 let helper;
7510 ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
7511 if (helper) {
7512 accessedGlobals.push(helper);
7513 }
7514 if (accessedGlobals.length > 0) {
7515 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
7516 }
7517 }
7518 setInternalResolution(inlineNamespace) {
7519 this.inlineNamespace = inlineNamespace;
7520 }
7521 getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
7522 const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
7523 {
7524 customResolution: typeof this.resolution === 'string' ? this.resolution : null,
7525 format: options.format,
7526 moduleId: this.context.module.id,
7527 targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
7528 }
7529 ]);
7530 if (mechanism) {
7531 return { helper: null, mechanism };
7532 }
7533 switch (options.format) {
7534 case 'cjs': {
7535 const _ = options.compact ? '' : ' ';
7536 const s = options.compact ? '' : ';';
7537 const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
7538 const helper = this.getInteropHelper(resolution, exportMode, options.interop);
7539 return {
7540 helper,
7541 mechanism: helper
7542 ? {
7543 left: `${leftStart} /*#__PURE__*/${helper}(require(`,
7544 right: `))${s}${_}})`
7545 }
7546 : {
7547 left: `${leftStart} require(`,
7548 right: `)${s}${_}})`
7549 }
7550 };
7551 }
7552 case 'amd': {
7553 const _ = options.compact ? '' : ' ';
7554 const resolve = options.compact ? 'c' : 'resolve';
7555 const reject = options.compact ? 'e' : 'reject';
7556 const helper = this.getInteropHelper(resolution, exportMode, options.interop);
7557 const resolveNamespace = helper
7558 ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
7559 : resolve;
7560 return {
7561 helper,
7562 mechanism: {
7563 left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
7564 right: `],${_}${resolveNamespace},${_}${reject})${_}})`
7565 }
7566 };
7567 }
7568 case 'system':
7569 return {
7570 helper: null,
7571 mechanism: {
7572 left: 'module.import(',
7573 right: ')'
7574 }
7575 };
7576 case 'es':
7577 if (options.dynamicImportFunction) {
7578 return {
7579 helper: null,
7580 mechanism: {
7581 left: `${options.dynamicImportFunction}(`,
7582 right: ')'
7583 }
7584 };
7585 }
7586 }
7587 return { helper: null, mechanism: null };
7588 }
7589 getInteropHelper(resolution, exportMode, interop) {
7590 return exportMode === 'external'
7591 ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
7592 : exportMode === 'default'
7593 ? getDefaultOnlyHelper()
7594 : null;
7595 }
7596}
7597const accessedImportGlobals = {
7598 amd: ['require'],
7599 cjs: ['require'],
7600 system: ['module']
7601};
7602
7603class ImportNamespaceSpecifier$1 extends NodeBase {
7604}
7605
7606class ImportSpecifier extends NodeBase {
7607}
7608
7609class LabeledStatement extends NodeBase {
7610 hasEffects(context) {
7611 const brokenFlow = context.brokenFlow;
7612 context.ignore.labels.add(this.label.name);
7613 if (this.body.hasEffects(context))
7614 return true;
7615 context.ignore.labels.delete(this.label.name);
7616 if (context.includedLabels.has(this.label.name)) {
7617 context.includedLabels.delete(this.label.name);
7618 context.brokenFlow = brokenFlow;
7619 }
7620 return false;
7621 }
7622 include(context, includeChildrenRecursively) {
7623 this.included = true;
7624 const brokenFlow = context.brokenFlow;
7625 this.body.include(context, includeChildrenRecursively);
7626 if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
7627 this.label.include();
7628 context.includedLabels.delete(this.label.name);
7629 context.brokenFlow = brokenFlow;
7630 }
7631 }
7632 render(code, options) {
7633 if (this.label.included) {
7634 this.label.render(code, options);
7635 }
7636 else {
7637 code.remove(this.start, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1);
7638 }
7639 this.body.render(code, options);
7640 }
7641}
7642
7643class LogicalExpression extends NodeBase {
7644 constructor() {
7645 super(...arguments);
7646 // We collect deoptimization information if usedBranch !== null
7647 this.expressionsToBeDeoptimized = [];
7648 this.isBranchResolutionAnalysed = false;
7649 this.unusedBranch = null;
7650 this.usedBranch = null;
7651 this.wasPathDeoptimizedWhileOptimized = false;
7652 }
7653 bind() {
7654 super.bind();
7655 // ensure the usedBranch is set for the tree-shaking passes
7656 this.getUsedBranch();
7657 }
7658 deoptimizeCache() {
7659 if (this.usedBranch !== null) {
7660 this.usedBranch = null;
7661 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
7662 this.expressionsToBeDeoptimized = [];
7663 if (this.wasPathDeoptimizedWhileOptimized) {
7664 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
7665 }
7666 for (const expression of expressionsToBeDeoptimized) {
7667 expression.deoptimizeCache();
7668 }
7669 }
7670 }
7671 deoptimizePath(path) {
7672 const usedBranch = this.getUsedBranch();
7673 if (usedBranch === null) {
7674 this.left.deoptimizePath(path);
7675 this.right.deoptimizePath(path);
7676 }
7677 else {
7678 this.wasPathDeoptimizedWhileOptimized = true;
7679 usedBranch.deoptimizePath(path);
7680 }
7681 }
7682 getLiteralValueAtPath(path, recursionTracker, origin) {
7683 const usedBranch = this.getUsedBranch();
7684 if (usedBranch === null)
7685 return UnknownValue;
7686 this.expressionsToBeDeoptimized.push(origin);
7687 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
7688 }
7689 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
7690 const usedBranch = this.getUsedBranch();
7691 if (usedBranch === null)
7692 return new MultiExpression([
7693 this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
7694 this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
7695 ]);
7696 this.expressionsToBeDeoptimized.push(origin);
7697 return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
7698 }
7699 hasEffects(context) {
7700 if (this.left.hasEffects(context)) {
7701 return true;
7702 }
7703 if (this.usedBranch !== this.left) {
7704 return this.right.hasEffects(context);
7705 }
7706 return false;
7707 }
7708 hasEffectsWhenAccessedAtPath(path, context) {
7709 if (path.length === 0)
7710 return false;
7711 if (this.usedBranch === null) {
7712 return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
7713 this.right.hasEffectsWhenAccessedAtPath(path, context));
7714 }
7715 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
7716 }
7717 hasEffectsWhenAssignedAtPath(path, context) {
7718 if (path.length === 0)
7719 return true;
7720 if (this.usedBranch === null) {
7721 return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
7722 this.right.hasEffectsWhenAssignedAtPath(path, context));
7723 }
7724 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
7725 }
7726 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7727 if (this.usedBranch === null) {
7728 return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
7729 this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
7730 }
7731 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
7732 }
7733 include(context, includeChildrenRecursively) {
7734 this.included = true;
7735 if (includeChildrenRecursively ||
7736 (this.usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
7737 this.usedBranch === null) {
7738 this.left.include(context, includeChildrenRecursively);
7739 this.right.include(context, includeChildrenRecursively);
7740 }
7741 else {
7742 this.usedBranch.include(context, includeChildrenRecursively);
7743 }
7744 }
7745 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
7746 if (!this.left.included || !this.right.included) {
7747 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
7748 if (this.right.included) {
7749 code.remove(this.start, operatorPos + 2);
7750 if (preventASI) {
7751 removeLineBreaks(code, operatorPos + 2, this.right.start);
7752 }
7753 }
7754 else {
7755 code.remove(operatorPos, this.end);
7756 }
7757 removeAnnotations(this, code);
7758 this.usedBranch.render(code, options, {
7759 isCalleeOfRenderedParent: renderedParentType
7760 ? isCalleeOfRenderedParent
7761 : this.parent.callee === this,
7762 preventASI,
7763 renderedParentType: renderedParentType || this.parent.type
7764 });
7765 }
7766 else {
7767 this.left.render(code, options, { preventASI });
7768 this.right.render(code, options);
7769 }
7770 }
7771 getUsedBranch() {
7772 if (!this.isBranchResolutionAnalysed) {
7773 this.isBranchResolutionAnalysed = true;
7774 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
7775 if (leftValue === UnknownValue) {
7776 return null;
7777 }
7778 else {
7779 if ((this.operator === '||' && leftValue) ||
7780 (this.operator === '&&' && !leftValue) ||
7781 (this.operator === '??' && leftValue != null)) {
7782 this.usedBranch = this.left;
7783 this.unusedBranch = this.right;
7784 }
7785 else {
7786 this.usedBranch = this.right;
7787 this.unusedBranch = this.left;
7788 }
7789 }
7790 }
7791 return this.usedBranch;
7792 }
7793}
7794
7795const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
7796const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
7797const FILE_PREFIX = 'ROLLUP_FILE_URL_';
7798class MetaProperty extends NodeBase {
7799 addAccessedGlobals(format, accessedGlobalsByScope) {
7800 const metaProperty = this.metaProperty;
7801 const accessedGlobals = (metaProperty &&
7802 (metaProperty.startsWith(FILE_PREFIX) ||
7803 metaProperty.startsWith(ASSET_PREFIX) ||
7804 metaProperty.startsWith(CHUNK_PREFIX))
7805 ? accessedFileUrlGlobals
7806 : accessedMetaUrlGlobals)[format];
7807 if (accessedGlobals.length > 0) {
7808 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
7809 }
7810 }
7811 getReferencedFileName(outputPluginDriver) {
7812 const metaProperty = this.metaProperty;
7813 if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
7814 return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
7815 }
7816 return null;
7817 }
7818 hasEffects() {
7819 return false;
7820 }
7821 hasEffectsWhenAccessedAtPath(path) {
7822 return path.length > 1;
7823 }
7824 include() {
7825 if (!this.included) {
7826 this.included = true;
7827 if (this.meta.name === 'import') {
7828 this.context.addImportMeta(this);
7829 const parent = this.parent;
7830 this.metaProperty =
7831 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
7832 ? parent.propertyKey
7833 : null;
7834 }
7835 }
7836 }
7837 renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
7838 var _a;
7839 const parent = this.parent;
7840 const metaProperty = this.metaProperty;
7841 if (metaProperty &&
7842 (metaProperty.startsWith(FILE_PREFIX) ||
7843 metaProperty.startsWith(ASSET_PREFIX) ||
7844 metaProperty.startsWith(CHUNK_PREFIX))) {
7845 let referenceId = null;
7846 let assetReferenceId = null;
7847 let chunkReferenceId = null;
7848 let fileName;
7849 if (metaProperty.startsWith(FILE_PREFIX)) {
7850 referenceId = metaProperty.substr(FILE_PREFIX.length);
7851 fileName = outputPluginDriver.getFileName(referenceId);
7852 }
7853 else if (metaProperty.startsWith(ASSET_PREFIX)) {
7854 warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
7855 assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
7856 fileName = outputPluginDriver.getFileName(assetReferenceId);
7857 }
7858 else {
7859 warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
7860 chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
7861 fileName = outputPluginDriver.getFileName(chunkReferenceId);
7862 }
7863 const relativePath = normalize(sysPath.relative(sysPath.dirname(chunkId), fileName));
7864 let replacement;
7865 if (assetReferenceId !== null) {
7866 replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
7867 {
7868 assetFileName: fileName,
7869 chunkId,
7870 format,
7871 moduleId: this.context.module.id,
7872 relativeAssetPath: relativePath
7873 }
7874 ]);
7875 }
7876 if (!replacement) {
7877 replacement =
7878 outputPluginDriver.hookFirstSync('resolveFileUrl', [
7879 {
7880 assetReferenceId,
7881 chunkId,
7882 chunkReferenceId,
7883 fileName,
7884 format,
7885 moduleId: this.context.module.id,
7886 referenceId: referenceId || assetReferenceId || chunkReferenceId,
7887 relativePath
7888 }
7889 ]) || relativeUrlMechanisms[format](relativePath);
7890 }
7891 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
7892 return;
7893 }
7894 const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
7895 metaProperty,
7896 {
7897 chunkId,
7898 format,
7899 moduleId: this.context.module.id
7900 }
7901 ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
7902 if (typeof replacement === 'string') {
7903 if (parent instanceof MemberExpression) {
7904 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
7905 }
7906 else {
7907 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
7908 }
7909 }
7910 }
7911}
7912const accessedMetaUrlGlobals = {
7913 amd: ['document', 'module', 'URL'],
7914 cjs: ['document', 'require', 'URL'],
7915 es: [],
7916 iife: ['document', 'URL'],
7917 system: ['module'],
7918 umd: ['document', 'require', 'URL']
7919};
7920const accessedFileUrlGlobals = {
7921 amd: ['document', 'require', 'URL'],
7922 cjs: ['document', 'require', 'URL'],
7923 es: [],
7924 iife: ['document', 'URL'],
7925 system: ['module', 'URL'],
7926 umd: ['document', 'require', 'URL']
7927};
7928const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
7929const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
7930const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
7931 const urlMechanism = getUrl(chunkId);
7932 return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
7933};
7934const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
7935const relativeUrlMechanisms = {
7936 amd: relativePath => {
7937 if (relativePath[0] !== '.')
7938 relativePath = './' + relativePath;
7939 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
7940 },
7941 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
7942 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
7943 iife: relativePath => getRelativeUrlFromDocument(relativePath),
7944 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
7945 umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
7946};
7947const importMetaMechanisms = {
7948 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
7949 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
7950 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
7951 system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
7952 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
7953};
7954
7955class NewExpression extends NodeBase {
7956 bind() {
7957 super.bind();
7958 for (const argument of this.arguments) {
7959 // This will make sure all properties of parameters behave as "unknown"
7960 argument.deoptimizePath(UNKNOWN_PATH);
7961 }
7962 }
7963 hasEffects(context) {
7964 for (const argument of this.arguments) {
7965 if (argument.hasEffects(context))
7966 return true;
7967 }
7968 if (this.context.options.treeshake.annotations &&
7969 this.annotatedPure)
7970 return false;
7971 return (this.callee.hasEffects(context) ||
7972 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
7973 }
7974 hasEffectsWhenAccessedAtPath(path) {
7975 return path.length > 1;
7976 }
7977 initialise() {
7978 this.callOptions = {
7979 args: this.arguments,
7980 withNew: true
7981 };
7982 }
7983}
7984
7985class ObjectExpression extends NodeBase {
7986 constructor() {
7987 super(...arguments);
7988 this.deoptimizedPaths = new Set();
7989 // We collect deoptimization information if we can resolve a computed property access
7990 this.expressionsToBeDeoptimized = new Map();
7991 this.hasUnknownDeoptimizedProperty = false;
7992 this.propertyMap = null;
7993 this.unmatchablePropertiesRead = [];
7994 this.unmatchablePropertiesWrite = [];
7995 }
7996 bind() {
7997 super.bind();
7998 // ensure the propertyMap is set for the tree-shaking passes
7999 this.getPropertyMap();
8000 }
8001 // We could also track this per-property but this would quickly become much more complex
8002 deoptimizeCache() {
8003 if (!this.hasUnknownDeoptimizedProperty)
8004 this.deoptimizeAllProperties();
8005 }
8006 deoptimizePath(path) {
8007 if (this.hasUnknownDeoptimizedProperty)
8008 return;
8009 const propertyMap = this.getPropertyMap();
8010 const key = path[0];
8011 if (path.length === 1) {
8012 if (typeof key !== 'string') {
8013 this.deoptimizeAllProperties();
8014 return;
8015 }
8016 if (!this.deoptimizedPaths.has(key)) {
8017 this.deoptimizedPaths.add(key);
8018 // we only deoptimizeCache exact matches as in all other cases,
8019 // we do not return a literal value or return expression
8020 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
8021 if (expressionsToBeDeoptimized) {
8022 for (const expression of expressionsToBeDeoptimized) {
8023 expression.deoptimizeCache();
8024 }
8025 }
8026 }
8027 }
8028 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
8029 for (const property of typeof key === 'string'
8030 ? propertyMap[key]
8031 ? propertyMap[key].propertiesRead
8032 : []
8033 : this.properties) {
8034 property.deoptimizePath(subPath);
8035 }
8036 }
8037 getLiteralValueAtPath(path, recursionTracker, origin) {
8038 const propertyMap = this.getPropertyMap();
8039 const key = path[0];
8040 if (path.length === 0 ||
8041 this.hasUnknownDeoptimizedProperty ||
8042 typeof key !== 'string' ||
8043 this.deoptimizedPaths.has(key)) {
8044 return UnknownValue;
8045 }
8046 if (path.length === 1 &&
8047 !propertyMap[key] &&
8048 !objectMembers[key] &&
8049 this.unmatchablePropertiesRead.length === 0) {
8050 getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
8051 return undefined;
8052 }
8053 if (!propertyMap[key] ||
8054 propertyMap[key].exactMatchRead === null ||
8055 propertyMap[key].propertiesRead.length > 1) {
8056 return UnknownValue;
8057 }
8058 getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
8059 return propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
8060 }
8061 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
8062 const propertyMap = this.getPropertyMap();
8063 const key = path[0];
8064 if (path.length === 0 ||
8065 this.hasUnknownDeoptimizedProperty ||
8066 typeof key !== 'string' ||
8067 this.deoptimizedPaths.has(key)) {
8068 return UNKNOWN_EXPRESSION;
8069 }
8070 if (path.length === 1 &&
8071 objectMembers[key] &&
8072 this.unmatchablePropertiesRead.length === 0 &&
8073 (!propertyMap[key] || propertyMap[key].exactMatchRead === null)) {
8074 return getMemberReturnExpressionWhenCalled(objectMembers, key);
8075 }
8076 if (!propertyMap[key] ||
8077 propertyMap[key].exactMatchRead === null ||
8078 propertyMap[key].propertiesRead.length > 1) {
8079 return UNKNOWN_EXPRESSION;
8080 }
8081 getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
8082 return propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
8083 }
8084 hasEffectsWhenAccessedAtPath(path, context) {
8085 if (path.length === 0)
8086 return false;
8087 const key = path[0];
8088 const propertyMap = this.propertyMap;
8089 if (path.length > 1 &&
8090 (this.hasUnknownDeoptimizedProperty ||
8091 typeof key !== 'string' ||
8092 this.deoptimizedPaths.has(key) ||
8093 !propertyMap[key] ||
8094 propertyMap[key].exactMatchRead === null))
8095 return true;
8096 const subPath = path.slice(1);
8097 for (const property of typeof key !== 'string'
8098 ? this.properties
8099 : propertyMap[key]
8100 ? propertyMap[key].propertiesRead
8101 : []) {
8102 if (property.hasEffectsWhenAccessedAtPath(subPath, context))
8103 return true;
8104 }
8105 return false;
8106 }
8107 hasEffectsWhenAssignedAtPath(path, context) {
8108 const key = path[0];
8109 const propertyMap = this.propertyMap;
8110 if (path.length > 1 &&
8111 (this.hasUnknownDeoptimizedProperty ||
8112 this.deoptimizedPaths.has(key) ||
8113 !propertyMap[key] ||
8114 propertyMap[key].exactMatchRead === null)) {
8115 return true;
8116 }
8117 const subPath = path.slice(1);
8118 for (const property of typeof key !== 'string'
8119 ? this.properties
8120 : path.length > 1
8121 ? propertyMap[key].propertiesRead
8122 : propertyMap[key]
8123 ? propertyMap[key].propertiesWrite
8124 : []) {
8125 if (property.hasEffectsWhenAssignedAtPath(subPath, context))
8126 return true;
8127 }
8128 return false;
8129 }
8130 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8131 const key = path[0];
8132 if (typeof key !== 'string' ||
8133 this.hasUnknownDeoptimizedProperty ||
8134 this.deoptimizedPaths.has(key) ||
8135 (this.propertyMap[key]
8136 ? !this.propertyMap[key].exactMatchRead
8137 : path.length > 1 || !objectMembers[key])) {
8138 return true;
8139 }
8140 const subPath = path.slice(1);
8141 if (this.propertyMap[key]) {
8142 for (const property of this.propertyMap[key].propertiesRead) {
8143 if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
8144 return true;
8145 }
8146 }
8147 if (path.length === 1 && objectMembers[key])
8148 return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
8149 return false;
8150 }
8151 render(code, options, { renderedParentType } = BLANK) {
8152 super.render(code, options);
8153 if (renderedParentType === ExpressionStatement ||
8154 renderedParentType === ArrowFunctionExpression) {
8155 code.appendRight(this.start, '(');
8156 code.prependLeft(this.end, ')');
8157 }
8158 }
8159 deoptimizeAllProperties() {
8160 this.hasUnknownDeoptimizedProperty = true;
8161 for (const property of this.properties) {
8162 property.deoptimizePath(UNKNOWN_PATH);
8163 }
8164 for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
8165 for (const expression of expressionsToBeDeoptimized) {
8166 expression.deoptimizeCache();
8167 }
8168 }
8169 }
8170 getPropertyMap() {
8171 if (this.propertyMap !== null) {
8172 return this.propertyMap;
8173 }
8174 const propertyMap = (this.propertyMap = Object.create(null));
8175 for (let index = this.properties.length - 1; index >= 0; index--) {
8176 const property = this.properties[index];
8177 if (property instanceof SpreadElement) {
8178 this.unmatchablePropertiesRead.push(property);
8179 continue;
8180 }
8181 const isWrite = property.kind !== 'get';
8182 const isRead = property.kind !== 'set';
8183 let key;
8184 if (property.computed) {
8185 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
8186 if (keyValue === UnknownValue) {
8187 if (isRead) {
8188 this.unmatchablePropertiesRead.push(property);
8189 }
8190 else {
8191 this.unmatchablePropertiesWrite.push(property);
8192 }
8193 continue;
8194 }
8195 key = String(keyValue);
8196 }
8197 else if (property.key instanceof Identifier$1) {
8198 key = property.key.name;
8199 }
8200 else {
8201 key = String(property.key.value);
8202 }
8203 const propertyMapProperty = propertyMap[key];
8204 if (!propertyMapProperty) {
8205 propertyMap[key] = {
8206 exactMatchRead: isRead ? property : null,
8207 exactMatchWrite: isWrite ? property : null,
8208 propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
8209 propertiesWrite: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
8210 };
8211 continue;
8212 }
8213 if (isRead && propertyMapProperty.exactMatchRead === null) {
8214 propertyMapProperty.exactMatchRead = property;
8215 propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
8216 }
8217 if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
8218 propertyMapProperty.exactMatchWrite = property;
8219 propertyMapProperty.propertiesWrite.push(property, ...this.unmatchablePropertiesWrite);
8220 }
8221 }
8222 return propertyMap;
8223 }
8224}
8225
8226class ObjectPattern extends NodeBase {
8227 addExportedVariables(variables, exportNamesByVariable) {
8228 for (const property of this.properties) {
8229 if (property.type === Property) {
8230 property.value.addExportedVariables(variables, exportNamesByVariable);
8231 }
8232 else {
8233 property.argument.addExportedVariables(variables, exportNamesByVariable);
8234 }
8235 }
8236 }
8237 declare(kind, init) {
8238 const variables = [];
8239 for (const property of this.properties) {
8240 variables.push(...property.declare(kind, init));
8241 }
8242 return variables;
8243 }
8244 deoptimizePath(path) {
8245 if (path.length === 0) {
8246 for (const property of this.properties) {
8247 property.deoptimizePath(path);
8248 }
8249 }
8250 }
8251 hasEffectsWhenAssignedAtPath(path, context) {
8252 if (path.length > 0)
8253 return true;
8254 for (const property of this.properties) {
8255 if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
8256 return true;
8257 }
8258 return false;
8259 }
8260}
8261
8262class PrivateName extends NodeBase {
8263}
8264
8265class Program$1 extends NodeBase {
8266 constructor() {
8267 super(...arguments);
8268 this.hasCachedEffect = false;
8269 }
8270 hasEffects(context) {
8271 // We are caching here to later more efficiently identify side-effect-free modules
8272 if (this.hasCachedEffect)
8273 return true;
8274 for (const node of this.body) {
8275 if (node.hasEffects(context)) {
8276 return (this.hasCachedEffect = true);
8277 }
8278 }
8279 return false;
8280 }
8281 include(context, includeChildrenRecursively) {
8282 this.included = true;
8283 for (const node of this.body) {
8284 if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
8285 node.include(context, includeChildrenRecursively);
8286 }
8287 }
8288 }
8289 render(code, options) {
8290 if (this.body.length) {
8291 renderStatementList(this.body, code, this.start, this.end, options);
8292 }
8293 else {
8294 super.render(code, options);
8295 }
8296 }
8297}
8298
8299class Property$1 extends NodeBase {
8300 constructor() {
8301 super(...arguments);
8302 this.declarationInit = null;
8303 this.returnExpression = null;
8304 }
8305 bind() {
8306 super.bind();
8307 if (this.kind === 'get') {
8308 // ensure the returnExpression is set for the tree-shaking passes
8309 this.getReturnExpression();
8310 }
8311 if (this.declarationInit !== null) {
8312 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
8313 }
8314 }
8315 declare(kind, init) {
8316 this.declarationInit = init;
8317 return this.value.declare(kind, UNKNOWN_EXPRESSION);
8318 }
8319 // As getter properties directly receive their values from function expressions that always
8320 // have a fixed return value, there is no known situation where a getter is deoptimized.
8321 deoptimizeCache() { }
8322 deoptimizePath(path) {
8323 if (this.kind === 'get') {
8324 this.getReturnExpression().deoptimizePath(path);
8325 }
8326 else {
8327 this.value.deoptimizePath(path);
8328 }
8329 }
8330 getLiteralValueAtPath(path, recursionTracker, origin) {
8331 if (this.kind === 'get') {
8332 return this.getReturnExpression().getLiteralValueAtPath(path, recursionTracker, origin);
8333 }
8334 return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
8335 }
8336 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
8337 if (this.kind === 'get') {
8338 return this.getReturnExpression().getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8339 }
8340 return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8341 }
8342 hasEffects(context) {
8343 return this.key.hasEffects(context) || this.value.hasEffects(context);
8344 }
8345 hasEffectsWhenAccessedAtPath(path, context) {
8346 if (this.kind === 'get') {
8347 const trackedExpressions = context.accessed.getEntities(path);
8348 if (trackedExpressions.has(this))
8349 return false;
8350 trackedExpressions.add(this);
8351 return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
8352 (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
8353 }
8354 return this.value.hasEffectsWhenAccessedAtPath(path, context);
8355 }
8356 hasEffectsWhenAssignedAtPath(path, context) {
8357 if (this.kind === 'get') {
8358 const trackedExpressions = context.assigned.getEntities(path);
8359 if (trackedExpressions.has(this))
8360 return false;
8361 trackedExpressions.add(this);
8362 return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
8363 }
8364 if (this.kind === 'set') {
8365 const trackedExpressions = context.assigned.getEntities(path);
8366 if (trackedExpressions.has(this))
8367 return false;
8368 trackedExpressions.add(this);
8369 return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
8370 }
8371 return this.value.hasEffectsWhenAssignedAtPath(path, context);
8372 }
8373 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8374 if (this.kind === 'get') {
8375 const trackedExpressions = (callOptions.withNew
8376 ? context.instantiated
8377 : context.called).getEntities(path, callOptions);
8378 if (trackedExpressions.has(this))
8379 return false;
8380 trackedExpressions.add(this);
8381 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
8382 }
8383 return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
8384 }
8385 initialise() {
8386 this.accessorCallOptions = {
8387 args: NO_ARGS,
8388 withNew: false
8389 };
8390 }
8391 render(code, options) {
8392 if (!this.shorthand) {
8393 this.key.render(code, options);
8394 }
8395 this.value.render(code, options, { isShorthandProperty: this.shorthand });
8396 }
8397 getReturnExpression() {
8398 if (this.returnExpression === null) {
8399 this.returnExpression = UNKNOWN_EXPRESSION;
8400 return (this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
8401 }
8402 return this.returnExpression;
8403 }
8404}
8405
8406class ReturnStatement$1 extends NodeBase {
8407 hasEffects(context) {
8408 if (!context.ignore.returnAwaitYield ||
8409 (this.argument !== null && this.argument.hasEffects(context)))
8410 return true;
8411 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8412 return false;
8413 }
8414 include(context, includeChildrenRecursively) {
8415 this.included = true;
8416 if (this.argument) {
8417 this.argument.include(context, includeChildrenRecursively);
8418 }
8419 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8420 }
8421 initialise() {
8422 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
8423 }
8424 render(code, options) {
8425 if (this.argument) {
8426 this.argument.render(code, options, { preventASI: true });
8427 if (this.argument.start === this.start + 6 /* 'return'.length */) {
8428 code.prependLeft(this.start + 6, ' ');
8429 }
8430 }
8431 }
8432}
8433
8434class SequenceExpression extends NodeBase {
8435 deoptimizePath(path) {
8436 if (path.length > 0)
8437 this.expressions[this.expressions.length - 1].deoptimizePath(path);
8438 }
8439 getLiteralValueAtPath(path, recursionTracker, origin) {
8440 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
8441 }
8442 hasEffects(context) {
8443 for (const expression of this.expressions) {
8444 if (expression.hasEffects(context))
8445 return true;
8446 }
8447 return false;
8448 }
8449 hasEffectsWhenAccessedAtPath(path, context) {
8450 return (path.length > 0 &&
8451 this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
8452 }
8453 hasEffectsWhenAssignedAtPath(path, context) {
8454 return (path.length === 0 ||
8455 this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
8456 }
8457 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8458 return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
8459 }
8460 include(context, includeChildrenRecursively) {
8461 this.included = true;
8462 for (let i = 0; i < this.expressions.length - 1; i++) {
8463 const node = this.expressions[i];
8464 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8465 node.include(context, includeChildrenRecursively);
8466 }
8467 this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
8468 }
8469 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
8470 let includedNodes = 0;
8471 for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
8472 if (!node.included) {
8473 treeshakeNode(node, code, start, end);
8474 continue;
8475 }
8476 includedNodes++;
8477 if (includedNodes === 1 && preventASI) {
8478 removeLineBreaks(code, start, node.start);
8479 }
8480 if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
8481 node.render(code, options, {
8482 isCalleeOfRenderedParent: renderedParentType
8483 ? isCalleeOfRenderedParent
8484 : this.parent.callee === this,
8485 renderedParentType: renderedParentType || this.parent.type
8486 });
8487 }
8488 else {
8489 node.render(code, options);
8490 }
8491 }
8492 }
8493}
8494
8495class Super extends NodeBase {
8496}
8497
8498class SwitchCase extends NodeBase {
8499 hasEffects(context) {
8500 if (this.test && this.test.hasEffects(context))
8501 return true;
8502 for (const node of this.consequent) {
8503 if (context.brokenFlow)
8504 break;
8505 if (node.hasEffects(context))
8506 return true;
8507 }
8508 return false;
8509 }
8510 include(context, includeChildrenRecursively) {
8511 this.included = true;
8512 if (this.test)
8513 this.test.include(context, includeChildrenRecursively);
8514 for (const node of this.consequent) {
8515 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8516 node.include(context, includeChildrenRecursively);
8517 }
8518 }
8519 render(code, options, nodeRenderOptions) {
8520 if (this.consequent.length) {
8521 this.test && this.test.render(code, options);
8522 const testEnd = this.test
8523 ? this.test.end
8524 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
8525 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
8526 renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
8527 }
8528 else {
8529 super.render(code, options);
8530 }
8531 }
8532}
8533SwitchCase.prototype.needsBoundaries = true;
8534
8535class SwitchStatement extends NodeBase {
8536 createScope(parentScope) {
8537 this.scope = new BlockScope(parentScope);
8538 }
8539 hasEffects(context) {
8540 if (this.discriminant.hasEffects(context))
8541 return true;
8542 const { brokenFlow, ignore: { breaks } } = context;
8543 let minBrokenFlow = Infinity;
8544 context.ignore.breaks = true;
8545 for (const switchCase of this.cases) {
8546 if (switchCase.hasEffects(context))
8547 return true;
8548 minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
8549 context.brokenFlow = brokenFlow;
8550 }
8551 if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8552 context.brokenFlow = minBrokenFlow;
8553 }
8554 context.ignore.breaks = breaks;
8555 return false;
8556 }
8557 include(context, includeChildrenRecursively) {
8558 this.included = true;
8559 this.discriminant.include(context, includeChildrenRecursively);
8560 const { brokenFlow } = context;
8561 let minBrokenFlow = Infinity;
8562 let isCaseIncluded = includeChildrenRecursively ||
8563 (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
8564 for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
8565 const switchCase = this.cases[caseIndex];
8566 if (switchCase.included) {
8567 isCaseIncluded = true;
8568 }
8569 if (!isCaseIncluded) {
8570 const hasEffectsContext = createHasEffectsContext();
8571 hasEffectsContext.ignore.breaks = true;
8572 isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
8573 }
8574 if (isCaseIncluded) {
8575 switchCase.include(context, includeChildrenRecursively);
8576 minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
8577 context.brokenFlow = brokenFlow;
8578 }
8579 else {
8580 minBrokenFlow = brokenFlow;
8581 }
8582 }
8583 if (isCaseIncluded &&
8584 this.defaultCase !== null &&
8585 !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8586 context.brokenFlow = minBrokenFlow;
8587 }
8588 }
8589 initialise() {
8590 for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
8591 if (this.cases[caseIndex].test === null) {
8592 this.defaultCase = caseIndex;
8593 return;
8594 }
8595 }
8596 this.defaultCase = null;
8597 }
8598 render(code, options) {
8599 this.discriminant.render(code, options);
8600 if (this.cases.length > 0) {
8601 renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
8602 }
8603 }
8604}
8605
8606class TaggedTemplateExpression extends NodeBase {
8607 bind() {
8608 super.bind();
8609 if (this.tag.type === Identifier) {
8610 const name = this.tag.name;
8611 const variable = this.scope.findVariable(name);
8612 if (variable.isNamespace) {
8613 this.context.warn({
8614 code: 'CANNOT_CALL_NAMESPACE',
8615 message: `Cannot call a namespace ('${name}')`,
8616 }, this.start);
8617 }
8618 if (name === 'eval') {
8619 this.context.warn({
8620 code: 'EVAL',
8621 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
8622 url: 'https://rollupjs.org/guide/en/#avoiding-eval',
8623 }, this.start);
8624 }
8625 }
8626 }
8627 hasEffects(context) {
8628 return (super.hasEffects(context) ||
8629 this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
8630 }
8631 initialise() {
8632 this.callOptions = {
8633 args: NO_ARGS,
8634 withNew: false,
8635 };
8636 }
8637}
8638
8639class TemplateElement extends NodeBase {
8640 bind() { }
8641 hasEffects() {
8642 return false;
8643 }
8644 include() {
8645 this.included = true;
8646 }
8647 parseNode(esTreeNode) {
8648 this.value = esTreeNode.value;
8649 super.parseNode(esTreeNode);
8650 }
8651 render() { }
8652}
8653
8654class TemplateLiteral extends NodeBase {
8655 getLiteralValueAtPath(path) {
8656 if (path.length > 0 || this.quasis.length !== 1) {
8657 return UnknownValue;
8658 }
8659 return this.quasis[0].value.cooked;
8660 }
8661 render(code, options) {
8662 code.indentExclusionRanges.push([this.start, this.end]);
8663 super.render(code, options);
8664 }
8665}
8666
8667class ModuleScope extends ChildScope {
8668 constructor(parent, context) {
8669 super(parent);
8670 this.context = context;
8671 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
8672 }
8673 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
8674 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
8675 this.variables.set('default', variable);
8676 return variable;
8677 }
8678 addNamespaceMemberAccess() { }
8679 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
8680 // all module level variables are already deconflicted when deconflicting the chunk
8681 for (const scope of this.children)
8682 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
8683 }
8684 findLexicalBoundary() {
8685 return this;
8686 }
8687 findVariable(name) {
8688 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
8689 if (knownVariable) {
8690 return knownVariable;
8691 }
8692 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
8693 if (variable instanceof GlobalVariable) {
8694 this.accessedOutsideVariables.set(name, variable);
8695 }
8696 return variable;
8697 }
8698}
8699
8700class ThisExpression extends NodeBase {
8701 bind() {
8702 super.bind();
8703 this.variable = this.scope.findVariable('this');
8704 }
8705 hasEffectsWhenAccessedAtPath(path, context) {
8706 return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
8707 }
8708 hasEffectsWhenAssignedAtPath(path, context) {
8709 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
8710 }
8711 initialise() {
8712 this.alias =
8713 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
8714 if (this.alias === 'undefined') {
8715 this.context.warn({
8716 code: 'THIS_IS_UNDEFINED',
8717 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
8718 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
8719 }, this.start);
8720 }
8721 }
8722 render(code) {
8723 if (this.alias !== null) {
8724 code.overwrite(this.start, this.end, this.alias, {
8725 contentOnly: false,
8726 storeName: true
8727 });
8728 }
8729 }
8730}
8731
8732class ThrowStatement extends NodeBase {
8733 hasEffects() {
8734 return true;
8735 }
8736 include(context, includeChildrenRecursively) {
8737 this.included = true;
8738 this.argument.include(context, includeChildrenRecursively);
8739 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8740 }
8741 render(code, options) {
8742 this.argument.render(code, options, { preventASI: true });
8743 if (this.argument.start === this.start + 5 /* 'throw'.length */) {
8744 code.prependLeft(this.start + 5, ' ');
8745 }
8746 }
8747}
8748
8749class TryStatement extends NodeBase {
8750 constructor() {
8751 super(...arguments);
8752 this.directlyIncluded = false;
8753 }
8754 hasEffects(context) {
8755 return ((this.context.options.treeshake.tryCatchDeoptimization
8756 ? this.block.body.length > 0
8757 : this.block.hasEffects(context)) ||
8758 (this.finalizer !== null && this.finalizer.hasEffects(context)));
8759 }
8760 include(context, includeChildrenRecursively) {
8761 var _a;
8762 const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
8763 const { brokenFlow } = context;
8764 if (!this.directlyIncluded || !tryCatchDeoptimization) {
8765 this.included = true;
8766 this.directlyIncluded = true;
8767 this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
8768 context.brokenFlow = brokenFlow;
8769 }
8770 if (this.handler !== null) {
8771 this.handler.include(context, includeChildrenRecursively);
8772 context.brokenFlow = brokenFlow;
8773 }
8774 if (this.finalizer !== null) {
8775 this.finalizer.include(context, includeChildrenRecursively);
8776 }
8777 }
8778}
8779
8780const unaryOperators = {
8781 '!': value => !value,
8782 '+': value => +value,
8783 '-': value => -value,
8784 delete: () => UnknownValue,
8785 typeof: value => typeof value,
8786 void: () => undefined,
8787 '~': value => ~value
8788};
8789class UnaryExpression extends NodeBase {
8790 bind() {
8791 super.bind();
8792 if (this.operator === 'delete') {
8793 this.argument.deoptimizePath(EMPTY_PATH);
8794 }
8795 }
8796 getLiteralValueAtPath(path, recursionTracker, origin) {
8797 if (path.length > 0)
8798 return UnknownValue;
8799 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8800 if (argumentValue === UnknownValue)
8801 return UnknownValue;
8802 return unaryOperators[this.operator](argumentValue);
8803 }
8804 hasEffects(context) {
8805 if (this.operator === 'typeof' && this.argument instanceof Identifier$1)
8806 return false;
8807 return (this.argument.hasEffects(context) ||
8808 (this.operator === 'delete' &&
8809 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
8810 }
8811 hasEffectsWhenAccessedAtPath(path) {
8812 if (this.operator === 'void') {
8813 return path.length > 0;
8814 }
8815 return path.length > 1;
8816 }
8817}
8818
8819class UnknownNode extends NodeBase {
8820 hasEffects() {
8821 return true;
8822 }
8823 include(context) {
8824 super.include(context, true);
8825 }
8826}
8827
8828class UpdateExpression extends NodeBase {
8829 bind() {
8830 super.bind();
8831 this.argument.deoptimizePath(EMPTY_PATH);
8832 if (this.argument instanceof Identifier$1) {
8833 const variable = this.scope.findVariable(this.argument.name);
8834 variable.isReassigned = true;
8835 }
8836 }
8837 hasEffects(context) {
8838 return (this.argument.hasEffects(context) ||
8839 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
8840 }
8841 hasEffectsWhenAccessedAtPath(path) {
8842 return path.length > 1;
8843 }
8844 render(code, options) {
8845 this.argument.render(code, options);
8846 if (options.format === 'system') {
8847 const variable = this.argument.variable;
8848 const exportNames = options.exportNamesByVariable.get(variable);
8849 if (exportNames && exportNames.length) {
8850 const _ = options.compact ? '' : ' ';
8851 const name = variable.getName();
8852 if (this.prefix) {
8853 if (exportNames.length === 1) {
8854 code.overwrite(this.start, this.end, `exports('${exportNames[0]}',${_}${this.operator}${name})`);
8855 }
8856 else {
8857 code.overwrite(this.start, this.end, `(${this.operator}${name},${_}${getSystemExportStatement([variable], options)},${_}${name})`);
8858 }
8859 }
8860 else if (exportNames.length > 1) {
8861 code.overwrite(this.start, this.end, `${getSystemExportFunctionLeft([variable], false, options)}${this.operator}${name})`);
8862 }
8863 else {
8864 let op;
8865 switch (this.operator) {
8866 case '++':
8867 op = `${name}${_}+${_}1`;
8868 break;
8869 case '--':
8870 op = `${name}${_}-${_}1`;
8871 break;
8872 }
8873 code.overwrite(this.start, this.end, `(exports('${exportNames[0]}',${_}${op}),${_}${name}${this.operator})`);
8874 }
8875 }
8876 }
8877 }
8878}
8879
8880function isReassignedExportsMember(variable, exportNamesByVariable) {
8881 return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
8882}
8883function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
8884 for (const declarator of declarations) {
8885 if (!declarator.included)
8886 return false;
8887 if (declarator.id.type === Identifier) {
8888 if (exportNamesByVariable.has(declarator.id.variable))
8889 return false;
8890 }
8891 else {
8892 const exportedVariables = [];
8893 declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
8894 if (exportedVariables.length > 0)
8895 return false;
8896 }
8897 }
8898 return true;
8899}
8900class VariableDeclaration extends NodeBase {
8901 deoptimizePath() {
8902 for (const declarator of this.declarations) {
8903 declarator.deoptimizePath(EMPTY_PATH);
8904 }
8905 }
8906 hasEffectsWhenAssignedAtPath() {
8907 return false;
8908 }
8909 include(context, includeChildrenRecursively) {
8910 this.included = true;
8911 for (const declarator of this.declarations) {
8912 if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
8913 declarator.include(context, includeChildrenRecursively);
8914 }
8915 }
8916 includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
8917 this.included = true;
8918 for (const declarator of this.declarations) {
8919 declarator.include(context, includeChildrenRecursively);
8920 }
8921 }
8922 initialise() {
8923 for (const declarator of this.declarations) {
8924 declarator.declareDeclarator(this.kind);
8925 }
8926 }
8927 render(code, options, nodeRenderOptions = BLANK) {
8928 if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
8929 for (const declarator of this.declarations) {
8930 declarator.render(code, options);
8931 }
8932 if (!nodeRenderOptions.isNoStatement &&
8933 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
8934 code.appendLeft(this.end, ';');
8935 }
8936 }
8937 else {
8938 this.renderReplacedDeclarations(code, options, nodeRenderOptions);
8939 }
8940 }
8941 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports, options) {
8942 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
8943 code.remove(this.end - 1, this.end);
8944 }
8945 if (addSemicolon) {
8946 separatorString += ';';
8947 }
8948 if (lastSeparatorPos !== null) {
8949 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
8950 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
8951 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
8952 actualContentEnd--;
8953 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
8954 actualContentEnd--;
8955 }
8956 }
8957 if (actualContentEnd === lastSeparatorPos + 1) {
8958 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
8959 }
8960 else {
8961 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
8962 code.remove(actualContentEnd, renderedContentEnd);
8963 }
8964 }
8965 else {
8966 code.appendLeft(renderedContentEnd, separatorString);
8967 }
8968 if (systemPatternExports.length > 0) {
8969 code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
8970 }
8971 }
8972 renderReplacedDeclarations(code, options, { start = this.start, end = this.end, isNoStatement }) {
8973 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
8974 let actualContentEnd, renderedContentEnd;
8975 if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
8976 renderedContentEnd = this.start + this.kind.length;
8977 }
8978 else {
8979 renderedContentEnd = separatedNodes[0].start;
8980 }
8981 let lastSeparatorPos = renderedContentEnd - 1;
8982 code.remove(this.start, lastSeparatorPos);
8983 let isInDeclaration = false;
8984 let hasRenderedContent = false;
8985 let separatorString = '', leadingString, nextSeparatorString;
8986 const systemPatternExports = [];
8987 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
8988 if (!node.included ||
8989 (node.id instanceof Identifier$1 &&
8990 isReassignedExportsMember(node.id.variable, options.exportNamesByVariable) &&
8991 node.init === null)) {
8992 code.remove(start, end);
8993 continue;
8994 }
8995 leadingString = '';
8996 nextSeparatorString = '';
8997 if (node.id instanceof Identifier$1 &&
8998 isReassignedExportsMember(node.id.variable, options.exportNamesByVariable)) {
8999 if (hasRenderedContent) {
9000 separatorString += ';';
9001 }
9002 isInDeclaration = false;
9003 }
9004 else {
9005 if (options.format === 'system' && node.init !== null) {
9006 if (node.id.type !== Identifier) {
9007 node.id.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
9008 }
9009 else {
9010 const exportNames = options.exportNamesByVariable.get(node.id.variable);
9011 if (exportNames) {
9012 const _ = options.compact ? '' : ' ';
9013 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
9014 code.prependLeft(findNonWhiteSpace(code.original, operatorPos + 1), exportNames.length === 1
9015 ? `exports('${exportNames[0]}',${_}`
9016 : getSystemExportFunctionLeft([node.id.variable], false, options));
9017 nextSeparatorString += ')';
9018 }
9019 }
9020 }
9021 if (isInDeclaration) {
9022 separatorString += ',';
9023 }
9024 else {
9025 if (hasRenderedContent) {
9026 separatorString += ';';
9027 }
9028 leadingString += `${this.kind} `;
9029 isInDeclaration = true;
9030 }
9031 }
9032 if (renderedContentEnd === lastSeparatorPos + 1) {
9033 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
9034 }
9035 else {
9036 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
9037 code.appendLeft(renderedContentEnd, leadingString);
9038 }
9039 node.render(code, options);
9040 actualContentEnd = contentEnd;
9041 renderedContentEnd = end;
9042 hasRenderedContent = true;
9043 lastSeparatorPos = separator;
9044 separatorString = nextSeparatorString;
9045 }
9046 if (hasRenderedContent) {
9047 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports, options);
9048 }
9049 else {
9050 code.remove(start, end);
9051 }
9052 }
9053}
9054
9055class VariableDeclarator extends NodeBase {
9056 declareDeclarator(kind) {
9057 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
9058 }
9059 deoptimizePath(path) {
9060 this.id.deoptimizePath(path);
9061 }
9062}
9063
9064class WhileStatement extends NodeBase {
9065 hasEffects(context) {
9066 if (this.test.hasEffects(context))
9067 return true;
9068 const { brokenFlow, ignore: { breaks, continues } } = context;
9069 context.ignore.breaks = true;
9070 context.ignore.continues = true;
9071 if (this.body.hasEffects(context))
9072 return true;
9073 context.ignore.breaks = breaks;
9074 context.ignore.continues = continues;
9075 context.brokenFlow = brokenFlow;
9076 return false;
9077 }
9078 include(context, includeChildrenRecursively) {
9079 this.included = true;
9080 this.test.include(context, includeChildrenRecursively);
9081 const { brokenFlow } = context;
9082 this.body.include(context, includeChildrenRecursively);
9083 context.brokenFlow = brokenFlow;
9084 }
9085}
9086
9087class YieldExpression extends NodeBase {
9088 bind() {
9089 super.bind();
9090 if (this.argument !== null) {
9091 this.argument.deoptimizePath(UNKNOWN_PATH);
9092 }
9093 }
9094 hasEffects(context) {
9095 return (!context.ignore.returnAwaitYield ||
9096 (this.argument !== null && this.argument.hasEffects(context)));
9097 }
9098 render(code, options) {
9099 if (this.argument) {
9100 this.argument.render(code, options, { preventASI: true });
9101 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
9102 code.prependLeft(this.start + 5, ' ');
9103 }
9104 }
9105 }
9106}
9107
9108const nodeConstructors = {
9109 ArrayExpression,
9110 ArrayPattern,
9111 ArrowFunctionExpression: ArrowFunctionExpression$1,
9112 AssignmentExpression,
9113 AssignmentPattern,
9114 AwaitExpression,
9115 BinaryExpression,
9116 BlockStatement: BlockStatement$1,
9117 BreakStatement,
9118 CallExpression: CallExpression$1,
9119 CatchClause,
9120 ChainExpression,
9121 ClassBody,
9122 ClassDeclaration,
9123 ClassExpression,
9124 ConditionalExpression,
9125 ContinueStatement,
9126 DoWhileStatement,
9127 EmptyStatement,
9128 ExportAllDeclaration,
9129 ExportDefaultDeclaration,
9130 ExportNamedDeclaration,
9131 ExportSpecifier,
9132 ExpressionStatement: ExpressionStatement$1,
9133 FieldDefinition,
9134 ForInStatement,
9135 ForOfStatement,
9136 ForStatement,
9137 FunctionDeclaration,
9138 FunctionExpression: FunctionExpression$1,
9139 Identifier: Identifier$1,
9140 IfStatement,
9141 ImportDeclaration,
9142 ImportDefaultSpecifier: ImportDefaultSpecifier$1,
9143 ImportExpression,
9144 ImportNamespaceSpecifier: ImportNamespaceSpecifier$1,
9145 ImportSpecifier,
9146 LabeledStatement,
9147 Literal,
9148 LogicalExpression,
9149 MemberExpression,
9150 MetaProperty,
9151 MethodDefinition,
9152 NewExpression,
9153 ObjectExpression,
9154 ObjectPattern,
9155 PrivateName,
9156 Program: Program$1,
9157 Property: Property$1,
9158 RestElement,
9159 ReturnStatement: ReturnStatement$1,
9160 SequenceExpression,
9161 SpreadElement,
9162 Super,
9163 SwitchCase,
9164 SwitchStatement,
9165 TaggedTemplateExpression,
9166 TemplateElement,
9167 TemplateLiteral,
9168 ThisExpression,
9169 ThrowStatement,
9170 TryStatement,
9171 UnaryExpression,
9172 UnknownNode,
9173 UpdateExpression,
9174 VariableDeclaration,
9175 VariableDeclarator,
9176 WhileStatement,
9177 YieldExpression
9178};
9179
9180function getId(m) {
9181 return m.id;
9182}
9183
9184function getOriginalLocation(sourcemapChain, location) {
9185 // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
9186 const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
9187 while (filteredSourcemapChain.length > 0) {
9188 const sourcemap = filteredSourcemapChain.pop();
9189 const line = sourcemap.mappings[location.line - 1];
9190 let locationFound = false;
9191 if (line !== undefined) {
9192 for (const segment of line) {
9193 if (segment[0] >= location.column) {
9194 if (segment.length === 1)
9195 break;
9196 location = {
9197 column: segment[3],
9198 line: segment[2] + 1,
9199 name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
9200 source: sourcemap.sources[segment[1]]
9201 };
9202 locationFound = true;
9203 break;
9204 }
9205 }
9206 }
9207 if (!locationFound) {
9208 throw new Error("Can't resolve original location of error.");
9209 }
9210 }
9211 return location;
9212}
9213
9214// AST walker module for Mozilla Parser API compatible trees
9215
9216function skipThrough(node, st, c) { c(node, st); }
9217function ignore(_node, _st, _c) {}
9218
9219// Node walkers.
9220
9221var base$1 = {};
9222
9223base$1.Program = base$1.BlockStatement = function (node, st, c) {
9224 for (var i = 0, list = node.body; i < list.length; i += 1)
9225 {
9226 var stmt = list[i];
9227
9228 c(stmt, st, "Statement");
9229 }
9230};
9231base$1.Statement = skipThrough;
9232base$1.EmptyStatement = ignore;
9233base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
9234 function (node, st, c) { return c(node.expression, st, "Expression"); };
9235base$1.IfStatement = function (node, st, c) {
9236 c(node.test, st, "Expression");
9237 c(node.consequent, st, "Statement");
9238 if (node.alternate) { c(node.alternate, st, "Statement"); }
9239};
9240base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
9241base$1.BreakStatement = base$1.ContinueStatement = ignore;
9242base$1.WithStatement = function (node, st, c) {
9243 c(node.object, st, "Expression");
9244 c(node.body, st, "Statement");
9245};
9246base$1.SwitchStatement = function (node, st, c) {
9247 c(node.discriminant, st, "Expression");
9248 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
9249 var cs = list$1[i$1];
9250
9251 if (cs.test) { c(cs.test, st, "Expression"); }
9252 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
9253 {
9254 var cons = list[i];
9255
9256 c(cons, st, "Statement");
9257 }
9258 }
9259};
9260base$1.SwitchCase = function (node, st, c) {
9261 if (node.test) { c(node.test, st, "Expression"); }
9262 for (var i = 0, list = node.consequent; i < list.length; i += 1)
9263 {
9264 var cons = list[i];
9265
9266 c(cons, st, "Statement");
9267 }
9268};
9269base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
9270 if (node.argument) { c(node.argument, st, "Expression"); }
9271};
9272base$1.ThrowStatement = base$1.SpreadElement =
9273 function (node, st, c) { return c(node.argument, st, "Expression"); };
9274base$1.TryStatement = function (node, st, c) {
9275 c(node.block, st, "Statement");
9276 if (node.handler) { c(node.handler, st); }
9277 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
9278};
9279base$1.CatchClause = function (node, st, c) {
9280 if (node.param) { c(node.param, st, "Pattern"); }
9281 c(node.body, st, "Statement");
9282};
9283base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
9284 c(node.test, st, "Expression");
9285 c(node.body, st, "Statement");
9286};
9287base$1.ForStatement = function (node, st, c) {
9288 if (node.init) { c(node.init, st, "ForInit"); }
9289 if (node.test) { c(node.test, st, "Expression"); }
9290 if (node.update) { c(node.update, st, "Expression"); }
9291 c(node.body, st, "Statement");
9292};
9293base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
9294 c(node.left, st, "ForInit");
9295 c(node.right, st, "Expression");
9296 c(node.body, st, "Statement");
9297};
9298base$1.ForInit = function (node, st, c) {
9299 if (node.type === "VariableDeclaration") { c(node, st); }
9300 else { c(node, st, "Expression"); }
9301};
9302base$1.DebuggerStatement = ignore;
9303
9304base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
9305base$1.VariableDeclaration = function (node, st, c) {
9306 for (var i = 0, list = node.declarations; i < list.length; i += 1)
9307 {
9308 var decl = list[i];
9309
9310 c(decl, st);
9311 }
9312};
9313base$1.VariableDeclarator = function (node, st, c) {
9314 c(node.id, st, "Pattern");
9315 if (node.init) { c(node.init, st, "Expression"); }
9316};
9317
9318base$1.Function = function (node, st, c) {
9319 if (node.id) { c(node.id, st, "Pattern"); }
9320 for (var i = 0, list = node.params; i < list.length; i += 1)
9321 {
9322 var param = list[i];
9323
9324 c(param, st, "Pattern");
9325 }
9326 c(node.body, st, node.expression ? "Expression" : "Statement");
9327};
9328
9329base$1.Pattern = function (node, st, c) {
9330 if (node.type === "Identifier")
9331 { c(node, st, "VariablePattern"); }
9332 else if (node.type === "MemberExpression")
9333 { c(node, st, "MemberPattern"); }
9334 else
9335 { c(node, st); }
9336};
9337base$1.VariablePattern = ignore;
9338base$1.MemberPattern = skipThrough;
9339base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
9340base$1.ArrayPattern = function (node, st, c) {
9341 for (var i = 0, list = node.elements; i < list.length; i += 1) {
9342 var elt = list[i];
9343
9344 if (elt) { c(elt, st, "Pattern"); }
9345 }
9346};
9347base$1.ObjectPattern = function (node, st, c) {
9348 for (var i = 0, list = node.properties; i < list.length; i += 1) {
9349 var prop = list[i];
9350
9351 if (prop.type === "Property") {
9352 if (prop.computed) { c(prop.key, st, "Expression"); }
9353 c(prop.value, st, "Pattern");
9354 } else if (prop.type === "RestElement") {
9355 c(prop.argument, st, "Pattern");
9356 }
9357 }
9358};
9359
9360base$1.Expression = skipThrough;
9361base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
9362base$1.ArrayExpression = function (node, st, c) {
9363 for (var i = 0, list = node.elements; i < list.length; i += 1) {
9364 var elt = list[i];
9365
9366 if (elt) { c(elt, st, "Expression"); }
9367 }
9368};
9369base$1.ObjectExpression = function (node, st, c) {
9370 for (var i = 0, list = node.properties; i < list.length; i += 1)
9371 {
9372 var prop = list[i];
9373
9374 c(prop, st);
9375 }
9376};
9377base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
9378base$1.SequenceExpression = function (node, st, c) {
9379 for (var i = 0, list = node.expressions; i < list.length; i += 1)
9380 {
9381 var expr = list[i];
9382
9383 c(expr, st, "Expression");
9384 }
9385};
9386base$1.TemplateLiteral = function (node, st, c) {
9387 for (var i = 0, list = node.quasis; i < list.length; i += 1)
9388 {
9389 var quasi = list[i];
9390
9391 c(quasi, st);
9392 }
9393
9394 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
9395 {
9396 var expr = list$1[i$1];
9397
9398 c(expr, st, "Expression");
9399 }
9400};
9401base$1.TemplateElement = ignore;
9402base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
9403 c(node.argument, st, "Expression");
9404};
9405base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
9406 c(node.left, st, "Expression");
9407 c(node.right, st, "Expression");
9408};
9409base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
9410 c(node.left, st, "Pattern");
9411 c(node.right, st, "Expression");
9412};
9413base$1.ConditionalExpression = function (node, st, c) {
9414 c(node.test, st, "Expression");
9415 c(node.consequent, st, "Expression");
9416 c(node.alternate, st, "Expression");
9417};
9418base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
9419 c(node.callee, st, "Expression");
9420 if (node.arguments)
9421 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
9422 {
9423 var arg = list[i];
9424
9425 c(arg, st, "Expression");
9426 } }
9427};
9428base$1.MemberExpression = function (node, st, c) {
9429 c(node.object, st, "Expression");
9430 if (node.computed) { c(node.property, st, "Expression"); }
9431};
9432base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
9433 if (node.declaration)
9434 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
9435 if (node.source) { c(node.source, st, "Expression"); }
9436};
9437base$1.ExportAllDeclaration = function (node, st, c) {
9438 if (node.exported)
9439 { c(node.exported, st); }
9440 c(node.source, st, "Expression");
9441};
9442base$1.ImportDeclaration = function (node, st, c) {
9443 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
9444 {
9445 var spec = list[i];
9446
9447 c(spec, st);
9448 }
9449 c(node.source, st, "Expression");
9450};
9451base$1.ImportExpression = function (node, st, c) {
9452 c(node.source, st, "Expression");
9453};
9454base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
9455
9456base$1.TaggedTemplateExpression = function (node, st, c) {
9457 c(node.tag, st, "Expression");
9458 c(node.quasi, st, "Expression");
9459};
9460base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
9461base$1.Class = function (node, st, c) {
9462 if (node.id) { c(node.id, st, "Pattern"); }
9463 if (node.superClass) { c(node.superClass, st, "Expression"); }
9464 c(node.body, st);
9465};
9466base$1.ClassBody = function (node, st, c) {
9467 for (var i = 0, list = node.body; i < list.length; i += 1)
9468 {
9469 var elt = list[i];
9470
9471 c(elt, st);
9472 }
9473};
9474base$1.MethodDefinition = base$1.Property = function (node, st, c) {
9475 if (node.computed) { c(node.key, st, "Expression"); }
9476 c(node.value, st, "Expression");
9477};
9478
9479// @ts-ignore
9480// patch up acorn-walk until class-fields are officially supported
9481base$1.FieldDefinition = function (node, st, c) {
9482 if (node.computed) {
9483 c(node.key, st, 'Expression');
9484 }
9485 if (node.value) {
9486 c(node.value, st, 'Expression');
9487 }
9488};
9489function handlePureAnnotationsOfNode(node, state, type = node.type) {
9490 let commentNode = state.commentNodes[state.commentIndex];
9491 while (commentNode && node.start >= commentNode.end) {
9492 markPureNode(node, commentNode);
9493 commentNode = state.commentNodes[++state.commentIndex];
9494 }
9495 if (commentNode && commentNode.end <= node.end) {
9496 base$1[type](node, state, handlePureAnnotationsOfNode);
9497 }
9498}
9499function markPureNode(node, comment) {
9500 if (node.annotations) {
9501 node.annotations.push(comment);
9502 }
9503 else {
9504 node.annotations = [comment];
9505 }
9506 if (node.type === 'ExpressionStatement') {
9507 node = node.expression;
9508 }
9509 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
9510 node.annotatedPure = true;
9511 }
9512}
9513const pureCommentRegex = /[@#]__PURE__/;
9514const isPureComment = (comment) => pureCommentRegex.test(comment.text);
9515function markPureCallExpressions(comments, esTreeAst) {
9516 handlePureAnnotationsOfNode(esTreeAst, {
9517 commentIndex: 0,
9518 commentNodes: comments.filter(isPureComment)
9519 });
9520}
9521
9522// this looks ridiculous, but it prevents sourcemap tooling from mistaking
9523// this for an actual sourceMappingURL
9524let SOURCEMAPPING_URL = 'sourceMa';
9525SOURCEMAPPING_URL += 'ppingURL';
9526const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
9527
9528const NOOP = () => { };
9529let getStartTime = () => [0, 0];
9530let getElapsedTime = () => 0;
9531let getMemory = () => 0;
9532let timers = {};
9533const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
9534function setTimeHelpers() {
9535 if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
9536 getStartTime = process.hrtime.bind(process);
9537 getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
9538 }
9539 else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
9540 getStartTime = () => [performance.now(), 0];
9541 getElapsedTime = previous => performance.now() - previous[0];
9542 }
9543 if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
9544 getMemory = () => process.memoryUsage().heapUsed;
9545 }
9546}
9547function getPersistedLabel(label, level) {
9548 switch (level) {
9549 case 1:
9550 return `# ${label}`;
9551 case 2:
9552 return `## ${label}`;
9553 case 3:
9554 return label;
9555 default:
9556 return `${' '.repeat(level - 4)}- ${label}`;
9557 }
9558}
9559function timeStartImpl(label, level = 3) {
9560 label = getPersistedLabel(label, level);
9561 if (!timers.hasOwnProperty(label)) {
9562 timers[label] = {
9563 memory: 0,
9564 startMemory: undefined,
9565 startTime: undefined,
9566 time: 0,
9567 totalMemory: 0
9568 };
9569 }
9570 const currentMemory = getMemory();
9571 timers[label].startTime = getStartTime();
9572 timers[label].startMemory = currentMemory;
9573}
9574function timeEndImpl(label, level = 3) {
9575 label = getPersistedLabel(label, level);
9576 if (timers.hasOwnProperty(label)) {
9577 const currentMemory = getMemory();
9578 timers[label].time += getElapsedTime(timers[label].startTime);
9579 timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
9580 timers[label].memory += currentMemory - timers[label].startMemory;
9581 }
9582}
9583function getTimings() {
9584 const newTimings = {};
9585 for (const label of Object.keys(timers)) {
9586 newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
9587 }
9588 return newTimings;
9589}
9590let timeStart = NOOP, timeEnd = NOOP;
9591const TIMED_PLUGIN_HOOKS = {
9592 load: true,
9593 resolveDynamicImport: true,
9594 resolveId: true,
9595 transform: true
9596};
9597function getPluginWithTimers(plugin, index) {
9598 const timedPlugin = {};
9599 for (const hook of Object.keys(plugin)) {
9600 if (TIMED_PLUGIN_HOOKS[hook] === true) {
9601 let timerLabel = `plugin ${index}`;
9602 if (plugin.name) {
9603 timerLabel += ` (${plugin.name})`;
9604 }
9605 timerLabel += ` - ${hook}`;
9606 timedPlugin[hook] = function () {
9607 timeStart(timerLabel, 4);
9608 const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
9609 timeEnd(timerLabel, 4);
9610 if (result && typeof result.then === 'function') {
9611 timeStart(`${timerLabel} (async)`, 4);
9612 result.then(() => timeEnd(`${timerLabel} (async)`, 4));
9613 }
9614 return result;
9615 };
9616 }
9617 else {
9618 timedPlugin[hook] = plugin[hook];
9619 }
9620 }
9621 return timedPlugin;
9622}
9623function initialiseTimers(inputOptions) {
9624 if (inputOptions.perf) {
9625 timers = {};
9626 setTimeHelpers();
9627 timeStart = timeStartImpl;
9628 timeEnd = timeEndImpl;
9629 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
9630 }
9631 else {
9632 timeStart = NOOP;
9633 timeEnd = NOOP;
9634 }
9635}
9636
9637function tryParse(module, Parser, acornOptions) {
9638 try {
9639 return Parser.parse(module.code, {
9640 ...acornOptions,
9641 onComment: (block, text, start, end) => module.comments.push({ block, text, start, end })
9642 });
9643 }
9644 catch (err) {
9645 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
9646 if (module.id.endsWith('.json')) {
9647 message += ' (Note that you need @rollup/plugin-json to import JSON files)';
9648 }
9649 else if (!module.id.endsWith('.js')) {
9650 message += ' (Note that you need plugins to import files that are not JavaScript)';
9651 }
9652 return module.error({
9653 code: 'PARSE_ERROR',
9654 message,
9655 parserError: err
9656 }, err.pos);
9657 }
9658}
9659function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
9660 return importingModule.error({
9661 code: 'MISSING_EXPORT',
9662 message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule.id)}`,
9663 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
9664 }, importerStart);
9665}
9666const MISSING_EXPORT_SHIM_DESCRIPTION = {
9667 identifier: null,
9668 localName: MISSING_EXPORT_SHIM_VARIABLE
9669};
9670function getVariableForExportNameRecursive(target, name, isExportAllSearch, searchedNamesAndModules = new Map()) {
9671 const searchedModules = searchedNamesAndModules.get(name);
9672 if (searchedModules) {
9673 if (searchedModules.has(target)) {
9674 return null;
9675 }
9676 searchedModules.add(target);
9677 }
9678 else {
9679 searchedNamesAndModules.set(name, new Set([target]));
9680 }
9681 return target.getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules);
9682}
9683class Module {
9684 constructor(graph, id, options, isEntryPoint, moduleSideEffects, syntheticNamedExports, meta) {
9685 this.graph = graph;
9686 this.id = id;
9687 this.options = options;
9688 this.isEntryPoint = isEntryPoint;
9689 this.moduleSideEffects = moduleSideEffects;
9690 this.syntheticNamedExports = syntheticNamedExports;
9691 this.meta = meta;
9692 this.chunkFileNames = new Set();
9693 this.chunkName = null;
9694 this.comments = [];
9695 this.dependencies = new Set();
9696 this.dynamicDependencies = new Set();
9697 this.dynamicImporters = [];
9698 this.dynamicImports = [];
9699 this.execIndex = Infinity;
9700 this.exportAllSources = new Set();
9701 this.exports = Object.create(null);
9702 this.exportsAll = Object.create(null);
9703 this.implicitlyLoadedAfter = new Set();
9704 this.implicitlyLoadedBefore = new Set();
9705 this.importDescriptions = Object.create(null);
9706 this.importers = [];
9707 this.importMetas = [];
9708 this.imports = new Set();
9709 this.includedDynamicImporters = [];
9710 this.isExecuted = false;
9711 this.isUserDefinedEntryPoint = false;
9712 this.preserveSignature = this.options.preserveEntrySignatures;
9713 this.reexportDescriptions = Object.create(null);
9714 this.sources = new Set();
9715 this.userChunkNames = new Set();
9716 this.usesTopLevelAwait = false;
9717 this.allExportNames = null;
9718 this.exportAllModules = [];
9719 this.exportNamesByVariable = null;
9720 this.exportShimVariable = new ExportShimVariable(this);
9721 this.relevantDependencies = null;
9722 this.syntheticExports = new Map();
9723 this.syntheticNamespace = null;
9724 this.transformDependencies = [];
9725 this.transitiveReexports = null;
9726 this.excludeFromSourcemap = /\0/.test(id);
9727 this.context = options.moduleContext(id);
9728 }
9729 basename() {
9730 const base = sysPath.basename(this.id);
9731 const ext = sysPath.extname(this.id);
9732 return makeLegal(ext ? base.slice(0, -ext.length) : base);
9733 }
9734 bindReferences() {
9735 this.ast.bind();
9736 }
9737 error(props, pos) {
9738 this.addLocationToLogProps(props, pos);
9739 return error(props);
9740 }
9741 getAllExportNames() {
9742 if (this.allExportNames) {
9743 return this.allExportNames;
9744 }
9745 const allExportNames = (this.allExportNames = new Set());
9746 for (const name of Object.keys(this.exports)) {
9747 allExportNames.add(name);
9748 }
9749 for (const name of Object.keys(this.reexportDescriptions)) {
9750 allExportNames.add(name);
9751 }
9752 for (const module of this.exportAllModules) {
9753 if (module instanceof ExternalModule) {
9754 allExportNames.add(`*${module.id}`);
9755 continue;
9756 }
9757 for (const name of module.getAllExportNames()) {
9758 if (name !== 'default')
9759 allExportNames.add(name);
9760 }
9761 }
9762 return allExportNames;
9763 }
9764 getDependenciesToBeIncluded() {
9765 if (this.relevantDependencies)
9766 return this.relevantDependencies;
9767 const relevantDependencies = new Set();
9768 const additionalSideEffectModules = new Set();
9769 const possibleDependencies = new Set(this.dependencies);
9770 let dependencyVariables = this.imports;
9771 if (this.isEntryPoint ||
9772 this.includedDynamicImporters.length > 0 ||
9773 this.namespace.included ||
9774 this.implicitlyLoadedAfter.size > 0) {
9775 dependencyVariables = new Set(dependencyVariables);
9776 for (const exportName of [...this.getReexports(), ...this.getExports()]) {
9777 dependencyVariables.add(this.getVariableForExportName(exportName));
9778 }
9779 }
9780 for (let variable of dependencyVariables) {
9781 if (variable instanceof SyntheticNamedExportVariable) {
9782 variable = variable.getBaseVariable();
9783 }
9784 else if (variable instanceof ExportDefaultVariable) {
9785 const { modules, original } = variable.getOriginalVariableAndDeclarationModules();
9786 variable = original;
9787 for (const module of modules) {
9788 additionalSideEffectModules.add(module);
9789 possibleDependencies.add(module);
9790 }
9791 }
9792 relevantDependencies.add(variable.module);
9793 }
9794 if (this.options.treeshake && this.moduleSideEffects !== 'no-treeshake') {
9795 for (const dependency of possibleDependencies) {
9796 if (!(dependency.moduleSideEffects || additionalSideEffectModules.has(dependency)) ||
9797 relevantDependencies.has(dependency)) {
9798 continue;
9799 }
9800 if (dependency instanceof ExternalModule || dependency.hasEffects()) {
9801 relevantDependencies.add(dependency);
9802 }
9803 else {
9804 for (const transitiveDependency of dependency.dependencies) {
9805 possibleDependencies.add(transitiveDependency);
9806 }
9807 }
9808 }
9809 }
9810 else {
9811 for (const dependency of this.dependencies) {
9812 relevantDependencies.add(dependency);
9813 }
9814 }
9815 return (this.relevantDependencies = relevantDependencies);
9816 }
9817 getExportNamesByVariable() {
9818 if (this.exportNamesByVariable) {
9819 return this.exportNamesByVariable;
9820 }
9821 const exportNamesByVariable = new Map();
9822 for (const exportName of this.getAllExportNames()) {
9823 if (exportName === this.syntheticNamedExports)
9824 continue;
9825 let tracedVariable = this.getVariableForExportName(exportName);
9826 if (tracedVariable instanceof ExportDefaultVariable) {
9827 tracedVariable = tracedVariable.getOriginalVariable();
9828 }
9829 if (!tracedVariable ||
9830 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
9831 continue;
9832 }
9833 const existingExportNames = exportNamesByVariable.get(tracedVariable);
9834 if (existingExportNames) {
9835 existingExportNames.push(exportName);
9836 }
9837 else {
9838 exportNamesByVariable.set(tracedVariable, [exportName]);
9839 }
9840 }
9841 return (this.exportNamesByVariable = exportNamesByVariable);
9842 }
9843 getExports() {
9844 return Object.keys(this.exports);
9845 }
9846 getReexports() {
9847 if (this.transitiveReexports) {
9848 return this.transitiveReexports;
9849 }
9850 // to avoid infinite recursion when using circular `export * from X`
9851 this.transitiveReexports = [];
9852 const reexports = new Set();
9853 for (const name in this.reexportDescriptions) {
9854 reexports.add(name);
9855 }
9856 for (const module of this.exportAllModules) {
9857 if (module instanceof ExternalModule) {
9858 reexports.add(`*${module.id}`);
9859 }
9860 else {
9861 for (const name of [...module.getReexports(), ...module.getExports()]) {
9862 if (name !== 'default')
9863 reexports.add(name);
9864 }
9865 }
9866 }
9867 return (this.transitiveReexports = [...reexports]);
9868 }
9869 getRenderedExports() {
9870 // only direct exports are counted here, not reexports at all
9871 const renderedExports = [];
9872 const removedExports = [];
9873 for (const exportName in this.exports) {
9874 const variable = this.getVariableForExportName(exportName);
9875 (variable && variable.included ? renderedExports : removedExports).push(exportName);
9876 }
9877 return { renderedExports, removedExports };
9878 }
9879 getSyntheticNamespace() {
9880 if (this.syntheticNamespace === null) {
9881 this.syntheticNamespace = undefined;
9882 this.syntheticNamespace = this.getVariableForExportName(typeof this.syntheticNamedExports === 'string' ? this.syntheticNamedExports : 'default');
9883 }
9884 if (!this.syntheticNamespace) {
9885 return error({
9886 code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
9887 id: this.id,
9888 message: `Module "${relativeId(this.id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(this.syntheticNamedExports)}' needs ${typeof this.syntheticNamedExports === 'string' && this.syntheticNamedExports !== 'default'
9889 ? `an export named "${this.syntheticNamedExports}"`
9890 : 'a default export'}.`
9891 });
9892 }
9893 return this.syntheticNamespace;
9894 }
9895 getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules) {
9896 if (name[0] === '*') {
9897 if (name.length === 1) {
9898 return this.namespace;
9899 }
9900 else {
9901 // export * from 'external'
9902 const module = this.graph.modulesById.get(name.slice(1));
9903 return module.getVariableForExportName('*');
9904 }
9905 }
9906 // export { foo } from './other'
9907 const reexportDeclaration = this.reexportDescriptions[name];
9908 if (reexportDeclaration) {
9909 const declaration = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, false, searchedNamesAndModules);
9910 if (!declaration) {
9911 return handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
9912 }
9913 return declaration;
9914 }
9915 const exportDeclaration = this.exports[name];
9916 if (exportDeclaration) {
9917 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
9918 return this.exportShimVariable;
9919 }
9920 const name = exportDeclaration.localName;
9921 return this.traceVariable(name);
9922 }
9923 if (name !== 'default') {
9924 for (const module of this.exportAllModules) {
9925 const declaration = getVariableForExportNameRecursive(module, name, true, searchedNamesAndModules);
9926 if (declaration)
9927 return declaration;
9928 }
9929 }
9930 // we don't want to create shims when we are just
9931 // probing export * modules for exports
9932 if (!isExportAllSearch) {
9933 if (this.syntheticNamedExports) {
9934 let syntheticExport = this.syntheticExports.get(name);
9935 if (!syntheticExport) {
9936 const syntheticNamespace = this.getSyntheticNamespace();
9937 syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
9938 this.syntheticExports.set(name, syntheticExport);
9939 return syntheticExport;
9940 }
9941 return syntheticExport;
9942 }
9943 if (this.options.shimMissingExports) {
9944 this.shimMissingExport(name);
9945 return this.exportShimVariable;
9946 }
9947 }
9948 return null;
9949 }
9950 hasEffects() {
9951 return (this.moduleSideEffects === 'no-treeshake' ||
9952 (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
9953 }
9954 include() {
9955 const context = createInclusionContext();
9956 if (this.ast.shouldBeIncluded(context))
9957 this.ast.include(context, false);
9958 }
9959 includeAllExports(includeNamespaceMembers) {
9960 if (!this.isExecuted) {
9961 this.graph.needsTreeshakingPass = true;
9962 markModuleAndImpureDependenciesAsExecuted(this);
9963 }
9964 for (const exportName of this.getExports()) {
9965 if (includeNamespaceMembers || exportName !== this.syntheticNamedExports) {
9966 const variable = this.getVariableForExportName(exportName);
9967 variable.deoptimizePath(UNKNOWN_PATH);
9968 if (!variable.included) {
9969 variable.include();
9970 this.graph.needsTreeshakingPass = true;
9971 }
9972 }
9973 }
9974 for (const name of this.getReexports()) {
9975 const variable = this.getVariableForExportName(name);
9976 variable.deoptimizePath(UNKNOWN_PATH);
9977 if (!variable.included) {
9978 variable.include();
9979 this.graph.needsTreeshakingPass = true;
9980 }
9981 if (variable instanceof ExternalVariable) {
9982 variable.module.reexported = true;
9983 }
9984 }
9985 if (includeNamespaceMembers) {
9986 this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
9987 }
9988 }
9989 includeAllInBundle() {
9990 this.ast.include(createInclusionContext(), true);
9991 }
9992 isIncluded() {
9993 return this.ast.included || this.namespace.included;
9994 }
9995 linkImports() {
9996 this.addModulesToImportDescriptions(this.importDescriptions);
9997 this.addModulesToImportDescriptions(this.reexportDescriptions);
9998 for (const name in this.exports) {
9999 if (name !== 'default') {
10000 this.exportsAll[name] = this.id;
10001 }
10002 }
10003 const externalExportAllModules = [];
10004 for (const source of this.exportAllSources) {
10005 const module = this.graph.modulesById.get(this.resolvedIds[source].id);
10006 if (module instanceof ExternalModule) {
10007 externalExportAllModules.push(module);
10008 continue;
10009 }
10010 this.exportAllModules.push(module);
10011 for (const name in module.exportsAll) {
10012 if (name in this.exportsAll) {
10013 this.options.onwarn(errNamespaceConflict(name, this, module));
10014 }
10015 else {
10016 this.exportsAll[name] = module.exportsAll[name];
10017 }
10018 }
10019 }
10020 this.exportAllModules.push(...externalExportAllModules);
10021 }
10022 render(options) {
10023 const magicString = this.magicString.clone();
10024 this.ast.render(magicString, options);
10025 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
10026 return magicString;
10027 }
10028 setSource({ alwaysRemovedCode, ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
10029 this.code = code;
10030 this.originalCode = originalCode;
10031 this.originalSourcemap = originalSourcemap;
10032 this.sourcemapChain = sourcemapChain;
10033 if (transformFiles) {
10034 this.transformFiles = transformFiles;
10035 }
10036 this.transformDependencies = transformDependencies;
10037 this.customTransformCache = customTransformCache;
10038 this.updateOptions(moduleOptions);
10039 timeStart('generate ast', 3);
10040 this.alwaysRemovedCode = alwaysRemovedCode || [];
10041 if (ast) {
10042 this.esTreeAst = ast;
10043 }
10044 else {
10045 this.esTreeAst = tryParse(this, this.graph.acornParser, this.options.acorn);
10046 for (const comment of this.comments) {
10047 if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
10048 this.alwaysRemovedCode.push([comment.start, comment.end]);
10049 }
10050 }
10051 markPureCallExpressions(this.comments, this.esTreeAst);
10052 }
10053 timeEnd('generate ast', 3);
10054 this.resolvedIds = resolvedIds || Object.create(null);
10055 // By default, `id` is the file name. Custom resolvers and loaders
10056 // can change that, but it makes sense to use it for the source file name
10057 const fileName = this.id;
10058 this.magicString = new MagicString(code, {
10059 filename: (this.excludeFromSourcemap ? null : fileName),
10060 indentExclusionRanges: []
10061 });
10062 for (const [start, end] of this.alwaysRemovedCode) {
10063 this.magicString.remove(start, end);
10064 }
10065 timeStart('analyse ast', 3);
10066 this.astContext = {
10067 addDynamicImport: this.addDynamicImport.bind(this),
10068 addExport: this.addExport.bind(this),
10069 addImport: this.addImport.bind(this),
10070 addImportMeta: this.addImportMeta.bind(this),
10071 code,
10072 deoptimizationTracker: this.graph.deoptimizationTracker,
10073 error: this.error.bind(this),
10074 fileName,
10075 getExports: this.getExports.bind(this),
10076 getModuleExecIndex: () => this.execIndex,
10077 getModuleName: this.basename.bind(this),
10078 getReexports: this.getReexports.bind(this),
10079 importDescriptions: this.importDescriptions,
10080 includeAllExports: () => this.includeAllExports(true),
10081 includeDynamicImport: this.includeDynamicImport.bind(this),
10082 includeVariable: this.includeVariable.bind(this),
10083 magicString: this.magicString,
10084 module: this,
10085 moduleContext: this.context,
10086 nodeConstructors,
10087 options: this.options,
10088 traceExport: this.getVariableForExportName.bind(this),
10089 traceVariable: this.traceVariable.bind(this),
10090 usesTopLevelAwait: false,
10091 warn: this.warn.bind(this)
10092 };
10093 this.scope = new ModuleScope(this.graph.scope, this.astContext);
10094 this.namespace = new NamespaceVariable(this.astContext, this.syntheticNamedExports);
10095 this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
10096 timeEnd('analyse ast', 3);
10097 }
10098 toJSON() {
10099 return {
10100 alwaysRemovedCode: this.alwaysRemovedCode,
10101 ast: this.esTreeAst,
10102 code: this.code,
10103 customTransformCache: this.customTransformCache,
10104 dependencies: Array.from(this.dependencies, getId),
10105 id: this.id,
10106 meta: this.meta,
10107 moduleSideEffects: this.moduleSideEffects,
10108 originalCode: this.originalCode,
10109 originalSourcemap: this.originalSourcemap,
10110 resolvedIds: this.resolvedIds,
10111 sourcemapChain: this.sourcemapChain,
10112 syntheticNamedExports: this.syntheticNamedExports,
10113 transformDependencies: this.transformDependencies,
10114 transformFiles: this.transformFiles
10115 };
10116 }
10117 traceVariable(name) {
10118 const localVariable = this.scope.variables.get(name);
10119 if (localVariable) {
10120 return localVariable;
10121 }
10122 if (name in this.importDescriptions) {
10123 const importDeclaration = this.importDescriptions[name];
10124 const otherModule = importDeclaration.module;
10125 if (otherModule instanceof Module && importDeclaration.name === '*') {
10126 return otherModule.namespace;
10127 }
10128 const declaration = otherModule.getVariableForExportName(importDeclaration.name);
10129 if (!declaration) {
10130 return handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
10131 }
10132 return declaration;
10133 }
10134 return null;
10135 }
10136 updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
10137 if (moduleSideEffects != null) {
10138 this.moduleSideEffects = moduleSideEffects;
10139 }
10140 if (syntheticNamedExports != null) {
10141 this.syntheticNamedExports = syntheticNamedExports;
10142 }
10143 if (meta != null) {
10144 this.meta = { ...this.meta, ...meta };
10145 }
10146 }
10147 warn(props, pos) {
10148 this.addLocationToLogProps(props, pos);
10149 this.options.onwarn(props);
10150 }
10151 addDynamicImport(node) {
10152 let argument = node.source;
10153 if (argument instanceof TemplateLiteral) {
10154 if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
10155 argument = argument.quasis[0].value.cooked;
10156 }
10157 }
10158 else if (argument instanceof Literal && typeof argument.value === 'string') {
10159 argument = argument.value;
10160 }
10161 this.dynamicImports.push({ node, resolution: null, argument });
10162 }
10163 addExport(node) {
10164 if (node instanceof ExportDefaultDeclaration) {
10165 // export default foo;
10166 this.exports.default = {
10167 identifier: node.variable.getAssignedVariableName(),
10168 localName: 'default'
10169 };
10170 }
10171 else if (node instanceof ExportAllDeclaration) {
10172 const source = node.source.value;
10173 this.sources.add(source);
10174 if (node.exported) {
10175 // export * as name from './other'
10176 const name = node.exported.name;
10177 this.reexportDescriptions[name] = {
10178 localName: '*',
10179 module: null,
10180 source,
10181 start: node.start
10182 };
10183 }
10184 else {
10185 // export * from './other'
10186 this.exportAllSources.add(source);
10187 }
10188 }
10189 else if (node.source instanceof Literal) {
10190 // export { name } from './other'
10191 const source = node.source.value;
10192 this.sources.add(source);
10193 for (const specifier of node.specifiers) {
10194 const name = specifier.exported.name;
10195 this.reexportDescriptions[name] = {
10196 localName: specifier.local.name,
10197 module: null,
10198 source,
10199 start: specifier.start
10200 };
10201 }
10202 }
10203 else if (node.declaration) {
10204 const declaration = node.declaration;
10205 if (declaration instanceof VariableDeclaration) {
10206 // export var { foo, bar } = ...
10207 // export var foo = 1, bar = 2;
10208 for (const declarator of declaration.declarations) {
10209 for (const localName of extractAssignedNames(declarator.id)) {
10210 this.exports[localName] = { identifier: null, localName };
10211 }
10212 }
10213 }
10214 else {
10215 // export function foo () {}
10216 const localName = declaration.id.name;
10217 this.exports[localName] = { identifier: null, localName };
10218 }
10219 }
10220 else {
10221 // export { foo, bar, baz }
10222 for (const specifier of node.specifiers) {
10223 const localName = specifier.local.name;
10224 const exportedName = specifier.exported.name;
10225 this.exports[exportedName] = { identifier: null, localName };
10226 }
10227 }
10228 }
10229 addImport(node) {
10230 const source = node.source.value;
10231 this.sources.add(source);
10232 for (const specifier of node.specifiers) {
10233 const isDefault = specifier.type === ImportDefaultSpecifier;
10234 const isNamespace = specifier.type === ImportNamespaceSpecifier;
10235 const name = isDefault
10236 ? 'default'
10237 : isNamespace
10238 ? '*'
10239 : specifier.imported.name;
10240 this.importDescriptions[specifier.local.name] = {
10241 module: null,
10242 name,
10243 source,
10244 start: specifier.start
10245 };
10246 }
10247 }
10248 addImportMeta(node) {
10249 this.importMetas.push(node);
10250 }
10251 addLocationToLogProps(props, pos) {
10252 props.id = this.id;
10253 props.pos = pos;
10254 let code = this.code;
10255 let { column, line } = locate(code, pos, { offsetLine: 1 });
10256 try {
10257 ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
10258 code = this.originalCode;
10259 }
10260 catch (e) {
10261 this.options.onwarn({
10262 code: 'SOURCEMAP_ERROR',
10263 id: this.id,
10264 loc: {
10265 column,
10266 file: this.id,
10267 line
10268 },
10269 message: `Error when using sourcemap for reporting an error: ${e.message}`,
10270 pos
10271 });
10272 }
10273 augmentCodeLocation(props, { column, line }, code, this.id);
10274 }
10275 addModulesToImportDescriptions(importDescription) {
10276 for (const name of Object.keys(importDescription)) {
10277 const specifier = importDescription[name];
10278 const id = this.resolvedIds[specifier.source].id;
10279 specifier.module = this.graph.modulesById.get(id);
10280 }
10281 }
10282 includeAndGetAdditionalMergedNamespaces() {
10283 const mergedNamespaces = [];
10284 for (const module of this.exportAllModules) {
10285 if (module instanceof ExternalModule) {
10286 const externalVariable = module.getVariableForExportName('*');
10287 externalVariable.include();
10288 this.imports.add(externalVariable);
10289 mergedNamespaces.push(externalVariable);
10290 }
10291 else if (module.syntheticNamedExports) {
10292 const syntheticNamespace = module.getSyntheticNamespace();
10293 syntheticNamespace.include();
10294 this.imports.add(syntheticNamespace);
10295 mergedNamespaces.push(syntheticNamespace);
10296 }
10297 }
10298 return mergedNamespaces;
10299 }
10300 includeDynamicImport(node) {
10301 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
10302 if (resolution instanceof Module) {
10303 resolution.includedDynamicImporters.push(this);
10304 resolution.includeAllExports(true);
10305 }
10306 }
10307 includeVariable(variable) {
10308 const variableModule = variable.module;
10309 if (!variable.included) {
10310 variable.include();
10311 this.graph.needsTreeshakingPass = true;
10312 }
10313 if (variableModule && variableModule !== this) {
10314 this.imports.add(variable);
10315 }
10316 }
10317 shimMissingExport(name) {
10318 this.options.onwarn({
10319 code: 'SHIMMED_EXPORT',
10320 exporter: relativeId(this.id),
10321 exportName: name,
10322 message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
10323 });
10324 this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
10325 }
10326}
10327
10328class Source {
10329 constructor(filename, content) {
10330 this.isOriginal = true;
10331 this.filename = filename;
10332 this.content = content;
10333 }
10334 traceSegment(line, column, name) {
10335 return { line, column, name, source: this };
10336 }
10337}
10338class Link {
10339 constructor(map, sources) {
10340 this.sources = sources;
10341 this.names = map.names;
10342 this.mappings = map.mappings;
10343 }
10344 traceMappings() {
10345 const sources = [];
10346 const sourcesContent = [];
10347 const names = [];
10348 const mappings = [];
10349 for (const line of this.mappings) {
10350 const tracedLine = [];
10351 for (const segment of line) {
10352 if (segment.length == 1)
10353 continue;
10354 const source = this.sources[segment[1]];
10355 if (!source)
10356 continue;
10357 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
10358 if (traced) {
10359 // newer sources are more likely to be used, so search backwards.
10360 let sourceIndex = sources.lastIndexOf(traced.source.filename);
10361 if (sourceIndex === -1) {
10362 sourceIndex = sources.length;
10363 sources.push(traced.source.filename);
10364 sourcesContent[sourceIndex] = traced.source.content;
10365 }
10366 else if (sourcesContent[sourceIndex] == null) {
10367 sourcesContent[sourceIndex] = traced.source.content;
10368 }
10369 else if (traced.source.content != null &&
10370 sourcesContent[sourceIndex] !== traced.source.content) {
10371 return error({
10372 message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
10373 });
10374 }
10375 const tracedSegment = [
10376 segment[0],
10377 sourceIndex,
10378 traced.line,
10379 traced.column
10380 ];
10381 if (traced.name) {
10382 let nameIndex = names.indexOf(traced.name);
10383 if (nameIndex === -1) {
10384 nameIndex = names.length;
10385 names.push(traced.name);
10386 }
10387 tracedSegment[4] = nameIndex;
10388 }
10389 tracedLine.push(tracedSegment);
10390 }
10391 }
10392 mappings.push(tracedLine);
10393 }
10394 return { sources, sourcesContent, names, mappings };
10395 }
10396 traceSegment(line, column, name) {
10397 const segments = this.mappings[line];
10398 if (!segments)
10399 return null;
10400 // binary search through segments for the given column
10401 let i = 0;
10402 let j = segments.length - 1;
10403 while (i <= j) {
10404 const m = (i + j) >> 1;
10405 const segment = segments[m];
10406 if (segment[0] === column) {
10407 if (segment.length == 1)
10408 return null;
10409 const source = this.sources[segment[1]];
10410 if (!source)
10411 return null;
10412 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
10413 }
10414 if (segment[0] > column) {
10415 j = m - 1;
10416 }
10417 else {
10418 i = m + 1;
10419 }
10420 }
10421 return null;
10422 }
10423}
10424function getLinkMap(warn) {
10425 return function linkMap(source, map) {
10426 if (map.mappings) {
10427 return new Link(map, [source]);
10428 }
10429 warn({
10430 code: 'SOURCEMAP_BROKEN',
10431 message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
10432 "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
10433 'documentation for help',
10434 plugin: map.plugin,
10435 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
10436 });
10437 return new Link({
10438 mappings: [],
10439 names: []
10440 }, [source]);
10441 };
10442}
10443function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
10444 let source;
10445 if (!originalSourcemap) {
10446 source = new Source(id, originalCode);
10447 }
10448 else {
10449 const sources = originalSourcemap.sources;
10450 const sourcesContent = originalSourcemap.sourcesContent || [];
10451 // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
10452 const directory = sysPath.dirname(id) || '.';
10453 const sourceRoot = originalSourcemap.sourceRoot || '.';
10454 const baseSources = sources.map((source, i) => new Source(sysPath.resolve(directory, sourceRoot, source), sourcesContent[i]));
10455 source = new Link(originalSourcemap, baseSources);
10456 }
10457 return sourcemapChain.reduce(linkMap, source);
10458}
10459function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
10460 const linkMap = getLinkMap(warn);
10461 const moduleSources = modules
10462 .filter(module => !module.excludeFromSourcemap)
10463 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
10464 // DecodedSourceMap (from magic-string) uses a number[] instead of the more
10465 // correct SourceMapSegment tuples. Cast it here to gain type safety.
10466 let source = new Link(map, moduleSources);
10467 source = bundleSourcemapChain.reduce(linkMap, source);
10468 let { sources, sourcesContent, names, mappings } = source.traceMappings();
10469 if (file) {
10470 const directory = sysPath.dirname(file);
10471 sources = sources.map((source) => sysPath.relative(directory, source));
10472 file = sysPath.basename(file);
10473 }
10474 sourcesContent = (excludeContent ? null : sourcesContent);
10475 return new SourceMap({ file, sources, sourcesContent, names, mappings });
10476}
10477function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
10478 if (!sourcemapChain.length) {
10479 return originalSourcemap;
10480 }
10481 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
10482 const map = source.traceMappings();
10483 return { version: 3, ...map };
10484}
10485
10486const createHash = () => crypto.createHash('sha256');
10487
10488const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
10489 amd: deconflictImportsOther,
10490 cjs: deconflictImportsOther,
10491 es: deconflictImportsEsmOrSystem,
10492 iife: deconflictImportsOther,
10493 system: deconflictImportsEsmOrSystem,
10494 umd: deconflictImportsOther
10495};
10496function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
10497 for (const module of modules) {
10498 module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
10499 }
10500 deconflictTopLevelVariables(usedNames, modules, includedNamespaces);
10501 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
10502 for (const module of modules) {
10503 module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
10504 }
10505}
10506function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
10507 // This is needed for namespace reexports
10508 for (const dependency of dependenciesToBeDeconflicted.dependencies) {
10509 if (preserveModules || dependency instanceof ExternalModule) {
10510 dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
10511 }
10512 }
10513 for (const variable of imports) {
10514 const module = variable.module;
10515 const name = variable.name;
10516 if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
10517 variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
10518 }
10519 else if (module instanceof ExternalModule && name === 'default') {
10520 variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
10521 ? module.suggestedVariableName + '__default'
10522 : module.suggestedVariableName, usedNames));
10523 }
10524 else {
10525 variable.setRenderNames(null, getSafeName(name, usedNames));
10526 }
10527 }
10528 for (const variable of syntheticExports) {
10529 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
10530 }
10531}
10532function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
10533 for (const chunkOrExternalModule of dependencies) {
10534 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
10535 }
10536 for (const externalModuleOrChunk of deconflictedNamespace) {
10537 externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
10538 }
10539 for (const externalModule of deconflictedDefault) {
10540 if (deconflictedNamespace.has(externalModule) &&
10541 canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
10542 externalModule.defaultVariableName = externalModule.namespaceVariableName;
10543 }
10544 else {
10545 externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
10546 }
10547 }
10548 for (const variable of imports) {
10549 const module = variable.module;
10550 if (module instanceof ExternalModule) {
10551 const name = variable.name;
10552 if (name === 'default') {
10553 const moduleInterop = String(interop(module.id));
10554 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
10555 ? module.defaultVariableName
10556 : module.variableName;
10557 if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
10558 variable.setRenderNames(variableName, 'default');
10559 }
10560 else {
10561 variable.setRenderNames(null, variableName);
10562 }
10563 }
10564 else if (name === '*') {
10565 variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
10566 ? module.namespaceVariableName
10567 : module.variableName);
10568 }
10569 else {
10570 // if the second parameter is `null`, it uses its "name" for the property name
10571 variable.setRenderNames(module.variableName, null);
10572 }
10573 }
10574 else {
10575 const chunk = chunkByModule.get(module);
10576 if (preserveModules && variable.isNamespace) {
10577 variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
10578 }
10579 else if (chunk.exportMode === 'default') {
10580 variable.setRenderNames(null, chunk.variableName);
10581 }
10582 else {
10583 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
10584 }
10585 }
10586 }
10587}
10588function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
10589 for (const module of modules) {
10590 for (const variable of module.scope.variables.values()) {
10591 if (variable.included &&
10592 // this will only happen for exports in some formats
10593 !(variable.renderBaseName ||
10594 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
10595 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
10596 }
10597 }
10598 if (includedNamespaces.has(module)) {
10599 const namespace = module.namespace;
10600 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
10601 }
10602 }
10603}
10604
10605const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
10606const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
10607const backSlashRegEx = /\\/g;
10608function escapeId(id) {
10609 if (!id.match(needsEscapeRegEx))
10610 return id;
10611 return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
10612}
10613
10614const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
10615function sortByExecutionOrder(units) {
10616 units.sort(compareExecIndex);
10617}
10618function analyseModuleExecution(entryModules) {
10619 let nextExecIndex = 0;
10620 const cyclePaths = [];
10621 const analysedModules = new Set();
10622 const dynamicImports = new Set();
10623 const parents = new Map();
10624 const orderedModules = [];
10625 const analyseModule = (module) => {
10626 if (module instanceof Module) {
10627 for (const dependency of module.dependencies) {
10628 if (parents.has(dependency)) {
10629 if (!analysedModules.has(dependency)) {
10630 cyclePaths.push(getCyclePath(dependency, module, parents));
10631 }
10632 continue;
10633 }
10634 parents.set(dependency, module);
10635 analyseModule(dependency);
10636 }
10637 for (const dependency of module.implicitlyLoadedBefore) {
10638 dynamicImports.add(dependency);
10639 }
10640 for (const { resolution } of module.dynamicImports) {
10641 if (resolution instanceof Module) {
10642 dynamicImports.add(resolution);
10643 }
10644 }
10645 orderedModules.push(module);
10646 }
10647 module.execIndex = nextExecIndex++;
10648 analysedModules.add(module);
10649 };
10650 for (const curEntry of entryModules) {
10651 if (!parents.has(curEntry)) {
10652 parents.set(curEntry, null);
10653 analyseModule(curEntry);
10654 }
10655 }
10656 for (const curEntry of dynamicImports) {
10657 if (!parents.has(curEntry)) {
10658 parents.set(curEntry, null);
10659 analyseModule(curEntry);
10660 }
10661 }
10662 return { orderedModules, cyclePaths };
10663}
10664function getCyclePath(module, parent, parents) {
10665 const path = [relativeId(module.id)];
10666 let nextModule = parent;
10667 while (nextModule !== module) {
10668 path.push(relativeId(nextModule.id));
10669 nextModule = parents.get(nextModule);
10670 }
10671 path.push(path[0]);
10672 path.reverse();
10673 return path;
10674}
10675
10676function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
10677 let nameIndex = 0;
10678 for (const variable of exports) {
10679 let exportName = variable.name[0];
10680 if (exportsByName[exportName]) {
10681 do {
10682 exportName = toBase64(++nameIndex);
10683 // skip past leading number identifiers
10684 if (exportName.charCodeAt(0) === 49 /* '1' */) {
10685 nameIndex += 9 * 64 ** (exportName.length - 1);
10686 exportName = toBase64(nameIndex);
10687 }
10688 } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
10689 }
10690 exportsByName[exportName] = variable;
10691 exportNamesByVariable.set(variable, [exportName]);
10692 }
10693}
10694function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
10695 for (const variable of exports) {
10696 let nameIndex = 0;
10697 let exportName = variable.name;
10698 while (exportsByName[exportName]) {
10699 exportName = variable.name + '$' + ++nameIndex;
10700 }
10701 exportsByName[exportName] = variable;
10702 exportNamesByVariable.set(variable, [exportName]);
10703 }
10704}
10705
10706function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
10707 const exportKeys = chunk.getExportNames();
10708 if (exportMode === 'default') {
10709 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
10710 return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
10711 }
10712 }
10713 else if (exportMode === 'none' && exportKeys.length) {
10714 return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
10715 }
10716 if (exportMode === 'auto') {
10717 if (exportKeys.length === 0) {
10718 exportMode = 'none';
10719 }
10720 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
10721 if (format === 'cjs' && unsetOptions.has('exports')) {
10722 warn(errPreferNamedExports(facadeModuleId));
10723 }
10724 exportMode = 'default';
10725 }
10726 else {
10727 if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
10728 warn(errMixedExport(facadeModuleId, name));
10729 }
10730 exportMode = 'named';
10731 }
10732 }
10733 return exportMode;
10734}
10735
10736function guessIndentString(code) {
10737 const lines = code.split('\n');
10738 const tabbed = lines.filter(line => /^\t+/.test(line));
10739 const spaced = lines.filter(line => /^ {2,}/.test(line));
10740 if (tabbed.length === 0 && spaced.length === 0) {
10741 return null;
10742 }
10743 // More lines tabbed than spaced? Assume tabs, and
10744 // default to tabs in the case of a tie (or nothing
10745 // to go on)
10746 if (tabbed.length >= spaced.length) {
10747 return '\t';
10748 }
10749 // Otherwise, we need to guess the multiple
10750 const min = spaced.reduce((previous, current) => {
10751 const numSpaces = /^ +/.exec(current)[0].length;
10752 return Math.min(numSpaces, previous);
10753 }, Infinity);
10754 return new Array(min + 1).join(' ');
10755}
10756function getIndentString(modules, options) {
10757 if (options.indent !== true)
10758 return options.indent;
10759 for (let i = 0; i < modules.length; i++) {
10760 const indent = guessIndentString(modules[i].originalCode);
10761 if (indent !== null)
10762 return indent;
10763 }
10764 return '\t';
10765}
10766
10767function decodedSourcemap(map) {
10768 if (!map)
10769 return null;
10770 if (typeof map === 'string') {
10771 map = JSON.parse(map);
10772 }
10773 if (map.mappings === '') {
10774 return {
10775 mappings: [],
10776 names: [],
10777 sources: [],
10778 version: 3
10779 };
10780 }
10781 let mappings;
10782 if (typeof map.mappings === 'string') {
10783 mappings = decode(map.mappings);
10784 }
10785 else {
10786 mappings = map.mappings;
10787 }
10788 return { ...map, mappings };
10789}
10790
10791function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
10792 const renderChunkReducer = (code, result, plugin) => {
10793 if (result == null)
10794 return code;
10795 if (typeof result === 'string')
10796 result = {
10797 code: result,
10798 map: undefined
10799 };
10800 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
10801 if (result.map !== null) {
10802 const map = decodedSourcemap(result.map);
10803 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
10804 }
10805 return result.code;
10806 };
10807 return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
10808}
10809
10810function renderNamePattern(pattern, patternName, replacements, getFileInfo) {
10811 if (typeof pattern === 'function') {
10812 pattern = pattern(getFileInfo());
10813 }
10814 if (!isPlainPathFragment(pattern))
10815 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
10816 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
10817 if (!replacements.hasOwnProperty(type)) {
10818 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
10819 }
10820 const replacement = replacements[type]();
10821 if (!isPlainPathFragment(replacement))
10822 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
10823 return replacement;
10824 });
10825}
10826function makeUnique(name, existingNames) {
10827 const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
10828 if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
10829 return name;
10830 const ext = sysPath.extname(name);
10831 name = name.substr(0, name.length - ext.length);
10832 let uniqueName, uniqueIndex = 1;
10833 while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
10834 ;
10835 return uniqueName;
10836}
10837
10838const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
10839function getGlobalName(module, globals, hasExports, warn) {
10840 const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
10841 if (globalName) {
10842 return globalName;
10843 }
10844 if (hasExports) {
10845 warn({
10846 code: 'MISSING_GLOBAL_NAME',
10847 guess: module.variableName,
10848 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
10849 source: module.id
10850 });
10851 return module.variableName;
10852 }
10853}
10854class Chunk$1 {
10855 constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
10856 this.orderedModules = orderedModules;
10857 this.inputOptions = inputOptions;
10858 this.outputOptions = outputOptions;
10859 this.unsetOptions = unsetOptions;
10860 this.pluginDriver = pluginDriver;
10861 this.modulesById = modulesById;
10862 this.chunkByModule = chunkByModule;
10863 this.facadeChunkByModule = facadeChunkByModule;
10864 this.includedNamespaces = includedNamespaces;
10865 this.manualChunkAlias = manualChunkAlias;
10866 this.entryModules = [];
10867 this.exportMode = 'named';
10868 this.facadeModule = null;
10869 this.id = null;
10870 this.namespaceVariableName = '';
10871 this.variableName = '';
10872 this.accessedGlobalsByScope = new Map();
10873 this.dependencies = new Set();
10874 this.dynamicDependencies = new Set();
10875 this.dynamicEntryModules = [];
10876 this.exportNamesByVariable = new Map();
10877 this.exports = new Set();
10878 this.exportsByName = Object.create(null);
10879 this.fileName = null;
10880 this.implicitEntryModules = [];
10881 this.implicitlyLoadedBefore = new Set();
10882 this.imports = new Set();
10883 this.indentString = undefined;
10884 this.isEmpty = true;
10885 this.name = null;
10886 this.needsExportsShim = false;
10887 this.renderedDependencies = null;
10888 this.renderedExports = null;
10889 this.renderedHash = undefined;
10890 this.renderedModules = Object.create(null);
10891 this.renderedModuleSources = new Map();
10892 this.renderedSource = null;
10893 this.sortedExportNames = null;
10894 this.strictFacade = false;
10895 this.usedModules = undefined;
10896 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
10897 const chunkModules = new Set(orderedModules);
10898 for (const module of orderedModules) {
10899 if (module.namespace.included) {
10900 includedNamespaces.add(module);
10901 }
10902 if (this.isEmpty && module.isIncluded()) {
10903 this.isEmpty = false;
10904 }
10905 if (module.isEntryPoint || outputOptions.preserveModules) {
10906 this.entryModules.push(module);
10907 }
10908 for (const importer of module.includedDynamicImporters) {
10909 if (!chunkModules.has(importer)) {
10910 this.dynamicEntryModules.push(module);
10911 // Modules with synthetic exports need an artificial namespace for dynamic imports
10912 if (module.syntheticNamedExports && !outputOptions.preserveModules) {
10913 includedNamespaces.add(module);
10914 this.exports.add(module.namespace);
10915 }
10916 }
10917 }
10918 if (module.implicitlyLoadedAfter.size > 0) {
10919 this.implicitEntryModules.push(module);
10920 }
10921 }
10922 this.suggestedVariableName = makeLegal(this.generateVariableName());
10923 }
10924 static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
10925 const chunk = new Chunk$1([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
10926 chunk.assignFacadeName(facadeName, facadedModule);
10927 if (!facadeChunkByModule.has(facadedModule)) {
10928 facadeChunkByModule.set(facadedModule, chunk);
10929 }
10930 for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
10931 chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
10932 }
10933 if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
10934 facadedModule.moduleSideEffects &&
10935 facadedModule.hasEffects()) {
10936 chunk.dependencies.add(chunkByModule.get(facadedModule));
10937 }
10938 chunk.ensureReexportsAreAvailableForModule(facadedModule);
10939 chunk.facadeModule = facadedModule;
10940 chunk.strictFacade = true;
10941 return chunk;
10942 }
10943 canModuleBeFacade(module, exposedVariables) {
10944 const moduleExportNamesByVariable = module.getExportNamesByVariable();
10945 for (const exposedVariable of this.exports) {
10946 if (!moduleExportNamesByVariable.has(exposedVariable)) {
10947 if (moduleExportNamesByVariable.size === 0 &&
10948 module.isUserDefinedEntryPoint &&
10949 module.preserveSignature === 'strict' &&
10950 this.unsetOptions.has('preserveEntrySignatures')) {
10951 this.inputOptions.onwarn({
10952 code: 'EMPTY_FACADE',
10953 id: module.id,
10954 message: `To preserve the export signature of the entry module "${relativeId(module.id)}", an empty facade chunk was created. This often happens when creating a bundle for a web app where chunks are placed in script tags and exports are ignored. In this case it is recommended to set "preserveEntrySignatures: false" to avoid this and reduce the number of chunks. Otherwise if this is intentional, set "preserveEntrySignatures: 'strict'" explicitly to silence this warning.`,
10955 url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
10956 });
10957 }
10958 return false;
10959 }
10960 }
10961 for (const exposedVariable of exposedVariables) {
10962 if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
10963 return false;
10964 }
10965 }
10966 return true;
10967 }
10968 generateExports() {
10969 this.sortedExportNames = null;
10970 const remainingExports = new Set(this.exports);
10971 if (this.facadeModule !== null &&
10972 (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
10973 const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
10974 for (const [variable, exportNames] of exportNamesByVariable) {
10975 this.exportNamesByVariable.set(variable, [...exportNames]);
10976 for (const exportName of exportNames) {
10977 this.exportsByName[exportName] = variable;
10978 }
10979 remainingExports.delete(variable);
10980 }
10981 }
10982 if (this.outputOptions.minifyInternalExports) {
10983 assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
10984 }
10985 else {
10986 assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
10987 }
10988 if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.isEntryPoint))
10989 this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
10990 }
10991 generateFacades() {
10992 var _a;
10993 const facades = [];
10994 const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
10995 const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
10996 for (const module of entryModules) {
10997 if (module.preserveSignature) {
10998 for (const exportedVariable of module.getExportNamesByVariable().keys()) {
10999 exposedVariables.add(exportedVariable);
11000 }
11001 }
11002 }
11003 for (const module of entryModules) {
11004 const requiredFacades = Array.from(module.userChunkNames, name => ({
11005 name
11006 }));
11007 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
11008 requiredFacades.push({});
11009 }
11010 requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
11011 if (requiredFacades.length === 0) {
11012 requiredFacades.push({});
11013 }
11014 if (!this.facadeModule &&
11015 (this.outputOptions.preserveModules ||
11016 module.preserveSignature !== 'strict' ||
11017 this.canModuleBeFacade(module, exposedVariables))) {
11018 this.facadeModule = module;
11019 this.facadeChunkByModule.set(module, this);
11020 if (module.preserveSignature) {
11021 this.strictFacade = module.preserveSignature === 'strict';
11022 this.ensureReexportsAreAvailableForModule(module);
11023 }
11024 this.assignFacadeName(requiredFacades.shift(), module);
11025 }
11026 for (const facadeName of requiredFacades) {
11027 facades.push(Chunk$1.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
11028 }
11029 }
11030 for (const module of this.dynamicEntryModules) {
11031 if (module.syntheticNamedExports)
11032 continue;
11033 if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
11034 this.facadeModule = module;
11035 this.facadeChunkByModule.set(module, this);
11036 this.strictFacade = true;
11037 this.assignFacadeName({}, module);
11038 }
11039 else if (this.facadeModule === module &&
11040 !this.strictFacade &&
11041 this.canModuleBeFacade(module, exposedVariables)) {
11042 this.strictFacade = true;
11043 }
11044 else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
11045 this.includedNamespaces.add(module);
11046 this.exports.add(module.namespace);
11047 }
11048 }
11049 return facades;
11050 }
11051 generateId(addons, options, existingNames, includeHash) {
11052 if (this.fileName !== null) {
11053 return this.fileName;
11054 }
11055 const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
11056 ? [options.entryFileNames, 'output.entryFileNames']
11057 : [options.chunkFileNames, 'output.chunkFileNames'];
11058 return makeUnique(renderNamePattern(pattern, patternName, {
11059 format: () => options.format,
11060 hash: () => includeHash
11061 ? this.computeContentHashWithDependencies(addons, options, existingNames)
11062 : '[hash]',
11063 name: () => this.getChunkName()
11064 }, this.getChunkInfo.bind(this)), existingNames);
11065 }
11066 generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
11067 const id = this.orderedModules[0].id;
11068 const sanitizedId = sanitizeFileName(id);
11069 let path;
11070 if (isAbsolute(id)) {
11071 const extension = sysPath.extname(id);
11072 const pattern = unsetOptions.has('entryFileNames')
11073 ? NON_ASSET_EXTENSIONS.includes(extension)
11074 ? '[name].js'
11075 : '[name][extname].js'
11076 : options.entryFileNames;
11077 const currentDir = sysPath.dirname(sanitizedId);
11078 const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
11079 ext: () => extension.substr(1),
11080 extname: () => extension,
11081 format: () => options.format,
11082 name: () => this.getChunkName()
11083 }, this.getChunkInfo.bind(this));
11084 const currentPath = `${currentDir}/${fileName}`;
11085 const { preserveModulesRoot } = options;
11086 if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
11087 path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
11088 }
11089 else {
11090 path = relative(preserveModulesRelativeDir, currentPath);
11091 }
11092 }
11093 else {
11094 path = `_virtual/${sysPath.basename(sanitizedId)}`;
11095 }
11096 return makeUnique(normalize(path), existingNames);
11097 }
11098 getChunkInfo() {
11099 const facadeModule = this.facadeModule;
11100 const getChunkName = this.getChunkName.bind(this);
11101 return {
11102 exports: this.getExportNames(),
11103 facadeModuleId: facadeModule && facadeModule.id,
11104 isDynamicEntry: this.dynamicEntryModules.length > 0,
11105 isEntry: facadeModule !== null && facadeModule.isEntryPoint,
11106 isImplicitEntry: this.implicitEntryModules.length > 0,
11107 modules: this.renderedModules,
11108 get name() {
11109 return getChunkName();
11110 },
11111 type: 'chunk'
11112 };
11113 }
11114 getChunkInfoWithFileNames() {
11115 return Object.assign(this.getChunkInfo(), {
11116 code: undefined,
11117 dynamicImports: Array.from(this.dynamicDependencies, getId),
11118 fileName: this.id,
11119 implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
11120 importedBindings: this.getImportedBindingsPerDependency(),
11121 imports: Array.from(this.dependencies, getId),
11122 map: undefined,
11123 referencedFiles: this.getReferencedFiles()
11124 });
11125 }
11126 getChunkName() {
11127 return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName()));
11128 }
11129 getExportNames() {
11130 return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
11131 }
11132 getRenderedHash() {
11133 if (this.renderedHash)
11134 return this.renderedHash;
11135 const hash = createHash();
11136 const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
11137 if (pluginHash) {
11138 augmentation += pluginHash;
11139 }
11140 return augmentation;
11141 });
11142 hash.update(hashAugmentation);
11143 hash.update(this.renderedSource.toString());
11144 hash.update(this.getExportNames()
11145 .map(exportName => {
11146 const variable = this.exportsByName[exportName];
11147 return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
11148 })
11149 .join(','));
11150 return (this.renderedHash = hash.digest('hex'));
11151 }
11152 getVariableExportName(variable) {
11153 if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
11154 return '*';
11155 }
11156 return this.exportNamesByVariable.get(variable)[0];
11157 }
11158 link() {
11159 for (const module of this.orderedModules) {
11160 this.addDependenciesToChunk(module.getDependenciesToBeIncluded(), this.dependencies);
11161 this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
11162 this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
11163 this.setUpChunkImportsAndExportsForModule(module);
11164 }
11165 }
11166 // prerender allows chunk hashes and names to be generated before finalizing
11167 preRender(options, inputBase) {
11168 const magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
11169 this.usedModules = [];
11170 this.indentString = getIndentString(this.orderedModules, options);
11171 const n = options.compact ? '' : '\n';
11172 const _ = options.compact ? '' : ' ';
11173 const renderOptions = {
11174 compact: options.compact,
11175 dynamicImportFunction: options.dynamicImportFunction,
11176 exportNamesByVariable: this.exportNamesByVariable,
11177 format: options.format,
11178 freeze: options.freeze,
11179 indent: this.indentString,
11180 namespaceToStringTag: options.namespaceToStringTag,
11181 outputPluginDriver: this.pluginDriver,
11182 varOrConst: options.preferConst ? 'const' : 'var'
11183 };
11184 // for static and dynamic entry points, inline the execution list to avoid loading latency
11185 if (options.hoistTransitiveImports &&
11186 !this.outputOptions.preserveModules &&
11187 this.facadeModule !== null) {
11188 for (const dep of this.dependencies) {
11189 if (dep instanceof Chunk$1)
11190 this.inlineChunkDependencies(dep);
11191 }
11192 }
11193 const sortedDependencies = [...this.dependencies];
11194 sortByExecutionOrder(sortedDependencies);
11195 this.dependencies = new Set(sortedDependencies);
11196 this.prepareDynamicImportsAndImportMetas();
11197 this.setIdentifierRenderResolutions(options);
11198 let hoistedSource = '';
11199 const renderedModules = this.renderedModules;
11200 for (const module of this.orderedModules) {
11201 let renderedLength = 0;
11202 if (module.isIncluded() || this.includedNamespaces.has(module)) {
11203 const source = module.render(renderOptions).trim();
11204 renderedLength = source.length();
11205 if (renderedLength) {
11206 if (options.compact && source.lastLine().indexOf('//') !== -1)
11207 source.append('\n');
11208 this.renderedModuleSources.set(module, source);
11209 magicString.addSource(source);
11210 this.usedModules.push(module);
11211 }
11212 const namespace = module.namespace;
11213 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
11214 const rendered = namespace.renderBlock(renderOptions);
11215 if (namespace.renderFirst())
11216 hoistedSource += n + rendered;
11217 else
11218 magicString.addSource(new MagicString(rendered));
11219 }
11220 }
11221 const { renderedExports, removedExports } = module.getRenderedExports();
11222 renderedModules[module.id] = {
11223 originalLength: module.originalCode.length,
11224 removedExports,
11225 renderedExports,
11226 renderedLength
11227 };
11228 }
11229 if (hoistedSource)
11230 magicString.prepend(hoistedSource + n + n);
11231 if (this.needsExportsShim) {
11232 magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
11233 }
11234 if (options.compact) {
11235 this.renderedSource = magicString;
11236 }
11237 else {
11238 this.renderedSource = magicString.trim();
11239 }
11240 this.renderedHash = undefined;
11241 if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
11242 const chunkName = this.getChunkName();
11243 this.inputOptions.onwarn({
11244 chunkName,
11245 code: 'EMPTY_BUNDLE',
11246 message: `Generated an empty chunk: "${chunkName}"`
11247 });
11248 }
11249 this.setExternalRenderPaths(options, inputBase);
11250 this.renderedDependencies = this.getChunkDependencyDeclarations(options);
11251 this.renderedExports =
11252 this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
11253 }
11254 async render(options, addons, outputChunk) {
11255 timeStart('render format', 2);
11256 const format = options.format;
11257 const finalise = finalisers[format];
11258 if (options.dynamicImportFunction && format !== 'es') {
11259 this.inputOptions.onwarn({
11260 code: 'INVALID_OPTION',
11261 message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
11262 });
11263 }
11264 // populate ids in the rendered declarations only here
11265 // as chunk ids known only after prerender
11266 for (const dependency of this.dependencies) {
11267 const renderedDependency = this.renderedDependencies.get(dependency);
11268 if (dependency instanceof ExternalModule) {
11269 const originalId = dependency.renderPath;
11270 renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
11271 }
11272 else {
11273 renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
11274 renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
11275 }
11276 }
11277 this.finaliseDynamicImports(options);
11278 this.finaliseImportMetas(format);
11279 const hasExports = this.renderedExports.length !== 0 ||
11280 [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
11281 let usesTopLevelAwait = false;
11282 const accessedGlobals = new Set();
11283 for (const module of this.orderedModules) {
11284 if (module.usesTopLevelAwait) {
11285 usesTopLevelAwait = true;
11286 }
11287 const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
11288 if (accessedGlobalVariables) {
11289 for (const name of accessedGlobalVariables) {
11290 accessedGlobals.add(name);
11291 }
11292 }
11293 }
11294 if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
11295 return error({
11296 code: 'INVALID_TLA_FORMAT',
11297 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
11298 });
11299 }
11300 const magicString = finalise(this.renderedSource, {
11301 accessedGlobals,
11302 dependencies: [...this.renderedDependencies.values()],
11303 exports: this.renderedExports,
11304 hasExports,
11305 indentString: this.indentString,
11306 intro: addons.intro,
11307 isEntryModuleFacade: this.outputOptions.preserveModules ||
11308 (this.facadeModule !== null && this.facadeModule.isEntryPoint),
11309 namedExportsMode: this.exportMode !== 'default',
11310 outro: addons.outro,
11311 usesTopLevelAwait,
11312 varOrConst: options.preferConst ? 'const' : 'var',
11313 warn: this.inputOptions.onwarn
11314 }, options);
11315 if (addons.banner)
11316 magicString.prepend(addons.banner);
11317 if (addons.footer)
11318 magicString.append(addons.footer);
11319 const prevCode = magicString.toString();
11320 timeEnd('render format', 2);
11321 let map = null;
11322 const chunkSourcemapChain = [];
11323 let code = await renderChunk({
11324 code: prevCode,
11325 options,
11326 outputPluginDriver: this.pluginDriver,
11327 renderChunk: outputChunk,
11328 sourcemapChain: chunkSourcemapChain
11329 });
11330 if (options.sourcemap) {
11331 timeStart('sourcemap', 2);
11332 let file;
11333 if (options.file)
11334 file = sysPath.resolve(options.sourcemapFile || options.file);
11335 else if (options.dir)
11336 file = sysPath.resolve(options.dir, this.id);
11337 else
11338 file = sysPath.resolve(this.id);
11339 const decodedMap = magicString.generateDecodedMap({});
11340 map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
11341 map.sources = map.sources
11342 .map(sourcePath => {
11343 const { sourcemapPathTransform } = options;
11344 if (sourcemapPathTransform) {
11345 const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
11346 if (typeof newSourcePath !== 'string') {
11347 error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
11348 }
11349 return newSourcePath;
11350 }
11351 return sourcePath;
11352 })
11353 .map(normalize);
11354 timeEnd('sourcemap', 2);
11355 }
11356 if (!options.compact && code[code.length - 1] !== '\n')
11357 code += '\n';
11358 return { code, map };
11359 }
11360 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
11361 for (const module of moduleDependencies) {
11362 if (module instanceof Module) {
11363 const chunk = this.chunkByModule.get(module);
11364 if (chunk && chunk !== this) {
11365 chunkDependencies.add(chunk);
11366 }
11367 }
11368 else {
11369 chunkDependencies.add(module);
11370 }
11371 }
11372 }
11373 assignFacadeName({ fileName, name }, facadedModule) {
11374 if (fileName) {
11375 this.fileName = fileName;
11376 }
11377 else {
11378 this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id));
11379 }
11380 }
11381 computeContentHashWithDependencies(addons, options, existingNames) {
11382 const hash = createHash();
11383 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
11384 hash.update(options.format);
11385 const dependenciesForHashing = new Set([this]);
11386 for (const current of dependenciesForHashing) {
11387 if (current instanceof ExternalModule) {
11388 hash.update(':' + current.renderPath);
11389 }
11390 else {
11391 hash.update(current.getRenderedHash());
11392 hash.update(current.generateId(addons, options, existingNames, false));
11393 }
11394 if (current instanceof ExternalModule)
11395 continue;
11396 for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
11397 dependenciesForHashing.add(dependency);
11398 }
11399 }
11400 return hash.digest('hex').substr(0, 8);
11401 }
11402 ensureReexportsAreAvailableForModule(module) {
11403 const map = module.getExportNamesByVariable();
11404 for (const exportedVariable of map.keys()) {
11405 const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
11406 const importedVariable = isSynthetic
11407 ? exportedVariable.getBaseVariable()
11408 : exportedVariable;
11409 if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
11410 const exportingModule = importedVariable.module;
11411 if (exportingModule instanceof Module) {
11412 const chunk = this.chunkByModule.get(exportingModule);
11413 if (chunk && chunk !== this) {
11414 chunk.exports.add(importedVariable);
11415 if (isSynthetic) {
11416 this.imports.add(importedVariable);
11417 }
11418 }
11419 }
11420 }
11421 }
11422 }
11423 finaliseDynamicImports(options) {
11424 const stripKnownJsExtensions = options.format === 'amd';
11425 for (const [module, code] of this.renderedModuleSources) {
11426 for (const { node, resolution } of module.dynamicImports) {
11427 const chunk = this.chunkByModule.get(resolution);
11428 const facadeChunk = this.facadeChunkByModule.get(resolution);
11429 if (!resolution || !node.included || chunk === this) {
11430 continue;
11431 }
11432 const renderedResolution = resolution instanceof Module
11433 ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
11434 : resolution instanceof ExternalModule
11435 ? `'${resolution.renormalizeRenderPath
11436 ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
11437 : resolution.renderPath}'`
11438 : resolution;
11439 node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
11440 !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
11441 chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
11442 }
11443 }
11444 }
11445 finaliseImportMetas(format) {
11446 for (const [module, code] of this.renderedModuleSources) {
11447 for (const importMeta of module.importMetas) {
11448 importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
11449 }
11450 }
11451 }
11452 generateVariableName() {
11453 if (this.manualChunkAlias) {
11454 return this.manualChunkAlias;
11455 }
11456 const moduleForNaming = this.entryModules[0] ||
11457 this.implicitEntryModules[0] ||
11458 this.dynamicEntryModules[0] ||
11459 this.orderedModules[this.orderedModules.length - 1];
11460 if (moduleForNaming) {
11461 return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
11462 }
11463 return 'chunk';
11464 }
11465 getChunkDependencyDeclarations(options) {
11466 const importSpecifiers = this.getImportSpecifiers();
11467 const reexportSpecifiers = this.getReexportSpecifiers();
11468 const dependencyDeclaration = new Map();
11469 for (const dep of this.dependencies) {
11470 const imports = importSpecifiers.get(dep) || null;
11471 const reexports = reexportSpecifiers.get(dep) || null;
11472 const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
11473 dependencyDeclaration.set(dep, {
11474 defaultVariableName: dep.defaultVariableName,
11475 globalName: (dep instanceof ExternalModule &&
11476 (options.format === 'umd' || options.format === 'iife') &&
11477 getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
11478 id: undefined,
11479 imports,
11480 isChunk: dep instanceof Chunk$1,
11481 name: dep.variableName,
11482 namedExportsMode,
11483 namespaceVariableName: dep.namespaceVariableName,
11484 reexports
11485 });
11486 }
11487 return dependencyDeclaration;
11488 }
11489 getChunkExportDeclarations(format) {
11490 const exports = [];
11491 for (const exportName of this.getExportNames()) {
11492 if (exportName[0] === '*')
11493 continue;
11494 const variable = this.exportsByName[exportName];
11495 if (!(variable instanceof SyntheticNamedExportVariable)) {
11496 const module = variable.module;
11497 if (module && this.chunkByModule.get(module) !== this)
11498 continue;
11499 }
11500 let expression = null;
11501 let hoisted = false;
11502 let uninitialized = false;
11503 let local = variable.getName();
11504 if (variable instanceof LocalVariable) {
11505 if (variable.init === UNDEFINED_EXPRESSION) {
11506 uninitialized = true;
11507 }
11508 for (const declaration of variable.declarations) {
11509 if (declaration.parent instanceof FunctionDeclaration ||
11510 (declaration instanceof ExportDefaultDeclaration &&
11511 declaration.declaration instanceof FunctionDeclaration)) {
11512 hoisted = true;
11513 break;
11514 }
11515 }
11516 }
11517 else if (variable instanceof SyntheticNamedExportVariable) {
11518 expression = local;
11519 if (format === 'es' && exportName !== 'default') {
11520 local = variable.renderName;
11521 }
11522 }
11523 exports.push({
11524 exported: exportName,
11525 expression,
11526 hoisted,
11527 local,
11528 uninitialized
11529 });
11530 }
11531 return exports;
11532 }
11533 getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
11534 const dependencies = new Set();
11535 const deconflictedDefault = new Set();
11536 const deconflictedNamespace = new Set();
11537 for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
11538 if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
11539 const module = variable.module;
11540 if (module instanceof ExternalModule) {
11541 dependencies.add(module);
11542 if (addNonNamespacesAndInteropHelpers) {
11543 if (variable.name === 'default') {
11544 if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
11545 deconflictedDefault.add(module);
11546 }
11547 }
11548 else if (variable.name === '*') {
11549 if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
11550 deconflictedNamespace.add(module);
11551 }
11552 }
11553 }
11554 }
11555 else {
11556 const chunk = this.chunkByModule.get(module);
11557 if (chunk !== this) {
11558 dependencies.add(chunk);
11559 if (addNonNamespacesAndInteropHelpers &&
11560 chunk.exportMode === 'default' &&
11561 variable.isNamespace) {
11562 deconflictedNamespace.add(chunk);
11563 }
11564 }
11565 }
11566 }
11567 }
11568 if (addDependenciesWithoutBindings) {
11569 for (const dependency of this.dependencies) {
11570 dependencies.add(dependency);
11571 }
11572 }
11573 return { deconflictedDefault, deconflictedNamespace, dependencies };
11574 }
11575 getFallbackChunkName() {
11576 if (this.manualChunkAlias) {
11577 return this.manualChunkAlias;
11578 }
11579 if (this.fileName) {
11580 return getAliasName(this.fileName);
11581 }
11582 return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
11583 }
11584 getImportedBindingsPerDependency() {
11585 const importSpecifiers = {};
11586 for (const [dependency, declaration] of this.renderedDependencies) {
11587 const specifiers = new Set();
11588 if (declaration.imports) {
11589 for (const { imported } of declaration.imports) {
11590 specifiers.add(imported);
11591 }
11592 }
11593 if (declaration.reexports) {
11594 for (const { imported } of declaration.reexports) {
11595 specifiers.add(imported);
11596 }
11597 }
11598 importSpecifiers[dependency.id] = [...specifiers];
11599 }
11600 return importSpecifiers;
11601 }
11602 getImportSpecifiers() {
11603 const { interop } = this.outputOptions;
11604 const importsByDependency = new Map();
11605 for (const variable of this.imports) {
11606 const module = variable.module;
11607 let dependency;
11608 let imported;
11609 if (module instanceof ExternalModule) {
11610 dependency = module;
11611 imported = variable.name;
11612 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
11613 return error(errUnexpectedNamedImport(module.id, imported, false));
11614 }
11615 }
11616 else {
11617 dependency = this.chunkByModule.get(module);
11618 imported = dependency.getVariableExportName(variable);
11619 }
11620 getOrCreate(importsByDependency, dependency, () => []).push({
11621 imported,
11622 local: variable.getName()
11623 });
11624 }
11625 return importsByDependency;
11626 }
11627 getReexportSpecifiers() {
11628 const { externalLiveBindings, interop } = this.outputOptions;
11629 const reexportSpecifiers = new Map();
11630 for (let exportName of this.getExportNames()) {
11631 let dependency;
11632 let imported;
11633 let needsLiveBinding = false;
11634 if (exportName[0] === '*') {
11635 const id = exportName.substr(1);
11636 if (interop(id) === 'defaultOnly') {
11637 this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
11638 }
11639 needsLiveBinding = externalLiveBindings;
11640 dependency = this.modulesById.get(id);
11641 imported = exportName = '*';
11642 }
11643 else {
11644 const variable = this.exportsByName[exportName];
11645 if (variable instanceof SyntheticNamedExportVariable)
11646 continue;
11647 const module = variable.module;
11648 if (module instanceof Module) {
11649 dependency = this.chunkByModule.get(module);
11650 if (dependency === this)
11651 continue;
11652 imported = dependency.getVariableExportName(variable);
11653 needsLiveBinding = variable.isReassigned;
11654 }
11655 else {
11656 dependency = module;
11657 imported = variable.name;
11658 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
11659 return error(errUnexpectedNamedImport(module.id, imported, true));
11660 }
11661 needsLiveBinding =
11662 externalLiveBindings &&
11663 (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
11664 }
11665 }
11666 getOrCreate(reexportSpecifiers, dependency, () => []).push({
11667 imported,
11668 needsLiveBinding,
11669 reexported: exportName
11670 });
11671 }
11672 return reexportSpecifiers;
11673 }
11674 getReferencedFiles() {
11675 const referencedFiles = [];
11676 for (const module of this.orderedModules) {
11677 for (const meta of module.importMetas) {
11678 const fileName = meta.getReferencedFileName(this.pluginDriver);
11679 if (fileName) {
11680 referencedFiles.push(fileName);
11681 }
11682 }
11683 }
11684 return referencedFiles;
11685 }
11686 getRelativePath(targetPath, stripJsExtension) {
11687 let relativePath = normalize(relative(sysPath.dirname(this.id), targetPath));
11688 if (stripJsExtension && relativePath.endsWith('.js')) {
11689 relativePath = relativePath.slice(0, -3);
11690 }
11691 if (relativePath === '..')
11692 return '../../' + sysPath.basename(targetPath);
11693 if (relativePath === '')
11694 return '../' + sysPath.basename(targetPath);
11695 return relativePath.startsWith('../') ? relativePath : './' + relativePath;
11696 }
11697 inlineChunkDependencies(chunk) {
11698 for (const dep of chunk.dependencies) {
11699 if (this.dependencies.has(dep))
11700 continue;
11701 this.dependencies.add(dep);
11702 if (dep instanceof Chunk$1) {
11703 this.inlineChunkDependencies(dep);
11704 }
11705 }
11706 }
11707 prepareDynamicImportsAndImportMetas() {
11708 var _a;
11709 const accessedGlobalsByScope = this.accessedGlobalsByScope;
11710 for (const module of this.orderedModules) {
11711 for (const { node, resolution } of module.dynamicImports) {
11712 if (node.included) {
11713 if (resolution instanceof Module) {
11714 const chunk = this.chunkByModule.get(resolution);
11715 if (chunk === this) {
11716 node.setInternalResolution(resolution.namespace);
11717 }
11718 else {
11719 node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
11720 }
11721 }
11722 else {
11723 node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
11724 }
11725 }
11726 }
11727 for (const importMeta of module.importMetas) {
11728 importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
11729 }
11730 }
11731 }
11732 setExternalRenderPaths(options, inputBase) {
11733 for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
11734 if (dependency instanceof ExternalModule) {
11735 dependency.setRenderPath(options, inputBase);
11736 }
11737 }
11738 }
11739 setIdentifierRenderResolutions({ format, interop }) {
11740 const syntheticExports = new Set();
11741 for (const exportName of this.getExportNames()) {
11742 const exportVariable = this.exportsByName[exportName];
11743 if (exportVariable instanceof ExportShimVariable) {
11744 this.needsExportsShim = true;
11745 }
11746 if (format !== 'es' &&
11747 format !== 'system' &&
11748 exportVariable.isReassigned &&
11749 !exportVariable.isId) {
11750 exportVariable.setRenderNames('exports', exportName);
11751 }
11752 else if (exportVariable instanceof SyntheticNamedExportVariable) {
11753 syntheticExports.add(exportVariable);
11754 }
11755 else {
11756 exportVariable.setRenderNames(null, null);
11757 }
11758 }
11759 const usedNames = new Set();
11760 if (this.needsExportsShim) {
11761 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
11762 }
11763 switch (format) {
11764 case 'system':
11765 usedNames.add('module').add('exports');
11766 break;
11767 case 'es':
11768 break;
11769 case 'cjs':
11770 usedNames.add('module').add('require').add('__filename').add('__dirname');
11771 // fallthrough
11772 default:
11773 usedNames.add('exports');
11774 for (const helper of HELPER_NAMES) {
11775 usedNames.add(helper);
11776 }
11777 }
11778 deconflictChunk(this.orderedModules, this.getDependenciesToBeDeconflicted(format !== 'es' && format !== 'system', format === 'amd' || format === 'umd' || format === 'iife', interop), this.imports, usedNames, format, interop, this.outputOptions.preserveModules, this.outputOptions.externalLiveBindings, this.chunkByModule, syntheticExports, this.exportNamesByVariable, this.accessedGlobalsByScope, this.includedNamespaces);
11779 }
11780 setUpChunkImportsAndExportsForModule(module) {
11781 const moduleImports = new Set(module.imports);
11782 // when we are not preserving modules, we need to make all namespace variables available for
11783 // rendering the namespace object
11784 if (!this.outputOptions.preserveModules) {
11785 if (this.includedNamespaces.has(module)) {
11786 const memberVariables = module.namespace.getMemberVariables();
11787 for (const name of Object.keys(memberVariables)) {
11788 moduleImports.add(memberVariables[name]);
11789 }
11790 }
11791 }
11792 for (let variable of moduleImports) {
11793 if (variable instanceof ExportDefaultVariable) {
11794 variable = variable.getOriginalVariable();
11795 }
11796 if (variable instanceof SyntheticNamedExportVariable) {
11797 variable = variable.getBaseVariable();
11798 }
11799 const chunk = this.chunkByModule.get(variable.module);
11800 if (chunk !== this) {
11801 this.imports.add(variable);
11802 if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
11803 variable.module instanceof Module) {
11804 chunk.exports.add(variable);
11805 }
11806 }
11807 }
11808 if (this.includedNamespaces.has(module) ||
11809 (module.isEntryPoint && module.preserveSignature !== false) ||
11810 module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
11811 this.ensureReexportsAreAvailableForModule(module);
11812 }
11813 for (const { node, resolution } of module.dynamicImports) {
11814 if (node.included &&
11815 resolution instanceof Module &&
11816 this.chunkByModule.get(resolution) === this &&
11817 !this.includedNamespaces.has(resolution)) {
11818 this.includedNamespaces.add(resolution);
11819 this.ensureReexportsAreAvailableForModule(resolution);
11820 }
11821 }
11822 }
11823}
11824
11825const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
11826const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
11827async function createAddons(options, outputPluginDriver) {
11828 try {
11829 let [banner, footer, intro, outro] = await Promise.all([
11830 outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
11831 outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
11832 outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
11833 outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
11834 ]);
11835 if (intro)
11836 intro += '\n\n';
11837 if (outro)
11838 outro = `\n\n${outro}`;
11839 if (banner.length)
11840 banner += '\n';
11841 if (footer.length)
11842 footer = '\n' + footer;
11843 return { intro, outro, banner, footer };
11844 }
11845 catch (err) {
11846 return error({
11847 code: 'ADDON_ERROR',
11848 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
11849\tError Message: ${err.message}`
11850 });
11851 }
11852}
11853
11854function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
11855 const chunkDefinitions = [];
11856 const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
11857 const manualChunkModulesByAlias = Object.create(null);
11858 for (const [entry, alias] of manualChunkAliasByEntry) {
11859 const chunkModules = (manualChunkModulesByAlias[alias] =
11860 manualChunkModulesByAlias[alias] || []);
11861 addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
11862 }
11863 for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
11864 chunkDefinitions.push({ alias, modules });
11865 }
11866 const assignedEntryPointsByModule = new Map();
11867 const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
11868 const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
11869 const staticEntries = new Set(entryModules);
11870 function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
11871 const modulesToHandle = new Set([entry]);
11872 for (const module of modulesToHandle) {
11873 const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
11874 if (dynamicDependentEntryPoints &&
11875 areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
11876 continue;
11877 }
11878 else {
11879 assignedEntryPoints.add(entry);
11880 }
11881 for (const dependency of module.getDependenciesToBeIncluded()) {
11882 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
11883 modulesToHandle.add(dependency);
11884 }
11885 }
11886 }
11887 }
11888 function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
11889 const entriesToCheck = new Set(entryPoints);
11890 for (const entry of entriesToCheck) {
11891 if (!containedIn.has(entry)) {
11892 if (staticEntries.has(entry))
11893 return false;
11894 const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
11895 for (const dependentEntry of dynamicallyDependentEntryPoints) {
11896 entriesToCheck.add(dependentEntry);
11897 }
11898 }
11899 }
11900 return true;
11901 }
11902 for (const entry of entryModules) {
11903 if (!modulesInManualChunks.has(entry)) {
11904 assignEntryToStaticDependencies(entry, null);
11905 }
11906 }
11907 for (const entry of dynamicEntryModules) {
11908 if (!modulesInManualChunks.has(entry)) {
11909 assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
11910 }
11911 }
11912 chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
11913 return chunkDefinitions;
11914}
11915function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
11916 const modulesToHandle = new Set([entry]);
11917 for (const module of modulesToHandle) {
11918 modulesInManualChunks.add(module);
11919 manualChunkModules.push(module);
11920 for (const dependency of module.dependencies) {
11921 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
11922 modulesToHandle.add(dependency);
11923 }
11924 }
11925 }
11926}
11927function analyzeModuleGraph(entryModules) {
11928 const dynamicEntryModules = new Set();
11929 const dependentEntryPointsByModule = new Map();
11930 const entriesToHandle = new Set(entryModules);
11931 for (const currentEntry of entriesToHandle) {
11932 const modulesToHandle = new Set([currentEntry]);
11933 for (const module of modulesToHandle) {
11934 getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
11935 for (const dependency of module.getDependenciesToBeIncluded()) {
11936 if (!(dependency instanceof ExternalModule)) {
11937 modulesToHandle.add(dependency);
11938 }
11939 }
11940 for (const { resolution } of module.dynamicImports) {
11941 if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
11942 dynamicEntryModules.add(resolution);
11943 entriesToHandle.add(resolution);
11944 }
11945 }
11946 for (const dependency of module.implicitlyLoadedBefore) {
11947 dynamicEntryModules.add(dependency);
11948 entriesToHandle.add(dependency);
11949 }
11950 }
11951 }
11952 return { dependentEntryPointsByModule, dynamicEntryModules };
11953}
11954function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
11955 const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
11956 for (const dynamicEntry of dynamicEntryModules) {
11957 const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
11958 for (const importer of [
11959 ...dynamicEntry.includedDynamicImporters,
11960 ...dynamicEntry.implicitlyLoadedAfter
11961 ]) {
11962 for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
11963 dynamicDependentEntryPoints.add(entryPoint);
11964 }
11965 }
11966 }
11967 return dynamicallyDependentEntryPointsByDynamicEntry;
11968}
11969function createChunks(allEntryPoints, assignedEntryPointsByModule) {
11970 const chunkModules = Object.create(null);
11971 for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
11972 let chunkSignature = '';
11973 for (const entry of allEntryPoints) {
11974 chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
11975 }
11976 const chunk = chunkModules[chunkSignature];
11977 if (chunk) {
11978 chunk.push(module);
11979 }
11980 else {
11981 chunkModules[chunkSignature] = [module];
11982 }
11983 }
11984 return Object.keys(chunkModules).map(chunkSignature => ({
11985 alias: null,
11986 modules: chunkModules[chunkSignature]
11987 }));
11988}
11989
11990// ported from https://github.com/substack/node-commondir
11991function commondir(files) {
11992 if (files.length === 0)
11993 return '/';
11994 if (files.length === 1)
11995 return sysPath.dirname(files[0]);
11996 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
11997 const pathSegements = file.split(/\/+|\\+/);
11998 let i;
11999 for (i = 0; commonSegments[i] === pathSegements[i] &&
12000 i < Math.min(commonSegments.length, pathSegements.length); i++)
12001 ;
12002 return commonSegments.slice(0, i);
12003 }, files[0].split(/\/+|\\+/));
12004 // Windows correctly handles paths with forward-slashes
12005 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
12006}
12007
12008var BuildPhase;
12009(function (BuildPhase) {
12010 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
12011 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
12012 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
12013})(BuildPhase || (BuildPhase = {}));
12014
12015function generateAssetFileName(name, source, output) {
12016 const emittedName = name || 'asset';
12017 return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
12018 hash() {
12019 const hash = createHash();
12020 hash.update(emittedName);
12021 hash.update(':');
12022 hash.update(source);
12023 return hash.digest('hex').substr(0, 8);
12024 },
12025 ext: () => sysPath.extname(emittedName).substr(1),
12026 extname: () => sysPath.extname(emittedName),
12027 name: () => emittedName.substr(0, emittedName.length - sysPath.extname(emittedName).length)
12028 }, () => ({ name, source, type: 'asset' })), output.bundle);
12029}
12030function reserveFileNameInBundle(fileName, bundle, warn) {
12031 if (fileName in bundle) {
12032 warn(errFileNameConflict(fileName));
12033 }
12034 bundle[fileName] = FILE_PLACEHOLDER;
12035}
12036const FILE_PLACEHOLDER = {
12037 type: 'placeholder'
12038};
12039function hasValidType(emittedFile) {
12040 return (emittedFile &&
12041 (emittedFile.type === 'asset' ||
12042 emittedFile.type === 'chunk'));
12043}
12044function hasValidName(emittedFile) {
12045 const validatedName = emittedFile.fileName || emittedFile.name;
12046 return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName)));
12047}
12048function getValidSource(source, emittedFile, fileReferenceId) {
12049 if (!(typeof source === 'string' || source instanceof Uint8Array)) {
12050 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
12051 return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string, Uint8Array or Buffer.`));
12052 }
12053 return source;
12054}
12055function getAssetFileName(file, referenceId) {
12056 if (typeof file.fileName !== 'string') {
12057 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
12058 }
12059 return file.fileName;
12060}
12061function getChunkFileName(file, facadeChunkByModule) {
12062 var _a;
12063 const fileName = file.fileName || (file.module && ((_a = facadeChunkByModule === null || facadeChunkByModule === void 0 ? void 0 : facadeChunkByModule.get(file.module)) === null || _a === void 0 ? void 0 : _a.id));
12064 if (!fileName)
12065 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
12066 return fileName;
12067}
12068class FileEmitter {
12069 constructor(graph, options, baseFileEmitter) {
12070 this.graph = graph;
12071 this.options = options;
12072 this.facadeChunkByModule = null;
12073 this.output = null;
12074 this.assertAssetsFinalized = () => {
12075 for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
12076 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
12077 return error(errNoAssetSourceSet(emittedFile.name || referenceId));
12078 }
12079 };
12080 this.emitFile = (emittedFile) => {
12081 if (!hasValidType(emittedFile)) {
12082 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
12083 }
12084 if (!hasValidName(emittedFile)) {
12085 return error(errFailedValidation(`The "fileName" or "name" properties of emitted files must be strings that are neither absolute nor relative paths and do not contain invalid characters, received "${emittedFile.fileName || emittedFile.name}".`));
12086 }
12087 if (emittedFile.type === 'chunk') {
12088 return this.emitChunk(emittedFile);
12089 }
12090 else {
12091 return this.emitAsset(emittedFile);
12092 }
12093 };
12094 this.getFileName = (fileReferenceId) => {
12095 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
12096 if (!emittedFile)
12097 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
12098 if (emittedFile.type === 'chunk') {
12099 return getChunkFileName(emittedFile, this.facadeChunkByModule);
12100 }
12101 else {
12102 return getAssetFileName(emittedFile, fileReferenceId);
12103 }
12104 };
12105 this.setAssetSource = (referenceId, requestedSource) => {
12106 const consumedFile = this.filesByReferenceId.get(referenceId);
12107 if (!consumedFile)
12108 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
12109 if (consumedFile.type !== 'asset') {
12110 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
12111 }
12112 if (consumedFile.source !== undefined) {
12113 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
12114 }
12115 const source = getValidSource(requestedSource, consumedFile, referenceId);
12116 if (this.output) {
12117 this.finalizeAsset(consumedFile, source, referenceId, this.output);
12118 }
12119 else {
12120 consumedFile.source = source;
12121 }
12122 };
12123 this.setOutputBundle = (outputBundle, assetFileNames, facadeChunkByModule) => {
12124 this.output = {
12125 assetFileNames,
12126 bundle: outputBundle
12127 };
12128 this.facadeChunkByModule = facadeChunkByModule;
12129 for (const emittedFile of this.filesByReferenceId.values()) {
12130 if (emittedFile.fileName) {
12131 reserveFileNameInBundle(emittedFile.fileName, this.output.bundle, this.options.onwarn);
12132 }
12133 }
12134 for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
12135 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
12136 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
12137 }
12138 }
12139 };
12140 this.filesByReferenceId = baseFileEmitter
12141 ? new Map(baseFileEmitter.filesByReferenceId)
12142 : new Map();
12143 }
12144 assignReferenceId(file, idBase) {
12145 let referenceId;
12146 do {
12147 const hash = createHash();
12148 if (referenceId) {
12149 hash.update(referenceId);
12150 }
12151 else {
12152 hash.update(idBase);
12153 }
12154 referenceId = hash.digest('hex').substr(0, 8);
12155 } while (this.filesByReferenceId.has(referenceId));
12156 this.filesByReferenceId.set(referenceId, file);
12157 return referenceId;
12158 }
12159 emitAsset(emittedAsset) {
12160 const source = typeof emittedAsset.source !== 'undefined'
12161 ? getValidSource(emittedAsset.source, emittedAsset, null)
12162 : undefined;
12163 const consumedAsset = {
12164 fileName: emittedAsset.fileName,
12165 name: emittedAsset.name,
12166 source,
12167 type: 'asset'
12168 };
12169 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
12170 if (this.output) {
12171 if (emittedAsset.fileName) {
12172 reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle, this.options.onwarn);
12173 }
12174 if (source !== undefined) {
12175 this.finalizeAsset(consumedAsset, source, referenceId, this.output);
12176 }
12177 }
12178 return referenceId;
12179 }
12180 emitChunk(emittedChunk) {
12181 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
12182 return error(errInvalidRollupPhaseForChunkEmission());
12183 }
12184 if (typeof emittedChunk.id !== 'string') {
12185 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
12186 }
12187 const consumedChunk = {
12188 fileName: emittedChunk.fileName,
12189 module: null,
12190 name: emittedChunk.name || emittedChunk.id,
12191 type: 'chunk'
12192 };
12193 this.graph.moduleLoader
12194 .emitChunk(emittedChunk)
12195 .then(module => (consumedChunk.module = module))
12196 .catch(() => {
12197 // Avoid unhandled Promise rejection as the error will be thrown later
12198 // once module loading has finished
12199 });
12200 return this.assignReferenceId(consumedChunk, emittedChunk.id);
12201 }
12202 finalizeAsset(consumedFile, source, referenceId, output) {
12203 const fileName = consumedFile.fileName ||
12204 findExistingAssetFileNameWithSource(output.bundle, source) ||
12205 generateAssetFileName(consumedFile.name, source, output);
12206 // We must not modify the original assets to avoid interaction between outputs
12207 const assetWithFileName = { ...consumedFile, source, fileName };
12208 this.filesByReferenceId.set(referenceId, assetWithFileName);
12209 const options = this.options;
12210 output.bundle[fileName] = {
12211 fileName,
12212 name: consumedFile.name,
12213 get isAsset() {
12214 warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
12215 return true;
12216 },
12217 source,
12218 type: 'asset'
12219 };
12220 }
12221}
12222function findExistingAssetFileNameWithSource(bundle, source) {
12223 for (const fileName of Object.keys(bundle)) {
12224 const outputFile = bundle[fileName];
12225 if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
12226 return fileName;
12227 }
12228 return null;
12229}
12230function areSourcesEqual(sourceA, sourceB) {
12231 if (typeof sourceA === 'string') {
12232 return sourceA === sourceB;
12233 }
12234 if (typeof sourceB === 'string') {
12235 return false;
12236 }
12237 if ('equals' in sourceA) {
12238 return sourceA.equals(sourceB);
12239 }
12240 if (sourceA.length !== sourceB.length) {
12241 return false;
12242 }
12243 for (let index = 0; index < sourceA.length; index++) {
12244 if (sourceA[index] !== sourceB[index]) {
12245 return false;
12246 }
12247 }
12248 return true;
12249}
12250
12251class Bundle$1 {
12252 constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
12253 this.outputOptions = outputOptions;
12254 this.unsetOptions = unsetOptions;
12255 this.inputOptions = inputOptions;
12256 this.pluginDriver = pluginDriver;
12257 this.graph = graph;
12258 this.facadeChunkByModule = new Map();
12259 this.includedNamespaces = new Set();
12260 }
12261 async generate(isWrite) {
12262 timeStart('GENERATE', 1);
12263 const outputBundle = Object.create(null);
12264 this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions.assetFileNames, this.facadeChunkByModule);
12265 try {
12266 await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
12267 timeStart('generate chunks', 2);
12268 const chunks = await this.generateChunks();
12269 if (chunks.length > 1) {
12270 validateOptionsForMultiChunkOutput(this.outputOptions);
12271 }
12272 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
12273 timeEnd('generate chunks', 2);
12274 timeStart('render modules', 2);
12275 // We need to create addons before prerender because at the moment, there
12276 // can be no async code between prerender and render due to internal state
12277 const addons = await createAddons(this.outputOptions, this.pluginDriver);
12278 this.prerenderChunks(chunks, inputBase);
12279 timeEnd('render modules', 2);
12280 await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
12281 }
12282 catch (error) {
12283 await this.pluginDriver.hookParallel('renderError', [error]);
12284 throw error;
12285 }
12286 await this.pluginDriver.hookSeq('generateBundle', [
12287 this.outputOptions,
12288 outputBundle,
12289 isWrite
12290 ]);
12291 this.finaliseAssets(outputBundle);
12292 timeEnd('GENERATE', 1);
12293 return outputBundle;
12294 }
12295 async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
12296 this.assignChunkIds(chunks, inputBase, addons, outputBundle);
12297 for (const chunk of chunks) {
12298 outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
12299 }
12300 await Promise.all(chunks.map(async (chunk) => {
12301 const outputChunk = outputBundle[chunk.id];
12302 Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
12303 }));
12304 }
12305 async addManualChunks(manualChunks) {
12306 const manualChunkAliasByEntry = new Map();
12307 const chunkEntries = await Promise.all(Object.keys(manualChunks).map(async (alias) => ({
12308 alias,
12309 entries: await this.graph.moduleLoader.addAdditionalModules(manualChunks[alias])
12310 })));
12311 for (const { alias, entries } of chunkEntries) {
12312 for (const entry of entries) {
12313 addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
12314 }
12315 }
12316 return manualChunkAliasByEntry;
12317 }
12318 assignChunkIds(chunks, inputBase, addons, bundle) {
12319 const entryChunks = [];
12320 const otherChunks = [];
12321 for (const chunk of chunks) {
12322 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
12323 ? entryChunks
12324 : otherChunks).push(chunk);
12325 }
12326 // make sure entry chunk names take precedence with regard to deconflicting
12327 const chunksForNaming = entryChunks.concat(otherChunks);
12328 for (const chunk of chunksForNaming) {
12329 if (this.outputOptions.file) {
12330 chunk.id = sysPath.basename(this.outputOptions.file);
12331 }
12332 else if (this.outputOptions.preserveModules) {
12333 chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
12334 }
12335 else {
12336 chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
12337 }
12338 bundle[chunk.id] = FILE_PLACEHOLDER;
12339 }
12340 }
12341 assignManualChunks(getManualChunk) {
12342 const manualChunkAliasByEntry = new Map();
12343 const manualChunksApi = {
12344 getModuleIds: () => this.graph.modulesById.keys(),
12345 getModuleInfo: this.graph.getModuleInfo
12346 };
12347 for (const module of this.graph.modulesById.values()) {
12348 if (module instanceof Module) {
12349 const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
12350 if (typeof manualChunkAlias === 'string') {
12351 addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
12352 }
12353 }
12354 }
12355 return manualChunkAliasByEntry;
12356 }
12357 finaliseAssets(outputBundle) {
12358 for (const key of Object.keys(outputBundle)) {
12359 const file = outputBundle[key];
12360 if (!file.type) {
12361 warnDeprecation('A plugin is directly adding properties to the bundle object in the "generateBundle" hook. This is deprecated and will be removed in a future Rollup version, please use "this.emitFile" instead.', true, this.inputOptions);
12362 file.type = 'asset';
12363 }
12364 }
12365 this.pluginDriver.finaliseAssets();
12366 }
12367 async generateChunks() {
12368 const { manualChunks } = this.outputOptions;
12369 const manualChunkAliasByEntry = typeof manualChunks === 'object'
12370 ? await this.addManualChunks(manualChunks)
12371 : this.assignManualChunks(manualChunks);
12372 const chunks = [];
12373 const chunkByModule = new Map();
12374 for (const { alias, modules } of this.outputOptions.inlineDynamicImports
12375 ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
12376 : this.outputOptions.preserveModules
12377 ? getIncludedModules(this.graph.modulesById).map(module => ({
12378 alias: null,
12379 modules: [module]
12380 }))
12381 : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
12382 sortByExecutionOrder(modules);
12383 const chunk = new Chunk$1(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
12384 chunks.push(chunk);
12385 for (const module of modules) {
12386 chunkByModule.set(module, chunk);
12387 }
12388 }
12389 for (const chunk of chunks) {
12390 chunk.link();
12391 }
12392 const facades = [];
12393 for (const chunk of chunks) {
12394 facades.push(...chunk.generateFacades());
12395 }
12396 return [...chunks, ...facades];
12397 }
12398 prerenderChunks(chunks, inputBase) {
12399 for (const chunk of chunks) {
12400 chunk.generateExports();
12401 }
12402 for (const chunk of chunks) {
12403 chunk.preRender(this.outputOptions, inputBase);
12404 }
12405 }
12406}
12407function getAbsoluteEntryModulePaths(chunks) {
12408 const absoluteEntryModulePaths = [];
12409 for (const chunk of chunks) {
12410 for (const entryModule of chunk.entryModules) {
12411 if (isAbsolute(entryModule.id)) {
12412 absoluteEntryModulePaths.push(entryModule.id);
12413 }
12414 }
12415 }
12416 return absoluteEntryModulePaths;
12417}
12418function validateOptionsForMultiChunkOutput(outputOptions) {
12419 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
12420 return error({
12421 code: 'INVALID_OPTION',
12422 message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
12423 });
12424 if (typeof outputOptions.file === 'string')
12425 return error({
12426 code: 'INVALID_OPTION',
12427 message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
12428 'To inline dynamic imports, set the "inlineDynamicImports" option.'
12429 });
12430 if (outputOptions.sourcemapFile)
12431 return error({
12432 code: 'INVALID_OPTION',
12433 message: '"output.sourcemapFile" is only supported for single-file builds.'
12434 });
12435}
12436function getIncludedModules(modulesById) {
12437 return [...modulesById.values()].filter(module => module instanceof Module &&
12438 (module.isIncluded() || module.isEntryPoint || module.includedDynamicImporters.length > 0));
12439}
12440function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
12441 const existingAlias = manualChunkAliasByEntry.get(module);
12442 if (typeof existingAlias === 'string' && existingAlias !== alias) {
12443 return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
12444 }
12445 manualChunkAliasByEntry.set(module, alias);
12446}
12447
12448// Reserved word lists for various dialects of the language
12449
12450var reservedWords$1 = {
12451 3: "abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile",
12452 5: "class enum extends super const export import",
12453 6: "enum",
12454 strict: "implements interface let package private protected public static yield",
12455 strictBind: "eval arguments"
12456};
12457
12458// And the keywords
12459
12460var 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";
12461
12462var keywords = {
12463 5: ecma5AndLessKeywords,
12464 "5module": ecma5AndLessKeywords + " export import",
12465 6: ecma5AndLessKeywords + " const class extends export import super"
12466};
12467
12468var keywordRelationalOperator = /^in(stanceof)?$/;
12469
12470// ## Character categories
12471
12472// Big ugly regular expressions that match characters in the
12473// whitespace, identifier, and identifier-start categories. These
12474// are only applied when a character is found to actually have a
12475// code point above 128.
12476// Generated by `bin/generate-identifier-regex.js`.
12477var 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\u0560-\u0588\u05d0-\u05ea\u05ef-\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\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\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\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\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-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\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-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
12478var 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\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\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\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\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\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\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\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
12479
12480var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
12481var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
12482
12483nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
12484
12485// These are a run-length and offset encoded representation of the
12486// >0xffff code points that are a valid part of identifiers. The
12487// offset starts at 0x10000, and each pair of numbers represents an
12488// offset to the next range, and then a size of the range. They were
12489// generated by bin/generate-identifier-regex.js
12490
12491// eslint-disable-next-line comma-spacing
12492var astralIdentifierStartCodes = [0,11,2,25,2,18,2,1,2,14,3,13,35,122,70,52,268,28,4,48,48,31,14,29,6,37,11,29,3,35,5,7,2,4,43,157,19,35,5,35,5,39,9,51,157,310,10,21,11,7,153,5,3,0,2,43,2,1,4,0,3,22,11,22,10,30,66,18,2,1,11,21,11,25,71,55,7,1,65,0,16,3,2,2,2,28,43,28,4,28,36,7,2,27,28,53,11,21,11,18,14,17,111,72,56,50,14,50,14,35,349,41,7,1,79,28,11,0,9,21,107,20,28,22,13,52,76,44,33,24,27,35,30,0,3,0,9,34,4,0,13,47,15,3,22,0,2,0,36,17,2,24,85,6,2,0,2,3,2,14,2,9,8,46,39,7,3,1,3,21,2,6,2,1,2,4,4,0,19,0,13,4,159,52,19,3,21,2,31,47,21,1,2,0,185,46,42,3,37,47,21,0,60,42,14,0,72,26,230,43,117,63,32,7,3,0,3,7,2,1,2,23,16,0,2,0,95,7,3,38,17,0,2,0,29,0,11,39,8,0,22,0,12,45,20,0,35,56,264,8,2,36,18,0,50,29,113,6,2,1,2,37,22,0,26,5,2,1,2,31,15,0,328,18,190,0,80,921,103,110,18,195,2749,1070,4050,582,8634,568,8,30,114,29,19,47,17,3,32,20,6,18,689,63,129,74,6,0,67,12,65,1,2,0,29,6135,9,1237,43,8,8952,286,50,2,18,3,9,395,2309,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,2357,44,11,6,17,0,370,43,1301,196,60,67,8,0,1205,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,42717,35,4148,12,221,3,5761,15,7472,3104,541,1507,4938];
12493
12494// eslint-disable-next-line comma-spacing
12495var astralIdentifierCodes = [509,0,227,0,150,4,294,9,1368,2,2,1,6,3,41,2,5,0,166,1,574,3,9,9,370,1,154,10,176,2,54,14,32,9,16,3,46,10,54,9,7,2,37,13,2,9,6,1,45,0,13,2,49,13,9,3,2,11,83,11,7,0,161,11,6,9,7,3,56,1,2,6,3,1,3,2,10,0,11,1,3,6,4,4,193,17,10,9,5,0,82,19,13,9,214,6,3,8,28,1,83,16,16,9,82,12,9,9,84,14,5,9,243,14,166,9,71,5,2,1,3,3,2,0,2,1,13,9,120,6,3,6,4,0,29,9,41,6,2,3,9,0,10,10,47,15,406,7,2,7,17,9,57,21,2,13,123,5,4,0,2,1,2,6,2,0,9,9,49,4,2,1,2,4,9,9,330,3,19306,9,135,4,60,6,26,9,1014,0,2,54,8,3,82,0,12,1,19628,1,5319,4,4,5,9,7,3,6,31,3,149,2,1418,49,513,54,5,49,9,0,15,0,23,4,2,14,1361,6,2,16,3,6,2,1,2,4,262,6,10,9,419,13,1495,6,110,6,6,9,4759,9,787719,239];
12496
12497// This has a complexity linear to the value of the code. The
12498// assumption is that looking up astral identifier characters is
12499// rare.
12500function isInAstralSet(code, set) {
12501 var pos = 0x10000;
12502 for (var i = 0; i < set.length; i += 2) {
12503 pos += set[i];
12504 if (pos > code) { return false }
12505 pos += set[i + 1];
12506 if (pos >= code) { return true }
12507 }
12508}
12509
12510// Test whether a given character code starts an identifier.
12511
12512function isIdentifierStart(code, astral) {
12513 if (code < 65) { return code === 36 }
12514 if (code < 91) { return true }
12515 if (code < 97) { return code === 95 }
12516 if (code < 123) { return true }
12517 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
12518 if (astral === false) { return false }
12519 return isInAstralSet(code, astralIdentifierStartCodes)
12520}
12521
12522// Test whether a given character is part of an identifier.
12523
12524function isIdentifierChar(code, astral) {
12525 if (code < 48) { return code === 36 }
12526 if (code < 58) { return true }
12527 if (code < 65) { return false }
12528 if (code < 91) { return true }
12529 if (code < 97) { return code === 95 }
12530 if (code < 123) { return true }
12531 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
12532 if (astral === false) { return false }
12533 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
12534}
12535
12536// ## Token types
12537
12538// The assignment of fine-grained, information-carrying type objects
12539// allows the tokenizer to store the information it has about a
12540// token in a way that is very cheap for the parser to look up.
12541
12542// All token type variables start with an underscore, to make them
12543// easy to recognize.
12544
12545// The `beforeExpr` property is used to disambiguate between regular
12546// expressions and divisions. It is set on all token types that can
12547// be followed by an expression (thus, a slash after them would be a
12548// regular expression).
12549//
12550// The `startsExpr` property is used to check if the token ends a
12551// `yield` expression. It is set on all token types that either can
12552// directly start an expression (like a quotation mark) or can
12553// continue an expression (like the body of a string).
12554//
12555// `isLoop` marks a keyword as starting a loop, which is important
12556// to know when parsing a label, in order to allow or disallow
12557// continue jumps to that label.
12558
12559var TokenType = function TokenType(label, conf) {
12560 if ( conf === void 0 ) conf = {};
12561
12562 this.label = label;
12563 this.keyword = conf.keyword;
12564 this.beforeExpr = !!conf.beforeExpr;
12565 this.startsExpr = !!conf.startsExpr;
12566 this.isLoop = !!conf.isLoop;
12567 this.isAssign = !!conf.isAssign;
12568 this.prefix = !!conf.prefix;
12569 this.postfix = !!conf.postfix;
12570 this.binop = conf.binop || null;
12571 this.updateContext = null;
12572};
12573
12574function binop(name, prec) {
12575 return new TokenType(name, {beforeExpr: true, binop: prec})
12576}
12577var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
12578
12579// Map keyword names to token types.
12580
12581var keywords$1 = {};
12582
12583// Succinct definitions of keyword token types
12584function kw(name, options) {
12585 if ( options === void 0 ) options = {};
12586
12587 options.keyword = name;
12588 return keywords$1[name] = new TokenType(name, options)
12589}
12590
12591var types = {
12592 num: new TokenType("num", startsExpr),
12593 regexp: new TokenType("regexp", startsExpr),
12594 string: new TokenType("string", startsExpr),
12595 name: new TokenType("name", startsExpr),
12596 eof: new TokenType("eof"),
12597
12598 // Punctuation token types.
12599 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
12600 bracketR: new TokenType("]"),
12601 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
12602 braceR: new TokenType("}"),
12603 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
12604 parenR: new TokenType(")"),
12605 comma: new TokenType(",", beforeExpr),
12606 semi: new TokenType(";", beforeExpr),
12607 colon: new TokenType(":", beforeExpr),
12608 dot: new TokenType("."),
12609 question: new TokenType("?", beforeExpr),
12610 questionDot: new TokenType("?."),
12611 arrow: new TokenType("=>", beforeExpr),
12612 template: new TokenType("template"),
12613 invalidTemplate: new TokenType("invalidTemplate"),
12614 ellipsis: new TokenType("...", beforeExpr),
12615 backQuote: new TokenType("`", startsExpr),
12616 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
12617
12618 // Operators. These carry several kinds of properties to help the
12619 // parser use them properly (the presence of these properties is
12620 // what categorizes them as operators).
12621 //
12622 // `binop`, when present, specifies that this operator is a binary
12623 // operator, and will refer to its precedence.
12624 //
12625 // `prefix` and `postfix` mark the operator as a prefix or postfix
12626 // unary operator.
12627 //
12628 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
12629 // binary operators with a very low precedence, that should result
12630 // in AssignmentExpression nodes.
12631
12632 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
12633 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
12634 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
12635 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
12636 logicalOR: binop("||", 1),
12637 logicalAND: binop("&&", 2),
12638 bitwiseOR: binop("|", 3),
12639 bitwiseXOR: binop("^", 4),
12640 bitwiseAND: binop("&", 5),
12641 equality: binop("==/!=/===/!==", 6),
12642 relational: binop("</>/<=/>=", 7),
12643 bitShift: binop("<</>>/>>>", 8),
12644 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
12645 modulo: binop("%", 10),
12646 star: binop("*", 10),
12647 slash: binop("/", 10),
12648 starstar: new TokenType("**", {beforeExpr: true}),
12649 coalesce: binop("??", 1),
12650
12651 // Keyword token types.
12652 _break: kw("break"),
12653 _case: kw("case", beforeExpr),
12654 _catch: kw("catch"),
12655 _continue: kw("continue"),
12656 _debugger: kw("debugger"),
12657 _default: kw("default", beforeExpr),
12658 _do: kw("do", {isLoop: true, beforeExpr: true}),
12659 _else: kw("else", beforeExpr),
12660 _finally: kw("finally"),
12661 _for: kw("for", {isLoop: true}),
12662 _function: kw("function", startsExpr),
12663 _if: kw("if"),
12664 _return: kw("return", beforeExpr),
12665 _switch: kw("switch"),
12666 _throw: kw("throw", beforeExpr),
12667 _try: kw("try"),
12668 _var: kw("var"),
12669 _const: kw("const"),
12670 _while: kw("while", {isLoop: true}),
12671 _with: kw("with"),
12672 _new: kw("new", {beforeExpr: true, startsExpr: true}),
12673 _this: kw("this", startsExpr),
12674 _super: kw("super", startsExpr),
12675 _class: kw("class", startsExpr),
12676 _extends: kw("extends", beforeExpr),
12677 _export: kw("export"),
12678 _import: kw("import", startsExpr),
12679 _null: kw("null", startsExpr),
12680 _true: kw("true", startsExpr),
12681 _false: kw("false", startsExpr),
12682 _in: kw("in", {beforeExpr: true, binop: 7}),
12683 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
12684 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
12685 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
12686 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
12687};
12688
12689// Matches a whole line break (where CRLF is considered a single
12690// line break). Used to count lines.
12691
12692var lineBreak = /\r\n?|\n|\u2028|\u2029/;
12693var lineBreakG = new RegExp(lineBreak.source, "g");
12694
12695function isNewLine(code, ecma2019String) {
12696 return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
12697}
12698
12699var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
12700
12701var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
12702
12703var ref = Object.prototype;
12704var hasOwnProperty = ref.hasOwnProperty;
12705var toString$1 = ref.toString;
12706
12707// Checks if an object has a property.
12708
12709function has(obj, propName) {
12710 return hasOwnProperty.call(obj, propName)
12711}
12712
12713var isArray = Array.isArray || (function (obj) { return (
12714 toString$1.call(obj) === "[object Array]"
12715); });
12716
12717function wordsRegexp(words) {
12718 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
12719}
12720
12721// These are used when `options.locations` is on, for the
12722// `startLoc` and `endLoc` properties.
12723
12724var Position = function Position(line, col) {
12725 this.line = line;
12726 this.column = col;
12727};
12728
12729Position.prototype.offset = function offset (n) {
12730 return new Position(this.line, this.column + n)
12731};
12732
12733var SourceLocation = function SourceLocation(p, start, end) {
12734 this.start = start;
12735 this.end = end;
12736 if (p.sourceFile !== null) { this.source = p.sourceFile; }
12737};
12738
12739// The `getLineInfo` function is mostly useful when the
12740// `locations` option is off (for performance reasons) and you
12741// want to find the line/column position for a given character
12742// offset. `input` should be the code string that the offset refers
12743// into.
12744
12745function getLineInfo(input, offset) {
12746 for (var line = 1, cur = 0;;) {
12747 lineBreakG.lastIndex = cur;
12748 var match = lineBreakG.exec(input);
12749 if (match && match.index < offset) {
12750 ++line;
12751 cur = match.index + match[0].length;
12752 } else {
12753 return new Position(line, offset - cur)
12754 }
12755 }
12756}
12757
12758// A second argument must be given to configure the parser process.
12759// These options are recognized (only `ecmaVersion` is required):
12760
12761var defaultOptions = {
12762 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
12763 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
12764 // (2019), 11 (2020), 12 (2021), or `"latest"` (the latest version
12765 // the library supports). This influences support for strict mode,
12766 // the set of reserved words, and support for new syntax features.
12767 ecmaVersion: null,
12768 // `sourceType` indicates the mode the code should be parsed in.
12769 // Can be either `"script"` or `"module"`. This influences global
12770 // strict mode and parsing of `import` and `export` declarations.
12771 sourceType: "script",
12772 // `onInsertedSemicolon` can be a callback that will be called
12773 // when a semicolon is automatically inserted. It will be passed
12774 // the position of the comma as an offset, and if `locations` is
12775 // enabled, it is given the location as a `{line, column}` object
12776 // as second argument.
12777 onInsertedSemicolon: null,
12778 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
12779 // trailing commas.
12780 onTrailingComma: null,
12781 // By default, reserved words are only enforced if ecmaVersion >= 5.
12782 // Set `allowReserved` to a boolean value to explicitly turn this on
12783 // an off. When this option has the value "never", reserved words
12784 // and keywords can also not be used as property names.
12785 allowReserved: null,
12786 // When enabled, a return at the top level is not considered an
12787 // error.
12788 allowReturnOutsideFunction: false,
12789 // When enabled, import/export statements are not constrained to
12790 // appearing at the top of the program.
12791 allowImportExportEverywhere: false,
12792 // When enabled, await identifiers are allowed to appear at the top-level scope,
12793 // but they are still not allowed in non-async functions.
12794 allowAwaitOutsideFunction: false,
12795 // When enabled, hashbang directive in the beginning of file
12796 // is allowed and treated as a line comment.
12797 allowHashBang: false,
12798 // When `locations` is on, `loc` properties holding objects with
12799 // `start` and `end` properties in `{line, column}` form (with
12800 // line being 1-based and column 0-based) will be attached to the
12801 // nodes.
12802 locations: false,
12803 // A function can be passed as `onToken` option, which will
12804 // cause Acorn to call that function with object in the same
12805 // format as tokens returned from `tokenizer().getToken()`. Note
12806 // that you are not allowed to call the parser from the
12807 // callback—that will corrupt its internal state.
12808 onToken: null,
12809 // A function can be passed as `onComment` option, which will
12810 // cause Acorn to call that function with `(block, text, start,
12811 // end)` parameters whenever a comment is skipped. `block` is a
12812 // boolean indicating whether this is a block (`/* */`) comment,
12813 // `text` is the content of the comment, and `start` and `end` are
12814 // character offsets that denote the start and end of the comment.
12815 // When the `locations` option is on, two more parameters are
12816 // passed, the full `{line, column}` locations of the start and
12817 // end of the comments. Note that you are not allowed to call the
12818 // parser from the callback—that will corrupt its internal state.
12819 onComment: null,
12820 // Nodes have their start and end characters offsets recorded in
12821 // `start` and `end` properties (directly on the node, rather than
12822 // the `loc` object, which holds line/column data. To also add a
12823 // [semi-standardized][range] `range` property holding a `[start,
12824 // end]` array with the same numbers, set the `ranges` option to
12825 // `true`.
12826 //
12827 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
12828 ranges: false,
12829 // It is possible to parse multiple files into a single AST by
12830 // passing the tree produced by parsing the first file as
12831 // `program` option in subsequent parses. This will add the
12832 // toplevel forms of the parsed file to the `Program` (top) node
12833 // of an existing parse tree.
12834 program: null,
12835 // When `locations` is on, you can pass this to record the source
12836 // file in every node's `loc` object.
12837 sourceFile: null,
12838 // This value, if given, is stored in every node, whether
12839 // `locations` is on or off.
12840 directSourceFile: null,
12841 // When enabled, parenthesized expressions are represented by
12842 // (non-standard) ParenthesizedExpression nodes
12843 preserveParens: false
12844};
12845
12846// Interpret and default an options object
12847
12848var warnedAboutEcmaVersion = false;
12849
12850function getOptions(opts) {
12851 var options = {};
12852
12853 for (var opt in defaultOptions)
12854 { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
12855
12856 if (options.ecmaVersion === "latest") {
12857 options.ecmaVersion = 1e8;
12858 } else if (options.ecmaVersion == null) {
12859 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
12860 warnedAboutEcmaVersion = true;
12861 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
12862 }
12863 options.ecmaVersion = 11;
12864 } else if (options.ecmaVersion >= 2015) {
12865 options.ecmaVersion -= 2009;
12866 }
12867
12868 if (options.allowReserved == null)
12869 { options.allowReserved = options.ecmaVersion < 5; }
12870
12871 if (isArray(options.onToken)) {
12872 var tokens = options.onToken;
12873 options.onToken = function (token) { return tokens.push(token); };
12874 }
12875 if (isArray(options.onComment))
12876 { options.onComment = pushComment(options, options.onComment); }
12877
12878 return options
12879}
12880
12881function pushComment(options, array) {
12882 return function(block, text, start, end, startLoc, endLoc) {
12883 var comment = {
12884 type: block ? "Block" : "Line",
12885 value: text,
12886 start: start,
12887 end: end
12888 };
12889 if (options.locations)
12890 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
12891 if (options.ranges)
12892 { comment.range = [start, end]; }
12893 array.push(comment);
12894 }
12895}
12896
12897// Each scope gets a bitset that may contain these flags
12898var
12899 SCOPE_TOP = 1,
12900 SCOPE_FUNCTION = 2,
12901 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
12902 SCOPE_ASYNC = 4,
12903 SCOPE_GENERATOR = 8,
12904 SCOPE_ARROW = 16,
12905 SCOPE_SIMPLE_CATCH = 32,
12906 SCOPE_SUPER = 64,
12907 SCOPE_DIRECT_SUPER = 128;
12908
12909function functionFlags(async, generator) {
12910 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
12911}
12912
12913// Used in checkLVal* and declareName to determine the type of a binding
12914var
12915 BIND_NONE = 0, // Not a binding
12916 BIND_VAR = 1, // Var-style binding
12917 BIND_LEXICAL = 2, // Let- or const-style binding
12918 BIND_FUNCTION = 3, // Function declaration
12919 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
12920 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
12921
12922var Parser = function Parser(options, input, startPos) {
12923 this.options = options = getOptions(options);
12924 this.sourceFile = options.sourceFile;
12925 this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
12926 var reserved = "";
12927 if (options.allowReserved !== true) {
12928 reserved = reservedWords$1[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
12929 if (options.sourceType === "module") { reserved += " await"; }
12930 }
12931 this.reservedWords = wordsRegexp(reserved);
12932 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$1.strict;
12933 this.reservedWordsStrict = wordsRegexp(reservedStrict);
12934 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords$1.strictBind);
12935 this.input = String(input);
12936
12937 // Used to signal to callers of `readWord1` whether the word
12938 // contained any escape sequences. This is needed because words with
12939 // escape sequences must not be interpreted as keywords.
12940 this.containsEsc = false;
12941
12942 // Set up token state
12943
12944 // The current position of the tokenizer in the input.
12945 if (startPos) {
12946 this.pos = startPos;
12947 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
12948 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
12949 } else {
12950 this.pos = this.lineStart = 0;
12951 this.curLine = 1;
12952 }
12953
12954 // Properties of the current token:
12955 // Its type
12956 this.type = types.eof;
12957 // For tokens that include more information than their type, the value
12958 this.value = null;
12959 // Its start and end offset
12960 this.start = this.end = this.pos;
12961 // And, if locations are used, the {line, column} object
12962 // corresponding to those offsets
12963 this.startLoc = this.endLoc = this.curPosition();
12964
12965 // Position information for the previous token
12966 this.lastTokEndLoc = this.lastTokStartLoc = null;
12967 this.lastTokStart = this.lastTokEnd = this.pos;
12968
12969 // The context stack is used to superficially track syntactic
12970 // context to predict whether a regular expression is allowed in a
12971 // given position.
12972 this.context = this.initialContext();
12973 this.exprAllowed = true;
12974
12975 // Figure out if it's a module code.
12976 this.inModule = options.sourceType === "module";
12977 this.strict = this.inModule || this.strictDirective(this.pos);
12978
12979 // Used to signify the start of a potential arrow function
12980 this.potentialArrowAt = -1;
12981
12982 // Positions to delayed-check that yield/await does not exist in default parameters.
12983 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
12984 // Labels in scope.
12985 this.labels = [];
12986 // Thus-far undefined exports.
12987 this.undefinedExports = {};
12988
12989 // If enabled, skip leading hashbang line.
12990 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
12991 { this.skipLineComment(2); }
12992
12993 // Scope tracking for duplicate variable names (see scope.js)
12994 this.scopeStack = [];
12995 this.enterScope(SCOPE_TOP);
12996
12997 // For RegExp validation
12998 this.regexpState = null;
12999};
13000
13001var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
13002
13003Parser.prototype.parse = function parse () {
13004 var node = this.options.program || this.startNode();
13005 this.nextToken();
13006 return this.parseTopLevel(node)
13007};
13008
13009prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
13010prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
13011prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
13012prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
13013prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
13014prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
13015prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };
13016
13017Parser.extend = function extend () {
13018 var plugins = [], len = arguments.length;
13019 while ( len-- ) plugins[ len ] = arguments[ len ];
13020
13021 var cls = this;
13022 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
13023 return cls
13024};
13025
13026Parser.parse = function parse (input, options) {
13027 return new this(options, input).parse()
13028};
13029
13030Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
13031 var parser = new this(options, input, pos);
13032 parser.nextToken();
13033 return parser.parseExpression()
13034};
13035
13036Parser.tokenizer = function tokenizer (input, options) {
13037 return new this(options, input)
13038};
13039
13040Object.defineProperties( Parser.prototype, prototypeAccessors );
13041
13042var pp = Parser.prototype;
13043
13044// ## Parser utilities
13045
13046var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/;
13047pp.strictDirective = function(start) {
13048 for (;;) {
13049 // Try to find string literal.
13050 skipWhiteSpace.lastIndex = start;
13051 start += skipWhiteSpace.exec(this.input)[0].length;
13052 var match = literal.exec(this.input.slice(start));
13053 if (!match) { return false }
13054 if ((match[1] || match[2]) === "use strict") {
13055 skipWhiteSpace.lastIndex = start + match[0].length;
13056 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
13057 var next = this.input.charAt(end);
13058 return next === ";" || next === "}" ||
13059 (lineBreak.test(spaceAfter[0]) &&
13060 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
13061 }
13062 start += match[0].length;
13063
13064 // Skip semicolon, if any.
13065 skipWhiteSpace.lastIndex = start;
13066 start += skipWhiteSpace.exec(this.input)[0].length;
13067 if (this.input[start] === ";")
13068 { start++; }
13069 }
13070};
13071
13072// Predicate that tests whether the next token is of the given
13073// type, and if yes, consumes it as a side effect.
13074
13075pp.eat = function(type) {
13076 if (this.type === type) {
13077 this.next();
13078 return true
13079 } else {
13080 return false
13081 }
13082};
13083
13084// Tests whether parsed token is a contextual keyword.
13085
13086pp.isContextual = function(name) {
13087 return this.type === types.name && this.value === name && !this.containsEsc
13088};
13089
13090// Consumes contextual keyword if possible.
13091
13092pp.eatContextual = function(name) {
13093 if (!this.isContextual(name)) { return false }
13094 this.next();
13095 return true
13096};
13097
13098// Asserts that following token is given contextual keyword.
13099
13100pp.expectContextual = function(name) {
13101 if (!this.eatContextual(name)) { this.unexpected(); }
13102};
13103
13104// Test whether a semicolon can be inserted at the current position.
13105
13106pp.canInsertSemicolon = function() {
13107 return this.type === types.eof ||
13108 this.type === types.braceR ||
13109 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
13110};
13111
13112pp.insertSemicolon = function() {
13113 if (this.canInsertSemicolon()) {
13114 if (this.options.onInsertedSemicolon)
13115 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
13116 return true
13117 }
13118};
13119
13120// Consume a semicolon, or, failing that, see if we are allowed to
13121// pretend that there is a semicolon at this position.
13122
13123pp.semicolon = function() {
13124 if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
13125};
13126
13127pp.afterTrailingComma = function(tokType, notNext) {
13128 if (this.type === tokType) {
13129 if (this.options.onTrailingComma)
13130 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
13131 if (!notNext)
13132 { this.next(); }
13133 return true
13134 }
13135};
13136
13137// Expect a token of a given type. If found, consume it, otherwise,
13138// raise an unexpected token error.
13139
13140pp.expect = function(type) {
13141 this.eat(type) || this.unexpected();
13142};
13143
13144// Raise an unexpected token error.
13145
13146pp.unexpected = function(pos) {
13147 this.raise(pos != null ? pos : this.start, "Unexpected token");
13148};
13149
13150function DestructuringErrors() {
13151 this.shorthandAssign =
13152 this.trailingComma =
13153 this.parenthesizedAssign =
13154 this.parenthesizedBind =
13155 this.doubleProto =
13156 -1;
13157}
13158
13159pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
13160 if (!refDestructuringErrors) { return }
13161 if (refDestructuringErrors.trailingComma > -1)
13162 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
13163 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
13164 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
13165};
13166
13167pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
13168 if (!refDestructuringErrors) { return false }
13169 var shorthandAssign = refDestructuringErrors.shorthandAssign;
13170 var doubleProto = refDestructuringErrors.doubleProto;
13171 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
13172 if (shorthandAssign >= 0)
13173 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
13174 if (doubleProto >= 0)
13175 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
13176};
13177
13178pp.checkYieldAwaitInDefaultParams = function() {
13179 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
13180 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
13181 if (this.awaitPos)
13182 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
13183};
13184
13185pp.isSimpleAssignTarget = function(expr) {
13186 if (expr.type === "ParenthesizedExpression")
13187 { return this.isSimpleAssignTarget(expr.expression) }
13188 return expr.type === "Identifier" || expr.type === "MemberExpression"
13189};
13190
13191var pp$1 = Parser.prototype;
13192
13193// ### Statement parsing
13194
13195// Parse a program. Initializes the parser, reads any number of
13196// statements, and wraps them in a Program node. Optionally takes a
13197// `program` argument. If present, the statements will be appended
13198// to its body instead of creating a new node.
13199
13200pp$1.parseTopLevel = function(node) {
13201 var exports = {};
13202 if (!node.body) { node.body = []; }
13203 while (this.type !== types.eof) {
13204 var stmt = this.parseStatement(null, true, exports);
13205 node.body.push(stmt);
13206 }
13207 if (this.inModule)
13208 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
13209 {
13210 var name = list[i];
13211
13212 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
13213 } }
13214 this.adaptDirectivePrologue(node.body);
13215 this.next();
13216 node.sourceType = this.options.sourceType;
13217 return this.finishNode(node, "Program")
13218};
13219
13220var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
13221
13222pp$1.isLet = function(context) {
13223 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
13224 skipWhiteSpace.lastIndex = this.pos;
13225 var skip = skipWhiteSpace.exec(this.input);
13226 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
13227 // For ambiguous cases, determine if a LexicalDeclaration (or only a
13228 // Statement) is allowed here. If context is not empty then only a Statement
13229 // is allowed. However, `let [` is an explicit negative lookahead for
13230 // ExpressionStatement, so special-case it first.
13231 if (nextCh === 91) { return true } // '['
13232 if (context) { return false }
13233
13234 if (nextCh === 123) { return true } // '{'
13235 if (isIdentifierStart(nextCh, true)) {
13236 var pos = next + 1;
13237 while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
13238 var ident = this.input.slice(next, pos);
13239 if (!keywordRelationalOperator.test(ident)) { return true }
13240 }
13241 return false
13242};
13243
13244// check 'async [no LineTerminator here] function'
13245// - 'async /*foo*/ function' is OK.
13246// - 'async /*\n*/ function' is invalid.
13247pp$1.isAsyncFunction = function() {
13248 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
13249 { return false }
13250
13251 skipWhiteSpace.lastIndex = this.pos;
13252 var skip = skipWhiteSpace.exec(this.input);
13253 var next = this.pos + skip[0].length;
13254 return !lineBreak.test(this.input.slice(this.pos, next)) &&
13255 this.input.slice(next, next + 8) === "function" &&
13256 (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
13257};
13258
13259// Parse a single statement.
13260//
13261// If expecting a statement and finding a slash operator, parse a
13262// regular expression literal. This is to handle cases like
13263// `if (foo) /blah/.exec(foo)`, where looking at the previous token
13264// does not help.
13265
13266pp$1.parseStatement = function(context, topLevel, exports) {
13267 var starttype = this.type, node = this.startNode(), kind;
13268
13269 if (this.isLet(context)) {
13270 starttype = types._var;
13271 kind = "let";
13272 }
13273
13274 // Most types of statements are recognized by the keyword they
13275 // start with. Many are trivial to parse, some require a bit of
13276 // complexity.
13277
13278 switch (starttype) {
13279 case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
13280 case types._debugger: return this.parseDebuggerStatement(node)
13281 case types._do: return this.parseDoStatement(node)
13282 case types._for: return this.parseForStatement(node)
13283 case types._function:
13284 // Function as sole body of either an if statement or a labeled statement
13285 // works, but not when it is part of a labeled statement that is the sole
13286 // body of an if statement.
13287 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
13288 return this.parseFunctionStatement(node, false, !context)
13289 case types._class:
13290 if (context) { this.unexpected(); }
13291 return this.parseClass(node, true)
13292 case types._if: return this.parseIfStatement(node)
13293 case types._return: return this.parseReturnStatement(node)
13294 case types._switch: return this.parseSwitchStatement(node)
13295 case types._throw: return this.parseThrowStatement(node)
13296 case types._try: return this.parseTryStatement(node)
13297 case types._const: case types._var:
13298 kind = kind || this.value;
13299 if (context && kind !== "var") { this.unexpected(); }
13300 return this.parseVarStatement(node, kind)
13301 case types._while: return this.parseWhileStatement(node)
13302 case types._with: return this.parseWithStatement(node)
13303 case types.braceL: return this.parseBlock(true, node)
13304 case types.semi: return this.parseEmptyStatement(node)
13305 case types._export:
13306 case types._import:
13307 if (this.options.ecmaVersion > 10 && starttype === types._import) {
13308 skipWhiteSpace.lastIndex = this.pos;
13309 var skip = skipWhiteSpace.exec(this.input);
13310 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
13311 if (nextCh === 40 || nextCh === 46) // '(' or '.'
13312 { return this.parseExpressionStatement(node, this.parseExpression()) }
13313 }
13314
13315 if (!this.options.allowImportExportEverywhere) {
13316 if (!topLevel)
13317 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
13318 if (!this.inModule)
13319 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
13320 }
13321 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
13322
13323 // If the statement does not start with a statement keyword or a
13324 // brace, it's an ExpressionStatement or LabeledStatement. We
13325 // simply start parsing an expression, and afterwards, if the
13326 // next token is a colon and the expression was a simple
13327 // Identifier node, we switch to interpreting it as a label.
13328 default:
13329 if (this.isAsyncFunction()) {
13330 if (context) { this.unexpected(); }
13331 this.next();
13332 return this.parseFunctionStatement(node, true, !context)
13333 }
13334
13335 var maybeName = this.value, expr = this.parseExpression();
13336 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
13337 { return this.parseLabeledStatement(node, maybeName, expr, context) }
13338 else { return this.parseExpressionStatement(node, expr) }
13339 }
13340};
13341
13342pp$1.parseBreakContinueStatement = function(node, keyword) {
13343 var isBreak = keyword === "break";
13344 this.next();
13345 if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
13346 else if (this.type !== types.name) { this.unexpected(); }
13347 else {
13348 node.label = this.parseIdent();
13349 this.semicolon();
13350 }
13351
13352 // Verify that there is an actual destination to break or
13353 // continue to.
13354 var i = 0;
13355 for (; i < this.labels.length; ++i) {
13356 var lab = this.labels[i];
13357 if (node.label == null || lab.name === node.label.name) {
13358 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
13359 if (node.label && isBreak) { break }
13360 }
13361 }
13362 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
13363 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
13364};
13365
13366pp$1.parseDebuggerStatement = function(node) {
13367 this.next();
13368 this.semicolon();
13369 return this.finishNode(node, "DebuggerStatement")
13370};
13371
13372pp$1.parseDoStatement = function(node) {
13373 this.next();
13374 this.labels.push(loopLabel);
13375 node.body = this.parseStatement("do");
13376 this.labels.pop();
13377 this.expect(types._while);
13378 node.test = this.parseParenExpression();
13379 if (this.options.ecmaVersion >= 6)
13380 { this.eat(types.semi); }
13381 else
13382 { this.semicolon(); }
13383 return this.finishNode(node, "DoWhileStatement")
13384};
13385
13386// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
13387// loop is non-trivial. Basically, we have to parse the init `var`
13388// statement or expression, disallowing the `in` operator (see
13389// the second parameter to `parseExpression`), and then check
13390// whether the next token is `in` or `of`. When there is no init
13391// part (semicolon immediately after the opening parenthesis), it
13392// is a regular `for` loop.
13393
13394pp$1.parseForStatement = function(node) {
13395 this.next();
13396 var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
13397 this.labels.push(loopLabel);
13398 this.enterScope(0);
13399 this.expect(types.parenL);
13400 if (this.type === types.semi) {
13401 if (awaitAt > -1) { this.unexpected(awaitAt); }
13402 return this.parseFor(node, null)
13403 }
13404 var isLet = this.isLet();
13405 if (this.type === types._var || this.type === types._const || isLet) {
13406 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
13407 this.next();
13408 this.parseVar(init$1, true, kind);
13409 this.finishNode(init$1, "VariableDeclaration");
13410 if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
13411 if (this.options.ecmaVersion >= 9) {
13412 if (this.type === types._in) {
13413 if (awaitAt > -1) { this.unexpected(awaitAt); }
13414 } else { node.await = awaitAt > -1; }
13415 }
13416 return this.parseForIn(node, init$1)
13417 }
13418 if (awaitAt > -1) { this.unexpected(awaitAt); }
13419 return this.parseFor(node, init$1)
13420 }
13421 var refDestructuringErrors = new DestructuringErrors;
13422 var init = this.parseExpression(true, refDestructuringErrors);
13423 if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
13424 if (this.options.ecmaVersion >= 9) {
13425 if (this.type === types._in) {
13426 if (awaitAt > -1) { this.unexpected(awaitAt); }
13427 } else { node.await = awaitAt > -1; }
13428 }
13429 this.toAssignable(init, false, refDestructuringErrors);
13430 this.checkLValPattern(init);
13431 return this.parseForIn(node, init)
13432 } else {
13433 this.checkExpressionErrors(refDestructuringErrors, true);
13434 }
13435 if (awaitAt > -1) { this.unexpected(awaitAt); }
13436 return this.parseFor(node, init)
13437};
13438
13439pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
13440 this.next();
13441 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
13442};
13443
13444pp$1.parseIfStatement = function(node) {
13445 this.next();
13446 node.test = this.parseParenExpression();
13447 // allow function declarations in branches, but only in non-strict mode
13448 node.consequent = this.parseStatement("if");
13449 node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
13450 return this.finishNode(node, "IfStatement")
13451};
13452
13453pp$1.parseReturnStatement = function(node) {
13454 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
13455 { this.raise(this.start, "'return' outside of function"); }
13456 this.next();
13457
13458 // In `return` (and `break`/`continue`), the keywords with
13459 // optional arguments, we eagerly look for a semicolon or the
13460 // possibility to insert one.
13461
13462 if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
13463 else { node.argument = this.parseExpression(); this.semicolon(); }
13464 return this.finishNode(node, "ReturnStatement")
13465};
13466
13467pp$1.parseSwitchStatement = function(node) {
13468 this.next();
13469 node.discriminant = this.parseParenExpression();
13470 node.cases = [];
13471 this.expect(types.braceL);
13472 this.labels.push(switchLabel);
13473 this.enterScope(0);
13474
13475 // Statements under must be grouped (by label) in SwitchCase
13476 // nodes. `cur` is used to keep the node that we are currently
13477 // adding statements to.
13478
13479 var cur;
13480 for (var sawDefault = false; this.type !== types.braceR;) {
13481 if (this.type === types._case || this.type === types._default) {
13482 var isCase = this.type === types._case;
13483 if (cur) { this.finishNode(cur, "SwitchCase"); }
13484 node.cases.push(cur = this.startNode());
13485 cur.consequent = [];
13486 this.next();
13487 if (isCase) {
13488 cur.test = this.parseExpression();
13489 } else {
13490 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
13491 sawDefault = true;
13492 cur.test = null;
13493 }
13494 this.expect(types.colon);
13495 } else {
13496 if (!cur) { this.unexpected(); }
13497 cur.consequent.push(this.parseStatement(null));
13498 }
13499 }
13500 this.exitScope();
13501 if (cur) { this.finishNode(cur, "SwitchCase"); }
13502 this.next(); // Closing brace
13503 this.labels.pop();
13504 return this.finishNode(node, "SwitchStatement")
13505};
13506
13507pp$1.parseThrowStatement = function(node) {
13508 this.next();
13509 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
13510 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
13511 node.argument = this.parseExpression();
13512 this.semicolon();
13513 return this.finishNode(node, "ThrowStatement")
13514};
13515
13516// Reused empty array added for node fields that are always empty.
13517
13518var empty = [];
13519
13520pp$1.parseTryStatement = function(node) {
13521 this.next();
13522 node.block = this.parseBlock();
13523 node.handler = null;
13524 if (this.type === types._catch) {
13525 var clause = this.startNode();
13526 this.next();
13527 if (this.eat(types.parenL)) {
13528 clause.param = this.parseBindingAtom();
13529 var simple = clause.param.type === "Identifier";
13530 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
13531 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
13532 this.expect(types.parenR);
13533 } else {
13534 if (this.options.ecmaVersion < 10) { this.unexpected(); }
13535 clause.param = null;
13536 this.enterScope(0);
13537 }
13538 clause.body = this.parseBlock(false);
13539 this.exitScope();
13540 node.handler = this.finishNode(clause, "CatchClause");
13541 }
13542 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
13543 if (!node.handler && !node.finalizer)
13544 { this.raise(node.start, "Missing catch or finally clause"); }
13545 return this.finishNode(node, "TryStatement")
13546};
13547
13548pp$1.parseVarStatement = function(node, kind) {
13549 this.next();
13550 this.parseVar(node, false, kind);
13551 this.semicolon();
13552 return this.finishNode(node, "VariableDeclaration")
13553};
13554
13555pp$1.parseWhileStatement = function(node) {
13556 this.next();
13557 node.test = this.parseParenExpression();
13558 this.labels.push(loopLabel);
13559 node.body = this.parseStatement("while");
13560 this.labels.pop();
13561 return this.finishNode(node, "WhileStatement")
13562};
13563
13564pp$1.parseWithStatement = function(node) {
13565 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
13566 this.next();
13567 node.object = this.parseParenExpression();
13568 node.body = this.parseStatement("with");
13569 return this.finishNode(node, "WithStatement")
13570};
13571
13572pp$1.parseEmptyStatement = function(node) {
13573 this.next();
13574 return this.finishNode(node, "EmptyStatement")
13575};
13576
13577pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
13578 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
13579 {
13580 var label = list[i$1];
13581
13582 if (label.name === maybeName)
13583 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
13584 } }
13585 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
13586 for (var i = this.labels.length - 1; i >= 0; i--) {
13587 var label$1 = this.labels[i];
13588 if (label$1.statementStart === node.start) {
13589 // Update information about previous labels on this node
13590 label$1.statementStart = this.start;
13591 label$1.kind = kind;
13592 } else { break }
13593 }
13594 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
13595 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
13596 this.labels.pop();
13597 node.label = expr;
13598 return this.finishNode(node, "LabeledStatement")
13599};
13600
13601pp$1.parseExpressionStatement = function(node, expr) {
13602 node.expression = expr;
13603 this.semicolon();
13604 return this.finishNode(node, "ExpressionStatement")
13605};
13606
13607// Parse a semicolon-enclosed block of statements, handling `"use
13608// strict"` declarations when `allowStrict` is true (used for
13609// function bodies).
13610
13611pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
13612 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
13613 if ( node === void 0 ) node = this.startNode();
13614
13615 node.body = [];
13616 this.expect(types.braceL);
13617 if (createNewLexicalScope) { this.enterScope(0); }
13618 while (this.type !== types.braceR) {
13619 var stmt = this.parseStatement(null);
13620 node.body.push(stmt);
13621 }
13622 if (exitStrict) { this.strict = false; }
13623 this.next();
13624 if (createNewLexicalScope) { this.exitScope(); }
13625 return this.finishNode(node, "BlockStatement")
13626};
13627
13628// Parse a regular `for` loop. The disambiguation code in
13629// `parseStatement` will already have parsed the init statement or
13630// expression.
13631
13632pp$1.parseFor = function(node, init) {
13633 node.init = init;
13634 this.expect(types.semi);
13635 node.test = this.type === types.semi ? null : this.parseExpression();
13636 this.expect(types.semi);
13637 node.update = this.type === types.parenR ? null : this.parseExpression();
13638 this.expect(types.parenR);
13639 node.body = this.parseStatement("for");
13640 this.exitScope();
13641 this.labels.pop();
13642 return this.finishNode(node, "ForStatement")
13643};
13644
13645// Parse a `for`/`in` and `for`/`of` loop, which are almost
13646// same from parser's perspective.
13647
13648pp$1.parseForIn = function(node, init) {
13649 var isForIn = this.type === types._in;
13650 this.next();
13651
13652 if (
13653 init.type === "VariableDeclaration" &&
13654 init.declarations[0].init != null &&
13655 (
13656 !isForIn ||
13657 this.options.ecmaVersion < 8 ||
13658 this.strict ||
13659 init.kind !== "var" ||
13660 init.declarations[0].id.type !== "Identifier"
13661 )
13662 ) {
13663 this.raise(
13664 init.start,
13665 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
13666 );
13667 }
13668 node.left = init;
13669 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
13670 this.expect(types.parenR);
13671 node.body = this.parseStatement("for");
13672 this.exitScope();
13673 this.labels.pop();
13674 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
13675};
13676
13677// Parse a list of variable declarations.
13678
13679pp$1.parseVar = function(node, isFor, kind) {
13680 node.declarations = [];
13681 node.kind = kind;
13682 for (;;) {
13683 var decl = this.startNode();
13684 this.parseVarId(decl, kind);
13685 if (this.eat(types.eq)) {
13686 decl.init = this.parseMaybeAssign(isFor);
13687 } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
13688 this.unexpected();
13689 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
13690 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
13691 } else {
13692 decl.init = null;
13693 }
13694 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
13695 if (!this.eat(types.comma)) { break }
13696 }
13697 return node
13698};
13699
13700pp$1.parseVarId = function(decl, kind) {
13701 decl.id = this.parseBindingAtom();
13702 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
13703};
13704
13705var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
13706
13707// Parse a function declaration or literal (depending on the
13708// `statement & FUNC_STATEMENT`).
13709
13710// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
13711pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
13712 this.initFunction(node);
13713 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
13714 if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
13715 { this.unexpected(); }
13716 node.generator = this.eat(types.star);
13717 }
13718 if (this.options.ecmaVersion >= 8)
13719 { node.async = !!isAsync; }
13720
13721 if (statement & FUNC_STATEMENT) {
13722 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
13723 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
13724 // If it is a regular function declaration in sloppy mode, then it is
13725 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
13726 // mode depends on properties of the current scope (see
13727 // treatFunctionsAsVar).
13728 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
13729 }
13730
13731 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
13732 this.yieldPos = 0;
13733 this.awaitPos = 0;
13734 this.awaitIdentPos = 0;
13735 this.enterScope(functionFlags(node.async, node.generator));
13736
13737 if (!(statement & FUNC_STATEMENT))
13738 { node.id = this.type === types.name ? this.parseIdent() : null; }
13739
13740 this.parseFunctionParams(node);
13741 this.parseFunctionBody(node, allowExpressionBody, false);
13742
13743 this.yieldPos = oldYieldPos;
13744 this.awaitPos = oldAwaitPos;
13745 this.awaitIdentPos = oldAwaitIdentPos;
13746 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
13747};
13748
13749pp$1.parseFunctionParams = function(node) {
13750 this.expect(types.parenL);
13751 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
13752 this.checkYieldAwaitInDefaultParams();
13753};
13754
13755// Parse a class declaration or literal (depending on the
13756// `isStatement` parameter).
13757
13758pp$1.parseClass = function(node, isStatement) {
13759 this.next();
13760
13761 // ecma-262 14.6 Class Definitions
13762 // A class definition is always strict mode code.
13763 var oldStrict = this.strict;
13764 this.strict = true;
13765
13766 this.parseClassId(node, isStatement);
13767 this.parseClassSuper(node);
13768 var classBody = this.startNode();
13769 var hadConstructor = false;
13770 classBody.body = [];
13771 this.expect(types.braceL);
13772 while (this.type !== types.braceR) {
13773 var element = this.parseClassElement(node.superClass !== null);
13774 if (element) {
13775 classBody.body.push(element);
13776 if (element.type === "MethodDefinition" && element.kind === "constructor") {
13777 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
13778 hadConstructor = true;
13779 }
13780 }
13781 }
13782 this.strict = oldStrict;
13783 this.next();
13784 node.body = this.finishNode(classBody, "ClassBody");
13785 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
13786};
13787
13788pp$1.parseClassElement = function(constructorAllowsSuper) {
13789 var this$1 = this;
13790
13791 if (this.eat(types.semi)) { return null }
13792
13793 var method = this.startNode();
13794 var tryContextual = function (k, noLineBreak) {
13795 if ( noLineBreak === void 0 ) noLineBreak = false;
13796
13797 var start = this$1.start, startLoc = this$1.startLoc;
13798 if (!this$1.eatContextual(k)) { return false }
13799 if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
13800 if (method.key) { this$1.unexpected(); }
13801 method.computed = false;
13802 method.key = this$1.startNodeAt(start, startLoc);
13803 method.key.name = k;
13804 this$1.finishNode(method.key, "Identifier");
13805 return false
13806 };
13807
13808 method.kind = "method";
13809 method.static = tryContextual("static");
13810 var isGenerator = this.eat(types.star);
13811 var isAsync = false;
13812 if (!isGenerator) {
13813 if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
13814 isAsync = true;
13815 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
13816 } else if (tryContextual("get")) {
13817 method.kind = "get";
13818 } else if (tryContextual("set")) {
13819 method.kind = "set";
13820 }
13821 }
13822 if (!method.key) { this.parsePropertyName(method); }
13823 var key = method.key;
13824 var allowsDirectSuper = false;
13825 if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
13826 key.type === "Literal" && key.value === "constructor")) {
13827 if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
13828 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
13829 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
13830 method.kind = "constructor";
13831 allowsDirectSuper = constructorAllowsSuper;
13832 } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
13833 this.raise(key.start, "Classes may not have a static property named prototype");
13834 }
13835 this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
13836 if (method.kind === "get" && method.value.params.length !== 0)
13837 { this.raiseRecoverable(method.value.start, "getter should have no params"); }
13838 if (method.kind === "set" && method.value.params.length !== 1)
13839 { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
13840 if (method.kind === "set" && method.value.params[0].type === "RestElement")
13841 { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
13842 return method
13843};
13844
13845pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
13846 method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
13847 return this.finishNode(method, "MethodDefinition")
13848};
13849
13850pp$1.parseClassId = function(node, isStatement) {
13851 if (this.type === types.name) {
13852 node.id = this.parseIdent();
13853 if (isStatement)
13854 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
13855 } else {
13856 if (isStatement === true)
13857 { this.unexpected(); }
13858 node.id = null;
13859 }
13860};
13861
13862pp$1.parseClassSuper = function(node) {
13863 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
13864};
13865
13866// Parses module export declaration.
13867
13868pp$1.parseExport = function(node, exports) {
13869 this.next();
13870 // export * from '...'
13871 if (this.eat(types.star)) {
13872 if (this.options.ecmaVersion >= 11) {
13873 if (this.eatContextual("as")) {
13874 node.exported = this.parseIdent(true);
13875 this.checkExport(exports, node.exported.name, this.lastTokStart);
13876 } else {
13877 node.exported = null;
13878 }
13879 }
13880 this.expectContextual("from");
13881 if (this.type !== types.string) { this.unexpected(); }
13882 node.source = this.parseExprAtom();
13883 this.semicolon();
13884 return this.finishNode(node, "ExportAllDeclaration")
13885 }
13886 if (this.eat(types._default)) { // export default ...
13887 this.checkExport(exports, "default", this.lastTokStart);
13888 var isAsync;
13889 if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
13890 var fNode = this.startNode();
13891 this.next();
13892 if (isAsync) { this.next(); }
13893 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
13894 } else if (this.type === types._class) {
13895 var cNode = this.startNode();
13896 node.declaration = this.parseClass(cNode, "nullableID");
13897 } else {
13898 node.declaration = this.parseMaybeAssign();
13899 this.semicolon();
13900 }
13901 return this.finishNode(node, "ExportDefaultDeclaration")
13902 }
13903 // export var|const|let|function|class ...
13904 if (this.shouldParseExportStatement()) {
13905 node.declaration = this.parseStatement(null);
13906 if (node.declaration.type === "VariableDeclaration")
13907 { this.checkVariableExport(exports, node.declaration.declarations); }
13908 else
13909 { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
13910 node.specifiers = [];
13911 node.source = null;
13912 } else { // export { x, y as z } [from '...']
13913 node.declaration = null;
13914 node.specifiers = this.parseExportSpecifiers(exports);
13915 if (this.eatContextual("from")) {
13916 if (this.type !== types.string) { this.unexpected(); }
13917 node.source = this.parseExprAtom();
13918 } else {
13919 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
13920 // check for keywords used as local names
13921 var spec = list[i];
13922
13923 this.checkUnreserved(spec.local);
13924 // check if export is defined
13925 this.checkLocalExport(spec.local);
13926 }
13927
13928 node.source = null;
13929 }
13930 this.semicolon();
13931 }
13932 return this.finishNode(node, "ExportNamedDeclaration")
13933};
13934
13935pp$1.checkExport = function(exports, name, pos) {
13936 if (!exports) { return }
13937 if (has(exports, name))
13938 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
13939 exports[name] = true;
13940};
13941
13942pp$1.checkPatternExport = function(exports, pat) {
13943 var type = pat.type;
13944 if (type === "Identifier")
13945 { this.checkExport(exports, pat.name, pat.start); }
13946 else if (type === "ObjectPattern")
13947 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
13948 {
13949 var prop = list[i];
13950
13951 this.checkPatternExport(exports, prop);
13952 } }
13953 else if (type === "ArrayPattern")
13954 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
13955 var elt = list$1[i$1];
13956
13957 if (elt) { this.checkPatternExport(exports, elt); }
13958 } }
13959 else if (type === "Property")
13960 { this.checkPatternExport(exports, pat.value); }
13961 else if (type === "AssignmentPattern")
13962 { this.checkPatternExport(exports, pat.left); }
13963 else if (type === "RestElement")
13964 { this.checkPatternExport(exports, pat.argument); }
13965 else if (type === "ParenthesizedExpression")
13966 { this.checkPatternExport(exports, pat.expression); }
13967};
13968
13969pp$1.checkVariableExport = function(exports, decls) {
13970 if (!exports) { return }
13971 for (var i = 0, list = decls; i < list.length; i += 1)
13972 {
13973 var decl = list[i];
13974
13975 this.checkPatternExport(exports, decl.id);
13976 }
13977};
13978
13979pp$1.shouldParseExportStatement = function() {
13980 return this.type.keyword === "var" ||
13981 this.type.keyword === "const" ||
13982 this.type.keyword === "class" ||
13983 this.type.keyword === "function" ||
13984 this.isLet() ||
13985 this.isAsyncFunction()
13986};
13987
13988// Parses a comma-separated list of module exports.
13989
13990pp$1.parseExportSpecifiers = function(exports) {
13991 var nodes = [], first = true;
13992 // export { x, y as z } [from '...']
13993 this.expect(types.braceL);
13994 while (!this.eat(types.braceR)) {
13995 if (!first) {
13996 this.expect(types.comma);
13997 if (this.afterTrailingComma(types.braceR)) { break }
13998 } else { first = false; }
13999
14000 var node = this.startNode();
14001 node.local = this.parseIdent(true);
14002 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
14003 this.checkExport(exports, node.exported.name, node.exported.start);
14004 nodes.push(this.finishNode(node, "ExportSpecifier"));
14005 }
14006 return nodes
14007};
14008
14009// Parses import declaration.
14010
14011pp$1.parseImport = function(node) {
14012 this.next();
14013 // import '...'
14014 if (this.type === types.string) {
14015 node.specifiers = empty;
14016 node.source = this.parseExprAtom();
14017 } else {
14018 node.specifiers = this.parseImportSpecifiers();
14019 this.expectContextual("from");
14020 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
14021 }
14022 this.semicolon();
14023 return this.finishNode(node, "ImportDeclaration")
14024};
14025
14026// Parses a comma-separated list of module imports.
14027
14028pp$1.parseImportSpecifiers = function() {
14029 var nodes = [], first = true;
14030 if (this.type === types.name) {
14031 // import defaultObj, { x, y as z } from '...'
14032 var node = this.startNode();
14033 node.local = this.parseIdent();
14034 this.checkLValSimple(node.local, BIND_LEXICAL);
14035 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
14036 if (!this.eat(types.comma)) { return nodes }
14037 }
14038 if (this.type === types.star) {
14039 var node$1 = this.startNode();
14040 this.next();
14041 this.expectContextual("as");
14042 node$1.local = this.parseIdent();
14043 this.checkLValSimple(node$1.local, BIND_LEXICAL);
14044 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
14045 return nodes
14046 }
14047 this.expect(types.braceL);
14048 while (!this.eat(types.braceR)) {
14049 if (!first) {
14050 this.expect(types.comma);
14051 if (this.afterTrailingComma(types.braceR)) { break }
14052 } else { first = false; }
14053
14054 var node$2 = this.startNode();
14055 node$2.imported = this.parseIdent(true);
14056 if (this.eatContextual("as")) {
14057 node$2.local = this.parseIdent();
14058 } else {
14059 this.checkUnreserved(node$2.imported);
14060 node$2.local = node$2.imported;
14061 }
14062 this.checkLValSimple(node$2.local, BIND_LEXICAL);
14063 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
14064 }
14065 return nodes
14066};
14067
14068// Set `ExpressionStatement#directive` property for directive prologues.
14069pp$1.adaptDirectivePrologue = function(statements) {
14070 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
14071 statements[i].directive = statements[i].expression.raw.slice(1, -1);
14072 }
14073};
14074pp$1.isDirectiveCandidate = function(statement) {
14075 return (
14076 statement.type === "ExpressionStatement" &&
14077 statement.expression.type === "Literal" &&
14078 typeof statement.expression.value === "string" &&
14079 // Reject parenthesized strings.
14080 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
14081 )
14082};
14083
14084var pp$2 = Parser.prototype;
14085
14086// Convert existing expression atom to assignable pattern
14087// if possible.
14088
14089pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
14090 if (this.options.ecmaVersion >= 6 && node) {
14091 switch (node.type) {
14092 case "Identifier":
14093 if (this.inAsync && node.name === "await")
14094 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
14095 break
14096
14097 case "ObjectPattern":
14098 case "ArrayPattern":
14099 case "AssignmentPattern":
14100 case "RestElement":
14101 break
14102
14103 case "ObjectExpression":
14104 node.type = "ObjectPattern";
14105 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
14106 for (var i = 0, list = node.properties; i < list.length; i += 1) {
14107 var prop = list[i];
14108
14109 this.toAssignable(prop, isBinding);
14110 // Early error:
14111 // AssignmentRestProperty[Yield, Await] :
14112 // `...` DestructuringAssignmentTarget[Yield, Await]
14113 //
14114 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
14115 if (
14116 prop.type === "RestElement" &&
14117 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
14118 ) {
14119 this.raise(prop.argument.start, "Unexpected token");
14120 }
14121 }
14122 break
14123
14124 case "Property":
14125 // AssignmentProperty has type === "Property"
14126 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
14127 this.toAssignable(node.value, isBinding);
14128 break
14129
14130 case "ArrayExpression":
14131 node.type = "ArrayPattern";
14132 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
14133 this.toAssignableList(node.elements, isBinding);
14134 break
14135
14136 case "SpreadElement":
14137 node.type = "RestElement";
14138 this.toAssignable(node.argument, isBinding);
14139 if (node.argument.type === "AssignmentPattern")
14140 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
14141 break
14142
14143 case "AssignmentExpression":
14144 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
14145 node.type = "AssignmentPattern";
14146 delete node.operator;
14147 this.toAssignable(node.left, isBinding);
14148 break
14149
14150 case "ParenthesizedExpression":
14151 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
14152 break
14153
14154 case "ChainExpression":
14155 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
14156 break
14157
14158 case "MemberExpression":
14159 if (!isBinding) { break }
14160
14161 default:
14162 this.raise(node.start, "Assigning to rvalue");
14163 }
14164 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
14165 return node
14166};
14167
14168// Convert list of expression atoms to binding list.
14169
14170pp$2.toAssignableList = function(exprList, isBinding) {
14171 var end = exprList.length;
14172 for (var i = 0; i < end; i++) {
14173 var elt = exprList[i];
14174 if (elt) { this.toAssignable(elt, isBinding); }
14175 }
14176 if (end) {
14177 var last = exprList[end - 1];
14178 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
14179 { this.unexpected(last.argument.start); }
14180 }
14181 return exprList
14182};
14183
14184// Parses spread element.
14185
14186pp$2.parseSpread = function(refDestructuringErrors) {
14187 var node = this.startNode();
14188 this.next();
14189 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
14190 return this.finishNode(node, "SpreadElement")
14191};
14192
14193pp$2.parseRestBinding = function() {
14194 var node = this.startNode();
14195 this.next();
14196
14197 // RestElement inside of a function parameter must be an identifier
14198 if (this.options.ecmaVersion === 6 && this.type !== types.name)
14199 { this.unexpected(); }
14200
14201 node.argument = this.parseBindingAtom();
14202
14203 return this.finishNode(node, "RestElement")
14204};
14205
14206// Parses lvalue (assignable) atom.
14207
14208pp$2.parseBindingAtom = function() {
14209 if (this.options.ecmaVersion >= 6) {
14210 switch (this.type) {
14211 case types.bracketL:
14212 var node = this.startNode();
14213 this.next();
14214 node.elements = this.parseBindingList(types.bracketR, true, true);
14215 return this.finishNode(node, "ArrayPattern")
14216
14217 case types.braceL:
14218 return this.parseObj(true)
14219 }
14220 }
14221 return this.parseIdent()
14222};
14223
14224pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
14225 var elts = [], first = true;
14226 while (!this.eat(close)) {
14227 if (first) { first = false; }
14228 else { this.expect(types.comma); }
14229 if (allowEmpty && this.type === types.comma) {
14230 elts.push(null);
14231 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
14232 break
14233 } else if (this.type === types.ellipsis) {
14234 var rest = this.parseRestBinding();
14235 this.parseBindingListItem(rest);
14236 elts.push(rest);
14237 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
14238 this.expect(close);
14239 break
14240 } else {
14241 var elem = this.parseMaybeDefault(this.start, this.startLoc);
14242 this.parseBindingListItem(elem);
14243 elts.push(elem);
14244 }
14245 }
14246 return elts
14247};
14248
14249pp$2.parseBindingListItem = function(param) {
14250 return param
14251};
14252
14253// Parses assignment pattern around given atom if possible.
14254
14255pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
14256 left = left || this.parseBindingAtom();
14257 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
14258 var node = this.startNodeAt(startPos, startLoc);
14259 node.left = left;
14260 node.right = this.parseMaybeAssign();
14261 return this.finishNode(node, "AssignmentPattern")
14262};
14263
14264// The following three functions all verify that a node is an lvalue —
14265// something that can be bound, or assigned to. In order to do so, they perform
14266// a variety of checks:
14267//
14268// - Check that none of the bound/assigned-to identifiers are reserved words.
14269// - Record name declarations for bindings in the appropriate scope.
14270// - Check duplicate argument names, if checkClashes is set.
14271//
14272// If a complex binding pattern is encountered (e.g., object and array
14273// destructuring), the entire pattern is recursively checked.
14274//
14275// There are three versions of checkLVal*() appropriate for different
14276// circumstances:
14277//
14278// - checkLValSimple() shall be used if the syntactic construct supports
14279// nothing other than identifiers and member expressions. Parenthesized
14280// expressions are also correctly handled. This is generally appropriate for
14281// constructs for which the spec says
14282//
14283// > It is a Syntax Error if AssignmentTargetType of [the production] is not
14284// > simple.
14285//
14286// It is also appropriate for checking if an identifier is valid and not
14287// defined elsewhere, like import declarations or function/class identifiers.
14288//
14289// Examples where this is used include:
14290// a += …;
14291// import a from '…';
14292// where a is the node to be checked.
14293//
14294// - checkLValPattern() shall be used if the syntactic construct supports
14295// anything checkLValSimple() supports, as well as object and array
14296// destructuring patterns. This is generally appropriate for constructs for
14297// which the spec says
14298//
14299// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
14300// > an ArrayLiteral and AssignmentTargetType of [the production] is not
14301// > simple.
14302//
14303// Examples where this is used include:
14304// (a = …);
14305// const a = …;
14306// try { … } catch (a) { … }
14307// where a is the node to be checked.
14308//
14309// - checkLValInnerPattern() shall be used if the syntactic construct supports
14310// anything checkLValPattern() supports, as well as default assignment
14311// patterns, rest elements, and other constructs that may appear within an
14312// object or array destructuring pattern.
14313//
14314// As a special case, function parameters also use checkLValInnerPattern(),
14315// as they also support defaults and rest constructs.
14316//
14317// These functions deliberately support both assignment and binding constructs,
14318// as the logic for both is exceedingly similar. If the node is the target of
14319// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
14320// should be set to the appropriate BIND_* constant, like BIND_VAR or
14321// BIND_LEXICAL.
14322//
14323// If the function is called with a non-BIND_NONE bindingType, then
14324// additionally a checkClashes object may be specified to allow checking for
14325// duplicate argument names. checkClashes is ignored if the provided construct
14326// is an assignment (i.e., bindingType is BIND_NONE).
14327
14328pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
14329 if ( bindingType === void 0 ) bindingType = BIND_NONE;
14330
14331 var isBind = bindingType !== BIND_NONE;
14332
14333 switch (expr.type) {
14334 case "Identifier":
14335 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
14336 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
14337 if (isBind) {
14338 if (bindingType === BIND_LEXICAL && expr.name === "let")
14339 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
14340 if (checkClashes) {
14341 if (has(checkClashes, expr.name))
14342 { this.raiseRecoverable(expr.start, "Argument name clash"); }
14343 checkClashes[expr.name] = true;
14344 }
14345 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
14346 }
14347 break
14348
14349 case "ChainExpression":
14350 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
14351 break
14352
14353 case "MemberExpression":
14354 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
14355 break
14356
14357 case "ParenthesizedExpression":
14358 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
14359 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
14360
14361 default:
14362 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
14363 }
14364};
14365
14366pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
14367 if ( bindingType === void 0 ) bindingType = BIND_NONE;
14368
14369 switch (expr.type) {
14370 case "ObjectPattern":
14371 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
14372 var prop = list[i];
14373
14374 this.checkLValInnerPattern(prop, bindingType, checkClashes);
14375 }
14376 break
14377
14378 case "ArrayPattern":
14379 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
14380 var elem = list$1[i$1];
14381
14382 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
14383 }
14384 break
14385
14386 default:
14387 this.checkLValSimple(expr, bindingType, checkClashes);
14388 }
14389};
14390
14391pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
14392 if ( bindingType === void 0 ) bindingType = BIND_NONE;
14393
14394 switch (expr.type) {
14395 case "Property":
14396 // AssignmentProperty has type === "Property"
14397 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
14398 break
14399
14400 case "AssignmentPattern":
14401 this.checkLValPattern(expr.left, bindingType, checkClashes);
14402 break
14403
14404 case "RestElement":
14405 this.checkLValPattern(expr.argument, bindingType, checkClashes);
14406 break
14407
14408 default:
14409 this.checkLValPattern(expr, bindingType, checkClashes);
14410 }
14411};
14412
14413// A recursive descent parser operates by defining functions for all
14414
14415var pp$3 = Parser.prototype;
14416
14417// Check if property name clashes with already added.
14418// Object/class getters and setters are not allowed to clash —
14419// either with each other or with an init property — and in
14420// strict mode, init properties are also not allowed to be repeated.
14421
14422pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
14423 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
14424 { return }
14425 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
14426 { return }
14427 var key = prop.key;
14428 var name;
14429 switch (key.type) {
14430 case "Identifier": name = key.name; break
14431 case "Literal": name = String(key.value); break
14432 default: return
14433 }
14434 var kind = prop.kind;
14435 if (this.options.ecmaVersion >= 6) {
14436 if (name === "__proto__" && kind === "init") {
14437 if (propHash.proto) {
14438 if (refDestructuringErrors) {
14439 if (refDestructuringErrors.doubleProto < 0)
14440 { refDestructuringErrors.doubleProto = key.start; }
14441 // Backwards-compat kludge. Can be removed in version 6.0
14442 } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
14443 }
14444 propHash.proto = true;
14445 }
14446 return
14447 }
14448 name = "$" + name;
14449 var other = propHash[name];
14450 if (other) {
14451 var redefinition;
14452 if (kind === "init") {
14453 redefinition = this.strict && other.init || other.get || other.set;
14454 } else {
14455 redefinition = other.init || other[kind];
14456 }
14457 if (redefinition)
14458 { this.raiseRecoverable(key.start, "Redefinition of property"); }
14459 } else {
14460 other = propHash[name] = {
14461 init: false,
14462 get: false,
14463 set: false
14464 };
14465 }
14466 other[kind] = true;
14467};
14468
14469// ### Expression parsing
14470
14471// These nest, from the most general expression type at the top to
14472// 'atomic', nondivisible expression types at the bottom. Most of
14473// the functions will simply let the function(s) below them parse,
14474// and, *if* the syntactic construct they handle is present, wrap
14475// the AST node that the inner parser gave them in another node.
14476
14477// Parse a full expression. The optional arguments are used to
14478// forbid the `in` operator (in for loops initalization expressions)
14479// and provide reference for storing '=' operator inside shorthand
14480// property assignment in contexts where both object expression
14481// and object pattern might appear (so it's possible to raise
14482// delayed syntax error at correct position).
14483
14484pp$3.parseExpression = function(noIn, refDestructuringErrors) {
14485 var startPos = this.start, startLoc = this.startLoc;
14486 var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
14487 if (this.type === types.comma) {
14488 var node = this.startNodeAt(startPos, startLoc);
14489 node.expressions = [expr];
14490 while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
14491 return this.finishNode(node, "SequenceExpression")
14492 }
14493 return expr
14494};
14495
14496// Parse an assignment expression. This includes applications of
14497// operators like `+=`.
14498
14499pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
14500 if (this.isContextual("yield")) {
14501 if (this.inGenerator) { return this.parseYield(noIn) }
14502 // The tokenizer will assume an expression is allowed after
14503 // `yield`, but this isn't that kind of yield
14504 else { this.exprAllowed = false; }
14505 }
14506
14507 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
14508 if (refDestructuringErrors) {
14509 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
14510 oldTrailingComma = refDestructuringErrors.trailingComma;
14511 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
14512 } else {
14513 refDestructuringErrors = new DestructuringErrors;
14514 ownDestructuringErrors = true;
14515 }
14516
14517 var startPos = this.start, startLoc = this.startLoc;
14518 if (this.type === types.parenL || this.type === types.name)
14519 { this.potentialArrowAt = this.start; }
14520 var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
14521 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
14522 if (this.type.isAssign) {
14523 var node = this.startNodeAt(startPos, startLoc);
14524 node.operator = this.value;
14525 if (this.type === types.eq)
14526 { left = this.toAssignable(left, false, refDestructuringErrors); }
14527 if (!ownDestructuringErrors) {
14528 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
14529 }
14530 if (refDestructuringErrors.shorthandAssign >= left.start)
14531 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
14532 if (this.type === types.eq)
14533 { this.checkLValPattern(left); }
14534 else
14535 { this.checkLValSimple(left); }
14536 node.left = left;
14537 this.next();
14538 node.right = this.parseMaybeAssign(noIn);
14539 return this.finishNode(node, "AssignmentExpression")
14540 } else {
14541 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
14542 }
14543 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
14544 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
14545 return left
14546};
14547
14548// Parse a ternary conditional (`?:`) operator.
14549
14550pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
14551 var startPos = this.start, startLoc = this.startLoc;
14552 var expr = this.parseExprOps(noIn, refDestructuringErrors);
14553 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
14554 if (this.eat(types.question)) {
14555 var node = this.startNodeAt(startPos, startLoc);
14556 node.test = expr;
14557 node.consequent = this.parseMaybeAssign();
14558 this.expect(types.colon);
14559 node.alternate = this.parseMaybeAssign(noIn);
14560 return this.finishNode(node, "ConditionalExpression")
14561 }
14562 return expr
14563};
14564
14565// Start the precedence parser.
14566
14567pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
14568 var startPos = this.start, startLoc = this.startLoc;
14569 var expr = this.parseMaybeUnary(refDestructuringErrors, false);
14570 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
14571 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
14572};
14573
14574// Parse binary operators with the operator precedence parsing
14575// algorithm. `left` is the left-hand side of the operator.
14576// `minPrec` provides context that allows the function to stop and
14577// defer further parser to one of its callers when it encounters an
14578// operator that has a lower precedence than the set it is parsing.
14579
14580pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
14581 var prec = this.type.binop;
14582 if (prec != null && (!noIn || this.type !== types._in)) {
14583 if (prec > minPrec) {
14584 var logical = this.type === types.logicalOR || this.type === types.logicalAND;
14585 var coalesce = this.type === types.coalesce;
14586 if (coalesce) {
14587 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
14588 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
14589 prec = types.logicalAND.binop;
14590 }
14591 var op = this.value;
14592 this.next();
14593 var startPos = this.start, startLoc = this.startLoc;
14594 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
14595 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
14596 if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
14597 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
14598 }
14599 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
14600 }
14601 }
14602 return left
14603};
14604
14605pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
14606 var node = this.startNodeAt(startPos, startLoc);
14607 node.left = left;
14608 node.operator = op;
14609 node.right = right;
14610 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
14611};
14612
14613// Parse unary operators, both prefix and postfix.
14614
14615pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
14616 var startPos = this.start, startLoc = this.startLoc, expr;
14617 if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
14618 expr = this.parseAwait();
14619 sawUnary = true;
14620 } else if (this.type.prefix) {
14621 var node = this.startNode(), update = this.type === types.incDec;
14622 node.operator = this.value;
14623 node.prefix = true;
14624 this.next();
14625 node.argument = this.parseMaybeUnary(null, true);
14626 this.checkExpressionErrors(refDestructuringErrors, true);
14627 if (update) { this.checkLValSimple(node.argument); }
14628 else if (this.strict && node.operator === "delete" &&
14629 node.argument.type === "Identifier")
14630 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
14631 else { sawUnary = true; }
14632 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
14633 } else {
14634 expr = this.parseExprSubscripts(refDestructuringErrors);
14635 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
14636 while (this.type.postfix && !this.canInsertSemicolon()) {
14637 var node$1 = this.startNodeAt(startPos, startLoc);
14638 node$1.operator = this.value;
14639 node$1.prefix = false;
14640 node$1.argument = expr;
14641 this.checkLValSimple(expr);
14642 this.next();
14643 expr = this.finishNode(node$1, "UpdateExpression");
14644 }
14645 }
14646
14647 if (!sawUnary && this.eat(types.starstar))
14648 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
14649 else
14650 { return expr }
14651};
14652
14653// Parse call, dot, and `[]`-subscript expressions.
14654
14655pp$3.parseExprSubscripts = function(refDestructuringErrors) {
14656 var startPos = this.start, startLoc = this.startLoc;
14657 var expr = this.parseExprAtom(refDestructuringErrors);
14658 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
14659 { return expr }
14660 var result = this.parseSubscripts(expr, startPos, startLoc);
14661 if (refDestructuringErrors && result.type === "MemberExpression") {
14662 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
14663 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
14664 }
14665 return result
14666};
14667
14668pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
14669 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
14670 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
14671 this.potentialArrowAt === base.start;
14672 var optionalChained = false;
14673
14674 while (true) {
14675 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
14676
14677 if (element.optional) { optionalChained = true; }
14678 if (element === base || element.type === "ArrowFunctionExpression") {
14679 if (optionalChained) {
14680 var chainNode = this.startNodeAt(startPos, startLoc);
14681 chainNode.expression = element;
14682 element = this.finishNode(chainNode, "ChainExpression");
14683 }
14684 return element
14685 }
14686
14687 base = element;
14688 }
14689};
14690
14691pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
14692 var optionalSupported = this.options.ecmaVersion >= 11;
14693 var optional = optionalSupported && this.eat(types.questionDot);
14694 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
14695
14696 var computed = this.eat(types.bracketL);
14697 if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
14698 var node = this.startNodeAt(startPos, startLoc);
14699 node.object = base;
14700 node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
14701 node.computed = !!computed;
14702 if (computed) { this.expect(types.bracketR); }
14703 if (optionalSupported) {
14704 node.optional = optional;
14705 }
14706 base = this.finishNode(node, "MemberExpression");
14707 } else if (!noCalls && this.eat(types.parenL)) {
14708 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
14709 this.yieldPos = 0;
14710 this.awaitPos = 0;
14711 this.awaitIdentPos = 0;
14712 var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
14713 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
14714 this.checkPatternErrors(refDestructuringErrors, false);
14715 this.checkYieldAwaitInDefaultParams();
14716 if (this.awaitIdentPos > 0)
14717 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
14718 this.yieldPos = oldYieldPos;
14719 this.awaitPos = oldAwaitPos;
14720 this.awaitIdentPos = oldAwaitIdentPos;
14721 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
14722 }
14723 this.checkExpressionErrors(refDestructuringErrors, true);
14724 this.yieldPos = oldYieldPos || this.yieldPos;
14725 this.awaitPos = oldAwaitPos || this.awaitPos;
14726 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
14727 var node$1 = this.startNodeAt(startPos, startLoc);
14728 node$1.callee = base;
14729 node$1.arguments = exprList;
14730 if (optionalSupported) {
14731 node$1.optional = optional;
14732 }
14733 base = this.finishNode(node$1, "CallExpression");
14734 } else if (this.type === types.backQuote) {
14735 if (optional || optionalChained) {
14736 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
14737 }
14738 var node$2 = this.startNodeAt(startPos, startLoc);
14739 node$2.tag = base;
14740 node$2.quasi = this.parseTemplate({isTagged: true});
14741 base = this.finishNode(node$2, "TaggedTemplateExpression");
14742 }
14743 return base
14744};
14745
14746// Parse an atomic expression — either a single token that is an
14747// expression, an expression started by a keyword like `function` or
14748// `new`, or an expression wrapped in punctuation like `()`, `[]`,
14749// or `{}`.
14750
14751pp$3.parseExprAtom = function(refDestructuringErrors) {
14752 // If a division operator appears in an expression position, the
14753 // tokenizer got confused, and we force it to read a regexp instead.
14754 if (this.type === types.slash) { this.readRegexp(); }
14755
14756 var node, canBeArrow = this.potentialArrowAt === this.start;
14757 switch (this.type) {
14758 case types._super:
14759 if (!this.allowSuper)
14760 { this.raise(this.start, "'super' keyword outside a method"); }
14761 node = this.startNode();
14762 this.next();
14763 if (this.type === types.parenL && !this.allowDirectSuper)
14764 { this.raise(node.start, "super() call outside constructor of a subclass"); }
14765 // The `super` keyword can appear at below:
14766 // SuperProperty:
14767 // super [ Expression ]
14768 // super . IdentifierName
14769 // SuperCall:
14770 // super ( Arguments )
14771 if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
14772 { this.unexpected(); }
14773 return this.finishNode(node, "Super")
14774
14775 case types._this:
14776 node = this.startNode();
14777 this.next();
14778 return this.finishNode(node, "ThisExpression")
14779
14780 case types.name:
14781 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
14782 var id = this.parseIdent(false);
14783 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
14784 { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
14785 if (canBeArrow && !this.canInsertSemicolon()) {
14786 if (this.eat(types.arrow))
14787 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
14788 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
14789 id = this.parseIdent(false);
14790 if (this.canInsertSemicolon() || !this.eat(types.arrow))
14791 { this.unexpected(); }
14792 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
14793 }
14794 }
14795 return id
14796
14797 case types.regexp:
14798 var value = this.value;
14799 node = this.parseLiteral(value.value);
14800 node.regex = {pattern: value.pattern, flags: value.flags};
14801 return node
14802
14803 case types.num: case types.string:
14804 return this.parseLiteral(this.value)
14805
14806 case types._null: case types._true: case types._false:
14807 node = this.startNode();
14808 node.value = this.type === types._null ? null : this.type === types._true;
14809 node.raw = this.type.keyword;
14810 this.next();
14811 return this.finishNode(node, "Literal")
14812
14813 case types.parenL:
14814 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
14815 if (refDestructuringErrors) {
14816 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
14817 { refDestructuringErrors.parenthesizedAssign = start; }
14818 if (refDestructuringErrors.parenthesizedBind < 0)
14819 { refDestructuringErrors.parenthesizedBind = start; }
14820 }
14821 return expr
14822
14823 case types.bracketL:
14824 node = this.startNode();
14825 this.next();
14826 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
14827 return this.finishNode(node, "ArrayExpression")
14828
14829 case types.braceL:
14830 return this.parseObj(false, refDestructuringErrors)
14831
14832 case types._function:
14833 node = this.startNode();
14834 this.next();
14835 return this.parseFunction(node, 0)
14836
14837 case types._class:
14838 return this.parseClass(this.startNode(), false)
14839
14840 case types._new:
14841 return this.parseNew()
14842
14843 case types.backQuote:
14844 return this.parseTemplate()
14845
14846 case types._import:
14847 if (this.options.ecmaVersion >= 11) {
14848 return this.parseExprImport()
14849 } else {
14850 return this.unexpected()
14851 }
14852
14853 default:
14854 this.unexpected();
14855 }
14856};
14857
14858pp$3.parseExprImport = function() {
14859 var node = this.startNode();
14860
14861 // Consume `import` as an identifier for `import.meta`.
14862 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
14863 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
14864 var meta = this.parseIdent(true);
14865
14866 switch (this.type) {
14867 case types.parenL:
14868 return this.parseDynamicImport(node)
14869 case types.dot:
14870 node.meta = meta;
14871 return this.parseImportMeta(node)
14872 default:
14873 this.unexpected();
14874 }
14875};
14876
14877pp$3.parseDynamicImport = function(node) {
14878 this.next(); // skip `(`
14879
14880 // Parse node.source.
14881 node.source = this.parseMaybeAssign();
14882
14883 // Verify ending.
14884 if (!this.eat(types.parenR)) {
14885 var errorPos = this.start;
14886 if (this.eat(types.comma) && this.eat(types.parenR)) {
14887 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
14888 } else {
14889 this.unexpected(errorPos);
14890 }
14891 }
14892
14893 return this.finishNode(node, "ImportExpression")
14894};
14895
14896pp$3.parseImportMeta = function(node) {
14897 this.next(); // skip `.`
14898
14899 var containsEsc = this.containsEsc;
14900 node.property = this.parseIdent(true);
14901
14902 if (node.property.name !== "meta")
14903 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
14904 if (containsEsc)
14905 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
14906 if (this.options.sourceType !== "module")
14907 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
14908
14909 return this.finishNode(node, "MetaProperty")
14910};
14911
14912pp$3.parseLiteral = function(value) {
14913 var node = this.startNode();
14914 node.value = value;
14915 node.raw = this.input.slice(this.start, this.end);
14916 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
14917 this.next();
14918 return this.finishNode(node, "Literal")
14919};
14920
14921pp$3.parseParenExpression = function() {
14922 this.expect(types.parenL);
14923 var val = this.parseExpression();
14924 this.expect(types.parenR);
14925 return val
14926};
14927
14928pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
14929 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
14930 if (this.options.ecmaVersion >= 6) {
14931 this.next();
14932
14933 var innerStartPos = this.start, innerStartLoc = this.startLoc;
14934 var exprList = [], first = true, lastIsComma = false;
14935 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
14936 this.yieldPos = 0;
14937 this.awaitPos = 0;
14938 // Do not save awaitIdentPos to allow checking awaits nested in parameters
14939 while (this.type !== types.parenR) {
14940 first ? first = false : this.expect(types.comma);
14941 if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
14942 lastIsComma = true;
14943 break
14944 } else if (this.type === types.ellipsis) {
14945 spreadStart = this.start;
14946 exprList.push(this.parseParenItem(this.parseRestBinding()));
14947 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
14948 break
14949 } else {
14950 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
14951 }
14952 }
14953 var innerEndPos = this.start, innerEndLoc = this.startLoc;
14954 this.expect(types.parenR);
14955
14956 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
14957 this.checkPatternErrors(refDestructuringErrors, false);
14958 this.checkYieldAwaitInDefaultParams();
14959 this.yieldPos = oldYieldPos;
14960 this.awaitPos = oldAwaitPos;
14961 return this.parseParenArrowList(startPos, startLoc, exprList)
14962 }
14963
14964 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
14965 if (spreadStart) { this.unexpected(spreadStart); }
14966 this.checkExpressionErrors(refDestructuringErrors, true);
14967 this.yieldPos = oldYieldPos || this.yieldPos;
14968 this.awaitPos = oldAwaitPos || this.awaitPos;
14969
14970 if (exprList.length > 1) {
14971 val = this.startNodeAt(innerStartPos, innerStartLoc);
14972 val.expressions = exprList;
14973 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
14974 } else {
14975 val = exprList[0];
14976 }
14977 } else {
14978 val = this.parseParenExpression();
14979 }
14980
14981 if (this.options.preserveParens) {
14982 var par = this.startNodeAt(startPos, startLoc);
14983 par.expression = val;
14984 return this.finishNode(par, "ParenthesizedExpression")
14985 } else {
14986 return val
14987 }
14988};
14989
14990pp$3.parseParenItem = function(item) {
14991 return item
14992};
14993
14994pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
14995 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
14996};
14997
14998// New's precedence is slightly tricky. It must allow its argument to
14999// be a `[]` or dot subscript expression, but not a call — at least,
15000// not without wrapping it in parentheses. Thus, it uses the noCalls
15001// argument to parseSubscripts to prevent it from consuming the
15002// argument list.
15003
15004var empty$1 = [];
15005
15006pp$3.parseNew = function() {
15007 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
15008 var node = this.startNode();
15009 var meta = this.parseIdent(true);
15010 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
15011 node.meta = meta;
15012 var containsEsc = this.containsEsc;
15013 node.property = this.parseIdent(true);
15014 if (node.property.name !== "target")
15015 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
15016 if (containsEsc)
15017 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
15018 if (!this.inNonArrowFunction)
15019 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
15020 return this.finishNode(node, "MetaProperty")
15021 }
15022 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
15023 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
15024 if (isImport && node.callee.type === "ImportExpression") {
15025 this.raise(startPos, "Cannot use new with import()");
15026 }
15027 if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
15028 else { node.arguments = empty$1; }
15029 return this.finishNode(node, "NewExpression")
15030};
15031
15032// Parse template expression.
15033
15034pp$3.parseTemplateElement = function(ref) {
15035 var isTagged = ref.isTagged;
15036
15037 var elem = this.startNode();
15038 if (this.type === types.invalidTemplate) {
15039 if (!isTagged) {
15040 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
15041 }
15042 elem.value = {
15043 raw: this.value,
15044 cooked: null
15045 };
15046 } else {
15047 elem.value = {
15048 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
15049 cooked: this.value
15050 };
15051 }
15052 this.next();
15053 elem.tail = this.type === types.backQuote;
15054 return this.finishNode(elem, "TemplateElement")
15055};
15056
15057pp$3.parseTemplate = function(ref) {
15058 if ( ref === void 0 ) ref = {};
15059 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
15060
15061 var node = this.startNode();
15062 this.next();
15063 node.expressions = [];
15064 var curElt = this.parseTemplateElement({isTagged: isTagged});
15065 node.quasis = [curElt];
15066 while (!curElt.tail) {
15067 if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
15068 this.expect(types.dollarBraceL);
15069 node.expressions.push(this.parseExpression());
15070 this.expect(types.braceR);
15071 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
15072 }
15073 this.next();
15074 return this.finishNode(node, "TemplateLiteral")
15075};
15076
15077pp$3.isAsyncProp = function(prop) {
15078 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
15079 (this.type === types.name || this.type === types.num || this.type === types.string || this.type === types.bracketL || this.type.keyword || (this.options.ecmaVersion >= 9 && this.type === types.star)) &&
15080 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
15081};
15082
15083// Parse an object literal or binding pattern.
15084
15085pp$3.parseObj = function(isPattern, refDestructuringErrors) {
15086 var node = this.startNode(), first = true, propHash = {};
15087 node.properties = [];
15088 this.next();
15089 while (!this.eat(types.braceR)) {
15090 if (!first) {
15091 this.expect(types.comma);
15092 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
15093 } else { first = false; }
15094
15095 var prop = this.parseProperty(isPattern, refDestructuringErrors);
15096 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
15097 node.properties.push(prop);
15098 }
15099 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
15100};
15101
15102pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
15103 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
15104 if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
15105 if (isPattern) {
15106 prop.argument = this.parseIdent(false);
15107 if (this.type === types.comma) {
15108 this.raise(this.start, "Comma is not permitted after the rest element");
15109 }
15110 return this.finishNode(prop, "RestElement")
15111 }
15112 // To disallow parenthesized identifier via `this.toAssignable()`.
15113 if (this.type === types.parenL && refDestructuringErrors) {
15114 if (refDestructuringErrors.parenthesizedAssign < 0) {
15115 refDestructuringErrors.parenthesizedAssign = this.start;
15116 }
15117 if (refDestructuringErrors.parenthesizedBind < 0) {
15118 refDestructuringErrors.parenthesizedBind = this.start;
15119 }
15120 }
15121 // Parse argument.
15122 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
15123 // To disallow trailing comma via `this.toAssignable()`.
15124 if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
15125 refDestructuringErrors.trailingComma = this.start;
15126 }
15127 // Finish
15128 return this.finishNode(prop, "SpreadElement")
15129 }
15130 if (this.options.ecmaVersion >= 6) {
15131 prop.method = false;
15132 prop.shorthand = false;
15133 if (isPattern || refDestructuringErrors) {
15134 startPos = this.start;
15135 startLoc = this.startLoc;
15136 }
15137 if (!isPattern)
15138 { isGenerator = this.eat(types.star); }
15139 }
15140 var containsEsc = this.containsEsc;
15141 this.parsePropertyName(prop);
15142 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
15143 isAsync = true;
15144 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
15145 this.parsePropertyName(prop, refDestructuringErrors);
15146 } else {
15147 isAsync = false;
15148 }
15149 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
15150 return this.finishNode(prop, "Property")
15151};
15152
15153pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
15154 if ((isGenerator || isAsync) && this.type === types.colon)
15155 { this.unexpected(); }
15156
15157 if (this.eat(types.colon)) {
15158 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
15159 prop.kind = "init";
15160 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
15161 if (isPattern) { this.unexpected(); }
15162 prop.kind = "init";
15163 prop.method = true;
15164 prop.value = this.parseMethod(isGenerator, isAsync);
15165 } else if (!isPattern && !containsEsc &&
15166 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
15167 (prop.key.name === "get" || prop.key.name === "set") &&
15168 (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
15169 if (isGenerator || isAsync) { this.unexpected(); }
15170 prop.kind = prop.key.name;
15171 this.parsePropertyName(prop);
15172 prop.value = this.parseMethod(false);
15173 var paramCount = prop.kind === "get" ? 0 : 1;
15174 if (prop.value.params.length !== paramCount) {
15175 var start = prop.value.start;
15176 if (prop.kind === "get")
15177 { this.raiseRecoverable(start, "getter should have no params"); }
15178 else
15179 { this.raiseRecoverable(start, "setter should have exactly one param"); }
15180 } else {
15181 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
15182 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
15183 }
15184 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
15185 if (isGenerator || isAsync) { this.unexpected(); }
15186 this.checkUnreserved(prop.key);
15187 if (prop.key.name === "await" && !this.awaitIdentPos)
15188 { this.awaitIdentPos = startPos; }
15189 prop.kind = "init";
15190 if (isPattern) {
15191 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
15192 } else if (this.type === types.eq && refDestructuringErrors) {
15193 if (refDestructuringErrors.shorthandAssign < 0)
15194 { refDestructuringErrors.shorthandAssign = this.start; }
15195 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
15196 } else {
15197 prop.value = this.copyNode(prop.key);
15198 }
15199 prop.shorthand = true;
15200 } else { this.unexpected(); }
15201};
15202
15203pp$3.parsePropertyName = function(prop) {
15204 if (this.options.ecmaVersion >= 6) {
15205 if (this.eat(types.bracketL)) {
15206 prop.computed = true;
15207 prop.key = this.parseMaybeAssign();
15208 this.expect(types.bracketR);
15209 return prop.key
15210 } else {
15211 prop.computed = false;
15212 }
15213 }
15214 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
15215};
15216
15217// Initialize empty function node.
15218
15219pp$3.initFunction = function(node) {
15220 node.id = null;
15221 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
15222 if (this.options.ecmaVersion >= 8) { node.async = false; }
15223};
15224
15225// Parse object or class method.
15226
15227pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
15228 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
15229
15230 this.initFunction(node);
15231 if (this.options.ecmaVersion >= 6)
15232 { node.generator = isGenerator; }
15233 if (this.options.ecmaVersion >= 8)
15234 { node.async = !!isAsync; }
15235
15236 this.yieldPos = 0;
15237 this.awaitPos = 0;
15238 this.awaitIdentPos = 0;
15239 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
15240
15241 this.expect(types.parenL);
15242 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
15243 this.checkYieldAwaitInDefaultParams();
15244 this.parseFunctionBody(node, false, true);
15245
15246 this.yieldPos = oldYieldPos;
15247 this.awaitPos = oldAwaitPos;
15248 this.awaitIdentPos = oldAwaitIdentPos;
15249 return this.finishNode(node, "FunctionExpression")
15250};
15251
15252// Parse arrow function expression with given parameters.
15253
15254pp$3.parseArrowExpression = function(node, params, isAsync) {
15255 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
15256
15257 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
15258 this.initFunction(node);
15259 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
15260
15261 this.yieldPos = 0;
15262 this.awaitPos = 0;
15263 this.awaitIdentPos = 0;
15264
15265 node.params = this.toAssignableList(params, true);
15266 this.parseFunctionBody(node, true, false);
15267
15268 this.yieldPos = oldYieldPos;
15269 this.awaitPos = oldAwaitPos;
15270 this.awaitIdentPos = oldAwaitIdentPos;
15271 return this.finishNode(node, "ArrowFunctionExpression")
15272};
15273
15274// Parse function body and check parameters.
15275
15276pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
15277 var isExpression = isArrowFunction && this.type !== types.braceL;
15278 var oldStrict = this.strict, useStrict = false;
15279
15280 if (isExpression) {
15281 node.body = this.parseMaybeAssign();
15282 node.expression = true;
15283 this.checkParams(node, false);
15284 } else {
15285 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
15286 if (!oldStrict || nonSimple) {
15287 useStrict = this.strictDirective(this.end);
15288 // If this is a strict mode function, verify that argument names
15289 // are not repeated, and it does not try to bind the words `eval`
15290 // or `arguments`.
15291 if (useStrict && nonSimple)
15292 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
15293 }
15294 // Start a new scope with regard to labels and the `inFunction`
15295 // flag (restore them to their old value afterwards).
15296 var oldLabels = this.labels;
15297 this.labels = [];
15298 if (useStrict) { this.strict = true; }
15299
15300 // Add the params to varDeclaredNames to ensure that an error is thrown
15301 // if a let/const declaration in the function clashes with one of the params.
15302 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
15303 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
15304 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
15305 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
15306 node.expression = false;
15307 this.adaptDirectivePrologue(node.body.body);
15308 this.labels = oldLabels;
15309 }
15310 this.exitScope();
15311};
15312
15313pp$3.isSimpleParamList = function(params) {
15314 for (var i = 0, list = params; i < list.length; i += 1)
15315 {
15316 var param = list[i];
15317
15318 if (param.type !== "Identifier") { return false
15319 } }
15320 return true
15321};
15322
15323// Checks function params for various disallowed patterns such as using "eval"
15324// or "arguments" and duplicate parameters.
15325
15326pp$3.checkParams = function(node, allowDuplicates) {
15327 var nameHash = {};
15328 for (var i = 0, list = node.params; i < list.length; i += 1)
15329 {
15330 var param = list[i];
15331
15332 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
15333 }
15334};
15335
15336// Parses a comma-separated list of expressions, and returns them as
15337// an array. `close` is the token type that ends the list, and
15338// `allowEmpty` can be turned on to allow subsequent commas with
15339// nothing in between them to be parsed as `null` (which is needed
15340// for array literals).
15341
15342pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
15343 var elts = [], first = true;
15344 while (!this.eat(close)) {
15345 if (!first) {
15346 this.expect(types.comma);
15347 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
15348 } else { first = false; }
15349
15350 var elt = (void 0);
15351 if (allowEmpty && this.type === types.comma)
15352 { elt = null; }
15353 else if (this.type === types.ellipsis) {
15354 elt = this.parseSpread(refDestructuringErrors);
15355 if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
15356 { refDestructuringErrors.trailingComma = this.start; }
15357 } else {
15358 elt = this.parseMaybeAssign(false, refDestructuringErrors);
15359 }
15360 elts.push(elt);
15361 }
15362 return elts
15363};
15364
15365pp$3.checkUnreserved = function(ref) {
15366 var start = ref.start;
15367 var end = ref.end;
15368 var name = ref.name;
15369
15370 if (this.inGenerator && name === "yield")
15371 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
15372 if (this.inAsync && name === "await")
15373 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
15374 if (this.keywords.test(name))
15375 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
15376 if (this.options.ecmaVersion < 6 &&
15377 this.input.slice(start, end).indexOf("\\") !== -1) { return }
15378 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
15379 if (re.test(name)) {
15380 if (!this.inAsync && name === "await")
15381 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
15382 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
15383 }
15384};
15385
15386// Parse the next token as an identifier. If `liberal` is true (used
15387// when parsing properties), it will also convert keywords into
15388// identifiers.
15389
15390pp$3.parseIdent = function(liberal, isBinding) {
15391 var node = this.startNode();
15392 if (this.type === types.name) {
15393 node.name = this.value;
15394 } else if (this.type.keyword) {
15395 node.name = this.type.keyword;
15396
15397 // To fix https://github.com/acornjs/acorn/issues/575
15398 // `class` and `function` keywords push new context into this.context.
15399 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
15400 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
15401 if ((node.name === "class" || node.name === "function") &&
15402 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
15403 this.context.pop();
15404 }
15405 } else {
15406 this.unexpected();
15407 }
15408 this.next(!!liberal);
15409 this.finishNode(node, "Identifier");
15410 if (!liberal) {
15411 this.checkUnreserved(node);
15412 if (node.name === "await" && !this.awaitIdentPos)
15413 { this.awaitIdentPos = node.start; }
15414 }
15415 return node
15416};
15417
15418// Parses yield expression inside generator.
15419
15420pp$3.parseYield = function(noIn) {
15421 if (!this.yieldPos) { this.yieldPos = this.start; }
15422
15423 var node = this.startNode();
15424 this.next();
15425 if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
15426 node.delegate = false;
15427 node.argument = null;
15428 } else {
15429 node.delegate = this.eat(types.star);
15430 node.argument = this.parseMaybeAssign(noIn);
15431 }
15432 return this.finishNode(node, "YieldExpression")
15433};
15434
15435pp$3.parseAwait = function() {
15436 if (!this.awaitPos) { this.awaitPos = this.start; }
15437
15438 var node = this.startNode();
15439 this.next();
15440 node.argument = this.parseMaybeUnary(null, false);
15441 return this.finishNode(node, "AwaitExpression")
15442};
15443
15444var pp$4 = Parser.prototype;
15445
15446// This function is used to raise exceptions on parse errors. It
15447// takes an offset integer (into the current `input`) to indicate
15448// the location of the error, attaches the position to the end
15449// of the error message, and then raises a `SyntaxError` with that
15450// message.
15451
15452pp$4.raise = function(pos, message) {
15453 var loc = getLineInfo(this.input, pos);
15454 message += " (" + loc.line + ":" + loc.column + ")";
15455 var err = new SyntaxError(message);
15456 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
15457 throw err
15458};
15459
15460pp$4.raiseRecoverable = pp$4.raise;
15461
15462pp$4.curPosition = function() {
15463 if (this.options.locations) {
15464 return new Position(this.curLine, this.pos - this.lineStart)
15465 }
15466};
15467
15468var pp$5 = Parser.prototype;
15469
15470var Scope$1 = function Scope(flags) {
15471 this.flags = flags;
15472 // A list of var-declared names in the current lexical scope
15473 this.var = [];
15474 // A list of lexically-declared names in the current lexical scope
15475 this.lexical = [];
15476 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
15477 this.functions = [];
15478};
15479
15480// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
15481
15482pp$5.enterScope = function(flags) {
15483 this.scopeStack.push(new Scope$1(flags));
15484};
15485
15486pp$5.exitScope = function() {
15487 this.scopeStack.pop();
15488};
15489
15490// The spec says:
15491// > At the top level of a function, or script, function declarations are
15492// > treated like var declarations rather than like lexical declarations.
15493pp$5.treatFunctionsAsVarInScope = function(scope) {
15494 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
15495};
15496
15497pp$5.declareName = function(name, bindingType, pos) {
15498 var redeclared = false;
15499 if (bindingType === BIND_LEXICAL) {
15500 var scope = this.currentScope();
15501 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
15502 scope.lexical.push(name);
15503 if (this.inModule && (scope.flags & SCOPE_TOP))
15504 { delete this.undefinedExports[name]; }
15505 } else if (bindingType === BIND_SIMPLE_CATCH) {
15506 var scope$1 = this.currentScope();
15507 scope$1.lexical.push(name);
15508 } else if (bindingType === BIND_FUNCTION) {
15509 var scope$2 = this.currentScope();
15510 if (this.treatFunctionsAsVar)
15511 { redeclared = scope$2.lexical.indexOf(name) > -1; }
15512 else
15513 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
15514 scope$2.functions.push(name);
15515 } else {
15516 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
15517 var scope$3 = this.scopeStack[i];
15518 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
15519 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
15520 redeclared = true;
15521 break
15522 }
15523 scope$3.var.push(name);
15524 if (this.inModule && (scope$3.flags & SCOPE_TOP))
15525 { delete this.undefinedExports[name]; }
15526 if (scope$3.flags & SCOPE_VAR) { break }
15527 }
15528 }
15529 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
15530};
15531
15532pp$5.checkLocalExport = function(id) {
15533 // scope.functions must be empty as Module code is always strict.
15534 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
15535 this.scopeStack[0].var.indexOf(id.name) === -1) {
15536 this.undefinedExports[id.name] = id;
15537 }
15538};
15539
15540pp$5.currentScope = function() {
15541 return this.scopeStack[this.scopeStack.length - 1]
15542};
15543
15544pp$5.currentVarScope = function() {
15545 for (var i = this.scopeStack.length - 1;; i--) {
15546 var scope = this.scopeStack[i];
15547 if (scope.flags & SCOPE_VAR) { return scope }
15548 }
15549};
15550
15551// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
15552pp$5.currentThisScope = function() {
15553 for (var i = this.scopeStack.length - 1;; i--) {
15554 var scope = this.scopeStack[i];
15555 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
15556 }
15557};
15558
15559var Node = function Node(parser, pos, loc) {
15560 this.type = "";
15561 this.start = pos;
15562 this.end = 0;
15563 if (parser.options.locations)
15564 { this.loc = new SourceLocation(parser, loc); }
15565 if (parser.options.directSourceFile)
15566 { this.sourceFile = parser.options.directSourceFile; }
15567 if (parser.options.ranges)
15568 { this.range = [pos, 0]; }
15569};
15570
15571// Start an AST node, attaching a start offset.
15572
15573var pp$6 = Parser.prototype;
15574
15575pp$6.startNode = function() {
15576 return new Node(this, this.start, this.startLoc)
15577};
15578
15579pp$6.startNodeAt = function(pos, loc) {
15580 return new Node(this, pos, loc)
15581};
15582
15583// Finish an AST node, adding `type` and `end` properties.
15584
15585function finishNodeAt(node, type, pos, loc) {
15586 node.type = type;
15587 node.end = pos;
15588 if (this.options.locations)
15589 { node.loc.end = loc; }
15590 if (this.options.ranges)
15591 { node.range[1] = pos; }
15592 return node
15593}
15594
15595pp$6.finishNode = function(node, type) {
15596 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
15597};
15598
15599// Finish node at given position
15600
15601pp$6.finishNodeAt = function(node, type, pos, loc) {
15602 return finishNodeAt.call(this, node, type, pos, loc)
15603};
15604
15605pp$6.copyNode = function(node) {
15606 var newNode = new Node(this, node.start, this.startLoc);
15607 for (var prop in node) { newNode[prop] = node[prop]; }
15608 return newNode
15609};
15610
15611// The algorithm used to determine whether a regexp can appear at a
15612
15613var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
15614 this.token = token;
15615 this.isExpr = !!isExpr;
15616 this.preserveSpace = !!preserveSpace;
15617 this.override = override;
15618 this.generator = !!generator;
15619};
15620
15621var types$1 = {
15622 b_stat: new TokContext("{", false),
15623 b_expr: new TokContext("{", true),
15624 b_tmpl: new TokContext("${", false),
15625 p_stat: new TokContext("(", false),
15626 p_expr: new TokContext("(", true),
15627 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
15628 f_stat: new TokContext("function", false),
15629 f_expr: new TokContext("function", true),
15630 f_expr_gen: new TokContext("function", true, false, null, true),
15631 f_gen: new TokContext("function", false, false, null, true)
15632};
15633
15634var pp$7 = Parser.prototype;
15635
15636pp$7.initialContext = function() {
15637 return [types$1.b_stat]
15638};
15639
15640pp$7.braceIsBlock = function(prevType) {
15641 var parent = this.curContext();
15642 if (parent === types$1.f_expr || parent === types$1.f_stat)
15643 { return true }
15644 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
15645 { return !parent.isExpr }
15646
15647 // The check for `tt.name && exprAllowed` detects whether we are
15648 // after a `yield` or `of` construct. See the `updateContext` for
15649 // `tt.name`.
15650 if (prevType === types._return || prevType === types.name && this.exprAllowed)
15651 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
15652 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
15653 { return true }
15654 if (prevType === types.braceL)
15655 { return parent === types$1.b_stat }
15656 if (prevType === types._var || prevType === types._const || prevType === types.name)
15657 { return false }
15658 return !this.exprAllowed
15659};
15660
15661pp$7.inGeneratorContext = function() {
15662 for (var i = this.context.length - 1; i >= 1; i--) {
15663 var context = this.context[i];
15664 if (context.token === "function")
15665 { return context.generator }
15666 }
15667 return false
15668};
15669
15670pp$7.updateContext = function(prevType) {
15671 var update, type = this.type;
15672 if (type.keyword && prevType === types.dot)
15673 { this.exprAllowed = false; }
15674 else if (update = type.updateContext)
15675 { update.call(this, prevType); }
15676 else
15677 { this.exprAllowed = type.beforeExpr; }
15678};
15679
15680// Token-specific context update code
15681
15682types.parenR.updateContext = types.braceR.updateContext = function() {
15683 if (this.context.length === 1) {
15684 this.exprAllowed = true;
15685 return
15686 }
15687 var out = this.context.pop();
15688 if (out === types$1.b_stat && this.curContext().token === "function") {
15689 out = this.context.pop();
15690 }
15691 this.exprAllowed = !out.isExpr;
15692};
15693
15694types.braceL.updateContext = function(prevType) {
15695 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
15696 this.exprAllowed = true;
15697};
15698
15699types.dollarBraceL.updateContext = function() {
15700 this.context.push(types$1.b_tmpl);
15701 this.exprAllowed = true;
15702};
15703
15704types.parenL.updateContext = function(prevType) {
15705 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
15706 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
15707 this.exprAllowed = true;
15708};
15709
15710types.incDec.updateContext = function() {
15711 // tokExprAllowed stays unchanged
15712};
15713
15714types._function.updateContext = types._class.updateContext = function(prevType) {
15715 if (prevType.beforeExpr && prevType !== types._else &&
15716 !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
15717 !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
15718 !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
15719 { this.context.push(types$1.f_expr); }
15720 else
15721 { this.context.push(types$1.f_stat); }
15722 this.exprAllowed = false;
15723};
15724
15725types.backQuote.updateContext = function() {
15726 if (this.curContext() === types$1.q_tmpl)
15727 { this.context.pop(); }
15728 else
15729 { this.context.push(types$1.q_tmpl); }
15730 this.exprAllowed = false;
15731};
15732
15733types.star.updateContext = function(prevType) {
15734 if (prevType === types._function) {
15735 var index = this.context.length - 1;
15736 if (this.context[index] === types$1.f_expr)
15737 { this.context[index] = types$1.f_expr_gen; }
15738 else
15739 { this.context[index] = types$1.f_gen; }
15740 }
15741 this.exprAllowed = true;
15742};
15743
15744types.name.updateContext = function(prevType) {
15745 var allowed = false;
15746 if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
15747 if (this.value === "of" && !this.exprAllowed ||
15748 this.value === "yield" && this.inGeneratorContext())
15749 { allowed = true; }
15750 }
15751 this.exprAllowed = allowed;
15752};
15753
15754// This file contains Unicode properties extracted from the ECMAScript
15755// specification. The lists are extracted like so:
15756// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
15757
15758// #table-binary-unicode-properties
15759var ecma9BinaryProperties = "ASCII ASCII_Hex_Digit AHex Alphabetic Alpha Any Assigned Bidi_Control Bidi_C Bidi_Mirrored Bidi_M Case_Ignorable CI Cased Changes_When_Casefolded CWCF Changes_When_Casemapped CWCM Changes_When_Lowercased CWL Changes_When_NFKC_Casefolded CWKCF Changes_When_Titlecased CWT Changes_When_Uppercased CWU Dash Default_Ignorable_Code_Point DI Deprecated Dep Diacritic Dia Emoji Emoji_Component Emoji_Modifier Emoji_Modifier_Base Emoji_Presentation Extender Ext Grapheme_Base Gr_Base Grapheme_Extend Gr_Ext Hex_Digit Hex IDS_Binary_Operator IDSB IDS_Trinary_Operator IDST ID_Continue IDC ID_Start IDS Ideographic Ideo Join_Control Join_C Logical_Order_Exception LOE Lowercase Lower Math Noncharacter_Code_Point NChar Pattern_Syntax Pat_Syn Pattern_White_Space Pat_WS Quotation_Mark QMark Radical Regional_Indicator RI Sentence_Terminal STerm Soft_Dotted SD Terminal_Punctuation Term Unified_Ideograph UIdeo Uppercase Upper Variation_Selector VS White_Space space XID_Continue XIDC XID_Start XIDS";
15760var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
15761var ecma11BinaryProperties = ecma10BinaryProperties;
15762var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
15763var unicodeBinaryProperties = {
15764 9: ecma9BinaryProperties,
15765 10: ecma10BinaryProperties,
15766 11: ecma11BinaryProperties,
15767 12: ecma12BinaryProperties
15768};
15769
15770// #table-unicode-general-category-values
15771var unicodeGeneralCategoryValues = "Cased_Letter LC Close_Punctuation Pe Connector_Punctuation Pc Control Cc cntrl Currency_Symbol Sc Dash_Punctuation Pd Decimal_Number Nd digit Enclosing_Mark Me Final_Punctuation Pf Format Cf Initial_Punctuation Pi Letter L Letter_Number Nl Line_Separator Zl Lowercase_Letter Ll Mark M Combining_Mark Math_Symbol Sm Modifier_Letter Lm Modifier_Symbol Sk Nonspacing_Mark Mn Number N Open_Punctuation Ps Other C Other_Letter Lo Other_Number No Other_Punctuation Po Other_Symbol So Paragraph_Separator Zp Private_Use Co Punctuation P punct Separator Z Space_Separator Zs Spacing_Mark Mc Surrogate Cs Symbol S Titlecase_Letter Lt Unassigned Cn Uppercase_Letter Lu";
15772
15773// #table-unicode-script-values
15774var ecma9ScriptValues = "Adlam Adlm Ahom Ahom Anatolian_Hieroglyphs Hluw Arabic Arab Armenian Armn Avestan Avst Balinese Bali Bamum Bamu Bassa_Vah Bass Batak Batk Bengali Beng Bhaiksuki Bhks Bopomofo Bopo Brahmi Brah Braille Brai Buginese Bugi Buhid Buhd Canadian_Aboriginal Cans Carian Cari Caucasian_Albanian Aghb Chakma Cakm Cham Cham Cherokee Cher Common Zyyy Coptic Copt Qaac Cuneiform Xsux Cypriot Cprt Cyrillic Cyrl Deseret Dsrt Devanagari Deva Duployan Dupl Egyptian_Hieroglyphs Egyp Elbasan Elba Ethiopic Ethi Georgian Geor Glagolitic Glag Gothic Goth Grantha Gran Greek Grek Gujarati Gujr Gurmukhi Guru Han Hani Hangul Hang Hanunoo Hano Hatran Hatr Hebrew Hebr Hiragana Hira Imperial_Aramaic Armi Inherited Zinh Qaai Inscriptional_Pahlavi Phli Inscriptional_Parthian Prti Javanese Java Kaithi Kthi Kannada Knda Katakana Kana Kayah_Li Kali Kharoshthi Khar Khmer Khmr Khojki Khoj Khudawadi Sind Lao Laoo Latin Latn Lepcha Lepc Limbu Limb Linear_A Lina Linear_B Linb Lisu Lisu Lycian Lyci Lydian Lydi Mahajani Mahj Malayalam Mlym Mandaic Mand Manichaean Mani Marchen Marc Masaram_Gondi Gonm Meetei_Mayek Mtei Mende_Kikakui Mend Meroitic_Cursive Merc Meroitic_Hieroglyphs Mero Miao Plrd Modi Modi Mongolian Mong Mro Mroo Multani Mult Myanmar Mymr Nabataean Nbat New_Tai_Lue Talu Newa Newa Nko Nkoo Nushu Nshu Ogham Ogam Ol_Chiki Olck Old_Hungarian Hung Old_Italic Ital Old_North_Arabian Narb Old_Permic Perm Old_Persian Xpeo Old_South_Arabian Sarb Old_Turkic Orkh Oriya Orya Osage Osge Osmanya Osma Pahawh_Hmong Hmng Palmyrene Palm Pau_Cin_Hau Pauc Phags_Pa Phag Phoenician Phnx Psalter_Pahlavi Phlp Rejang Rjng Runic Runr Samaritan Samr Saurashtra Saur Sharada Shrd Shavian Shaw Siddham Sidd SignWriting Sgnw Sinhala Sinh Sora_Sompeng Sora Soyombo Soyo Sundanese Sund Syloti_Nagri Sylo Syriac Syrc Tagalog Tglg Tagbanwa Tagb Tai_Le Tale Tai_Tham Lana Tai_Viet Tavt Takri Takr Tamil Taml Tangut Tang Telugu Telu Thaana Thaa Thai Thai Tibetan Tibt Tifinagh Tfng Tirhuta Tirh Ugaritic Ugar Vai Vaii Warang_Citi Wara Yi Yiii Zanabazar_Square Zanb";
15775var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
15776var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
15777var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
15778var unicodeScriptValues = {
15779 9: ecma9ScriptValues,
15780 10: ecma10ScriptValues,
15781 11: ecma11ScriptValues,
15782 12: ecma12ScriptValues
15783};
15784
15785var data = {};
15786function buildUnicodeData(ecmaVersion) {
15787 var d = data[ecmaVersion] = {
15788 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
15789 nonBinary: {
15790 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
15791 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
15792 }
15793 };
15794 d.nonBinary.Script_Extensions = d.nonBinary.Script;
15795
15796 d.nonBinary.gc = d.nonBinary.General_Category;
15797 d.nonBinary.sc = d.nonBinary.Script;
15798 d.nonBinary.scx = d.nonBinary.Script_Extensions;
15799}
15800buildUnicodeData(9);
15801buildUnicodeData(10);
15802buildUnicodeData(11);
15803buildUnicodeData(12);
15804
15805var pp$8 = Parser.prototype;
15806
15807var RegExpValidationState = function RegExpValidationState(parser) {
15808 this.parser = parser;
15809 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
15810 this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
15811 this.source = "";
15812 this.flags = "";
15813 this.start = 0;
15814 this.switchU = false;
15815 this.switchN = false;
15816 this.pos = 0;
15817 this.lastIntValue = 0;
15818 this.lastStringValue = "";
15819 this.lastAssertionIsQuantifiable = false;
15820 this.numCapturingParens = 0;
15821 this.maxBackReference = 0;
15822 this.groupNames = [];
15823 this.backReferenceNames = [];
15824};
15825
15826RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
15827 var unicode = flags.indexOf("u") !== -1;
15828 this.start = start | 0;
15829 this.source = pattern + "";
15830 this.flags = flags;
15831 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
15832 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
15833};
15834
15835RegExpValidationState.prototype.raise = function raise (message) {
15836 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
15837};
15838
15839// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
15840// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
15841RegExpValidationState.prototype.at = function at (i, forceU) {
15842 if ( forceU === void 0 ) forceU = false;
15843
15844 var s = this.source;
15845 var l = s.length;
15846 if (i >= l) {
15847 return -1
15848 }
15849 var c = s.charCodeAt(i);
15850 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
15851 return c
15852 }
15853 var next = s.charCodeAt(i + 1);
15854 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
15855};
15856
15857RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
15858 if ( forceU === void 0 ) forceU = false;
15859
15860 var s = this.source;
15861 var l = s.length;
15862 if (i >= l) {
15863 return l
15864 }
15865 var c = s.charCodeAt(i), next;
15866 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
15867 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
15868 return i + 1
15869 }
15870 return i + 2
15871};
15872
15873RegExpValidationState.prototype.current = function current (forceU) {
15874 if ( forceU === void 0 ) forceU = false;
15875
15876 return this.at(this.pos, forceU)
15877};
15878
15879RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
15880 if ( forceU === void 0 ) forceU = false;
15881
15882 return this.at(this.nextIndex(this.pos, forceU), forceU)
15883};
15884
15885RegExpValidationState.prototype.advance = function advance (forceU) {
15886 if ( forceU === void 0 ) forceU = false;
15887
15888 this.pos = this.nextIndex(this.pos, forceU);
15889};
15890
15891RegExpValidationState.prototype.eat = function eat (ch, forceU) {
15892 if ( forceU === void 0 ) forceU = false;
15893
15894 if (this.current(forceU) === ch) {
15895 this.advance(forceU);
15896 return true
15897 }
15898 return false
15899};
15900
15901function codePointToString(ch) {
15902 if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
15903 ch -= 0x10000;
15904 return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
15905}
15906
15907/**
15908 * Validate the flags part of a given RegExpLiteral.
15909 *
15910 * @param {RegExpValidationState} state The state to validate RegExp.
15911 * @returns {void}
15912 */
15913pp$8.validateRegExpFlags = function(state) {
15914 var validFlags = state.validFlags;
15915 var flags = state.flags;
15916
15917 for (var i = 0; i < flags.length; i++) {
15918 var flag = flags.charAt(i);
15919 if (validFlags.indexOf(flag) === -1) {
15920 this.raise(state.start, "Invalid regular expression flag");
15921 }
15922 if (flags.indexOf(flag, i + 1) > -1) {
15923 this.raise(state.start, "Duplicate regular expression flag");
15924 }
15925 }
15926};
15927
15928/**
15929 * Validate the pattern part of a given RegExpLiteral.
15930 *
15931 * @param {RegExpValidationState} state The state to validate RegExp.
15932 * @returns {void}
15933 */
15934pp$8.validateRegExpPattern = function(state) {
15935 this.regexp_pattern(state);
15936
15937 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
15938 // parsing contains a |GroupName|, reparse with the goal symbol
15939 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
15940 // exception if _P_ did not conform to the grammar, if any elements of _P_
15941 // were not matched by the parse, or if any Early Error conditions exist.
15942 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
15943 state.switchN = true;
15944 this.regexp_pattern(state);
15945 }
15946};
15947
15948// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
15949pp$8.regexp_pattern = function(state) {
15950 state.pos = 0;
15951 state.lastIntValue = 0;
15952 state.lastStringValue = "";
15953 state.lastAssertionIsQuantifiable = false;
15954 state.numCapturingParens = 0;
15955 state.maxBackReference = 0;
15956 state.groupNames.length = 0;
15957 state.backReferenceNames.length = 0;
15958
15959 this.regexp_disjunction(state);
15960
15961 if (state.pos !== state.source.length) {
15962 // Make the same messages as V8.
15963 if (state.eat(0x29 /* ) */)) {
15964 state.raise("Unmatched ')'");
15965 }
15966 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
15967 state.raise("Lone quantifier brackets");
15968 }
15969 }
15970 if (state.maxBackReference > state.numCapturingParens) {
15971 state.raise("Invalid escape");
15972 }
15973 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
15974 var name = list[i];
15975
15976 if (state.groupNames.indexOf(name) === -1) {
15977 state.raise("Invalid named capture referenced");
15978 }
15979 }
15980};
15981
15982// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
15983pp$8.regexp_disjunction = function(state) {
15984 this.regexp_alternative(state);
15985 while (state.eat(0x7C /* | */)) {
15986 this.regexp_alternative(state);
15987 }
15988
15989 // Make the same message as V8.
15990 if (this.regexp_eatQuantifier(state, true)) {
15991 state.raise("Nothing to repeat");
15992 }
15993 if (state.eat(0x7B /* { */)) {
15994 state.raise("Lone quantifier brackets");
15995 }
15996};
15997
15998// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
15999pp$8.regexp_alternative = function(state) {
16000 while (state.pos < state.source.length && this.regexp_eatTerm(state))
16001 { }
16002};
16003
16004// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
16005pp$8.regexp_eatTerm = function(state) {
16006 if (this.regexp_eatAssertion(state)) {
16007 // Handle `QuantifiableAssertion Quantifier` alternative.
16008 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
16009 // is a QuantifiableAssertion.
16010 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
16011 // Make the same message as V8.
16012 if (state.switchU) {
16013 state.raise("Invalid quantifier");
16014 }
16015 }
16016 return true
16017 }
16018
16019 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
16020 this.regexp_eatQuantifier(state);
16021 return true
16022 }
16023
16024 return false
16025};
16026
16027// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
16028pp$8.regexp_eatAssertion = function(state) {
16029 var start = state.pos;
16030 state.lastAssertionIsQuantifiable = false;
16031
16032 // ^, $
16033 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
16034 return true
16035 }
16036
16037 // \b \B
16038 if (state.eat(0x5C /* \ */)) {
16039 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
16040 return true
16041 }
16042 state.pos = start;
16043 }
16044
16045 // Lookahead / Lookbehind
16046 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
16047 var lookbehind = false;
16048 if (this.options.ecmaVersion >= 9) {
16049 lookbehind = state.eat(0x3C /* < */);
16050 }
16051 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
16052 this.regexp_disjunction(state);
16053 if (!state.eat(0x29 /* ) */)) {
16054 state.raise("Unterminated group");
16055 }
16056 state.lastAssertionIsQuantifiable = !lookbehind;
16057 return true
16058 }
16059 }
16060
16061 state.pos = start;
16062 return false
16063};
16064
16065// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
16066pp$8.regexp_eatQuantifier = function(state, noError) {
16067 if ( noError === void 0 ) noError = false;
16068
16069 if (this.regexp_eatQuantifierPrefix(state, noError)) {
16070 state.eat(0x3F /* ? */);
16071 return true
16072 }
16073 return false
16074};
16075
16076// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
16077pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
16078 return (
16079 state.eat(0x2A /* * */) ||
16080 state.eat(0x2B /* + */) ||
16081 state.eat(0x3F /* ? */) ||
16082 this.regexp_eatBracedQuantifier(state, noError)
16083 )
16084};
16085pp$8.regexp_eatBracedQuantifier = function(state, noError) {
16086 var start = state.pos;
16087 if (state.eat(0x7B /* { */)) {
16088 var min = 0, max = -1;
16089 if (this.regexp_eatDecimalDigits(state)) {
16090 min = state.lastIntValue;
16091 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
16092 max = state.lastIntValue;
16093 }
16094 if (state.eat(0x7D /* } */)) {
16095 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
16096 if (max !== -1 && max < min && !noError) {
16097 state.raise("numbers out of order in {} quantifier");
16098 }
16099 return true
16100 }
16101 }
16102 if (state.switchU && !noError) {
16103 state.raise("Incomplete quantifier");
16104 }
16105 state.pos = start;
16106 }
16107 return false
16108};
16109
16110// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
16111pp$8.regexp_eatAtom = function(state) {
16112 return (
16113 this.regexp_eatPatternCharacters(state) ||
16114 state.eat(0x2E /* . */) ||
16115 this.regexp_eatReverseSolidusAtomEscape(state) ||
16116 this.regexp_eatCharacterClass(state) ||
16117 this.regexp_eatUncapturingGroup(state) ||
16118 this.regexp_eatCapturingGroup(state)
16119 )
16120};
16121pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
16122 var start = state.pos;
16123 if (state.eat(0x5C /* \ */)) {
16124 if (this.regexp_eatAtomEscape(state)) {
16125 return true
16126 }
16127 state.pos = start;
16128 }
16129 return false
16130};
16131pp$8.regexp_eatUncapturingGroup = function(state) {
16132 var start = state.pos;
16133 if (state.eat(0x28 /* ( */)) {
16134 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
16135 this.regexp_disjunction(state);
16136 if (state.eat(0x29 /* ) */)) {
16137 return true
16138 }
16139 state.raise("Unterminated group");
16140 }
16141 state.pos = start;
16142 }
16143 return false
16144};
16145pp$8.regexp_eatCapturingGroup = function(state) {
16146 if (state.eat(0x28 /* ( */)) {
16147 if (this.options.ecmaVersion >= 9) {
16148 this.regexp_groupSpecifier(state);
16149 } else if (state.current() === 0x3F /* ? */) {
16150 state.raise("Invalid group");
16151 }
16152 this.regexp_disjunction(state);
16153 if (state.eat(0x29 /* ) */)) {
16154 state.numCapturingParens += 1;
16155 return true
16156 }
16157 state.raise("Unterminated group");
16158 }
16159 return false
16160};
16161
16162// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
16163pp$8.regexp_eatExtendedAtom = function(state) {
16164 return (
16165 state.eat(0x2E /* . */) ||
16166 this.regexp_eatReverseSolidusAtomEscape(state) ||
16167 this.regexp_eatCharacterClass(state) ||
16168 this.regexp_eatUncapturingGroup(state) ||
16169 this.regexp_eatCapturingGroup(state) ||
16170 this.regexp_eatInvalidBracedQuantifier(state) ||
16171 this.regexp_eatExtendedPatternCharacter(state)
16172 )
16173};
16174
16175// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
16176pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
16177 if (this.regexp_eatBracedQuantifier(state, true)) {
16178 state.raise("Nothing to repeat");
16179 }
16180 return false
16181};
16182
16183// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
16184pp$8.regexp_eatSyntaxCharacter = function(state) {
16185 var ch = state.current();
16186 if (isSyntaxCharacter(ch)) {
16187 state.lastIntValue = ch;
16188 state.advance();
16189 return true
16190 }
16191 return false
16192};
16193function isSyntaxCharacter(ch) {
16194 return (
16195 ch === 0x24 /* $ */ ||
16196 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
16197 ch === 0x2E /* . */ ||
16198 ch === 0x3F /* ? */ ||
16199 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
16200 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
16201 )
16202}
16203
16204// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
16205// But eat eager.
16206pp$8.regexp_eatPatternCharacters = function(state) {
16207 var start = state.pos;
16208 var ch = 0;
16209 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
16210 state.advance();
16211 }
16212 return state.pos !== start
16213};
16214
16215// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
16216pp$8.regexp_eatExtendedPatternCharacter = function(state) {
16217 var ch = state.current();
16218 if (
16219 ch !== -1 &&
16220 ch !== 0x24 /* $ */ &&
16221 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
16222 ch !== 0x2E /* . */ &&
16223 ch !== 0x3F /* ? */ &&
16224 ch !== 0x5B /* [ */ &&
16225 ch !== 0x5E /* ^ */ &&
16226 ch !== 0x7C /* | */
16227 ) {
16228 state.advance();
16229 return true
16230 }
16231 return false
16232};
16233
16234// GroupSpecifier ::
16235// [empty]
16236// `?` GroupName
16237pp$8.regexp_groupSpecifier = function(state) {
16238 if (state.eat(0x3F /* ? */)) {
16239 if (this.regexp_eatGroupName(state)) {
16240 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
16241 state.raise("Duplicate capture group name");
16242 }
16243 state.groupNames.push(state.lastStringValue);
16244 return
16245 }
16246 state.raise("Invalid group");
16247 }
16248};
16249
16250// GroupName ::
16251// `<` RegExpIdentifierName `>`
16252// Note: this updates `state.lastStringValue` property with the eaten name.
16253pp$8.regexp_eatGroupName = function(state) {
16254 state.lastStringValue = "";
16255 if (state.eat(0x3C /* < */)) {
16256 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
16257 return true
16258 }
16259 state.raise("Invalid capture group name");
16260 }
16261 return false
16262};
16263
16264// RegExpIdentifierName ::
16265// RegExpIdentifierStart
16266// RegExpIdentifierName RegExpIdentifierPart
16267// Note: this updates `state.lastStringValue` property with the eaten name.
16268pp$8.regexp_eatRegExpIdentifierName = function(state) {
16269 state.lastStringValue = "";
16270 if (this.regexp_eatRegExpIdentifierStart(state)) {
16271 state.lastStringValue += codePointToString(state.lastIntValue);
16272 while (this.regexp_eatRegExpIdentifierPart(state)) {
16273 state.lastStringValue += codePointToString(state.lastIntValue);
16274 }
16275 return true
16276 }
16277 return false
16278};
16279
16280// RegExpIdentifierStart ::
16281// UnicodeIDStart
16282// `$`
16283// `_`
16284// `\` RegExpUnicodeEscapeSequence[+U]
16285pp$8.regexp_eatRegExpIdentifierStart = function(state) {
16286 var start = state.pos;
16287 var forceU = this.options.ecmaVersion >= 11;
16288 var ch = state.current(forceU);
16289 state.advance(forceU);
16290
16291 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
16292 ch = state.lastIntValue;
16293 }
16294 if (isRegExpIdentifierStart(ch)) {
16295 state.lastIntValue = ch;
16296 return true
16297 }
16298
16299 state.pos = start;
16300 return false
16301};
16302function isRegExpIdentifierStart(ch) {
16303 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
16304}
16305
16306// RegExpIdentifierPart ::
16307// UnicodeIDContinue
16308// `$`
16309// `_`
16310// `\` RegExpUnicodeEscapeSequence[+U]
16311// <ZWNJ>
16312// <ZWJ>
16313pp$8.regexp_eatRegExpIdentifierPart = function(state) {
16314 var start = state.pos;
16315 var forceU = this.options.ecmaVersion >= 11;
16316 var ch = state.current(forceU);
16317 state.advance(forceU);
16318
16319 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
16320 ch = state.lastIntValue;
16321 }
16322 if (isRegExpIdentifierPart(ch)) {
16323 state.lastIntValue = ch;
16324 return true
16325 }
16326
16327 state.pos = start;
16328 return false
16329};
16330function isRegExpIdentifierPart(ch) {
16331 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
16332}
16333
16334// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
16335pp$8.regexp_eatAtomEscape = function(state) {
16336 if (
16337 this.regexp_eatBackReference(state) ||
16338 this.regexp_eatCharacterClassEscape(state) ||
16339 this.regexp_eatCharacterEscape(state) ||
16340 (state.switchN && this.regexp_eatKGroupName(state))
16341 ) {
16342 return true
16343 }
16344 if (state.switchU) {
16345 // Make the same message as V8.
16346 if (state.current() === 0x63 /* c */) {
16347 state.raise("Invalid unicode escape");
16348 }
16349 state.raise("Invalid escape");
16350 }
16351 return false
16352};
16353pp$8.regexp_eatBackReference = function(state) {
16354 var start = state.pos;
16355 if (this.regexp_eatDecimalEscape(state)) {
16356 var n = state.lastIntValue;
16357 if (state.switchU) {
16358 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
16359 if (n > state.maxBackReference) {
16360 state.maxBackReference = n;
16361 }
16362 return true
16363 }
16364 if (n <= state.numCapturingParens) {
16365 return true
16366 }
16367 state.pos = start;
16368 }
16369 return false
16370};
16371pp$8.regexp_eatKGroupName = function(state) {
16372 if (state.eat(0x6B /* k */)) {
16373 if (this.regexp_eatGroupName(state)) {
16374 state.backReferenceNames.push(state.lastStringValue);
16375 return true
16376 }
16377 state.raise("Invalid named reference");
16378 }
16379 return false
16380};
16381
16382// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
16383pp$8.regexp_eatCharacterEscape = function(state) {
16384 return (
16385 this.regexp_eatControlEscape(state) ||
16386 this.regexp_eatCControlLetter(state) ||
16387 this.regexp_eatZero(state) ||
16388 this.regexp_eatHexEscapeSequence(state) ||
16389 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
16390 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
16391 this.regexp_eatIdentityEscape(state)
16392 )
16393};
16394pp$8.regexp_eatCControlLetter = function(state) {
16395 var start = state.pos;
16396 if (state.eat(0x63 /* c */)) {
16397 if (this.regexp_eatControlLetter(state)) {
16398 return true
16399 }
16400 state.pos = start;
16401 }
16402 return false
16403};
16404pp$8.regexp_eatZero = function(state) {
16405 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
16406 state.lastIntValue = 0;
16407 state.advance();
16408 return true
16409 }
16410 return false
16411};
16412
16413// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
16414pp$8.regexp_eatControlEscape = function(state) {
16415 var ch = state.current();
16416 if (ch === 0x74 /* t */) {
16417 state.lastIntValue = 0x09; /* \t */
16418 state.advance();
16419 return true
16420 }
16421 if (ch === 0x6E /* n */) {
16422 state.lastIntValue = 0x0A; /* \n */
16423 state.advance();
16424 return true
16425 }
16426 if (ch === 0x76 /* v */) {
16427 state.lastIntValue = 0x0B; /* \v */
16428 state.advance();
16429 return true
16430 }
16431 if (ch === 0x66 /* f */) {
16432 state.lastIntValue = 0x0C; /* \f */
16433 state.advance();
16434 return true
16435 }
16436 if (ch === 0x72 /* r */) {
16437 state.lastIntValue = 0x0D; /* \r */
16438 state.advance();
16439 return true
16440 }
16441 return false
16442};
16443
16444// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
16445pp$8.regexp_eatControlLetter = function(state) {
16446 var ch = state.current();
16447 if (isControlLetter(ch)) {
16448 state.lastIntValue = ch % 0x20;
16449 state.advance();
16450 return true
16451 }
16452 return false
16453};
16454function isControlLetter(ch) {
16455 return (
16456 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
16457 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
16458 )
16459}
16460
16461// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
16462pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
16463 if ( forceU === void 0 ) forceU = false;
16464
16465 var start = state.pos;
16466 var switchU = forceU || state.switchU;
16467
16468 if (state.eat(0x75 /* u */)) {
16469 if (this.regexp_eatFixedHexDigits(state, 4)) {
16470 var lead = state.lastIntValue;
16471 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
16472 var leadSurrogateEnd = state.pos;
16473 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
16474 var trail = state.lastIntValue;
16475 if (trail >= 0xDC00 && trail <= 0xDFFF) {
16476 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
16477 return true
16478 }
16479 }
16480 state.pos = leadSurrogateEnd;
16481 state.lastIntValue = lead;
16482 }
16483 return true
16484 }
16485 if (
16486 switchU &&
16487 state.eat(0x7B /* { */) &&
16488 this.regexp_eatHexDigits(state) &&
16489 state.eat(0x7D /* } */) &&
16490 isValidUnicode(state.lastIntValue)
16491 ) {
16492 return true
16493 }
16494 if (switchU) {
16495 state.raise("Invalid unicode escape");
16496 }
16497 state.pos = start;
16498 }
16499
16500 return false
16501};
16502function isValidUnicode(ch) {
16503 return ch >= 0 && ch <= 0x10FFFF
16504}
16505
16506// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
16507pp$8.regexp_eatIdentityEscape = function(state) {
16508 if (state.switchU) {
16509 if (this.regexp_eatSyntaxCharacter(state)) {
16510 return true
16511 }
16512 if (state.eat(0x2F /* / */)) {
16513 state.lastIntValue = 0x2F; /* / */
16514 return true
16515 }
16516 return false
16517 }
16518
16519 var ch = state.current();
16520 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
16521 state.lastIntValue = ch;
16522 state.advance();
16523 return true
16524 }
16525
16526 return false
16527};
16528
16529// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
16530pp$8.regexp_eatDecimalEscape = function(state) {
16531 state.lastIntValue = 0;
16532 var ch = state.current();
16533 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
16534 do {
16535 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
16536 state.advance();
16537 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
16538 return true
16539 }
16540 return false
16541};
16542
16543// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
16544pp$8.regexp_eatCharacterClassEscape = function(state) {
16545 var ch = state.current();
16546
16547 if (isCharacterClassEscape(ch)) {
16548 state.lastIntValue = -1;
16549 state.advance();
16550 return true
16551 }
16552
16553 if (
16554 state.switchU &&
16555 this.options.ecmaVersion >= 9 &&
16556 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
16557 ) {
16558 state.lastIntValue = -1;
16559 state.advance();
16560 if (
16561 state.eat(0x7B /* { */) &&
16562 this.regexp_eatUnicodePropertyValueExpression(state) &&
16563 state.eat(0x7D /* } */)
16564 ) {
16565 return true
16566 }
16567 state.raise("Invalid property name");
16568 }
16569
16570 return false
16571};
16572function isCharacterClassEscape(ch) {
16573 return (
16574 ch === 0x64 /* d */ ||
16575 ch === 0x44 /* D */ ||
16576 ch === 0x73 /* s */ ||
16577 ch === 0x53 /* S */ ||
16578 ch === 0x77 /* w */ ||
16579 ch === 0x57 /* W */
16580 )
16581}
16582
16583// UnicodePropertyValueExpression ::
16584// UnicodePropertyName `=` UnicodePropertyValue
16585// LoneUnicodePropertyNameOrValue
16586pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
16587 var start = state.pos;
16588
16589 // UnicodePropertyName `=` UnicodePropertyValue
16590 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
16591 var name = state.lastStringValue;
16592 if (this.regexp_eatUnicodePropertyValue(state)) {
16593 var value = state.lastStringValue;
16594 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
16595 return true
16596 }
16597 }
16598 state.pos = start;
16599
16600 // LoneUnicodePropertyNameOrValue
16601 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
16602 var nameOrValue = state.lastStringValue;
16603 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
16604 return true
16605 }
16606 return false
16607};
16608pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
16609 if (!has(state.unicodeProperties.nonBinary, name))
16610 { state.raise("Invalid property name"); }
16611 if (!state.unicodeProperties.nonBinary[name].test(value))
16612 { state.raise("Invalid property value"); }
16613};
16614pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
16615 if (!state.unicodeProperties.binary.test(nameOrValue))
16616 { state.raise("Invalid property name"); }
16617};
16618
16619// UnicodePropertyName ::
16620// UnicodePropertyNameCharacters
16621pp$8.regexp_eatUnicodePropertyName = function(state) {
16622 var ch = 0;
16623 state.lastStringValue = "";
16624 while (isUnicodePropertyNameCharacter(ch = state.current())) {
16625 state.lastStringValue += codePointToString(ch);
16626 state.advance();
16627 }
16628 return state.lastStringValue !== ""
16629};
16630function isUnicodePropertyNameCharacter(ch) {
16631 return isControlLetter(ch) || ch === 0x5F /* _ */
16632}
16633
16634// UnicodePropertyValue ::
16635// UnicodePropertyValueCharacters
16636pp$8.regexp_eatUnicodePropertyValue = function(state) {
16637 var ch = 0;
16638 state.lastStringValue = "";
16639 while (isUnicodePropertyValueCharacter(ch = state.current())) {
16640 state.lastStringValue += codePointToString(ch);
16641 state.advance();
16642 }
16643 return state.lastStringValue !== ""
16644};
16645function isUnicodePropertyValueCharacter(ch) {
16646 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
16647}
16648
16649// LoneUnicodePropertyNameOrValue ::
16650// UnicodePropertyValueCharacters
16651pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
16652 return this.regexp_eatUnicodePropertyValue(state)
16653};
16654
16655// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
16656pp$8.regexp_eatCharacterClass = function(state) {
16657 if (state.eat(0x5B /* [ */)) {
16658 state.eat(0x5E /* ^ */);
16659 this.regexp_classRanges(state);
16660 if (state.eat(0x5D /* ] */)) {
16661 return true
16662 }
16663 // Unreachable since it threw "unterminated regular expression" error before.
16664 state.raise("Unterminated character class");
16665 }
16666 return false
16667};
16668
16669// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
16670// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
16671// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
16672pp$8.regexp_classRanges = function(state) {
16673 while (this.regexp_eatClassAtom(state)) {
16674 var left = state.lastIntValue;
16675 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
16676 var right = state.lastIntValue;
16677 if (state.switchU && (left === -1 || right === -1)) {
16678 state.raise("Invalid character class");
16679 }
16680 if (left !== -1 && right !== -1 && left > right) {
16681 state.raise("Range out of order in character class");
16682 }
16683 }
16684 }
16685};
16686
16687// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
16688// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
16689pp$8.regexp_eatClassAtom = function(state) {
16690 var start = state.pos;
16691
16692 if (state.eat(0x5C /* \ */)) {
16693 if (this.regexp_eatClassEscape(state)) {
16694 return true
16695 }
16696 if (state.switchU) {
16697 // Make the same message as V8.
16698 var ch$1 = state.current();
16699 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
16700 state.raise("Invalid class escape");
16701 }
16702 state.raise("Invalid escape");
16703 }
16704 state.pos = start;
16705 }
16706
16707 var ch = state.current();
16708 if (ch !== 0x5D /* ] */) {
16709 state.lastIntValue = ch;
16710 state.advance();
16711 return true
16712 }
16713
16714 return false
16715};
16716
16717// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
16718pp$8.regexp_eatClassEscape = function(state) {
16719 var start = state.pos;
16720
16721 if (state.eat(0x62 /* b */)) {
16722 state.lastIntValue = 0x08; /* <BS> */
16723 return true
16724 }
16725
16726 if (state.switchU && state.eat(0x2D /* - */)) {
16727 state.lastIntValue = 0x2D; /* - */
16728 return true
16729 }
16730
16731 if (!state.switchU && state.eat(0x63 /* c */)) {
16732 if (this.regexp_eatClassControlLetter(state)) {
16733 return true
16734 }
16735 state.pos = start;
16736 }
16737
16738 return (
16739 this.regexp_eatCharacterClassEscape(state) ||
16740 this.regexp_eatCharacterEscape(state)
16741 )
16742};
16743
16744// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
16745pp$8.regexp_eatClassControlLetter = function(state) {
16746 var ch = state.current();
16747 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
16748 state.lastIntValue = ch % 0x20;
16749 state.advance();
16750 return true
16751 }
16752 return false
16753};
16754
16755// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
16756pp$8.regexp_eatHexEscapeSequence = function(state) {
16757 var start = state.pos;
16758 if (state.eat(0x78 /* x */)) {
16759 if (this.regexp_eatFixedHexDigits(state, 2)) {
16760 return true
16761 }
16762 if (state.switchU) {
16763 state.raise("Invalid escape");
16764 }
16765 state.pos = start;
16766 }
16767 return false
16768};
16769
16770// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
16771pp$8.regexp_eatDecimalDigits = function(state) {
16772 var start = state.pos;
16773 var ch = 0;
16774 state.lastIntValue = 0;
16775 while (isDecimalDigit(ch = state.current())) {
16776 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
16777 state.advance();
16778 }
16779 return state.pos !== start
16780};
16781function isDecimalDigit(ch) {
16782 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
16783}
16784
16785// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
16786pp$8.regexp_eatHexDigits = function(state) {
16787 var start = state.pos;
16788 var ch = 0;
16789 state.lastIntValue = 0;
16790 while (isHexDigit(ch = state.current())) {
16791 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
16792 state.advance();
16793 }
16794 return state.pos !== start
16795};
16796function isHexDigit(ch) {
16797 return (
16798 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
16799 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
16800 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
16801 )
16802}
16803function hexToInt(ch) {
16804 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
16805 return 10 + (ch - 0x41 /* A */)
16806 }
16807 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
16808 return 10 + (ch - 0x61 /* a */)
16809 }
16810 return ch - 0x30 /* 0 */
16811}
16812
16813// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
16814// Allows only 0-377(octal) i.e. 0-255(decimal).
16815pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
16816 if (this.regexp_eatOctalDigit(state)) {
16817 var n1 = state.lastIntValue;
16818 if (this.regexp_eatOctalDigit(state)) {
16819 var n2 = state.lastIntValue;
16820 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
16821 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
16822 } else {
16823 state.lastIntValue = n1 * 8 + n2;
16824 }
16825 } else {
16826 state.lastIntValue = n1;
16827 }
16828 return true
16829 }
16830 return false
16831};
16832
16833// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
16834pp$8.regexp_eatOctalDigit = function(state) {
16835 var ch = state.current();
16836 if (isOctalDigit(ch)) {
16837 state.lastIntValue = ch - 0x30; /* 0 */
16838 state.advance();
16839 return true
16840 }
16841 state.lastIntValue = 0;
16842 return false
16843};
16844function isOctalDigit(ch) {
16845 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
16846}
16847
16848// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
16849// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
16850// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
16851pp$8.regexp_eatFixedHexDigits = function(state, length) {
16852 var start = state.pos;
16853 state.lastIntValue = 0;
16854 for (var i = 0; i < length; ++i) {
16855 var ch = state.current();
16856 if (!isHexDigit(ch)) {
16857 state.pos = start;
16858 return false
16859 }
16860 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
16861 state.advance();
16862 }
16863 return true
16864};
16865
16866// Object type used to represent tokens. Note that normally, tokens
16867// simply exist as properties on the parser object. This is only
16868// used for the onToken callback and the external tokenizer.
16869
16870var Token = function Token(p) {
16871 this.type = p.type;
16872 this.value = p.value;
16873 this.start = p.start;
16874 this.end = p.end;
16875 if (p.options.locations)
16876 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
16877 if (p.options.ranges)
16878 { this.range = [p.start, p.end]; }
16879};
16880
16881// ## Tokenizer
16882
16883var pp$9 = Parser.prototype;
16884
16885// Move to the next token
16886
16887pp$9.next = function(ignoreEscapeSequenceInKeyword) {
16888 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
16889 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
16890 if (this.options.onToken)
16891 { this.options.onToken(new Token(this)); }
16892
16893 this.lastTokEnd = this.end;
16894 this.lastTokStart = this.start;
16895 this.lastTokEndLoc = this.endLoc;
16896 this.lastTokStartLoc = this.startLoc;
16897 this.nextToken();
16898};
16899
16900pp$9.getToken = function() {
16901 this.next();
16902 return new Token(this)
16903};
16904
16905// If we're in an ES6 environment, make parsers iterable
16906if (typeof Symbol !== "undefined")
16907 { pp$9[Symbol.iterator] = function() {
16908 var this$1 = this;
16909
16910 return {
16911 next: function () {
16912 var token = this$1.getToken();
16913 return {
16914 done: token.type === types.eof,
16915 value: token
16916 }
16917 }
16918 }
16919 }; }
16920
16921// Toggle strict mode. Re-reads the next number or string to please
16922// pedantic tests (`"use strict"; 010;` should fail).
16923
16924pp$9.curContext = function() {
16925 return this.context[this.context.length - 1]
16926};
16927
16928// Read a single token, updating the parser object's token-related
16929// properties.
16930
16931pp$9.nextToken = function() {
16932 var curContext = this.curContext();
16933 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
16934
16935 this.start = this.pos;
16936 if (this.options.locations) { this.startLoc = this.curPosition(); }
16937 if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
16938
16939 if (curContext.override) { return curContext.override(this) }
16940 else { this.readToken(this.fullCharCodeAtPos()); }
16941};
16942
16943pp$9.readToken = function(code) {
16944 // Identifier or keyword. '\uXXXX' sequences are allowed in
16945 // identifiers, so '\' also dispatches to that.
16946 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
16947 { return this.readWord() }
16948
16949 return this.getTokenFromCode(code)
16950};
16951
16952pp$9.fullCharCodeAtPos = function() {
16953 var code = this.input.charCodeAt(this.pos);
16954 if (code <= 0xd7ff || code >= 0xe000) { return code }
16955 var next = this.input.charCodeAt(this.pos + 1);
16956 return (code << 10) + next - 0x35fdc00
16957};
16958
16959pp$9.skipBlockComment = function() {
16960 var startLoc = this.options.onComment && this.curPosition();
16961 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
16962 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
16963 this.pos = end + 2;
16964 if (this.options.locations) {
16965 lineBreakG.lastIndex = start;
16966 var match;
16967 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
16968 ++this.curLine;
16969 this.lineStart = match.index + match[0].length;
16970 }
16971 }
16972 if (this.options.onComment)
16973 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
16974 startLoc, this.curPosition()); }
16975};
16976
16977pp$9.skipLineComment = function(startSkip) {
16978 var start = this.pos;
16979 var startLoc = this.options.onComment && this.curPosition();
16980 var ch = this.input.charCodeAt(this.pos += startSkip);
16981 while (this.pos < this.input.length && !isNewLine(ch)) {
16982 ch = this.input.charCodeAt(++this.pos);
16983 }
16984 if (this.options.onComment)
16985 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
16986 startLoc, this.curPosition()); }
16987};
16988
16989// Called at the start of the parse and after every token. Skips
16990// whitespace and comments, and.
16991
16992pp$9.skipSpace = function() {
16993 loop: while (this.pos < this.input.length) {
16994 var ch = this.input.charCodeAt(this.pos);
16995 switch (ch) {
16996 case 32: case 160: // ' '
16997 ++this.pos;
16998 break
16999 case 13:
17000 if (this.input.charCodeAt(this.pos + 1) === 10) {
17001 ++this.pos;
17002 }
17003 case 10: case 8232: case 8233:
17004 ++this.pos;
17005 if (this.options.locations) {
17006 ++this.curLine;
17007 this.lineStart = this.pos;
17008 }
17009 break
17010 case 47: // '/'
17011 switch (this.input.charCodeAt(this.pos + 1)) {
17012 case 42: // '*'
17013 this.skipBlockComment();
17014 break
17015 case 47:
17016 this.skipLineComment(2);
17017 break
17018 default:
17019 break loop
17020 }
17021 break
17022 default:
17023 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
17024 ++this.pos;
17025 } else {
17026 break loop
17027 }
17028 }
17029 }
17030};
17031
17032// Called at the end of every token. Sets `end`, `val`, and
17033// maintains `context` and `exprAllowed`, and skips the space after
17034// the token, so that the next one's `start` will point at the
17035// right position.
17036
17037pp$9.finishToken = function(type, val) {
17038 this.end = this.pos;
17039 if (this.options.locations) { this.endLoc = this.curPosition(); }
17040 var prevType = this.type;
17041 this.type = type;
17042 this.value = val;
17043
17044 this.updateContext(prevType);
17045};
17046
17047// ### Token reading
17048
17049// This is the function that is called to fetch the next token. It
17050// is somewhat obscure, because it works in character codes rather
17051// than characters, and because operator parsing has been inlined
17052// into it.
17053//
17054// All in the name of speed.
17055//
17056pp$9.readToken_dot = function() {
17057 var next = this.input.charCodeAt(this.pos + 1);
17058 if (next >= 48 && next <= 57) { return this.readNumber(true) }
17059 var next2 = this.input.charCodeAt(this.pos + 2);
17060 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
17061 this.pos += 3;
17062 return this.finishToken(types.ellipsis)
17063 } else {
17064 ++this.pos;
17065 return this.finishToken(types.dot)
17066 }
17067};
17068
17069pp$9.readToken_slash = function() { // '/'
17070 var next = this.input.charCodeAt(this.pos + 1);
17071 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
17072 if (next === 61) { return this.finishOp(types.assign, 2) }
17073 return this.finishOp(types.slash, 1)
17074};
17075
17076pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
17077 var next = this.input.charCodeAt(this.pos + 1);
17078 var size = 1;
17079 var tokentype = code === 42 ? types.star : types.modulo;
17080
17081 // exponentiation operator ** and **=
17082 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
17083 ++size;
17084 tokentype = types.starstar;
17085 next = this.input.charCodeAt(this.pos + 2);
17086 }
17087
17088 if (next === 61) { return this.finishOp(types.assign, size + 1) }
17089 return this.finishOp(tokentype, size)
17090};
17091
17092pp$9.readToken_pipe_amp = function(code) { // '|&'
17093 var next = this.input.charCodeAt(this.pos + 1);
17094 if (next === code) {
17095 if (this.options.ecmaVersion >= 12) {
17096 var next2 = this.input.charCodeAt(this.pos + 2);
17097 if (next2 === 61) { return this.finishOp(types.assign, 3) }
17098 }
17099 return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
17100 }
17101 if (next === 61) { return this.finishOp(types.assign, 2) }
17102 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
17103};
17104
17105pp$9.readToken_caret = function() { // '^'
17106 var next = this.input.charCodeAt(this.pos + 1);
17107 if (next === 61) { return this.finishOp(types.assign, 2) }
17108 return this.finishOp(types.bitwiseXOR, 1)
17109};
17110
17111pp$9.readToken_plus_min = function(code) { // '+-'
17112 var next = this.input.charCodeAt(this.pos + 1);
17113 if (next === code) {
17114 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
17115 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
17116 // A `-->` line comment
17117 this.skipLineComment(3);
17118 this.skipSpace();
17119 return this.nextToken()
17120 }
17121 return this.finishOp(types.incDec, 2)
17122 }
17123 if (next === 61) { return this.finishOp(types.assign, 2) }
17124 return this.finishOp(types.plusMin, 1)
17125};
17126
17127pp$9.readToken_lt_gt = function(code) { // '<>'
17128 var next = this.input.charCodeAt(this.pos + 1);
17129 var size = 1;
17130 if (next === code) {
17131 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
17132 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
17133 return this.finishOp(types.bitShift, size)
17134 }
17135 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
17136 this.input.charCodeAt(this.pos + 3) === 45) {
17137 // `<!--`, an XML-style comment that should be interpreted as a line comment
17138 this.skipLineComment(4);
17139 this.skipSpace();
17140 return this.nextToken()
17141 }
17142 if (next === 61) { size = 2; }
17143 return this.finishOp(types.relational, size)
17144};
17145
17146pp$9.readToken_eq_excl = function(code) { // '=!'
17147 var next = this.input.charCodeAt(this.pos + 1);
17148 if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
17149 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
17150 this.pos += 2;
17151 return this.finishToken(types.arrow)
17152 }
17153 return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
17154};
17155
17156pp$9.readToken_question = function() { // '?'
17157 var ecmaVersion = this.options.ecmaVersion;
17158 if (ecmaVersion >= 11) {
17159 var next = this.input.charCodeAt(this.pos + 1);
17160 if (next === 46) {
17161 var next2 = this.input.charCodeAt(this.pos + 2);
17162 if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
17163 }
17164 if (next === 63) {
17165 if (ecmaVersion >= 12) {
17166 var next2$1 = this.input.charCodeAt(this.pos + 2);
17167 if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
17168 }
17169 return this.finishOp(types.coalesce, 2)
17170 }
17171 }
17172 return this.finishOp(types.question, 1)
17173};
17174
17175pp$9.getTokenFromCode = function(code) {
17176 switch (code) {
17177 // The interpretation of a dot depends on whether it is followed
17178 // by a digit or another two dots.
17179 case 46: // '.'
17180 return this.readToken_dot()
17181
17182 // Punctuation tokens.
17183 case 40: ++this.pos; return this.finishToken(types.parenL)
17184 case 41: ++this.pos; return this.finishToken(types.parenR)
17185 case 59: ++this.pos; return this.finishToken(types.semi)
17186 case 44: ++this.pos; return this.finishToken(types.comma)
17187 case 91: ++this.pos; return this.finishToken(types.bracketL)
17188 case 93: ++this.pos; return this.finishToken(types.bracketR)
17189 case 123: ++this.pos; return this.finishToken(types.braceL)
17190 case 125: ++this.pos; return this.finishToken(types.braceR)
17191 case 58: ++this.pos; return this.finishToken(types.colon)
17192
17193 case 96: // '`'
17194 if (this.options.ecmaVersion < 6) { break }
17195 ++this.pos;
17196 return this.finishToken(types.backQuote)
17197
17198 case 48: // '0'
17199 var next = this.input.charCodeAt(this.pos + 1);
17200 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
17201 if (this.options.ecmaVersion >= 6) {
17202 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
17203 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
17204 }
17205
17206 // Anything else beginning with a digit is an integer, octal
17207 // number, or float.
17208 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
17209 return this.readNumber(false)
17210
17211 // Quotes produce strings.
17212 case 34: case 39: // '"', "'"
17213 return this.readString(code)
17214
17215 // Operators are parsed inline in tiny state machines. '=' (61) is
17216 // often referred to. `finishOp` simply skips the amount of
17217 // characters it is given as second argument, and returns a token
17218 // of the type given by its first argument.
17219
17220 case 47: // '/'
17221 return this.readToken_slash()
17222
17223 case 37: case 42: // '%*'
17224 return this.readToken_mult_modulo_exp(code)
17225
17226 case 124: case 38: // '|&'
17227 return this.readToken_pipe_amp(code)
17228
17229 case 94: // '^'
17230 return this.readToken_caret()
17231
17232 case 43: case 45: // '+-'
17233 return this.readToken_plus_min(code)
17234
17235 case 60: case 62: // '<>'
17236 return this.readToken_lt_gt(code)
17237
17238 case 61: case 33: // '=!'
17239 return this.readToken_eq_excl(code)
17240
17241 case 63: // '?'
17242 return this.readToken_question()
17243
17244 case 126: // '~'
17245 return this.finishOp(types.prefix, 1)
17246 }
17247
17248 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
17249};
17250
17251pp$9.finishOp = function(type, size) {
17252 var str = this.input.slice(this.pos, this.pos + size);
17253 this.pos += size;
17254 return this.finishToken(type, str)
17255};
17256
17257pp$9.readRegexp = function() {
17258 var escaped, inClass, start = this.pos;
17259 for (;;) {
17260 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
17261 var ch = this.input.charAt(this.pos);
17262 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
17263 if (!escaped) {
17264 if (ch === "[") { inClass = true; }
17265 else if (ch === "]" && inClass) { inClass = false; }
17266 else if (ch === "/" && !inClass) { break }
17267 escaped = ch === "\\";
17268 } else { escaped = false; }
17269 ++this.pos;
17270 }
17271 var pattern = this.input.slice(start, this.pos);
17272 ++this.pos;
17273 var flagsStart = this.pos;
17274 var flags = this.readWord1();
17275 if (this.containsEsc) { this.unexpected(flagsStart); }
17276
17277 // Validate pattern
17278 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
17279 state.reset(start, pattern, flags);
17280 this.validateRegExpFlags(state);
17281 this.validateRegExpPattern(state);
17282
17283 // Create Literal#value property value.
17284 var value = null;
17285 try {
17286 value = new RegExp(pattern, flags);
17287 } catch (e) {
17288 // ESTree requires null if it failed to instantiate RegExp object.
17289 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
17290 }
17291
17292 return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
17293};
17294
17295// Read an integer in the given radix. Return null if zero digits
17296// were read, the integer value otherwise. When `len` is given, this
17297// will return `null` unless the integer has exactly `len` digits.
17298
17299pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
17300 // `len` is used for character escape sequences. In that case, disallow separators.
17301 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
17302
17303 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
17304 // and isn't fraction part nor exponent part. In that case, if the first digit
17305 // is zero then disallow separators.
17306 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
17307
17308 var start = this.pos, total = 0, lastCode = 0;
17309 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
17310 var code = this.input.charCodeAt(this.pos), val = (void 0);
17311
17312 if (allowSeparators && code === 95) {
17313 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
17314 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
17315 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
17316 lastCode = code;
17317 continue
17318 }
17319
17320 if (code >= 97) { val = code - 97 + 10; } // a
17321 else if (code >= 65) { val = code - 65 + 10; } // A
17322 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
17323 else { val = Infinity; }
17324 if (val >= radix) { break }
17325 lastCode = code;
17326 total = total * radix + val;
17327 }
17328
17329 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
17330 if (this.pos === start || len != null && this.pos - start !== len) { return null }
17331
17332 return total
17333};
17334
17335function stringToNumber(str, isLegacyOctalNumericLiteral) {
17336 if (isLegacyOctalNumericLiteral) {
17337 return parseInt(str, 8)
17338 }
17339
17340 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
17341 return parseFloat(str.replace(/_/g, ""))
17342}
17343
17344function stringToBigInt(str) {
17345 if (typeof BigInt !== "function") {
17346 return null
17347 }
17348
17349 // `BigInt(value)` throws syntax error if the string contains numeric separators.
17350 return BigInt(str.replace(/_/g, ""))
17351}
17352
17353pp$9.readRadixNumber = function(radix) {
17354 var start = this.pos;
17355 this.pos += 2; // 0x
17356 var val = this.readInt(radix);
17357 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
17358 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
17359 val = stringToBigInt(this.input.slice(start, this.pos));
17360 ++this.pos;
17361 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
17362 return this.finishToken(types.num, val)
17363};
17364
17365// Read an integer, octal integer, or floating-point number.
17366
17367pp$9.readNumber = function(startsWithDot) {
17368 var start = this.pos;
17369 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
17370 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
17371 if (octal && this.strict) { this.raise(start, "Invalid number"); }
17372 var next = this.input.charCodeAt(this.pos);
17373 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
17374 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
17375 ++this.pos;
17376 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
17377 return this.finishToken(types.num, val$1)
17378 }
17379 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
17380 if (next === 46 && !octal) { // '.'
17381 ++this.pos;
17382 this.readInt(10);
17383 next = this.input.charCodeAt(this.pos);
17384 }
17385 if ((next === 69 || next === 101) && !octal) { // 'eE'
17386 next = this.input.charCodeAt(++this.pos);
17387 if (next === 43 || next === 45) { ++this.pos; } // '+-'
17388 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
17389 }
17390 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
17391
17392 var val = stringToNumber(this.input.slice(start, this.pos), octal);
17393 return this.finishToken(types.num, val)
17394};
17395
17396// Read a string value, interpreting backslash-escapes.
17397
17398pp$9.readCodePoint = function() {
17399 var ch = this.input.charCodeAt(this.pos), code;
17400
17401 if (ch === 123) { // '{'
17402 if (this.options.ecmaVersion < 6) { this.unexpected(); }
17403 var codePos = ++this.pos;
17404 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
17405 ++this.pos;
17406 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
17407 } else {
17408 code = this.readHexChar(4);
17409 }
17410 return code
17411};
17412
17413function codePointToString$1(code) {
17414 // UTF-16 Decoding
17415 if (code <= 0xFFFF) { return String.fromCharCode(code) }
17416 code -= 0x10000;
17417 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
17418}
17419
17420pp$9.readString = function(quote) {
17421 var out = "", chunkStart = ++this.pos;
17422 for (;;) {
17423 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
17424 var ch = this.input.charCodeAt(this.pos);
17425 if (ch === quote) { break }
17426 if (ch === 92) { // '\'
17427 out += this.input.slice(chunkStart, this.pos);
17428 out += this.readEscapedChar(false);
17429 chunkStart = this.pos;
17430 } else {
17431 if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
17432 ++this.pos;
17433 }
17434 }
17435 out += this.input.slice(chunkStart, this.pos++);
17436 return this.finishToken(types.string, out)
17437};
17438
17439// Reads template string tokens.
17440
17441var INVALID_TEMPLATE_ESCAPE_ERROR = {};
17442
17443pp$9.tryReadTemplateToken = function() {
17444 this.inTemplateElement = true;
17445 try {
17446 this.readTmplToken();
17447 } catch (err) {
17448 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
17449 this.readInvalidTemplateToken();
17450 } else {
17451 throw err
17452 }
17453 }
17454
17455 this.inTemplateElement = false;
17456};
17457
17458pp$9.invalidStringToken = function(position, message) {
17459 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
17460 throw INVALID_TEMPLATE_ESCAPE_ERROR
17461 } else {
17462 this.raise(position, message);
17463 }
17464};
17465
17466pp$9.readTmplToken = function() {
17467 var out = "", chunkStart = this.pos;
17468 for (;;) {
17469 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
17470 var ch = this.input.charCodeAt(this.pos);
17471 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
17472 if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
17473 if (ch === 36) {
17474 this.pos += 2;
17475 return this.finishToken(types.dollarBraceL)
17476 } else {
17477 ++this.pos;
17478 return this.finishToken(types.backQuote)
17479 }
17480 }
17481 out += this.input.slice(chunkStart, this.pos);
17482 return this.finishToken(types.template, out)
17483 }
17484 if (ch === 92) { // '\'
17485 out += this.input.slice(chunkStart, this.pos);
17486 out += this.readEscapedChar(true);
17487 chunkStart = this.pos;
17488 } else if (isNewLine(ch)) {
17489 out += this.input.slice(chunkStart, this.pos);
17490 ++this.pos;
17491 switch (ch) {
17492 case 13:
17493 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
17494 case 10:
17495 out += "\n";
17496 break
17497 default:
17498 out += String.fromCharCode(ch);
17499 break
17500 }
17501 if (this.options.locations) {
17502 ++this.curLine;
17503 this.lineStart = this.pos;
17504 }
17505 chunkStart = this.pos;
17506 } else {
17507 ++this.pos;
17508 }
17509 }
17510};
17511
17512// Reads a template token to search for the end, without validating any escape sequences
17513pp$9.readInvalidTemplateToken = function() {
17514 for (; this.pos < this.input.length; this.pos++) {
17515 switch (this.input[this.pos]) {
17516 case "\\":
17517 ++this.pos;
17518 break
17519
17520 case "$":
17521 if (this.input[this.pos + 1] !== "{") {
17522 break
17523 }
17524 // falls through
17525
17526 case "`":
17527 return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
17528
17529 // no default
17530 }
17531 }
17532 this.raise(this.start, "Unterminated template");
17533};
17534
17535// Used to read escaped characters
17536
17537pp$9.readEscapedChar = function(inTemplate) {
17538 var ch = this.input.charCodeAt(++this.pos);
17539 ++this.pos;
17540 switch (ch) {
17541 case 110: return "\n" // 'n' -> '\n'
17542 case 114: return "\r" // 'r' -> '\r'
17543 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
17544 case 117: return codePointToString$1(this.readCodePoint()) // 'u'
17545 case 116: return "\t" // 't' -> '\t'
17546 case 98: return "\b" // 'b' -> '\b'
17547 case 118: return "\u000b" // 'v' -> '\u000b'
17548 case 102: return "\f" // 'f' -> '\f'
17549 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
17550 case 10: // ' \n'
17551 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
17552 return ""
17553 case 56:
17554 case 57:
17555 if (this.strict) {
17556 this.invalidStringToken(
17557 this.pos - 1,
17558 "Invalid escape sequence"
17559 );
17560 }
17561 if (inTemplate) {
17562 var codePos = this.pos - 1;
17563
17564 this.invalidStringToken(
17565 codePos,
17566 "Invalid escape sequence in template string"
17567 );
17568
17569 return null
17570 }
17571 default:
17572 if (ch >= 48 && ch <= 55) {
17573 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
17574 var octal = parseInt(octalStr, 8);
17575 if (octal > 255) {
17576 octalStr = octalStr.slice(0, -1);
17577 octal = parseInt(octalStr, 8);
17578 }
17579 this.pos += octalStr.length - 1;
17580 ch = this.input.charCodeAt(this.pos);
17581 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
17582 this.invalidStringToken(
17583 this.pos - 1 - octalStr.length,
17584 inTemplate
17585 ? "Octal literal in template string"
17586 : "Octal literal in strict mode"
17587 );
17588 }
17589 return String.fromCharCode(octal)
17590 }
17591 if (isNewLine(ch)) {
17592 // Unicode new line characters after \ get removed from output in both
17593 // template literals and strings
17594 return ""
17595 }
17596 return String.fromCharCode(ch)
17597 }
17598};
17599
17600// Used to read character escape sequences ('\x', '\u', '\U').
17601
17602pp$9.readHexChar = function(len) {
17603 var codePos = this.pos;
17604 var n = this.readInt(16, len);
17605 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
17606 return n
17607};
17608
17609// Read an identifier, and return it as a string. Sets `this.containsEsc`
17610// to whether the word contained a '\u' escape.
17611//
17612// Incrementally adds only escaped chars, adding other chunks as-is
17613// as a micro-optimization.
17614
17615pp$9.readWord1 = function() {
17616 this.containsEsc = false;
17617 var word = "", first = true, chunkStart = this.pos;
17618 var astral = this.options.ecmaVersion >= 6;
17619 while (this.pos < this.input.length) {
17620 var ch = this.fullCharCodeAtPos();
17621 if (isIdentifierChar(ch, astral)) {
17622 this.pos += ch <= 0xffff ? 1 : 2;
17623 } else if (ch === 92) { // "\"
17624 this.containsEsc = true;
17625 word += this.input.slice(chunkStart, this.pos);
17626 var escStart = this.pos;
17627 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
17628 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
17629 ++this.pos;
17630 var esc = this.readCodePoint();
17631 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
17632 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
17633 word += codePointToString$1(esc);
17634 chunkStart = this.pos;
17635 } else {
17636 break
17637 }
17638 first = false;
17639 }
17640 return word + this.input.slice(chunkStart, this.pos)
17641};
17642
17643// Read an identifier or keyword token. Will check for reserved
17644// words when necessary.
17645
17646pp$9.readWord = function() {
17647 var word = this.readWord1();
17648 var type = types.name;
17649 if (this.keywords.test(word)) {
17650 type = keywords$1[word];
17651 }
17652 return this.finishToken(type, word)
17653};
17654
17655// Acorn is a tiny, fast JavaScript parser written in JavaScript.
17656
17657var version$1 = "8.0.3";
17658
17659Parser.acorn = {
17660 Parser: Parser,
17661 version: version$1,
17662 defaultOptions: defaultOptions,
17663 Position: Position,
17664 SourceLocation: SourceLocation,
17665 getLineInfo: getLineInfo,
17666 Node: Node,
17667 TokenType: TokenType,
17668 tokTypes: types,
17669 keywordTypes: keywords$1,
17670 TokContext: TokContext,
17671 tokContexts: types$1,
17672 isIdentifierChar: isIdentifierChar,
17673 isIdentifierStart: isIdentifierStart,
17674 Token: Token,
17675 isNewLine: isNewLine,
17676 lineBreak: lineBreak,
17677 lineBreakG: lineBreakG,
17678 nonASCIIwhitespace: nonASCIIwhitespace
17679};
17680
17681// The main exported interface (under `self.acorn` when in the
17682// browser) is a `parse` function that takes a code string and
17683// returns an abstract syntax tree as specified by [Mozilla parser
17684// API][api].
17685//
17686// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
17687
17688function parse(input, options) {
17689 return Parser.parse(input, options)
17690}
17691
17692// This function tries to parse a single expression at a given
17693// offset in a string. Useful for parsing mixed-language formats
17694// that embed JavaScript expressions.
17695
17696function parseExpressionAt(input, pos, options) {
17697 return Parser.parseExpressionAt(input, pos, options)
17698}
17699
17700// Acorn is organized as a tokenizer and a recursive-descent parser.
17701// The `tokenizer` export provides an interface to the tokenizer.
17702
17703function tokenizer(input, options) {
17704 return Parser.tokenizer(input, options)
17705}
17706
17707var acorn = {
17708 __proto__: null,
17709 Node: Node,
17710 Parser: Parser,
17711 Position: Position,
17712 SourceLocation: SourceLocation,
17713 TokContext: TokContext,
17714 Token: Token,
17715 TokenType: TokenType,
17716 defaultOptions: defaultOptions,
17717 getLineInfo: getLineInfo,
17718 isIdentifierChar: isIdentifierChar,
17719 isIdentifierStart: isIdentifierStart,
17720 isNewLine: isNewLine,
17721 keywordTypes: keywords$1,
17722 lineBreak: lineBreak,
17723 lineBreakG: lineBreakG,
17724 nonASCIIwhitespace: nonASCIIwhitespace,
17725 parse: parse,
17726 parseExpressionAt: parseExpressionAt,
17727 tokContexts: types$1,
17728 tokTypes: types,
17729 tokenizer: tokenizer,
17730 version: version$1
17731};
17732
17733class GlobalScope extends Scope {
17734 constructor() {
17735 super();
17736 this.variables.set('undefined', new UndefinedVariable());
17737 }
17738 findVariable(name) {
17739 let variable = this.variables.get(name);
17740 if (!variable) {
17741 variable = new GlobalVariable(name);
17742 this.variables.set(name, variable);
17743 }
17744 return variable;
17745 }
17746}
17747
17748const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
17749function mkdirpath(path) {
17750 const dir = sysPath.dirname(path);
17751 try {
17752 fs.readdirSync(dir);
17753 }
17754 catch (err) {
17755 mkdirpath(dir);
17756 try {
17757 fs.mkdirSync(dir);
17758 }
17759 catch (err2) {
17760 if (err2.code !== 'EEXIST') {
17761 throw err2;
17762 }
17763 }
17764 }
17765}
17766function writeFile(dest, data) {
17767 return new Promise((fulfil, reject) => {
17768 mkdirpath(dest);
17769 fs.writeFile(dest, data, err => {
17770 if (err) {
17771 reject(err);
17772 }
17773 else {
17774 fulfil();
17775 }
17776 });
17777 });
17778}
17779
17780async function resolveId(source, importer, preserveSymlinks, pluginDriver, skip, customOptions) {
17781 const pluginResult = await pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], null, skip);
17782 if (pluginResult != null)
17783 return pluginResult;
17784 // external modules (non-entry modules that start with neither '.' or '/')
17785 // are skipped at this stage.
17786 if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
17787 return null;
17788 // `resolve` processes paths from right to left, prepending them until an
17789 // absolute path is created. Absolute importees therefore shortcircuit the
17790 // resolve call and require no special handing on our part.
17791 // See https://nodejs.org/api/path.html#path_path_resolve_paths
17792 return addJsExtensionIfNecessary(sysPath.resolve(importer ? sysPath.dirname(importer) : sysPath.resolve(), source), preserveSymlinks);
17793}
17794function addJsExtensionIfNecessary(file, preserveSymlinks) {
17795 let found = findFile(file, preserveSymlinks);
17796 if (found)
17797 return found;
17798 found = findFile(file + '.mjs', preserveSymlinks);
17799 if (found)
17800 return found;
17801 found = findFile(file + '.js', preserveSymlinks);
17802 return found;
17803}
17804function findFile(file, preserveSymlinks) {
17805 try {
17806 const stats = fs.lstatSync(file);
17807 if (!preserveSymlinks && stats.isSymbolicLink())
17808 return findFile(fs.realpathSync(file), preserveSymlinks);
17809 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
17810 // check case
17811 const name = sysPath.basename(file);
17812 const files = fs.readdirSync(sysPath.dirname(file));
17813 if (files.indexOf(name) !== -1)
17814 return file;
17815 }
17816 }
17817 catch (_a) {
17818 // suppress
17819 }
17820}
17821
17822const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
17823const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
17824function throwPluginError(err, plugin, { hook, id } = {}) {
17825 if (typeof err === 'string')
17826 err = { message: err };
17827 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
17828 err.pluginCode = err.code;
17829 }
17830 err.code = Errors.PLUGIN_ERROR;
17831 err.plugin = plugin;
17832 if (hook) {
17833 err.hook = hook;
17834 }
17835 if (id) {
17836 err.id = id;
17837 }
17838 return error(err);
17839}
17840const deprecatedHooks = [
17841 { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
17842];
17843function warnDeprecatedHooks(plugins, options) {
17844 for (const { active, deprecated, replacement } of deprecatedHooks) {
17845 for (const plugin of plugins) {
17846 if (deprecated in plugin) {
17847 warnDeprecation({
17848 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
17849 plugin: plugin.name
17850 }, active, options);
17851 }
17852 }
17853 }
17854}
17855
17856function createPluginCache(cache) {
17857 return {
17858 has(id) {
17859 const item = cache[id];
17860 if (!item)
17861 return false;
17862 item[0] = 0;
17863 return true;
17864 },
17865 get(id) {
17866 const item = cache[id];
17867 if (!item)
17868 return undefined;
17869 item[0] = 0;
17870 return item[1];
17871 },
17872 set(id, value) {
17873 cache[id] = [0, value];
17874 },
17875 delete(id) {
17876 return delete cache[id];
17877 }
17878 };
17879}
17880function getTrackedPluginCache(pluginCache, onUse) {
17881 return {
17882 has(id) {
17883 onUse();
17884 return pluginCache.has(id);
17885 },
17886 get(id) {
17887 onUse();
17888 return pluginCache.get(id);
17889 },
17890 set(id, value) {
17891 onUse();
17892 return pluginCache.set(id, value);
17893 },
17894 delete(id) {
17895 onUse();
17896 return pluginCache.delete(id);
17897 }
17898 };
17899}
17900const NO_CACHE = {
17901 has() {
17902 return false;
17903 },
17904 get() {
17905 return undefined;
17906 },
17907 set() { },
17908 delete() {
17909 return false;
17910 }
17911};
17912function uncacheablePluginError(pluginName) {
17913 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
17914 pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
17915 return error({
17916 code: 'ANONYMOUS_PLUGIN_CACHE',
17917 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
17918 });
17919 }
17920 return error({
17921 code: 'DUPLICATE_PLUGIN_NAME',
17922 message: `The plugin name ${pluginName} is being used twice in the same build. Plugin names must be distinct or provide a cacheKey (please post an issue to the plugin if you are a plugin user).`
17923 });
17924}
17925function getCacheForUncacheablePlugin(pluginName) {
17926 return {
17927 has() {
17928 return uncacheablePluginError(pluginName);
17929 },
17930 get() {
17931 return uncacheablePluginError(pluginName);
17932 },
17933 set() {
17934 return uncacheablePluginError(pluginName);
17935 },
17936 delete() {
17937 return uncacheablePluginError(pluginName);
17938 }
17939 };
17940}
17941
17942function transform(source, module, pluginDriver, warn) {
17943 const id = module.id;
17944 const sourcemapChain = [];
17945 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
17946 const originalCode = source.code;
17947 let ast = source.ast;
17948 const transformDependencies = [];
17949 const emittedFiles = [];
17950 let customTransformCache = false;
17951 const useCustomTransformCache = () => (customTransformCache = true);
17952 let curPlugin;
17953 const curSource = source.code;
17954 function transformReducer(previousCode, result, plugin) {
17955 let code;
17956 let map;
17957 if (typeof result === 'string') {
17958 code = result;
17959 }
17960 else if (result && typeof result === 'object') {
17961 module.updateOptions(result);
17962 if (result.code == null) {
17963 if (result.map || result.ast) {
17964 warn(errNoTransformMapOrAstWithoutCode(plugin.name));
17965 }
17966 return previousCode;
17967 }
17968 ({ code, map, ast } = result);
17969 }
17970 else {
17971 return previousCode;
17972 }
17973 // strict null check allows 'null' maps to not be pushed to the chain,
17974 // while 'undefined' gets the missing map warning
17975 if (map !== null) {
17976 sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
17977 missing: true,
17978 plugin: plugin.name
17979 });
17980 }
17981 return code;
17982 }
17983 return pluginDriver
17984 .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
17985 curPlugin = plugin;
17986 return {
17987 ...pluginContext,
17988 cache: customTransformCache
17989 ? pluginContext.cache
17990 : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
17991 warn(warning, pos) {
17992 if (typeof warning === 'string')
17993 warning = { message: warning };
17994 if (pos)
17995 augmentCodeLocation(warning, pos, curSource, id);
17996 warning.id = id;
17997 warning.hook = 'transform';
17998 pluginContext.warn(warning);
17999 },
18000 error(err, pos) {
18001 if (typeof err === 'string')
18002 err = { message: err };
18003 if (pos)
18004 augmentCodeLocation(err, pos, curSource, id);
18005 err.id = id;
18006 err.hook = 'transform';
18007 return pluginContext.error(err);
18008 },
18009 emitAsset(name, source) {
18010 emittedFiles.push({ type: 'asset', name, source });
18011 return pluginContext.emitAsset(name, source);
18012 },
18013 emitChunk(id, options) {
18014 emittedFiles.push({ type: 'chunk', id, name: options && options.name });
18015 return pluginContext.emitChunk(id, options);
18016 },
18017 emitFile(emittedFile) {
18018 emittedFiles.push(emittedFile);
18019 return pluginDriver.emitFile(emittedFile);
18020 },
18021 addWatchFile(id) {
18022 transformDependencies.push(id);
18023 pluginContext.addWatchFile(id);
18024 },
18025 setAssetSource() {
18026 return this.error({
18027 code: 'INVALID_SETASSETSOURCE',
18028 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
18029 });
18030 },
18031 getCombinedSourcemap() {
18032 const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
18033 if (!combinedMap) {
18034 const magicString = new MagicString(originalCode);
18035 return magicString.generateMap({ includeContent: true, hires: true, source: id });
18036 }
18037 if (originalSourcemap !== combinedMap) {
18038 originalSourcemap = combinedMap;
18039 sourcemapChain.length = 0;
18040 }
18041 return new SourceMap({
18042 ...combinedMap,
18043 file: null,
18044 sourcesContent: combinedMap.sourcesContent
18045 });
18046 }
18047 };
18048 })
18049 .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
18050 .then(code => {
18051 if (!customTransformCache) {
18052 // files emitted by a transform hook need to be emitted again if the hook is skipped
18053 if (emittedFiles.length)
18054 module.transformFiles = emittedFiles;
18055 }
18056 return {
18057 ast,
18058 code,
18059 customTransformCache,
18060 meta: module.meta,
18061 originalCode,
18062 originalSourcemap,
18063 sourcemapChain,
18064 transformDependencies
18065 };
18066 });
18067}
18068
18069class ModuleLoader {
18070 constructor(graph, modulesById, options, pluginDriver) {
18071 this.graph = graph;
18072 this.modulesById = modulesById;
18073 this.options = options;
18074 this.pluginDriver = pluginDriver;
18075 this.implicitEntryModules = new Set();
18076 this.indexedEntryModules = [];
18077 this.latestLoadModulesPromise = Promise.resolve();
18078 this.nextEntryModuleIndex = 0;
18079 this.hasModuleSideEffects = options.treeshake
18080 ? options.treeshake.moduleSideEffects
18081 : () => true;
18082 }
18083 async addAdditionalModules(unresolvedModules) {
18084 const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
18085 await this.awaitLoadModulesPromise();
18086 return result;
18087 }
18088 async addEntryModules(unresolvedEntryModules, isUserDefined) {
18089 const firstEntryModuleIndex = this.nextEntryModuleIndex;
18090 this.nextEntryModuleIndex += unresolvedEntryModules.length;
18091 const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
18092 let moduleIndex = firstEntryModuleIndex;
18093 for (let index = 0; index < entryModules.length; index++) {
18094 const entryModule = entryModules[index];
18095 entryModule.isUserDefinedEntryPoint =
18096 entryModule.isUserDefinedEntryPoint || isUserDefined;
18097 addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
18098 const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
18099 if (!existingIndexedModule) {
18100 this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
18101 }
18102 else {
18103 existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
18104 }
18105 moduleIndex++;
18106 }
18107 this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
18108 return entryModules;
18109 }));
18110 await this.awaitLoadModulesPromise();
18111 return {
18112 entryModules: this.indexedEntryModules.map(({ module }) => module),
18113 implicitEntryModules: [...this.implicitEntryModules],
18114 newEntryModules
18115 };
18116 }
18117 async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
18118 const unresolvedModule = {
18119 fileName: fileName || null,
18120 id,
18121 importer,
18122 name: name || null
18123 };
18124 const module = implicitlyLoadedAfterOneOf
18125 ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
18126 : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
18127 if (preserveSignature != null) {
18128 module.preserveSignature = preserveSignature;
18129 }
18130 return module;
18131 }
18132 async resolveId(source, importer, customOptions, skip = null) {
18133 return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
18134 ? false
18135 : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, skip, customOptions), importer, source));
18136 }
18137 addDefaultsToResolvedId(resolvedId) {
18138 var _a, _b;
18139 if (!resolvedId) {
18140 return null;
18141 }
18142 const external = resolvedId.external || false;
18143 return {
18144 external,
18145 id: resolvedId.id,
18146 meta: resolvedId.meta || EMPTY_OBJECT,
18147 moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, external),
18148 syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
18149 };
18150 }
18151 addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
18152 return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
18153 addChunkNamesToModule(entryModule, unresolvedModule, false);
18154 if (!entryModule.isEntryPoint) {
18155 this.implicitEntryModules.add(entryModule);
18156 const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
18157 for (const module of implicitlyLoadedAfterModules) {
18158 entryModule.implicitlyLoadedAfter.add(module);
18159 }
18160 for (const dependant of entryModule.implicitlyLoadedAfter) {
18161 dependant.implicitlyLoadedBefore.add(entryModule);
18162 }
18163 }
18164 return entryModule;
18165 }));
18166 }
18167 async addModuleSource(id, importer, module) {
18168 var _a;
18169 timeStart('load modules', 3);
18170 let source;
18171 try {
18172 source = (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await readFile(id));
18173 }
18174 catch (err) {
18175 timeEnd('load modules', 3);
18176 let msg = `Could not load ${id}`;
18177 if (importer)
18178 msg += ` (imported by ${relativeId(importer)})`;
18179 msg += `: ${err.message}`;
18180 err.message = msg;
18181 throw err;
18182 }
18183 timeEnd('load modules', 3);
18184 const sourceDescription = typeof source === 'string'
18185 ? { code: source }
18186 : typeof source === 'object' && typeof source.code === 'string'
18187 ? source
18188 : error(errBadLoader(id));
18189 const cachedModule = this.graph.cachedModules.get(id);
18190 if (cachedModule &&
18191 !cachedModule.customTransformCache &&
18192 cachedModule.originalCode === sourceDescription.code) {
18193 if (cachedModule.transformFiles) {
18194 for (const emittedFile of cachedModule.transformFiles)
18195 this.pluginDriver.emitFile(emittedFile);
18196 }
18197 module.setSource(cachedModule);
18198 }
18199 else {
18200 module.updateOptions(sourceDescription);
18201 module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
18202 }
18203 }
18204 async awaitLoadModulesPromise() {
18205 let startingPromise;
18206 do {
18207 startingPromise = this.latestLoadModulesPromise;
18208 await startingPromise;
18209 } while (startingPromise !== this.latestLoadModulesPromise);
18210 }
18211 extendLoadModulesPromise(loadNewModulesPromise) {
18212 this.latestLoadModulesPromise = Promise.all([
18213 loadNewModulesPromise,
18214 this.latestLoadModulesPromise
18215 ]);
18216 this.latestLoadModulesPromise.catch(() => {
18217 /* Avoid unhandled Promise rejections */
18218 });
18219 return loadNewModulesPromise;
18220 }
18221 async fetchDynamicDependencies(module) {
18222 const dependencies = await Promise.all(module.dynamicImports.map(async (dynamicImport) => {
18223 const resolvedId = await this.resolveDynamicImport(module, dynamicImport.argument, module.id);
18224 if (resolvedId === null)
18225 return null;
18226 if (typeof resolvedId === 'string') {
18227 dynamicImport.resolution = resolvedId;
18228 return null;
18229 }
18230 return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
18231 }));
18232 for (const dependency of dependencies) {
18233 if (dependency) {
18234 module.dynamicDependencies.add(dependency);
18235 dependency.dynamicImporters.push(module.id);
18236 }
18237 }
18238 }
18239 async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
18240 const existingModule = this.modulesById.get(id);
18241 if (existingModule instanceof Module) {
18242 if (isEntry) {
18243 existingModule.isEntryPoint = true;
18244 this.implicitEntryModules.delete(existingModule);
18245 for (const dependant of existingModule.implicitlyLoadedAfter) {
18246 dependant.implicitlyLoadedBefore.delete(existingModule);
18247 }
18248 existingModule.implicitlyLoadedAfter.clear();
18249 }
18250 return existingModule;
18251 }
18252 const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
18253 this.modulesById.set(id, module);
18254 this.graph.watchFiles[id] = true;
18255 await this.addModuleSource(id, importer, module);
18256 await Promise.all([
18257 this.fetchStaticDependencies(module),
18258 this.fetchDynamicDependencies(module)
18259 ]);
18260 module.linkImports();
18261 return module;
18262 }
18263 fetchResolvedDependency(source, importer, resolvedId) {
18264 if (resolvedId.external) {
18265 if (!this.modulesById.has(resolvedId.id)) {
18266 this.modulesById.set(resolvedId.id, new ExternalModule(this.options, resolvedId.id, resolvedId.moduleSideEffects, resolvedId.meta));
18267 }
18268 const externalModule = this.modulesById.get(resolvedId.id);
18269 if (!(externalModule instanceof ExternalModule)) {
18270 return error(errInternalIdCannotBeExternal(source, importer));
18271 }
18272 return Promise.resolve(externalModule);
18273 }
18274 else {
18275 return this.fetchModule(resolvedId, importer, false);
18276 }
18277 }
18278 async fetchStaticDependencies(module) {
18279 for (const dependency of await Promise.all(Array.from(module.sources, async (source) => this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
18280 module.resolvedIds[source] ||
18281 this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id)))))) {
18282 module.dependencies.add(dependency);
18283 dependency.importers.push(module.id);
18284 }
18285 }
18286 getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
18287 if (resolveIdResult) {
18288 if (typeof resolveIdResult === 'object') {
18289 return {
18290 ...resolveIdResult,
18291 external: resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true)
18292 };
18293 }
18294 const external = this.options.external(resolveIdResult, importer, true);
18295 return {
18296 external,
18297 id: external ? normalizeRelativeExternalId(resolveIdResult, importer) : resolveIdResult
18298 };
18299 }
18300 const id = normalizeRelativeExternalId(source, importer);
18301 if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
18302 return null;
18303 }
18304 return {
18305 external: true,
18306 id
18307 };
18308 }
18309 handleResolveId(resolvedId, source, importer) {
18310 if (resolvedId === null) {
18311 if (isRelative(source)) {
18312 return error(errUnresolvedImport(source, importer));
18313 }
18314 this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
18315 return {
18316 external: true,
18317 id: source,
18318 meta: EMPTY_OBJECT,
18319 moduleSideEffects: this.hasModuleSideEffects(source, true),
18320 syntheticNamedExports: false
18321 };
18322 }
18323 else {
18324 if (resolvedId.external && resolvedId.syntheticNamedExports) {
18325 this.options.onwarn(errExternalSyntheticExports(source, importer));
18326 }
18327 }
18328 return resolvedId;
18329 }
18330 async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
18331 const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, null, EMPTY_OBJECT);
18332 if (resolveIdResult == null) {
18333 return error(implicitlyLoadedBefore === null
18334 ? errUnresolvedEntry(unresolvedId)
18335 : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
18336 }
18337 if (resolveIdResult === false ||
18338 (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
18339 return error(implicitlyLoadedBefore === null
18340 ? errEntryCannotBeExternal(unresolvedId)
18341 : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
18342 }
18343 return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object' ? resolveIdResult : { id: resolveIdResult }), undefined, isEntry);
18344 }
18345 async resolveDynamicImport(module, specifier, importer) {
18346 // TODO we only should expose the acorn AST here
18347 const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
18348 specifier,
18349 importer
18350 ]);
18351 if (typeof specifier !== 'string') {
18352 if (typeof resolution === 'string') {
18353 return resolution;
18354 }
18355 if (!resolution) {
18356 return null;
18357 }
18358 return {
18359 external: false,
18360 moduleSideEffects: true,
18361 ...resolution
18362 };
18363 }
18364 if (resolution == null) {
18365 return (module.resolvedIds[specifier] =
18366 module.resolvedIds[specifier] ||
18367 this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
18368 }
18369 return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
18370 }
18371}
18372function normalizeRelativeExternalId(source, importer) {
18373 return isRelative(source)
18374 ? importer
18375 ? sysPath.resolve(importer, '..', source)
18376 : sysPath.resolve(source)
18377 : source;
18378}
18379function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
18380 if (fileName !== null) {
18381 module.chunkFileNames.add(fileName);
18382 }
18383 else if (name !== null) {
18384 if (module.chunkName === null) {
18385 module.chunkName = name;
18386 }
18387 if (isUserDefined) {
18388 module.userChunkNames.add(name);
18389 }
18390 }
18391}
18392
18393function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
18394 let deprecationWarningShown = false;
18395 return ((...args) => {
18396 if (!deprecationWarningShown) {
18397 deprecationWarningShown = true;
18398 warnDeprecation({
18399 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
18400 plugin: pluginName
18401 }, activeDeprecation, options);
18402 }
18403 return handler(...args);
18404 });
18405}
18406function getPluginContexts(pluginCache, graph, options, fileEmitter) {
18407 const existingPluginNames = new Set();
18408 return (plugin, pidx) => {
18409 let cacheable = true;
18410 if (typeof plugin.cacheKey !== 'string') {
18411 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
18412 plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
18413 existingPluginNames.has(plugin.name)) {
18414 cacheable = false;
18415 }
18416 else {
18417 existingPluginNames.add(plugin.name);
18418 }
18419 }
18420 let cacheInstance;
18421 if (!pluginCache) {
18422 cacheInstance = NO_CACHE;
18423 }
18424 else if (cacheable) {
18425 const cacheKey = plugin.cacheKey || plugin.name;
18426 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
18427 }
18428 else {
18429 cacheInstance = getCacheForUncacheablePlugin(plugin.name);
18430 }
18431 const context = {
18432 addWatchFile(id) {
18433 if (graph.phase >= BuildPhase.GENERATE) {
18434 return this.error(errInvalidRollupPhaseForAddWatchFile());
18435 }
18436 graph.watchFiles[id] = true;
18437 },
18438 cache: cacheInstance,
18439 emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, true, options),
18440 emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, true, options),
18441 emitFile: fileEmitter.emitFile,
18442 error(err) {
18443 return throwPluginError(err, plugin.name);
18444 },
18445 getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
18446 getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
18447 getFileName: fileEmitter.getFileName,
18448 getModuleIds: () => graph.modulesById.keys(),
18449 getModuleInfo: graph.getModuleInfo,
18450 isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
18451 meta: {
18452 rollupVersion: version,
18453 watchMode: graph.watchMode
18454 },
18455 get moduleIds() {
18456 function* wrappedModuleIds() {
18457 warnDeprecation({
18458 message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
18459 plugin: plugin.name
18460 }, false, options);
18461 yield* moduleIds;
18462 }
18463 const moduleIds = graph.modulesById.keys();
18464 return wrappedModuleIds();
18465 },
18466 parse: graph.contextParse,
18467 resolve(source, importer, { custom, skipSelf } = BLANK) {
18468 return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? pidx : null);
18469 },
18470 resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
18471 .resolveId(source, importer, BLANK)
18472 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
18473 setAssetSource: fileEmitter.setAssetSource,
18474 warn(warning) {
18475 if (typeof warning === 'string')
18476 warning = { message: warning };
18477 if (warning.code)
18478 warning.pluginCode = warning.code;
18479 warning.code = 'PLUGIN_WARNING';
18480 warning.plugin = plugin.name;
18481 options.onwarn(warning);
18482 }
18483 };
18484 return context;
18485 };
18486}
18487
18488const inputHookNames = {
18489 buildEnd: 1,
18490 buildStart: 1,
18491 load: 1,
18492 options: 1,
18493 resolveDynamicImport: 1,
18494 resolveId: 1,
18495 transform: 1,
18496 watchChange: 1
18497};
18498const inputHooks = Object.keys(inputHookNames);
18499function throwInvalidHookError(hookName, pluginName) {
18500 return error({
18501 code: 'INVALID_PLUGIN_HOOK',
18502 message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
18503 });
18504}
18505class PluginDriver {
18506 constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
18507 this.graph = graph;
18508 this.options = options;
18509 warnDeprecatedHooks(userPlugins, options);
18510 this.pluginCache = pluginCache;
18511 this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
18512 this.emitFile = this.fileEmitter.emitFile;
18513 this.getFileName = this.fileEmitter.getFileName;
18514 this.finaliseAssets = this.fileEmitter.assertAssetsFinalized;
18515 this.setOutputBundle = this.fileEmitter.setOutputBundle;
18516 this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
18517 this.pluginContexts = this.plugins.map(getPluginContexts(pluginCache, graph, options, this.fileEmitter));
18518 if (basePluginDriver) {
18519 for (const plugin of userPlugins) {
18520 for (const hook of inputHooks) {
18521 if (hook in plugin) {
18522 options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
18523 }
18524 }
18525 }
18526 }
18527 }
18528 createOutputPluginDriver(plugins) {
18529 return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
18530 }
18531 // chains, first non-null result stops and returns
18532 hookFirst(hookName, args, replaceContext, skip) {
18533 let promise = Promise.resolve(undefined);
18534 for (let i = 0; i < this.plugins.length; i++) {
18535 if (skip === i)
18536 continue;
18537 promise = promise.then(result => {
18538 if (result != null)
18539 return result;
18540 return this.runHook(hookName, args, i, false, replaceContext);
18541 });
18542 }
18543 return promise;
18544 }
18545 // chains synchronously, first non-null result stops and returns
18546 hookFirstSync(hookName, args, replaceContext) {
18547 for (let i = 0; i < this.plugins.length; i++) {
18548 const result = this.runHookSync(hookName, args, i, replaceContext);
18549 if (result != null)
18550 return result;
18551 }
18552 return null;
18553 }
18554 // parallel, ignores returns
18555 hookParallel(hookName, args, replaceContext) {
18556 const promises = [];
18557 for (let i = 0; i < this.plugins.length; i++) {
18558 const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
18559 if (!hookPromise)
18560 continue;
18561 promises.push(hookPromise);
18562 }
18563 return Promise.all(promises).then(() => { });
18564 }
18565 // chains, reduces returned value, handling the reduced value as the first hook argument
18566 hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
18567 let promise = Promise.resolve(arg0);
18568 for (let i = 0; i < this.plugins.length; i++) {
18569 promise = promise.then(arg0 => {
18570 const args = [arg0, ...rest];
18571 const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
18572 if (!hookPromise)
18573 return arg0;
18574 return hookPromise.then(result => reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]));
18575 });
18576 }
18577 return promise;
18578 }
18579 // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
18580 hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
18581 for (let i = 0; i < this.plugins.length; i++) {
18582 const args = [arg0, ...rest];
18583 const result = this.runHookSync(hookName, args, i, replaceContext);
18584 arg0 = reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]);
18585 }
18586 return arg0;
18587 }
18588 // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
18589 hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
18590 let promise = Promise.resolve(initialValue);
18591 for (let i = 0; i < this.plugins.length; i++) {
18592 promise = promise.then(value => {
18593 const hookPromise = this.runHook(hookName, args, i, true, replaceContext);
18594 if (!hookPromise)
18595 return value;
18596 return hookPromise.then(result => reduce.call(this.pluginContexts[i], value, result, this.plugins[i]));
18597 });
18598 }
18599 return promise;
18600 }
18601 // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
18602 hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
18603 let acc = initialValue;
18604 for (let i = 0; i < this.plugins.length; i++) {
18605 const result = this.runHookSync(hookName, args, i, replaceContext);
18606 acc = reduce.call(this.pluginContexts[i], acc, result, this.plugins[i]);
18607 }
18608 return acc;
18609 }
18610 // chains, ignores returns
18611 hookSeq(hookName, args, replaceContext) {
18612 let promise = Promise.resolve();
18613 for (let i = 0; i < this.plugins.length; i++) {
18614 promise = promise.then(() => this.runHook(hookName, args, i, false, replaceContext));
18615 }
18616 return promise;
18617 }
18618 // chains synchronously, ignores returns
18619 hookSeqSync(hookName, args, replaceContext) {
18620 for (let i = 0; i < this.plugins.length; i++) {
18621 this.runHookSync(hookName, args, i, replaceContext);
18622 }
18623 }
18624 runHook(hookName, args, pluginIndex, permitValues, hookContext) {
18625 const plugin = this.plugins[pluginIndex];
18626 const hook = plugin[hookName];
18627 if (!hook)
18628 return undefined;
18629 let context = this.pluginContexts[pluginIndex];
18630 if (hookContext) {
18631 context = hookContext(context, plugin);
18632 }
18633 return Promise.resolve()
18634 .then(() => {
18635 // permit values allows values to be returned instead of a functional hook
18636 if (typeof hook !== 'function') {
18637 if (permitValues)
18638 return hook;
18639 return throwInvalidHookError(hookName, plugin.name);
18640 }
18641 return hook.apply(context, args);
18642 })
18643 .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
18644 }
18645 /**
18646 * Run a sync plugin hook and return the result.
18647 * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
18648 * @param args Arguments passed to the plugin hook.
18649 * @param pluginIndex Index of the plugin inside `this.plugins[]`.
18650 * @param hookContext When passed, the plugin context can be overridden.
18651 */
18652 runHookSync(hookName, args, pluginIndex, hookContext) {
18653 const plugin = this.plugins[pluginIndex];
18654 const hook = plugin[hookName];
18655 if (!hook)
18656 return undefined;
18657 let context = this.pluginContexts[pluginIndex];
18658 if (hookContext) {
18659 context = hookContext(context, plugin);
18660 }
18661 try {
18662 // permit values allows values to be returned instead of a functional hook
18663 if (typeof hook !== 'function') {
18664 return throwInvalidHookError(hookName, plugin.name);
18665 }
18666 return hook.apply(context, args);
18667 }
18668 catch (err) {
18669 return throwPluginError(err, plugin.name, { hook: hookName });
18670 }
18671 }
18672}
18673
18674function normalizeEntryModules(entryModules) {
18675 if (Array.isArray(entryModules)) {
18676 return entryModules.map(id => ({
18677 fileName: null,
18678 id,
18679 implicitlyLoadedAfter: [],
18680 importer: undefined,
18681 name: null
18682 }));
18683 }
18684 return Object.keys(entryModules).map(name => ({
18685 fileName: null,
18686 id: entryModules[name],
18687 implicitlyLoadedAfter: [],
18688 importer: undefined,
18689 name
18690 }));
18691}
18692class Graph {
18693 constructor(options, watcher) {
18694 var _a, _b;
18695 this.options = options;
18696 this.entryModules = [];
18697 this.modulesById = new Map();
18698 this.needsTreeshakingPass = false;
18699 this.phase = BuildPhase.LOAD_AND_PARSE;
18700 this.watchFiles = Object.create(null);
18701 this.watchMode = false;
18702 this.externalModules = [];
18703 this.implicitEntryModules = [];
18704 this.modules = [];
18705 this.getModuleInfo = (moduleId) => {
18706 const foundModule = this.modulesById.get(moduleId);
18707 if (!foundModule)
18708 return null;
18709 return {
18710 get dynamicallyImportedIds() {
18711 if (foundModule instanceof Module) {
18712 const dynamicallyImportedIds = [];
18713 for (const { resolution } of foundModule.dynamicImports) {
18714 if (resolution instanceof Module || resolution instanceof ExternalModule) {
18715 dynamicallyImportedIds.push(resolution.id);
18716 }
18717 }
18718 return dynamicallyImportedIds;
18719 }
18720 return EMPTY_ARRAY;
18721 },
18722 get dynamicImporters() {
18723 return foundModule.dynamicImporters.sort();
18724 },
18725 hasModuleSideEffects: foundModule.moduleSideEffects,
18726 id: foundModule.id,
18727 get implicitlyLoadedAfterOneOf() {
18728 return foundModule instanceof Module
18729 ? Array.from(foundModule.implicitlyLoadedAfter, getId)
18730 : EMPTY_ARRAY;
18731 },
18732 get implicitlyLoadedBefore() {
18733 return foundModule instanceof Module
18734 ? Array.from(foundModule.implicitlyLoadedBefore, getId)
18735 : [];
18736 },
18737 get importedIds() {
18738 if (foundModule instanceof Module) {
18739 return Array.from(foundModule.sources, source => foundModule.resolvedIds[source].id);
18740 }
18741 return EMPTY_ARRAY;
18742 },
18743 get importers() {
18744 return foundModule.importers.sort();
18745 },
18746 isEntry: foundModule instanceof Module && foundModule.isEntryPoint,
18747 isExternal: foundModule instanceof ExternalModule,
18748 meta: foundModule.meta
18749 };
18750 };
18751 this.deoptimizationTracker = new PathTracker();
18752 this.cachedModules = new Map();
18753 if (options.cache !== false) {
18754 if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
18755 for (const module of options.cache.modules)
18756 this.cachedModules.set(module.id, module);
18757 }
18758 this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
18759 // increment access counter
18760 for (const name in this.pluginCache) {
18761 const cache = this.pluginCache[name];
18762 for (const key of Object.keys(cache))
18763 cache[key][0]++;
18764 }
18765 }
18766 this.contextParse = (code, options = {}) => this.acornParser.parse(code, {
18767 ...this.options.acorn,
18768 ...options
18769 });
18770 if (watcher) {
18771 this.watchMode = true;
18772 const handleChange = (id) => this.pluginDriver.hookSeqSync('watchChange', [id]);
18773 watcher.on('change', handleChange);
18774 watcher.once('restart', () => {
18775 watcher.removeListener('change', handleChange);
18776 });
18777 }
18778 this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
18779 this.scope = new GlobalScope();
18780 this.acornParser = Parser.extend(...options.acornInjectPlugins);
18781 this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
18782 }
18783 async build() {
18784 timeStart('generate module graph', 2);
18785 await this.generateModuleGraph();
18786 timeEnd('generate module graph', 2);
18787 timeStart('sort modules', 2);
18788 this.phase = BuildPhase.ANALYSE;
18789 this.sortModules();
18790 timeEnd('sort modules', 2);
18791 timeStart('mark included statements', 2);
18792 this.includeStatements();
18793 timeEnd('mark included statements', 2);
18794 this.phase = BuildPhase.GENERATE;
18795 }
18796 getCache() {
18797 // handle plugin cache eviction
18798 for (const name in this.pluginCache) {
18799 const cache = this.pluginCache[name];
18800 let allDeleted = true;
18801 for (const key of Object.keys(cache)) {
18802 if (cache[key][0] >= this.options.experimentalCacheExpiry)
18803 delete cache[key];
18804 else
18805 allDeleted = false;
18806 }
18807 if (allDeleted)
18808 delete this.pluginCache[name];
18809 }
18810 return {
18811 modules: this.modules.map(module => module.toJSON()),
18812 plugins: this.pluginCache
18813 };
18814 }
18815 async generateModuleGraph() {
18816 ({
18817 entryModules: this.entryModules,
18818 implicitEntryModules: this.implicitEntryModules
18819 } = await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
18820 if (this.entryModules.length === 0) {
18821 throw new Error('You must supply options.input to rollup');
18822 }
18823 for (const module of this.modulesById.values()) {
18824 if (module instanceof Module) {
18825 this.modules.push(module);
18826 }
18827 else {
18828 this.externalModules.push(module);
18829 }
18830 }
18831 }
18832 includeStatements() {
18833 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
18834 if (module.preserveSignature !== false) {
18835 module.includeAllExports(false);
18836 }
18837 else {
18838 markModuleAndImpureDependenciesAsExecuted(module);
18839 }
18840 }
18841 if (this.options.treeshake) {
18842 let treeshakingPass = 1;
18843 do {
18844 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
18845 this.needsTreeshakingPass = false;
18846 for (const module of this.modules) {
18847 if (module.isExecuted) {
18848 if (module.moduleSideEffects === 'no-treeshake') {
18849 module.includeAllInBundle();
18850 }
18851 else {
18852 module.include();
18853 }
18854 }
18855 }
18856 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
18857 } while (this.needsTreeshakingPass);
18858 }
18859 else {
18860 for (const module of this.modules)
18861 module.includeAllInBundle();
18862 }
18863 for (const externalModule of this.externalModules)
18864 externalModule.warnUnusedImports();
18865 for (const module of this.implicitEntryModules) {
18866 for (const dependant of module.implicitlyLoadedAfter) {
18867 if (!(dependant.isEntryPoint || dependant.isIncluded())) {
18868 error(errImplicitDependantIsNotIncluded(dependant));
18869 }
18870 }
18871 }
18872 }
18873 sortModules() {
18874 const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
18875 for (const cyclePath of cyclePaths) {
18876 this.options.onwarn({
18877 code: 'CIRCULAR_DEPENDENCY',
18878 cycle: cyclePath,
18879 importer: cyclePath[0],
18880 message: `Circular dependency: ${cyclePath.join(' -> ')}`
18881 });
18882 }
18883 this.modules = orderedModules;
18884 for (const module of this.modules) {
18885 module.bindReferences();
18886 }
18887 this.warnForMissingExports();
18888 }
18889 warnForMissingExports() {
18890 for (const module of this.modules) {
18891 for (const importName of Object.keys(module.importDescriptions)) {
18892 const importDescription = module.importDescriptions[importName];
18893 if (importDescription.name !== '*' &&
18894 !importDescription.module.getVariableForExportName(importDescription.name)) {
18895 module.warn({
18896 code: 'NON_EXISTENT_EXPORT',
18897 message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
18898 name: importDescription.name,
18899 source: importDescription.module.id
18900 }, importDescription.start);
18901 }
18902 }
18903 }
18904 }
18905}
18906
18907function createCommonjsModule(fn, basedir, module) {
18908 return module = {
18909 path: basedir,
18910 exports: {},
18911 require: function (path, base) {
18912 return commonjsRequire();
18913 }
18914 }, fn(module, module.exports), module.exports;
18915}
18916
18917function getAugmentedNamespace(n) {
18918 if (n.__esModule) return n;
18919 var a = Object.defineProperty({}, '__esModule', {value: true});
18920 Object.keys(n).forEach(function (k) {
18921 var d = Object.getOwnPropertyDescriptor(n, k);
18922 Object.defineProperty(a, k, d.get ? d : {
18923 enumerable: true,
18924 get: function () {
18925 return n[k];
18926 }
18927 });
18928 });
18929 return a;
18930}
18931
18932function commonjsRequire () {
18933 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
18934}
18935
18936var require$$0 = /*@__PURE__*/getAugmentedNamespace(acorn);
18937
18938const getPrototype = Object.getPrototypeOf || (o => o.__proto__);
18939
18940const getAcorn = Parser => {
18941 if (Parser.acorn) return Parser.acorn
18942
18943 const acorn = require$$0;
18944
18945 if (acorn.version.indexOf("6.") != 0 && acorn.version.indexOf("6.0.") == 0 && acorn.version.indexOf("7.") != 0) {
18946 throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn.version}`)
18947 }
18948
18949 // Make sure `Parser` comes from the same acorn as we `require`d,
18950 // otherwise the comparisons fail.
18951 for (let cur = Parser; cur && cur !== acorn.Parser; cur = getPrototype(cur)) {
18952 if (cur !== acorn.Parser) {
18953 throw new Error("acorn-private-class-elements does not support mixing different acorn copies")
18954 }
18955 }
18956 return acorn
18957};
18958
18959var acornPrivateClassElements = function(Parser) {
18960 // Only load this plugin once.
18961 if (Parser.prototype.parsePrivateName) {
18962 return Parser
18963 }
18964
18965 const acorn = getAcorn(Parser);
18966
18967 Parser = class extends Parser {
18968 _branch() {
18969 this.__branch = this.__branch || new Parser({ecmaVersion: this.options.ecmaVersion}, this.input);
18970 this.__branch.end = this.end;
18971 this.__branch.pos = this.pos;
18972 this.__branch.type = this.type;
18973 this.__branch.value = this.value;
18974 this.__branch.containsEsc = this.containsEsc;
18975 return this.__branch
18976 }
18977
18978 parsePrivateClassElementName(element) {
18979 element.computed = false;
18980 element.key = this.parsePrivateName();
18981 if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
18982 const accept = {get: "set", set: "get"}[element.kind];
18983 const privateBoundNames = this._privateBoundNames;
18984 if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
18985 this.raise(element.start, "Duplicate private element");
18986 }
18987 privateBoundNames[element.key.name] = element.kind || true;
18988 delete this._unresolvedPrivateNames[element.key.name];
18989 return element.key
18990 }
18991
18992 parsePrivateName() {
18993 const node = this.startNode();
18994 node.name = this.value;
18995 this.next();
18996 this.finishNode(node, "PrivateName");
18997 if (this.options.allowReserved == "never") this.checkUnreserved(node);
18998 return node
18999 }
19000
19001 // Parse # token
19002 getTokenFromCode(code) {
19003 if (code === 35) {
19004 ++this.pos;
19005 const word = this.readWord1();
19006 return this.finishToken(this.privateNameToken, word)
19007 }
19008 return super.getTokenFromCode(code)
19009 }
19010
19011 // Manage stacks and check for undeclared private names
19012 parseClass(node, isStatement) {
19013 const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
19014 this._outerPrivateBoundNames = this._privateBoundNames;
19015 this._privateBoundNames = Object.create(this._privateBoundNames || null);
19016 const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
19017 this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
19018 this._unresolvedPrivateNames = Object.create(null);
19019
19020 const _return = super.parseClass(node, isStatement);
19021
19022 const unresolvedPrivateNames = this._unresolvedPrivateNames;
19023 this._privateBoundNames = this._outerPrivateBoundNames;
19024 this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
19025 this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
19026 this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
19027 if (!this._unresolvedPrivateNames) {
19028 const names = Object.keys(unresolvedPrivateNames);
19029 if (names.length) {
19030 names.sort((n1, n2) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
19031 this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
19032 }
19033 } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
19034 return _return
19035 }
19036
19037 // Class heritage is evaluated with outer private environment
19038 parseClassSuper(node) {
19039 const privateBoundNames = this._privateBoundNames;
19040 this._privateBoundNames = this._outerPrivateBoundNames;
19041 const unresolvedPrivateNames = this._unresolvedPrivateNames;
19042 this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
19043 const _return = super.parseClassSuper(node);
19044 this._privateBoundNames = privateBoundNames;
19045 this._unresolvedPrivateNames = unresolvedPrivateNames;
19046 return _return
19047 }
19048
19049 // Parse private element access
19050 parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
19051 const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
19052 const branch = this._branch();
19053 if (!(
19054 (branch.eat(acorn.tokTypes.dot) || (optionalSupported && branch.eat(acorn.tokTypes.questionDot))) &&
19055 branch.type == this.privateNameToken
19056 )) {
19057 return super.parseSubscript.apply(this, arguments)
19058 }
19059 let optional = false;
19060 if (!this.eat(acorn.tokTypes.dot)) {
19061 this.expect(acorn.tokTypes.questionDot);
19062 optional = true;
19063 }
19064 let node = this.startNodeAt(startPos, startLoc);
19065 node.object = base;
19066 node.computed = false;
19067 if (optionalSupported) {
19068 node.optional = optional;
19069 }
19070 if (this.type == this.privateNameToken) {
19071 if (base.type == "Super") {
19072 this.raise(this.start, "Cannot access private element on super");
19073 }
19074 node.property = this.parsePrivateName();
19075 if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
19076 if (!this._unresolvedPrivateNames) {
19077 this.raise(node.property.start, "Usage of undeclared private name");
19078 }
19079 this._unresolvedPrivateNames[node.property.name] = node.property.start;
19080 }
19081 } else {
19082 node.property = this.parseIdent(true);
19083 }
19084 return this.finishNode(node, "MemberExpression")
19085 }
19086
19087 // Prohibit delete of private class elements
19088 parseMaybeUnary(refDestructuringErrors, sawUnary) {
19089 const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
19090 if (_return.operator == "delete") {
19091 if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateName") {
19092 this.raise(_return.start, "Private elements may not be deleted");
19093 }
19094 }
19095 return _return
19096 }
19097 };
19098 Parser.prototype.privateNameToken = new acorn.TokenType("privateName");
19099 return Parser
19100};
19101
19102var acornClassFields = function(Parser) {
19103 const acorn = Parser.acorn || require$$0;
19104 const tt = acorn.tokTypes;
19105
19106 Parser = acornPrivateClassElements(Parser);
19107 return class extends Parser {
19108 _maybeParseFieldValue(field) {
19109 if (this.eat(tt.eq)) {
19110 const oldInFieldValue = this._inFieldValue;
19111 this._inFieldValue = true;
19112 if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
19113 field.value = this.parseAwait();
19114 } else field.value = this.parseExpression();
19115 this._inFieldValue = oldInFieldValue;
19116 } else field.value = null;
19117 }
19118
19119 // Parse fields
19120 parseClassElement(_constructorAllowsSuper) {
19121 if (this.options.ecmaVersion >= 8 && (this.type == tt.name || this.type.keyword || this.type == this.privateNameToken || this.type == tt.bracketL || this.type == tt.string || this.type == tt.num)) {
19122 const branch = this._branch();
19123 if (branch.type == tt.bracketL) {
19124 let count = 0;
19125 do {
19126 if (branch.eat(tt.bracketL)) ++count;
19127 else if (branch.eat(tt.bracketR)) --count;
19128 else branch.next();
19129 } while (count > 0)
19130 } else branch.next(true);
19131 let isField = branch.type == tt.eq || branch.type == tt.semi;
19132 if (!isField && branch.canInsertSemicolon()) {
19133 isField = branch.type != tt.parenL;
19134 }
19135 if (isField) {
19136 const node = this.startNode();
19137 if (this.type == this.privateNameToken) {
19138 this.parsePrivateClassElementName(node);
19139 } else {
19140 this.parsePropertyName(node);
19141 }
19142 if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
19143 (node.key.type === "Literal" && node.key.value === "constructor")) {
19144 this.raise(node.key.start, "Classes may not have a field called constructor");
19145 }
19146 this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
19147 this._maybeParseFieldValue(node);
19148 this.exitScope();
19149 this.finishNode(node, "FieldDefinition");
19150 this.semicolon();
19151 return node
19152 }
19153 }
19154
19155 return super.parseClassElement.apply(this, arguments)
19156 }
19157
19158 // Prohibit arguments in class field initializers
19159 parseIdent(liberal, isBinding) {
19160 const ident = super.parseIdent(liberal, isBinding);
19161 if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
19162 return ident
19163 }
19164 }
19165};
19166
19167function withoutAcornBigInt(acorn, Parser) {
19168 return class extends Parser {
19169 readInt(radix, len) {
19170 // Hack: len is only != null for unicode escape sequences,
19171 // where numeric separators are not allowed
19172 if (len != null) return super.readInt(radix, len)
19173
19174 let start = this.pos, total = 0, acceptUnderscore = false;
19175 for (;;) {
19176 let code = this.input.charCodeAt(this.pos), val;
19177 if (code >= 97) val = code - 97 + 10; // a
19178 else if (code == 95) {
19179 if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
19180 ++this.pos;
19181 acceptUnderscore = false;
19182 continue
19183 } else if (code >= 65) val = code - 65 + 10; // A
19184 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
19185 else val = Infinity;
19186 if (val >= radix) break
19187 ++this.pos;
19188 total = total * radix + val;
19189 acceptUnderscore = true;
19190 }
19191 if (this.pos === start) return null
19192 if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
19193
19194 return total
19195 }
19196
19197 readNumber(startsWithDot) {
19198 const token = super.readNumber(startsWithDot);
19199 let octal = this.end - this.start >= 2 && this.input.charCodeAt(this.start) === 48;
19200 const stripped = this.getNumberInput(this.start, this.end);
19201 if (stripped.length < this.end - this.start) {
19202 if (octal) this.raise(this.start, "Invalid number");
19203 this.value = parseFloat(stripped);
19204 }
19205 return token
19206 }
19207
19208 // This is used by acorn-bigint
19209 getNumberInput(start, end) {
19210 return this.input.slice(start, end).replace(/_/g, "")
19211 }
19212 }
19213}
19214
19215function withAcornBigInt(acorn, Parser) {
19216 return class extends Parser {
19217 readInt(radix, len) {
19218 // Hack: len is only != null for unicode escape sequences,
19219 // where numeric separators are not allowed
19220 if (len != null) return super.readInt(radix, len)
19221
19222 let start = this.pos, total = 0, acceptUnderscore = false;
19223 for (;;) {
19224 let code = this.input.charCodeAt(this.pos), val;
19225 if (code >= 97) val = code - 97 + 10; // a
19226 else if (code == 95) {
19227 if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
19228 ++this.pos;
19229 acceptUnderscore = false;
19230 continue
19231 } else if (code >= 65) val = code - 65 + 10; // A
19232 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
19233 else val = Infinity;
19234 if (val >= radix) break
19235 ++this.pos;
19236 total = total * radix + val;
19237 acceptUnderscore = true;
19238 }
19239 if (this.pos === start) return null
19240 if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
19241
19242 return total
19243 }
19244
19245 readNumber(startsWithDot) {
19246 let start = this.pos;
19247 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
19248 let octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
19249 let octalLike = false;
19250 if (octal && this.strict) this.raise(start, "Invalid number");
19251 let next = this.input.charCodeAt(this.pos);
19252 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
19253 let str = this.getNumberInput(start, this.pos);
19254 // eslint-disable-next-line node/no-unsupported-features/es-builtins
19255 let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
19256 ++this.pos;
19257 if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
19258 return this.finishToken(acorn.tokTypes.num, val)
19259 }
19260 if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
19261 octal = false;
19262 octalLike = true;
19263 }
19264 if (next === 46 && !octal) { // '.'
19265 ++this.pos;
19266 this.readInt(10);
19267 next = this.input.charCodeAt(this.pos);
19268 }
19269 if ((next === 69 || next === 101) && !octal) { // 'eE'
19270 next = this.input.charCodeAt(++this.pos);
19271 if (next === 43 || next === 45) ++this.pos; // '+-'
19272 if (this.readInt(10) === null) this.raise(start, "Invalid number");
19273 }
19274 if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
19275 let str = this.getNumberInput(start, this.pos);
19276 if ((octal || octalLike) && str.length < this.pos - start) {
19277 this.raise(start, "Invalid number");
19278 }
19279
19280 let val = octal ? parseInt(str, 8) : parseFloat(str);
19281 return this.finishToken(acorn.tokTypes.num, val)
19282 }
19283
19284 parseLiteral(value) {
19285 const ret = super.parseLiteral(value);
19286 if (ret.bigint) ret.bigint = ret.bigint.replace(/_/g, "");
19287 return ret
19288 }
19289
19290 readRadixNumber(radix) {
19291 let start = this.pos;
19292 this.pos += 2; // 0x
19293 let val = this.readInt(radix);
19294 if (val == null) { this.raise(this.start + 2, `Expected number in radix ${radix}`); }
19295 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
19296 let str = this.getNumberInput(start, this.pos);
19297 // eslint-disable-next-line node/no-unsupported-features/es-builtins
19298 val = typeof BigInt !== "undefined" ? BigInt(str) : null;
19299 ++this.pos;
19300 } else if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
19301 return this.finishToken(acorn.tokTypes.num, val)
19302 }
19303
19304 // This is used by acorn-bigint, which theoretically could be used with acorn@6.2 || acorn@7
19305 getNumberInput(start, end) {
19306 return this.input.slice(start, end).replace(/_/g, "")
19307 }
19308 }
19309}
19310
19311// eslint-disable-next-line node/no-unsupported-features/es-syntax
19312function numericSeparator(Parser) {
19313 const acorn = Parser.acorn || require$$0;
19314 const withAcornBigIntSupport = (acorn.version.startsWith("6.") && !(acorn.version.startsWith("6.0.") || acorn.version.startsWith("6.1."))) || acorn.version.startsWith("7.");
19315
19316 return withAcornBigIntSupport ? withAcornBigInt(acorn, Parser) : withoutAcornBigInt(acorn, Parser)
19317}
19318
19319var acornNumericSeparator = numericSeparator;
19320
19321var acornStaticClassFeatures = function(Parser) {
19322 const ExtendedParser = acornPrivateClassElements(Parser);
19323
19324 const acorn = Parser.acorn || require$$0;
19325 const tt = acorn.tokTypes;
19326
19327 return class extends ExtendedParser {
19328 _maybeParseFieldValue(field) {
19329 if (this.eat(tt.eq)) {
19330 const oldInFieldValue = this._inStaticFieldScope;
19331 this._inStaticFieldScope = this.currentThisScope();
19332 field.value = this.parseExpression();
19333 this._inStaticFieldScope = oldInFieldValue;
19334 } else field.value = null;
19335 }
19336
19337 // Parse fields
19338 parseClassElement(_constructorAllowsSuper) {
19339 if (this.options.ecmaVersion < 8 || !this.isContextual("static")) {
19340 return super.parseClassElement.apply(this, arguments)
19341 }
19342
19343 const branch = this._branch();
19344 branch.next();
19345 if ([tt.name, tt.bracketL, tt.string, tt.num, this.privateNameToken].indexOf(branch.type) == -1 && !branch.type.keyword) {
19346 return super.parseClassElement.apply(this, arguments)
19347 }
19348 if (branch.type == tt.bracketL) {
19349 let count = 0;
19350 do {
19351 if (branch.eat(tt.bracketL)) ++count;
19352 else if (branch.eat(tt.bracketR)) --count;
19353 else branch.next();
19354 } while (count > 0)
19355 } else branch.next();
19356 if (branch.type != tt.eq && !branch.canInsertSemicolon() && branch.type != tt.semi) {
19357 return super.parseClassElement.apply(this, arguments)
19358 }
19359
19360 const node = this.startNode();
19361 node.static = this.eatContextual("static");
19362 if (this.type == this.privateNameToken) {
19363 this.parsePrivateClassElementName(node);
19364 } else {
19365 this.parsePropertyName(node);
19366 }
19367 if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
19368 (node.key.type === "Literal" && !node.computed && node.key.value === "constructor")) {
19369 this.raise(node.key.start, "Classes may not have a field called constructor");
19370 }
19371 if ((node.key.name || node.key.value) === "prototype" && !node.computed) {
19372 this.raise(node.key.start, "Classes may not have a static property named prototype");
19373 }
19374
19375 this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
19376 this._maybeParseFieldValue(node);
19377 this.exitScope();
19378 this.finishNode(node, "FieldDefinition");
19379 this.semicolon();
19380 return node
19381 }
19382
19383 // Parse private static methods
19384 parsePropertyName(prop) {
19385 if (prop.static && this.type == this.privateNameToken) {
19386 this.parsePrivateClassElementName(prop);
19387 } else {
19388 super.parsePropertyName(prop);
19389 }
19390 }
19391
19392 // Prohibit arguments in class field initializers
19393 parseIdent(liberal, isBinding) {
19394 const ident = super.parseIdent(liberal, isBinding);
19395 if (this._inStaticFieldScope && this.currentThisScope() === this._inStaticFieldScope && ident.name == "arguments") {
19396 this.raise(ident.start, "A static class field initializer may not contain arguments");
19397 }
19398 return ident
19399 }
19400 }
19401};
19402
19403function normalizeInputOptions(config) {
19404 var _a, _b;
19405 // These are options that may trigger special warnings or behaviour later
19406 // if the user did not select an explicit value
19407 const unsetOptions = new Set();
19408 const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
19409 const onwarn = getOnwarn(config);
19410 const strictDeprecations = config.strictDeprecations || false;
19411 const options = {
19412 acorn: getAcorn$1(config),
19413 acornInjectPlugins: getAcornInjectPlugins(config),
19414 cache: getCache(config),
19415 context,
19416 experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
19417 external: getIdMatcher(config.external),
19418 inlineDynamicImports: getInlineDynamicImports(config, onwarn, strictDeprecations),
19419 input: getInput(config),
19420 manualChunks: getManualChunks(config, onwarn, strictDeprecations),
19421 moduleContext: getModuleContext(config, context),
19422 onwarn,
19423 perf: config.perf || false,
19424 plugins: ensureArray(config.plugins),
19425 preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
19426 preserveModules: getPreserveModules(config, onwarn, strictDeprecations),
19427 preserveSymlinks: config.preserveSymlinks || false,
19428 shimMissingExports: config.shimMissingExports || false,
19429 strictDeprecations,
19430 treeshake: getTreeshake(config, onwarn, strictDeprecations)
19431 };
19432 warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
19433 return { options, unsetOptions };
19434}
19435const getOnwarn = (config) => {
19436 return config.onwarn
19437 ? warning => {
19438 warning.toString = () => {
19439 let str = '';
19440 if (warning.plugin)
19441 str += `(${warning.plugin} plugin) `;
19442 if (warning.loc)
19443 str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
19444 str += warning.message;
19445 return str;
19446 };
19447 config.onwarn(warning, defaultOnWarn);
19448 }
19449 : defaultOnWarn;
19450};
19451const getAcorn$1 = (config) => ({
19452 allowAwaitOutsideFunction: true,
19453 ecmaVersion: 'latest',
19454 preserveParens: false,
19455 sourceType: 'module',
19456 ...config.acorn
19457});
19458const getAcornInjectPlugins = (config) => [
19459 acornClassFields,
19460 acornStaticClassFeatures,
19461 acornNumericSeparator,
19462 ...ensureArray(config.acornInjectPlugins)
19463];
19464const getCache = (config) => {
19465 var _a;
19466 return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache;
19467};
19468const getIdMatcher = (option) => {
19469 if (option === true) {
19470 return () => true;
19471 }
19472 if (typeof option === 'function') {
19473 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
19474 }
19475 if (option) {
19476 const ids = new Set();
19477 const matchers = [];
19478 for (const value of ensureArray(option)) {
19479 if (value instanceof RegExp) {
19480 matchers.push(value);
19481 }
19482 else {
19483 ids.add(value);
19484 }
19485 }
19486 return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
19487 }
19488 return () => false;
19489};
19490const getInlineDynamicImports = (config, warn, strictDeprecations) => {
19491 const configInlineDynamicImports = config.inlineDynamicImports;
19492 if (configInlineDynamicImports) {
19493 warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
19494 }
19495 return configInlineDynamicImports;
19496};
19497const getInput = (config) => {
19498 const configInput = config.input;
19499 return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
19500};
19501const getManualChunks = (config, warn, strictDeprecations) => {
19502 const configManualChunks = config.manualChunks;
19503 if (configManualChunks) {
19504 warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
19505 }
19506 return configManualChunks;
19507};
19508const getModuleContext = (config, context) => {
19509 const configModuleContext = config.moduleContext;
19510 if (typeof configModuleContext === 'function') {
19511 return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
19512 }
19513 if (configModuleContext) {
19514 const contextByModuleId = Object.create(null);
19515 for (const key of Object.keys(configModuleContext)) {
19516 contextByModuleId[sysPath.resolve(key)] = configModuleContext[key];
19517 }
19518 return id => contextByModuleId[id] || context;
19519 }
19520 return () => context;
19521};
19522const getPreserveEntrySignatures = (config, unsetOptions) => {
19523 const configPreserveEntrySignatures = config.preserveEntrySignatures;
19524 if (configPreserveEntrySignatures == null) {
19525 unsetOptions.add('preserveEntrySignatures');
19526 }
19527 return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
19528};
19529const getPreserveModules = (config, warn, strictDeprecations) => {
19530 const configPreserveModules = config.preserveModules;
19531 if (configPreserveModules) {
19532 warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
19533 }
19534 return configPreserveModules;
19535};
19536const getTreeshake = (config, warn, strictDeprecations) => {
19537 const configTreeshake = config.treeshake;
19538 if (configTreeshake === false) {
19539 return false;
19540 }
19541 if (configTreeshake && configTreeshake !== true) {
19542 if (typeof configTreeshake.pureExternalModules !== 'undefined') {
19543 warnDeprecationWithOptions(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, true, warn, strictDeprecations);
19544 }
19545 return {
19546 annotations: configTreeshake.annotations !== false,
19547 moduleSideEffects: getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules, warn),
19548 propertyReadSideEffects: configTreeshake.propertyReadSideEffects !== false,
19549 tryCatchDeoptimization: configTreeshake.tryCatchDeoptimization !== false,
19550 unknownGlobalSideEffects: configTreeshake.unknownGlobalSideEffects !== false
19551 };
19552 }
19553 return {
19554 annotations: true,
19555 moduleSideEffects: () => true,
19556 propertyReadSideEffects: true,
19557 tryCatchDeoptimization: true,
19558 unknownGlobalSideEffects: true
19559 };
19560};
19561const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules, warn) => {
19562 if (typeof moduleSideEffectsOption === 'boolean') {
19563 return () => moduleSideEffectsOption;
19564 }
19565 if (moduleSideEffectsOption === 'no-external') {
19566 return (_id, external) => !external;
19567 }
19568 if (typeof moduleSideEffectsOption === 'function') {
19569 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
19570 }
19571 if (Array.isArray(moduleSideEffectsOption)) {
19572 const ids = new Set(moduleSideEffectsOption);
19573 return id => ids.has(id);
19574 }
19575 if (moduleSideEffectsOption) {
19576 warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
19577 }
19578 const isPureExternalModule = getIdMatcher(pureExternalModules);
19579 return (id, external) => !(external && isPureExternalModule(id));
19580};
19581
19582function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
19583 var _a, _b, _c, _d, _e, _f, _g;
19584 // These are options that may trigger special warnings or behaviour later
19585 // if the user did not select an explicit value
19586 const unsetOptions = new Set(unsetInputOptions);
19587 const compact = config.compact || false;
19588 const format = getFormat(config);
19589 const inlineDynamicImports = getInlineDynamicImports$1(config, inputOptions);
19590 const preserveModules = getPreserveModules$1(config, inlineDynamicImports, inputOptions);
19591 const file = getFile(config, preserveModules, inputOptions);
19592 const outputOptions = {
19593 amd: getAmd(config),
19594 assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
19595 banner: getAddon(config, 'banner'),
19596 chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
19597 compact,
19598 dir: getDir(config, file),
19599 dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
19600 entryFileNames: getEntryFileNames(config, unsetOptions),
19601 esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
19602 exports: getExports(config, unsetOptions),
19603 extend: config.extend || false,
19604 externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
19605 file,
19606 footer: getAddon(config, 'footer'),
19607 format,
19608 freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
19609 globals: config.globals || {},
19610 hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
19611 indent: getIndent(config, compact),
19612 inlineDynamicImports,
19613 interop: getInterop(config, inputOptions),
19614 intro: getAddon(config, 'intro'),
19615 manualChunks: getManualChunks$1(config, inlineDynamicImports, preserveModules, inputOptions),
19616 minifyInternalExports: getMinifyInternalExports(config, format, compact),
19617 name: config.name,
19618 namespaceToStringTag: config.namespaceToStringTag || false,
19619 noConflict: config.noConflict || false,
19620 outro: getAddon(config, 'outro'),
19621 paths: config.paths || {},
19622 plugins: ensureArray(config.plugins),
19623 preferConst: config.preferConst || false,
19624 preserveModules,
19625 preserveModulesRoot: getPreserveModulesRoot(config),
19626 sourcemap: config.sourcemap || false,
19627 sourcemapExcludeSources: config.sourcemapExcludeSources || false,
19628 sourcemapFile: config.sourcemapFile,
19629 sourcemapPathTransform: config.sourcemapPathTransform,
19630 strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
19631 systemNullSetters: config.systemNullSetters || false
19632 };
19633 warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
19634 return { options: outputOptions, unsetOptions };
19635}
19636const getFile = (config, preserveModules, inputOptions) => {
19637 const file = config.file;
19638 if (typeof file === 'string') {
19639 if (preserveModules) {
19640 return error({
19641 code: 'INVALID_OPTION',
19642 message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
19643 });
19644 }
19645 if (!Array.isArray(inputOptions.input))
19646 return error({
19647 code: 'INVALID_OPTION',
19648 message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
19649 });
19650 }
19651 return file;
19652};
19653const getFormat = (config) => {
19654 const configFormat = config.format;
19655 switch (configFormat) {
19656 case undefined:
19657 case 'es':
19658 case 'esm':
19659 case 'module':
19660 return 'es';
19661 case 'cjs':
19662 case 'commonjs':
19663 return 'cjs';
19664 case 'system':
19665 case 'systemjs':
19666 return 'system';
19667 case 'amd':
19668 case 'iife':
19669 case 'umd':
19670 return configFormat;
19671 default:
19672 return error({
19673 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
19674 url: `https://rollupjs.org/guide/en/#outputformat`
19675 });
19676 }
19677};
19678const getInlineDynamicImports$1 = (config, inputOptions) => {
19679 var _a;
19680 const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) ||
19681 false;
19682 const { input } = inputOptions;
19683 if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
19684 return error({
19685 code: 'INVALID_OPTION',
19686 message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
19687 });
19688 }
19689 return inlineDynamicImports;
19690};
19691const getPreserveModules$1 = (config, inlineDynamicImports, inputOptions) => {
19692 var _a;
19693 const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
19694 if (preserveModules) {
19695 if (inlineDynamicImports) {
19696 return error({
19697 code: 'INVALID_OPTION',
19698 message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
19699 });
19700 }
19701 if (inputOptions.preserveEntrySignatures === false) {
19702 return error({
19703 code: 'INVALID_OPTION',
19704 message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
19705 });
19706 }
19707 }
19708 return preserveModules;
19709};
19710const getPreserveModulesRoot = (config) => {
19711 const preserveModulesRoot = config.preserveModulesRoot;
19712 if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
19713 return undefined;
19714 }
19715 return sysPath.resolve(preserveModulesRoot);
19716};
19717const getAmd = (config) => ({
19718 define: 'define',
19719 ...config.amd
19720});
19721const getAddon = (config, name) => {
19722 const configAddon = config[name];
19723 if (typeof configAddon === 'function') {
19724 return configAddon;
19725 }
19726 return () => configAddon || '';
19727};
19728const getDir = (config, file) => {
19729 const dir = config.dir;
19730 if (typeof dir === 'string' && typeof file === 'string') {
19731 return error({
19732 code: 'INVALID_OPTION',
19733 message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
19734 });
19735 }
19736 return dir;
19737};
19738const getDynamicImportFunction = (config, inputOptions) => {
19739 const configDynamicImportFunction = config.dynamicImportFunction;
19740 if (configDynamicImportFunction) {
19741 warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
19742 }
19743 return configDynamicImportFunction;
19744};
19745const getEntryFileNames = (config, unsetOptions) => {
19746 const configEntryFileNames = config.entryFileNames;
19747 if (configEntryFileNames == null) {
19748 unsetOptions.add('entryFileNames');
19749 }
19750 return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
19751};
19752function getExports(config, unsetOptions) {
19753 const configExports = config.exports;
19754 if (configExports == null) {
19755 unsetOptions.add('exports');
19756 }
19757 else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
19758 return error(errInvalidExportOptionValue(configExports));
19759 }
19760 return configExports || 'auto';
19761}
19762const getIndent = (config, compact) => {
19763 if (compact) {
19764 return '';
19765 }
19766 const configIndent = config.indent;
19767 return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
19768};
19769const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
19770const getInterop = (config, inputOptions) => {
19771 const configInterop = config.interop;
19772 const validatedInteropTypes = new Set();
19773 const validateInterop = (interop) => {
19774 if (!validatedInteropTypes.has(interop)) {
19775 validatedInteropTypes.add(interop);
19776 if (!ALLOWED_INTEROP_TYPES.has(interop)) {
19777 return error({
19778 code: 'INVALID_OPTION',
19779 message: `The value ${JSON.stringify(interop)} is not supported for "output.interop". Use one of ${Array.from(ALLOWED_INTEROP_TYPES.values(), value => JSON.stringify(value)).join(', ')} instead.`,
19780 url: 'https://rollupjs.org/guide/en/#outputinterop'
19781 });
19782 }
19783 if (typeof interop === 'boolean') {
19784 warnDeprecation({
19785 message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
19786 url: 'https://rollupjs.org/guide/en/#outputinterop'
19787 }, false, inputOptions);
19788 }
19789 }
19790 return interop;
19791 };
19792 if (typeof configInterop === 'function') {
19793 const interopPerId = Object.create(null);
19794 let defaultInterop = null;
19795 return id => id === null
19796 ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
19797 : id in interopPerId
19798 ? interopPerId[id]
19799 : validateInterop((interopPerId[id] = configInterop(id)));
19800 }
19801 return configInterop === undefined ? () => true : () => validateInterop(configInterop);
19802};
19803const getManualChunks$1 = (config, inlineDynamicImports, preserveModules, inputOptions) => {
19804 const configManualChunks = config.manualChunks || inputOptions.manualChunks;
19805 if (configManualChunks) {
19806 if (inlineDynamicImports) {
19807 return error({
19808 code: 'INVALID_OPTION',
19809 message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
19810 });
19811 }
19812 if (preserveModules) {
19813 return error({
19814 code: 'INVALID_OPTION',
19815 message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
19816 });
19817 }
19818 }
19819 return configManualChunks || {};
19820};
19821const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
19822
19823function rollup(rawInputOptions) {
19824 return rollupInternal(rawInputOptions, null);
19825}
19826async function rollupInternal(rawInputOptions, watcher) {
19827 const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
19828 initialiseTimers(inputOptions);
19829 const graph = new Graph(inputOptions, watcher);
19830 // remove the cache option from the memory after graph creation (cache is not used anymore)
19831 const useCache = rawInputOptions.cache !== false;
19832 delete inputOptions.cache;
19833 delete rawInputOptions.cache;
19834 timeStart('BUILD', 1);
19835 try {
19836 await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
19837 await graph.build();
19838 }
19839 catch (err) {
19840 const watchFiles = Object.keys(graph.watchFiles);
19841 if (watchFiles.length > 0) {
19842 err.watchFiles = watchFiles;
19843 }
19844 await graph.pluginDriver.hookParallel('buildEnd', [err]);
19845 throw err;
19846 }
19847 await graph.pluginDriver.hookParallel('buildEnd', []);
19848 timeEnd('BUILD', 1);
19849 const result = {
19850 cache: useCache ? graph.getCache() : undefined,
19851 async generate(rawOutputOptions) {
19852 return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
19853 },
19854 watchFiles: Object.keys(graph.watchFiles),
19855 async write(rawOutputOptions) {
19856 return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
19857 }
19858 };
19859 if (inputOptions.perf)
19860 result.getTimings = getTimings;
19861 return result;
19862}
19863async function getInputOptions(rawInputOptions, watchMode) {
19864 if (!rawInputOptions) {
19865 throw new Error('You must supply an options object to rollup');
19866 }
19867 const rawPlugins = ensureArray(rawInputOptions.plugins);
19868 const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
19869 normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
19870 return { options, unsetOptions };
19871}
19872function applyOptionHook(watchMode) {
19873 return async (inputOptions, plugin) => {
19874 if (plugin.options)
19875 return (plugin.options.call({ meta: { rollupVersion: version, watchMode } }, await inputOptions) || inputOptions);
19876 return inputOptions;
19877 };
19878}
19879function normalizePlugins(plugins, anonymousPrefix) {
19880 for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
19881 const plugin = plugins[pluginIndex];
19882 if (!plugin.name) {
19883 plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
19884 }
19885 }
19886}
19887async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
19888 const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
19889 const bundle = new Bundle$1(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
19890 const generated = await bundle.generate(isWrite);
19891 if (isWrite) {
19892 if (!outputOptions.dir && !outputOptions.file) {
19893 return error({
19894 code: 'MISSING_OPTION',
19895 message: 'You must specify "output.file" or "output.dir" for the build.'
19896 });
19897 }
19898 await Promise.all(Object.keys(generated).map(chunkId => writeOutputFile(generated[chunkId], outputOptions)));
19899 await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
19900 }
19901 return createOutput(generated);
19902}
19903function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
19904 if (!rawOutputOptions) {
19905 throw new Error('You must supply an options object');
19906 }
19907 const rawPlugins = ensureArray(rawOutputOptions.plugins);
19908 normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
19909 const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
19910 return {
19911 ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
19912 outputPluginDriver
19913 };
19914}
19915function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
19916 return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
19917 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
19918 return {
19919 ...pluginContext,
19920 emitFile: emitError,
19921 setAssetSource: emitError
19922 };
19923 }), inputOptions, unsetInputOptions);
19924}
19925function createOutput(outputBundle) {
19926 return {
19927 output: Object.keys(outputBundle)
19928 .map(fileName => outputBundle[fileName])
19929 .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
19930 const fileTypeA = getSortingFileType(outputFileA);
19931 const fileTypeB = getSortingFileType(outputFileB);
19932 if (fileTypeA === fileTypeB)
19933 return 0;
19934 return fileTypeA < fileTypeB ? -1 : 1;
19935 })
19936 };
19937}
19938var SortingFileType;
19939(function (SortingFileType) {
19940 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
19941 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
19942 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
19943})(SortingFileType || (SortingFileType = {}));
19944function getSortingFileType(file) {
19945 if (file.type === 'asset') {
19946 return SortingFileType.ASSET;
19947 }
19948 if (file.isEntry) {
19949 return SortingFileType.ENTRY_CHUNK;
19950 }
19951 return SortingFileType.SECONDARY_CHUNK;
19952}
19953function writeOutputFile(outputFile, outputOptions) {
19954 const fileName = sysPath.resolve(outputOptions.dir || sysPath.dirname(outputOptions.file), outputFile.fileName);
19955 let writeSourceMapPromise;
19956 let source;
19957 if (outputFile.type === 'asset') {
19958 source = outputFile.source;
19959 }
19960 else {
19961 source = outputFile.code;
19962 if (outputOptions.sourcemap && outputFile.map) {
19963 let url;
19964 if (outputOptions.sourcemap === 'inline') {
19965 url = outputFile.map.toUrl();
19966 }
19967 else {
19968 url = `${sysPath.basename(outputFile.fileName)}.map`;
19969 writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
19970 }
19971 if (outputOptions.sourcemap !== 'hidden') {
19972 source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
19973 }
19974 }
19975 }
19976 return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
19977}
19978
19979class WatchEmitter extends require$$0$1.EventEmitter {
19980 constructor() {
19981 super();
19982 // Allows more than 10 bundles to be watched without
19983 // showing the `MaxListenersExceededWarning` to the user.
19984 this.setMaxListeners(Infinity);
19985 }
19986 close() { }
19987}
19988function watch(configs) {
19989 const emitter = new WatchEmitter();
19990 const configArray = ensureArray(configs);
19991 const watchConfigs = configArray.filter(config => config.watch !== false);
19992 if (watchConfigs.length === 0) {
19993 throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
19994 }
19995 loadFsEvents()
19996 .then(() => Promise.resolve().then(function () { return require('./watch.js'); }))
19997 .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
19998 return emitter;
19999}
20000
20001exports.createCommonjsModule = createCommonjsModule;
20002exports.defaultOnWarn = defaultOnWarn;
20003exports.ensureArray = ensureArray;
20004exports.error = error;
20005exports.fseventsImporter = fseventsImporter;
20006exports.getAliasName = getAliasName;
20007exports.getAugmentedNamespace = getAugmentedNamespace;
20008exports.getOrCreate = getOrCreate;
20009exports.loadFsEvents = loadFsEvents;
20010exports.relativeId = relativeId;
20011exports.rollup = rollup;
20012exports.rollupInternal = rollupInternal;
20013exports.version = version;
20014exports.warnUnknownOptions = warnUnknownOptions;
20015exports.watch = watch;
20016//# sourceMappingURL=rollup.js.map