UNPKG

748 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v2.33.0
4 Sun, 01 Nov 2020 06:52:02 GMT - commit 3d719bb543063288e64035c5fcd7892e0d204533
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11import { relative as relative$1, extname, basename, dirname, resolve } from 'path';
12import { createHash as createHash$1 } from 'crypto';
13import { writeFile as writeFile$1, readdirSync, mkdirSync, readFile as readFile$1, lstatSync, realpathSync } from 'fs';
14import { EventEmitter } from 'events';
15
16var version = "2.33.0";
17
18var charToInteger = {};
19var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
20for (var i = 0; i < chars.length; i++) {
21 charToInteger[chars.charCodeAt(i)] = i;
22}
23function decode(mappings) {
24 var decoded = [];
25 var line = [];
26 var segment = [
27 0,
28 0,
29 0,
30 0,
31 0,
32 ];
33 var j = 0;
34 for (var i = 0, shift = 0, value = 0; i < mappings.length; i++) {
35 var c = mappings.charCodeAt(i);
36 if (c === 44) { // ","
37 segmentify(line, segment, j);
38 j = 0;
39 }
40 else if (c === 59) { // ";"
41 segmentify(line, segment, j);
42 j = 0;
43 decoded.push(line);
44 line = [];
45 segment[0] = 0;
46 }
47 else {
48 var integer = charToInteger[c];
49 if (integer === undefined) {
50 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
51 }
52 var hasContinuationBit = integer & 32;
53 integer &= 31;
54 value += integer << shift;
55 if (hasContinuationBit) {
56 shift += 5;
57 }
58 else {
59 var shouldNegate = value & 1;
60 value >>>= 1;
61 if (shouldNegate) {
62 value = value === 0 ? -0x80000000 : -value;
63 }
64 segment[j] += value;
65 j++;
66 value = shift = 0; // reset
67 }
68 }
69 }
70 segmentify(line, segment, j);
71 decoded.push(line);
72 return decoded;
73}
74function segmentify(line, segment, j) {
75 // This looks ugly, but we're creating specialized arrays with a specific
76 // length. This is much faster than creating a new array (which v8 expands to
77 // a capacity of 17 after pushing the first item), or slicing out a subarray
78 // (which is slow). Length 4 is assumed to be the most frequent, followed by
79 // length 5 (since not everything will have an associated name), followed by
80 // length 1 (it's probably rare for a source substring to not have an
81 // associated segment data).
82 if (j === 4)
83 line.push([segment[0], segment[1], segment[2], segment[3]]);
84 else if (j === 5)
85 line.push([segment[0], segment[1], segment[2], segment[3], segment[4]]);
86 else if (j === 1)
87 line.push([segment[0]]);
88}
89function encode(decoded) {
90 var sourceFileIndex = 0; // second field
91 var sourceCodeLine = 0; // third field
92 var sourceCodeColumn = 0; // fourth field
93 var nameIndex = 0; // fifth field
94 var mappings = '';
95 for (var i = 0; i < decoded.length; i++) {
96 var line = decoded[i];
97 if (i > 0)
98 mappings += ';';
99 if (line.length === 0)
100 continue;
101 var generatedCodeColumn = 0; // first field
102 var lineMappings = [];
103 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
104 var segment = line_1[_i];
105 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
106 generatedCodeColumn = segment[0];
107 if (segment.length > 1) {
108 segmentMappings +=
109 encodeInteger(segment[1] - sourceFileIndex) +
110 encodeInteger(segment[2] - sourceCodeLine) +
111 encodeInteger(segment[3] - sourceCodeColumn);
112 sourceFileIndex = segment[1];
113 sourceCodeLine = segment[2];
114 sourceCodeColumn = segment[3];
115 }
116 if (segment.length === 5) {
117 segmentMappings += encodeInteger(segment[4] - nameIndex);
118 nameIndex = segment[4];
119 }
120 lineMappings.push(segmentMappings);
121 }
122 mappings += lineMappings.join(',');
123 }
124 return mappings;
125}
126function encodeInteger(num) {
127 var result = '';
128 num = num < 0 ? (-num << 1) | 1 : num << 1;
129 do {
130 var clamped = num & 31;
131 num >>>= 5;
132 if (num > 0) {
133 clamped |= 32;
134 }
135 result += chars[clamped];
136 } while (num > 0);
137 return result;
138}
139
140var BitSet = function BitSet(arg) {
141 this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
142};
143
144BitSet.prototype.add = function add (n) {
145 this.bits[n >> 5] |= 1 << (n & 31);
146};
147
148BitSet.prototype.has = function has (n) {
149 return !!(this.bits[n >> 5] & (1 << (n & 31)));
150};
151
152var Chunk = function Chunk(start, end, content) {
153 this.start = start;
154 this.end = end;
155 this.original = content;
156
157 this.intro = '';
158 this.outro = '';
159
160 this.content = content;
161 this.storeName = false;
162 this.edited = false;
163
164 // we make these non-enumerable, for sanity while debugging
165 Object.defineProperties(this, {
166 previous: { writable: true, value: null },
167 next: { writable: true, value: null }
168 });
169};
170
171Chunk.prototype.appendLeft = function appendLeft (content) {
172 this.outro += content;
173};
174
175Chunk.prototype.appendRight = function appendRight (content) {
176 this.intro = this.intro + content;
177};
178
179Chunk.prototype.clone = function clone () {
180 var chunk = new Chunk(this.start, this.end, this.original);
181
182 chunk.intro = this.intro;
183 chunk.outro = this.outro;
184 chunk.content = this.content;
185 chunk.storeName = this.storeName;
186 chunk.edited = this.edited;
187
188 return chunk;
189};
190
191Chunk.prototype.contains = function contains (index) {
192 return this.start < index && index < this.end;
193};
194
195Chunk.prototype.eachNext = function eachNext (fn) {
196 var chunk = this;
197 while (chunk) {
198 fn(chunk);
199 chunk = chunk.next;
200 }
201};
202
203Chunk.prototype.eachPrevious = function eachPrevious (fn) {
204 var chunk = this;
205 while (chunk) {
206 fn(chunk);
207 chunk = chunk.previous;
208 }
209};
210
211Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
212 this.content = content;
213 if (!contentOnly) {
214 this.intro = '';
215 this.outro = '';
216 }
217 this.storeName = storeName;
218
219 this.edited = true;
220
221 return this;
222};
223
224Chunk.prototype.prependLeft = function prependLeft (content) {
225 this.outro = content + this.outro;
226};
227
228Chunk.prototype.prependRight = function prependRight (content) {
229 this.intro = content + this.intro;
230};
231
232Chunk.prototype.split = function split (index) {
233 var sliceIndex = index - this.start;
234
235 var originalBefore = this.original.slice(0, sliceIndex);
236 var originalAfter = this.original.slice(sliceIndex);
237
238 this.original = originalBefore;
239
240 var newChunk = new Chunk(index, this.end, originalAfter);
241 newChunk.outro = this.outro;
242 this.outro = '';
243
244 this.end = index;
245
246 if (this.edited) {
247 // TODO is this block necessary?...
248 newChunk.edit('', false);
249 this.content = '';
250 } else {
251 this.content = originalBefore;
252 }
253
254 newChunk.next = this.next;
255 if (newChunk.next) { newChunk.next.previous = newChunk; }
256 newChunk.previous = this;
257 this.next = newChunk;
258
259 return newChunk;
260};
261
262Chunk.prototype.toString = function toString () {
263 return this.intro + this.content + this.outro;
264};
265
266Chunk.prototype.trimEnd = function trimEnd (rx) {
267 this.outro = this.outro.replace(rx, '');
268 if (this.outro.length) { return true; }
269
270 var trimmed = this.content.replace(rx, '');
271
272 if (trimmed.length) {
273 if (trimmed !== this.content) {
274 this.split(this.start + trimmed.length).edit('', undefined, true);
275 }
276 return true;
277
278 } else {
279 this.edit('', undefined, true);
280
281 this.intro = this.intro.replace(rx, '');
282 if (this.intro.length) { return true; }
283 }
284};
285
286Chunk.prototype.trimStart = function trimStart (rx) {
287 this.intro = this.intro.replace(rx, '');
288 if (this.intro.length) { return true; }
289
290 var trimmed = this.content.replace(rx, '');
291
292 if (trimmed.length) {
293 if (trimmed !== this.content) {
294 this.split(this.end - trimmed.length);
295 this.edit('', undefined, true);
296 }
297 return true;
298
299 } else {
300 this.edit('', undefined, true);
301
302 this.outro = this.outro.replace(rx, '');
303 if (this.outro.length) { return true; }
304 }
305};
306
307var btoa = function () {
308 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
309};
310if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
311 btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
312} else if (typeof Buffer === 'function') {
313 btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
314}
315
316var SourceMap = function SourceMap(properties) {
317 this.version = 3;
318 this.file = properties.file;
319 this.sources = properties.sources;
320 this.sourcesContent = properties.sourcesContent;
321 this.names = properties.names;
322 this.mappings = encode(properties.mappings);
323};
324
325SourceMap.prototype.toString = function toString () {
326 return JSON.stringify(this);
327};
328
329SourceMap.prototype.toUrl = function toUrl () {
330 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
331};
332
333function guessIndent(code) {
334 var lines = code.split('\n');
335
336 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
337 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
338
339 if (tabbed.length === 0 && spaced.length === 0) {
340 return null;
341 }
342
343 // More lines tabbed than spaced? Assume tabs, and
344 // default to tabs in the case of a tie (or nothing
345 // to go on)
346 if (tabbed.length >= spaced.length) {
347 return '\t';
348 }
349
350 // Otherwise, we need to guess the multiple
351 var min = spaced.reduce(function (previous, current) {
352 var numSpaces = /^ +/.exec(current)[0].length;
353 return Math.min(numSpaces, previous);
354 }, Infinity);
355
356 return new Array(min + 1).join(' ');
357}
358
359function getRelativePath(from, to) {
360 var fromParts = from.split(/[/\\]/);
361 var toParts = to.split(/[/\\]/);
362
363 fromParts.pop(); // get dirname
364
365 while (fromParts[0] === toParts[0]) {
366 fromParts.shift();
367 toParts.shift();
368 }
369
370 if (fromParts.length) {
371 var i = fromParts.length;
372 while (i--) { fromParts[i] = '..'; }
373 }
374
375 return fromParts.concat(toParts).join('/');
376}
377
378var toString = Object.prototype.toString;
379
380function isObject(thing) {
381 return toString.call(thing) === '[object Object]';
382}
383
384function getLocator(source) {
385 var originalLines = source.split('\n');
386 var lineOffsets = [];
387
388 for (var i = 0, pos = 0; i < originalLines.length; i++) {
389 lineOffsets.push(pos);
390 pos += originalLines[i].length + 1;
391 }
392
393 return function locate(index) {
394 var i = 0;
395 var j = lineOffsets.length;
396 while (i < j) {
397 var m = (i + j) >> 1;
398 if (index < lineOffsets[m]) {
399 j = m;
400 } else {
401 i = m + 1;
402 }
403 }
404 var line = i - 1;
405 var column = index - lineOffsets[line];
406 return { line: line, column: column };
407 };
408}
409
410var Mappings = function Mappings(hires) {
411 this.hires = hires;
412 this.generatedCodeLine = 0;
413 this.generatedCodeColumn = 0;
414 this.raw = [];
415 this.rawSegments = this.raw[this.generatedCodeLine] = [];
416 this.pending = null;
417};
418
419Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
420 if (content.length) {
421 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
422 if (nameIndex >= 0) {
423 segment.push(nameIndex);
424 }
425 this.rawSegments.push(segment);
426 } else if (this.pending) {
427 this.rawSegments.push(this.pending);
428 }
429
430 this.advance(content);
431 this.pending = null;
432};
433
434Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
435 var originalCharIndex = chunk.start;
436 var first = true;
437
438 while (originalCharIndex < chunk.end) {
439 if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
440 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
441 }
442
443 if (original[originalCharIndex] === '\n') {
444 loc.line += 1;
445 loc.column = 0;
446 this.generatedCodeLine += 1;
447 this.raw[this.generatedCodeLine] = this.rawSegments = [];
448 this.generatedCodeColumn = 0;
449 first = true;
450 } else {
451 loc.column += 1;
452 this.generatedCodeColumn += 1;
453 first = false;
454 }
455
456 originalCharIndex += 1;
457 }
458
459 this.pending = null;
460};
461
462Mappings.prototype.advance = function advance (str) {
463 if (!str) { return; }
464
465 var lines = str.split('\n');
466
467 if (lines.length > 1) {
468 for (var i = 0; i < lines.length - 1; i++) {
469 this.generatedCodeLine++;
470 this.raw[this.generatedCodeLine] = this.rawSegments = [];
471 }
472 this.generatedCodeColumn = 0;
473 }
474
475 this.generatedCodeColumn += lines[lines.length - 1].length;
476};
477
478var n = '\n';
479
480var warned = {
481 insertLeft: false,
482 insertRight: false,
483 storeName: false
484};
485
486var MagicString = function MagicString(string, options) {
487 if ( options === void 0 ) options = {};
488
489 var chunk = new Chunk(0, string.length, string);
490
491 Object.defineProperties(this, {
492 original: { writable: true, value: string },
493 outro: { writable: true, value: '' },
494 intro: { writable: true, value: '' },
495 firstChunk: { writable: true, value: chunk },
496 lastChunk: { writable: true, value: chunk },
497 lastSearchedChunk: { writable: true, value: chunk },
498 byStart: { writable: true, value: {} },
499 byEnd: { writable: true, value: {} },
500 filename: { writable: true, value: options.filename },
501 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
502 sourcemapLocations: { writable: true, value: new BitSet() },
503 storedNames: { writable: true, value: {} },
504 indentStr: { writable: true, value: guessIndent(string) }
505 });
506
507 this.byStart[0] = chunk;
508 this.byEnd[string.length] = chunk;
509};
510
511MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
512 this.sourcemapLocations.add(char);
513};
514
515MagicString.prototype.append = function append (content) {
516 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
517
518 this.outro += content;
519 return this;
520};
521
522MagicString.prototype.appendLeft = function appendLeft (index, content) {
523 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
524
525 this._split(index);
526
527 var chunk = this.byEnd[index];
528
529 if (chunk) {
530 chunk.appendLeft(content);
531 } else {
532 this.intro += content;
533 }
534 return this;
535};
536
537MagicString.prototype.appendRight = function appendRight (index, content) {
538 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
539
540 this._split(index);
541
542 var chunk = this.byStart[index];
543
544 if (chunk) {
545 chunk.appendRight(content);
546 } else {
547 this.outro += content;
548 }
549 return this;
550};
551
552MagicString.prototype.clone = function clone () {
553 var cloned = new MagicString(this.original, { filename: this.filename });
554
555 var originalChunk = this.firstChunk;
556 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
557
558 while (originalChunk) {
559 cloned.byStart[clonedChunk.start] = clonedChunk;
560 cloned.byEnd[clonedChunk.end] = clonedChunk;
561
562 var nextOriginalChunk = originalChunk.next;
563 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
564
565 if (nextClonedChunk) {
566 clonedChunk.next = nextClonedChunk;
567 nextClonedChunk.previous = clonedChunk;
568
569 clonedChunk = nextClonedChunk;
570 }
571
572 originalChunk = nextOriginalChunk;
573 }
574
575 cloned.lastChunk = clonedChunk;
576
577 if (this.indentExclusionRanges) {
578 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
579 }
580
581 cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
582
583 cloned.intro = this.intro;
584 cloned.outro = this.outro;
585
586 return cloned;
587};
588
589MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
590 var this$1 = this;
591
592 options = options || {};
593
594 var sourceIndex = 0;
595 var names = Object.keys(this.storedNames);
596 var mappings = new Mappings(options.hires);
597
598 var locate = getLocator(this.original);
599
600 if (this.intro) {
601 mappings.advance(this.intro);
602 }
603
604 this.firstChunk.eachNext(function (chunk) {
605 var loc = locate(chunk.start);
606
607 if (chunk.intro.length) { mappings.advance(chunk.intro); }
608
609 if (chunk.edited) {
610 mappings.addEdit(
611 sourceIndex,
612 chunk.content,
613 loc,
614 chunk.storeName ? names.indexOf(chunk.original) : -1
615 );
616 } else {
617 mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
618 }
619
620 if (chunk.outro.length) { mappings.advance(chunk.outro); }
621 });
622
623 return {
624 file: options.file ? options.file.split(/[/\\]/).pop() : null,
625 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
626 sourcesContent: options.includeContent ? [this.original] : [null],
627 names: names,
628 mappings: mappings.raw
629 };
630};
631
632MagicString.prototype.generateMap = function generateMap (options) {
633 return new SourceMap(this.generateDecodedMap(options));
634};
635
636MagicString.prototype.getIndentString = function getIndentString () {
637 return this.indentStr === null ? '\t' : this.indentStr;
638};
639
640MagicString.prototype.indent = function indent (indentStr, options) {
641 var pattern = /^[^\r\n]/gm;
642
643 if (isObject(indentStr)) {
644 options = indentStr;
645 indentStr = undefined;
646 }
647
648 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
649
650 if (indentStr === '') { return this; } // noop
651
652 options = options || {};
653
654 // Process exclusion ranges
655 var isExcluded = {};
656
657 if (options.exclude) {
658 var exclusions =
659 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
660 exclusions.forEach(function (exclusion) {
661 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
662 isExcluded[i] = true;
663 }
664 });
665 }
666
667 var shouldIndentNextCharacter = options.indentStart !== false;
668 var replacer = function (match) {
669 if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
670 shouldIndentNextCharacter = true;
671 return match;
672 };
673
674 this.intro = this.intro.replace(pattern, replacer);
675
676 var charIndex = 0;
677 var chunk = this.firstChunk;
678
679 while (chunk) {
680 var end = chunk.end;
681
682 if (chunk.edited) {
683 if (!isExcluded[charIndex]) {
684 chunk.content = chunk.content.replace(pattern, replacer);
685
686 if (chunk.content.length) {
687 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
688 }
689 }
690 } else {
691 charIndex = chunk.start;
692
693 while (charIndex < end) {
694 if (!isExcluded[charIndex]) {
695 var char = this.original[charIndex];
696
697 if (char === '\n') {
698 shouldIndentNextCharacter = true;
699 } else if (char !== '\r' && shouldIndentNextCharacter) {
700 shouldIndentNextCharacter = false;
701
702 if (charIndex === chunk.start) {
703 chunk.prependRight(indentStr);
704 } else {
705 this._splitChunk(chunk, charIndex);
706 chunk = chunk.next;
707 chunk.prependRight(indentStr);
708 }
709 }
710 }
711
712 charIndex += 1;
713 }
714 }
715
716 charIndex = chunk.end;
717 chunk = chunk.next;
718 }
719
720 this.outro = this.outro.replace(pattern, replacer);
721
722 return this;
723};
724
725MagicString.prototype.insert = function insert () {
726 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
727};
728
729MagicString.prototype.insertLeft = function insertLeft (index, content) {
730 if (!warned.insertLeft) {
731 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
732 warned.insertLeft = true;
733 }
734
735 return this.appendLeft(index, content);
736};
737
738MagicString.prototype.insertRight = function insertRight (index, content) {
739 if (!warned.insertRight) {
740 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
741 warned.insertRight = true;
742 }
743
744 return this.prependRight(index, content);
745};
746
747MagicString.prototype.move = function move (start, end, index) {
748 if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
749
750 this._split(start);
751 this._split(end);
752 this._split(index);
753
754 var first = this.byStart[start];
755 var last = this.byEnd[end];
756
757 var oldLeft = first.previous;
758 var oldRight = last.next;
759
760 var newRight = this.byStart[index];
761 if (!newRight && last === this.lastChunk) { return this; }
762 var newLeft = newRight ? newRight.previous : this.lastChunk;
763
764 if (oldLeft) { oldLeft.next = oldRight; }
765 if (oldRight) { oldRight.previous = oldLeft; }
766
767 if (newLeft) { newLeft.next = first; }
768 if (newRight) { newRight.previous = last; }
769
770 if (!first.previous) { this.firstChunk = last.next; }
771 if (!last.next) {
772 this.lastChunk = first.previous;
773 this.lastChunk.next = null;
774 }
775
776 first.previous = newLeft;
777 last.next = newRight || null;
778
779 if (!newLeft) { this.firstChunk = first; }
780 if (!newRight) { this.lastChunk = last; }
781 return this;
782};
783
784MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
785 if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
786
787 while (start < 0) { start += this.original.length; }
788 while (end < 0) { end += this.original.length; }
789
790 if (end > this.original.length) { throw new Error('end is out of bounds'); }
791 if (start === end)
792 { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
793
794 this._split(start);
795 this._split(end);
796
797 if (options === true) {
798 if (!warned.storeName) {
799 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
800 warned.storeName = true;
801 }
802
803 options = { storeName: true };
804 }
805 var storeName = options !== undefined ? options.storeName : false;
806 var contentOnly = options !== undefined ? options.contentOnly : false;
807
808 if (storeName) {
809 var original = this.original.slice(start, end);
810 this.storedNames[original] = true;
811 }
812
813 var first = this.byStart[start];
814 var last = this.byEnd[end];
815
816 if (first) {
817 if (end > first.end && first.next !== this.byStart[first.end]) {
818 throw new Error('Cannot overwrite across a split point');
819 }
820
821 first.edit(content, storeName, contentOnly);
822
823 if (first !== last) {
824 var chunk = first.next;
825 while (chunk !== last) {
826 chunk.edit('', false);
827 chunk = chunk.next;
828 }
829
830 chunk.edit('', false);
831 }
832 } else {
833 // must be inserting at the end
834 var newChunk = new Chunk(start, end, '').edit(content, storeName);
835
836 // TODO last chunk in the array may not be the last chunk, if it's moved...
837 last.next = newChunk;
838 newChunk.previous = last;
839 }
840 return this;
841};
842
843MagicString.prototype.prepend = function prepend (content) {
844 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
845
846 this.intro = content + this.intro;
847 return this;
848};
849
850MagicString.prototype.prependLeft = function prependLeft (index, content) {
851 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
852
853 this._split(index);
854
855 var chunk = this.byEnd[index];
856
857 if (chunk) {
858 chunk.prependLeft(content);
859 } else {
860 this.intro = content + this.intro;
861 }
862 return this;
863};
864
865MagicString.prototype.prependRight = function prependRight (index, content) {
866 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
867
868 this._split(index);
869
870 var chunk = this.byStart[index];
871
872 if (chunk) {
873 chunk.prependRight(content);
874 } else {
875 this.outro = content + this.outro;
876 }
877 return this;
878};
879
880MagicString.prototype.remove = function remove (start, end) {
881 while (start < 0) { start += this.original.length; }
882 while (end < 0) { end += this.original.length; }
883
884 if (start === end) { return this; }
885
886 if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
887 if (start > end) { throw new Error('end must be greater than start'); }
888
889 this._split(start);
890 this._split(end);
891
892 var chunk = this.byStart[start];
893
894 while (chunk) {
895 chunk.intro = '';
896 chunk.outro = '';
897 chunk.edit('');
898
899 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
900 }
901 return this;
902};
903
904MagicString.prototype.lastChar = function lastChar () {
905 if (this.outro.length)
906 { return this.outro[this.outro.length - 1]; }
907 var chunk = this.lastChunk;
908 do {
909 if (chunk.outro.length)
910 { return chunk.outro[chunk.outro.length - 1]; }
911 if (chunk.content.length)
912 { return chunk.content[chunk.content.length - 1]; }
913 if (chunk.intro.length)
914 { return chunk.intro[chunk.intro.length - 1]; }
915 } while (chunk = chunk.previous);
916 if (this.intro.length)
917 { return this.intro[this.intro.length - 1]; }
918 return '';
919};
920
921MagicString.prototype.lastLine = function lastLine () {
922 var lineIndex = this.outro.lastIndexOf(n);
923 if (lineIndex !== -1)
924 { return this.outro.substr(lineIndex + 1); }
925 var lineStr = this.outro;
926 var chunk = this.lastChunk;
927 do {
928 if (chunk.outro.length > 0) {
929 lineIndex = chunk.outro.lastIndexOf(n);
930 if (lineIndex !== -1)
931 { return chunk.outro.substr(lineIndex + 1) + lineStr; }
932 lineStr = chunk.outro + lineStr;
933 }
934
935 if (chunk.content.length > 0) {
936 lineIndex = chunk.content.lastIndexOf(n);
937 if (lineIndex !== -1)
938 { return chunk.content.substr(lineIndex + 1) + lineStr; }
939 lineStr = chunk.content + lineStr;
940 }
941
942 if (chunk.intro.length > 0) {
943 lineIndex = chunk.intro.lastIndexOf(n);
944 if (lineIndex !== -1)
945 { return chunk.intro.substr(lineIndex + 1) + lineStr; }
946 lineStr = chunk.intro + lineStr;
947 }
948 } while (chunk = chunk.previous);
949 lineIndex = this.intro.lastIndexOf(n);
950 if (lineIndex !== -1)
951 { return this.intro.substr(lineIndex + 1) + lineStr; }
952 return this.intro + lineStr;
953};
954
955MagicString.prototype.slice = function slice (start, end) {
956 if ( start === void 0 ) start = 0;
957 if ( end === void 0 ) end = this.original.length;
958
959 while (start < 0) { start += this.original.length; }
960 while (end < 0) { end += this.original.length; }
961
962 var result = '';
963
964 // find start chunk
965 var chunk = this.firstChunk;
966 while (chunk && (chunk.start > start || chunk.end <= start)) {
967 // found end chunk before start
968 if (chunk.start < end && chunk.end >= end) {
969 return result;
970 }
971
972 chunk = chunk.next;
973 }
974
975 if (chunk && chunk.edited && chunk.start !== start)
976 { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
977
978 var startChunk = chunk;
979 while (chunk) {
980 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
981 result += chunk.intro;
982 }
983
984 var containsEnd = chunk.start < end && chunk.end >= end;
985 if (containsEnd && chunk.edited && chunk.end !== end)
986 { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
987
988 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
989 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
990
991 result += chunk.content.slice(sliceStart, sliceEnd);
992
993 if (chunk.outro && (!containsEnd || chunk.end === end)) {
994 result += chunk.outro;
995 }
996
997 if (containsEnd) {
998 break;
999 }
1000
1001 chunk = chunk.next;
1002 }
1003
1004 return result;
1005};
1006
1007// TODO deprecate this? not really very useful
1008MagicString.prototype.snip = function snip (start, end) {
1009 var clone = this.clone();
1010 clone.remove(0, start);
1011 clone.remove(end, clone.original.length);
1012
1013 return clone;
1014};
1015
1016MagicString.prototype._split = function _split (index) {
1017 if (this.byStart[index] || this.byEnd[index]) { return; }
1018
1019 var chunk = this.lastSearchedChunk;
1020 var searchForward = index > chunk.end;
1021
1022 while (chunk) {
1023 if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
1024
1025 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1026 }
1027};
1028
1029MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
1030 if (chunk.edited && chunk.content.length) {
1031 // zero-length edited chunks are a special case (overlapping replacements)
1032 var loc = getLocator(this.original)(index);
1033 throw new Error(
1034 ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
1035 );
1036 }
1037
1038 var newChunk = chunk.split(index);
1039
1040 this.byEnd[index] = chunk;
1041 this.byStart[index] = newChunk;
1042 this.byEnd[newChunk.end] = newChunk;
1043
1044 if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
1045
1046 this.lastSearchedChunk = chunk;
1047 return true;
1048};
1049
1050MagicString.prototype.toString = function toString () {
1051 var str = this.intro;
1052
1053 var chunk = this.firstChunk;
1054 while (chunk) {
1055 str += chunk.toString();
1056 chunk = chunk.next;
1057 }
1058
1059 return str + this.outro;
1060};
1061
1062MagicString.prototype.isEmpty = function isEmpty () {
1063 var chunk = this.firstChunk;
1064 do {
1065 if (chunk.intro.length && chunk.intro.trim() ||
1066 chunk.content.length && chunk.content.trim() ||
1067 chunk.outro.length && chunk.outro.trim())
1068 { return false; }
1069 } while (chunk = chunk.next);
1070 return true;
1071};
1072
1073MagicString.prototype.length = function length () {
1074 var chunk = this.firstChunk;
1075 var length = 0;
1076 do {
1077 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1078 } while (chunk = chunk.next);
1079 return length;
1080};
1081
1082MagicString.prototype.trimLines = function trimLines () {
1083 return this.trim('[\\r\\n]');
1084};
1085
1086MagicString.prototype.trim = function trim (charType) {
1087 return this.trimStart(charType).trimEnd(charType);
1088};
1089
1090MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
1091 var rx = new RegExp((charType || '\\s') + '+$');
1092
1093 this.outro = this.outro.replace(rx, '');
1094 if (this.outro.length) { return true; }
1095
1096 var chunk = this.lastChunk;
1097
1098 do {
1099 var end = chunk.end;
1100 var aborted = chunk.trimEnd(rx);
1101
1102 // if chunk was trimmed, we have a new lastChunk
1103 if (chunk.end !== end) {
1104 if (this.lastChunk === chunk) {
1105 this.lastChunk = chunk.next;
1106 }
1107
1108 this.byEnd[chunk.end] = chunk;
1109 this.byStart[chunk.next.start] = chunk.next;
1110 this.byEnd[chunk.next.end] = chunk.next;
1111 }
1112
1113 if (aborted) { return true; }
1114 chunk = chunk.previous;
1115 } while (chunk);
1116
1117 return false;
1118};
1119
1120MagicString.prototype.trimEnd = function trimEnd (charType) {
1121 this.trimEndAborted(charType);
1122 return this;
1123};
1124MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
1125 var rx = new RegExp('^' + (charType || '\\s') + '+');
1126
1127 this.intro = this.intro.replace(rx, '');
1128 if (this.intro.length) { return true; }
1129
1130 var chunk = this.firstChunk;
1131
1132 do {
1133 var end = chunk.end;
1134 var aborted = chunk.trimStart(rx);
1135
1136 if (chunk.end !== end) {
1137 // special case...
1138 if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
1139
1140 this.byEnd[chunk.end] = chunk;
1141 this.byStart[chunk.next.start] = chunk.next;
1142 this.byEnd[chunk.next.end] = chunk.next;
1143 }
1144
1145 if (aborted) { return true; }
1146 chunk = chunk.next;
1147 } while (chunk);
1148
1149 return false;
1150};
1151
1152MagicString.prototype.trimStart = function trimStart (charType) {
1153 this.trimStartAborted(charType);
1154 return this;
1155};
1156
1157var hasOwnProp = Object.prototype.hasOwnProperty;
1158
1159var Bundle = function Bundle(options) {
1160 if ( options === void 0 ) options = {};
1161
1162 this.intro = options.intro || '';
1163 this.separator = options.separator !== undefined ? options.separator : '\n';
1164 this.sources = [];
1165 this.uniqueSources = [];
1166 this.uniqueSourceIndexByFilename = {};
1167};
1168
1169Bundle.prototype.addSource = function addSource (source) {
1170 if (source instanceof MagicString) {
1171 return this.addSource({
1172 content: source,
1173 filename: source.filename,
1174 separator: this.separator
1175 });
1176 }
1177
1178 if (!isObject(source) || !source.content) {
1179 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
1180 }
1181
1182 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
1183 if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
1184 });
1185
1186 if (source.separator === undefined) {
1187 // TODO there's a bunch of this sort of thing, needs cleaning up
1188 source.separator = this.separator;
1189 }
1190
1191 if (source.filename) {
1192 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1193 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1194 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1195 } else {
1196 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1197 if (source.content.original !== uniqueSource.content) {
1198 throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
1199 }
1200 }
1201 }
1202
1203 this.sources.push(source);
1204 return this;
1205};
1206
1207Bundle.prototype.append = function append (str, options) {
1208 this.addSource({
1209 content: new MagicString(str),
1210 separator: (options && options.separator) || ''
1211 });
1212
1213 return this;
1214};
1215
1216Bundle.prototype.clone = function clone () {
1217 var bundle = new Bundle({
1218 intro: this.intro,
1219 separator: this.separator
1220 });
1221
1222 this.sources.forEach(function (source) {
1223 bundle.addSource({
1224 filename: source.filename,
1225 content: source.content.clone(),
1226 separator: source.separator
1227 });
1228 });
1229
1230 return bundle;
1231};
1232
1233Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
1234 var this$1 = this;
1235 if ( options === void 0 ) options = {};
1236
1237 var names = [];
1238 this.sources.forEach(function (source) {
1239 Object.keys(source.content.storedNames).forEach(function (name) {
1240 if (!~names.indexOf(name)) { names.push(name); }
1241 });
1242 });
1243
1244 var mappings = new Mappings(options.hires);
1245
1246 if (this.intro) {
1247 mappings.advance(this.intro);
1248 }
1249
1250 this.sources.forEach(function (source, i) {
1251 if (i > 0) {
1252 mappings.advance(this$1.separator);
1253 }
1254
1255 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
1256 var magicString = source.content;
1257 var locate = getLocator(magicString.original);
1258
1259 if (magicString.intro) {
1260 mappings.advance(magicString.intro);
1261 }
1262
1263 magicString.firstChunk.eachNext(function (chunk) {
1264 var loc = locate(chunk.start);
1265
1266 if (chunk.intro.length) { mappings.advance(chunk.intro); }
1267
1268 if (source.filename) {
1269 if (chunk.edited) {
1270 mappings.addEdit(
1271 sourceIndex,
1272 chunk.content,
1273 loc,
1274 chunk.storeName ? names.indexOf(chunk.original) : -1
1275 );
1276 } else {
1277 mappings.addUneditedChunk(
1278 sourceIndex,
1279 chunk,
1280 magicString.original,
1281 loc,
1282 magicString.sourcemapLocations
1283 );
1284 }
1285 } else {
1286 mappings.advance(chunk.content);
1287 }
1288
1289 if (chunk.outro.length) { mappings.advance(chunk.outro); }
1290 });
1291
1292 if (magicString.outro) {
1293 mappings.advance(magicString.outro);
1294 }
1295 });
1296
1297 return {
1298 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1299 sources: this.uniqueSources.map(function (source) {
1300 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
1301 }),
1302 sourcesContent: this.uniqueSources.map(function (source) {
1303 return options.includeContent ? source.content : null;
1304 }),
1305 names: names,
1306 mappings: mappings.raw
1307 };
1308};
1309
1310Bundle.prototype.generateMap = function generateMap (options) {
1311 return new SourceMap(this.generateDecodedMap(options));
1312};
1313
1314Bundle.prototype.getIndentString = function getIndentString () {
1315 var indentStringCounts = {};
1316
1317 this.sources.forEach(function (source) {
1318 var indentStr = source.content.indentStr;
1319
1320 if (indentStr === null) { return; }
1321
1322 if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
1323 indentStringCounts[indentStr] += 1;
1324 });
1325
1326 return (
1327 Object.keys(indentStringCounts).sort(function (a, b) {
1328 return indentStringCounts[a] - indentStringCounts[b];
1329 })[0] || '\t'
1330 );
1331};
1332
1333Bundle.prototype.indent = function indent (indentStr) {
1334 var this$1 = this;
1335
1336 if (!arguments.length) {
1337 indentStr = this.getIndentString();
1338 }
1339
1340 if (indentStr === '') { return this; } // noop
1341
1342 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
1343
1344 this.sources.forEach(function (source, i) {
1345 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1346 var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
1347
1348 source.content.indent(indentStr, {
1349 exclude: source.indentExclusionRanges,
1350 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1351 });
1352
1353 trailingNewline = source.content.lastChar() === '\n';
1354 });
1355
1356 if (this.intro) {
1357 this.intro =
1358 indentStr +
1359 this.intro.replace(/^[^\n]/gm, function (match, index) {
1360 return index > 0 ? indentStr + match : match;
1361 });
1362 }
1363
1364 return this;
1365};
1366
1367Bundle.prototype.prepend = function prepend (str) {
1368 this.intro = str + this.intro;
1369 return this;
1370};
1371
1372Bundle.prototype.toString = function toString () {
1373 var this$1 = this;
1374
1375 var body = this.sources
1376 .map(function (source, i) {
1377 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1378 var str = (i > 0 ? separator : '') + source.content.toString();
1379
1380 return str;
1381 })
1382 .join('');
1383
1384 return this.intro + body;
1385};
1386
1387Bundle.prototype.isEmpty = function isEmpty () {
1388 if (this.intro.length && this.intro.trim())
1389 { return false; }
1390 if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
1391 { return false; }
1392 return true;
1393};
1394
1395Bundle.prototype.length = function length () {
1396 return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
1397};
1398
1399Bundle.prototype.trimLines = function trimLines () {
1400 return this.trim('[\\r\\n]');
1401};
1402
1403Bundle.prototype.trim = function trim (charType) {
1404 return this.trimStart(charType).trimEnd(charType);
1405};
1406
1407Bundle.prototype.trimStart = function trimStart (charType) {
1408 var rx = new RegExp('^' + (charType || '\\s') + '+');
1409 this.intro = this.intro.replace(rx, '');
1410
1411 if (!this.intro) {
1412 var source;
1413 var i = 0;
1414
1415 do {
1416 source = this.sources[i++];
1417 if (!source) {
1418 break;
1419 }
1420 } while (!source.content.trimStartAborted(charType));
1421 }
1422
1423 return this;
1424};
1425
1426Bundle.prototype.trimEnd = function trimEnd (charType) {
1427 var rx = new RegExp((charType || '\\s') + '+$');
1428
1429 var source;
1430 var i = this.sources.length - 1;
1431
1432 do {
1433 source = this.sources[i--];
1434 if (!source) {
1435 this.intro = this.intro.replace(rx, '');
1436 break;
1437 }
1438 } while (!source.content.trimEndAborted(charType));
1439
1440 return this;
1441};
1442
1443function relative(from, to) {
1444 const fromParts = from.split(/[/\\]/).filter(Boolean);
1445 const toParts = to.split(/[/\\]/).filter(Boolean);
1446 if (fromParts[0] === '.')
1447 fromParts.shift();
1448 if (toParts[0] === '.')
1449 toParts.shift();
1450 while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
1451 fromParts.shift();
1452 toParts.shift();
1453 }
1454 while (toParts[0] === '..' && fromParts.length > 0) {
1455 toParts.shift();
1456 fromParts.pop();
1457 }
1458 while (fromParts.pop()) {
1459 toParts.unshift('..');
1460 }
1461 return toParts.join('/');
1462}
1463
1464const ArrowFunctionExpression = 'ArrowFunctionExpression';
1465const BlockStatement = 'BlockStatement';
1466const CallExpression = 'CallExpression';
1467const ExpressionStatement = 'ExpressionStatement';
1468const FunctionExpression = 'FunctionExpression';
1469const Identifier = 'Identifier';
1470const ImportDefaultSpecifier = 'ImportDefaultSpecifier';
1471const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
1472const Program = 'Program';
1473const Property = 'Property';
1474const ReturnStatement = 'ReturnStatement';
1475
1476function treeshakeNode(node, code, start, end) {
1477 code.remove(start, end);
1478 if (node.annotations) {
1479 for (const annotation of node.annotations) {
1480 if (annotation.start < start) {
1481 code.remove(annotation.start, annotation.end);
1482 }
1483 else {
1484 return;
1485 }
1486 }
1487 }
1488}
1489function removeAnnotations(node, code) {
1490 if (!node.annotations && node.parent.type === ExpressionStatement) {
1491 node = node.parent;
1492 }
1493 if (node.annotations) {
1494 for (const annotation of node.annotations) {
1495 code.remove(annotation.start, annotation.end);
1496 }
1497 }
1498}
1499
1500const NO_SEMICOLON = { isNoStatement: true };
1501// This assumes there are only white-space and comments between start and the string we are looking for
1502function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
1503 let searchPos, charCodeAfterSlash;
1504 searchPos = code.indexOf(searchString, start);
1505 while (true) {
1506 start = code.indexOf('/', start);
1507 if (start === -1 || start >= searchPos)
1508 return searchPos;
1509 charCodeAfterSlash = code.charCodeAt(++start);
1510 ++start;
1511 // With our assumption, '/' always starts a comment. Determine comment type:
1512 start =
1513 charCodeAfterSlash === 47 /*"/"*/
1514 ? code.indexOf('\n', start) + 1
1515 : code.indexOf('*/', start) + 2;
1516 if (start > searchPos) {
1517 searchPos = code.indexOf(searchString, start);
1518 }
1519 }
1520}
1521const WHITESPACE = /\s/;
1522function findNonWhiteSpace(code, index) {
1523 while (index < code.length && WHITESPACE.test(code[index]))
1524 index++;
1525 return index;
1526}
1527// This assumes "code" only contains white-space and comments
1528// Returns position of line-comment if applicable
1529function findFirstLineBreakOutsideComment(code) {
1530 let lineBreakPos, charCodeAfterSlash, start = 0;
1531 lineBreakPos = code.indexOf('\n', start);
1532 while (true) {
1533 start = code.indexOf('/', start);
1534 if (start === -1 || start > lineBreakPos)
1535 return [lineBreakPos, lineBreakPos + 1];
1536 // With our assumption, '/' always starts a comment. Determine comment type:
1537 charCodeAfterSlash = code.charCodeAt(start + 1);
1538 if (charCodeAfterSlash === 47 /*"/"*/)
1539 return [start, lineBreakPos + 1];
1540 start = code.indexOf('*/', start + 3) + 2;
1541 if (start > lineBreakPos) {
1542 lineBreakPos = code.indexOf('\n', start);
1543 }
1544 }
1545}
1546function renderStatementList(statements, code, start, end, options) {
1547 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
1548 let nextNode = statements[0];
1549 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
1550 if (nextNodeNeedsBoundaries) {
1551 nextNodeStart =
1552 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start))[1];
1553 }
1554 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
1555 currentNode = nextNode;
1556 currentNodeStart = nextNodeStart;
1557 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
1558 nextNode = statements[nextIndex];
1559 nextNodeNeedsBoundaries =
1560 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
1561 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
1562 nextNodeStart =
1563 currentNode.end +
1564 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start))[1];
1565 if (currentNode.included) {
1566 currentNodeNeedsBoundaries
1567 ? currentNode.render(code, options, {
1568 end: nextNodeStart,
1569 start: currentNodeStart
1570 })
1571 : currentNode.render(code, options);
1572 }
1573 else {
1574 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
1575 }
1576 }
1577 else {
1578 currentNode.render(code, options);
1579 }
1580 }
1581}
1582// This assumes that the first character is not part of the first node
1583function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
1584 const splitUpNodes = [];
1585 let node, nextNode, nextNodeStart, contentEnd, char;
1586 let separator = start - 1;
1587 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
1588 nextNode = nodes[nextIndex];
1589 if (node !== undefined) {
1590 separator =
1591 node.end +
1592 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
1593 }
1594 nextNodeStart = contentEnd =
1595 separator +
1596 1 +
1597 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start))[1];
1598 while (((char = code.original.charCodeAt(nextNodeStart)),
1599 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
1600 nextNodeStart++;
1601 if (node !== undefined) {
1602 splitUpNodes.push({
1603 contentEnd,
1604 end: nextNodeStart,
1605 node,
1606 separator,
1607 start
1608 });
1609 }
1610 node = nextNode;
1611 start = nextNodeStart;
1612 }
1613 splitUpNodes.push({
1614 contentEnd: end,
1615 end,
1616 node: node,
1617 separator: null,
1618 start
1619 });
1620 return splitUpNodes;
1621}
1622// This assumes there are only white-space and comments between start and end
1623function removeLineBreaks(code, start, end) {
1624 while (true) {
1625 const [removeStart, removeEnd] = findFirstLineBreakOutsideComment(code.original.slice(start, end));
1626 if (removeStart === -1) {
1627 break;
1628 }
1629 code.remove(start + removeStart, (start += removeEnd));
1630 }
1631}
1632
1633function getSystemExportStatement(exportedVariables, options) {
1634 const _ = options.compact ? '' : ' ';
1635 if (exportedVariables.length === 1 &&
1636 options.exportNamesByVariable.get(exportedVariables[0]).length === 1) {
1637 const variable = exportedVariables[0];
1638 return `exports('${options.exportNamesByVariable.get(variable)}',${_}${variable.getName()})`;
1639 }
1640 else {
1641 return `exports({${_}${exportedVariables
1642 .map(variable => {
1643 return options.exportNamesByVariable
1644 .get(variable)
1645 .map(exportName => `${exportName}:${_}${variable.getName()}`)
1646 .join(`,${_}`);
1647 })
1648 .join(`,${_}`)}${_}})`;
1649 }
1650}
1651function getSystemExportFunctionLeft(exportedVariables, setFromExpression, options) {
1652 const _ = options.compact ? '' : ' ';
1653 const s = options.compact ? '' : ';';
1654 return `function${_}(v)${_}{${_}return exports({${_}${exportedVariables
1655 .map(variable => {
1656 return options.exportNamesByVariable
1657 .get(variable)
1658 .map(exportName => `${exportName}:${_}${setFromExpression ? variable.getName() : 'v'}`)
1659 .join(`,${_}`);
1660 })
1661 .join(`,${_}`)}${_}}),${_}v${s}${_}}(`;
1662}
1663
1664const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
1665const base = 64;
1666function toBase64(num) {
1667 let outStr = '';
1668 do {
1669 const curDigit = num % base;
1670 num = Math.floor(num / base);
1671 outStr = chars$1[curDigit] + outStr;
1672 } while (num !== 0);
1673 return outStr;
1674}
1675
1676const RESERVED_NAMES = {
1677 // @ts-ignore
1678 __proto__: null,
1679 await: true,
1680 break: true,
1681 case: true,
1682 catch: true,
1683 class: true,
1684 const: true,
1685 continue: true,
1686 debugger: true,
1687 default: true,
1688 delete: true,
1689 do: true,
1690 else: true,
1691 enum: true,
1692 eval: true,
1693 export: true,
1694 extends: true,
1695 false: true,
1696 finally: true,
1697 for: true,
1698 function: true,
1699 if: true,
1700 implements: true,
1701 import: true,
1702 in: true,
1703 instanceof: true,
1704 interface: true,
1705 let: true,
1706 new: true,
1707 null: true,
1708 package: true,
1709 private: true,
1710 protected: true,
1711 public: true,
1712 return: true,
1713 static: true,
1714 super: true,
1715 switch: true,
1716 this: true,
1717 throw: true,
1718 true: true,
1719 try: true,
1720 typeof: true,
1721 undefined: true,
1722 var: true,
1723 void: true,
1724 while: true,
1725 with: true,
1726 yield: true
1727};
1728
1729function getSafeName(baseName, usedNames) {
1730 let safeName = baseName;
1731 let count = 1;
1732 while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
1733 safeName = `${baseName}$${toBase64(count++)}`;
1734 }
1735 usedNames.add(safeName);
1736 return safeName;
1737}
1738
1739const NO_ARGS = [];
1740
1741function getOrCreate(map, key, init) {
1742 const existing = map.get(key);
1743 if (existing) {
1744 return existing;
1745 }
1746 const value = init();
1747 map.set(key, value);
1748 return value;
1749}
1750
1751const UnknownKey = Symbol('Unknown Key');
1752const EMPTY_PATH = [];
1753const UNKNOWN_PATH = [UnknownKey];
1754const EntitiesKey = Symbol('Entities');
1755class PathTracker {
1756 constructor() {
1757 this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } });
1758 }
1759 getEntities(path) {
1760 let currentPaths = this.entityPaths;
1761 for (const pathSegment of path) {
1762 currentPaths = currentPaths[pathSegment] =
1763 currentPaths[pathSegment] ||
1764 Object.create(null, { [EntitiesKey]: { value: new Set() } });
1765 }
1766 return currentPaths[EntitiesKey];
1767 }
1768}
1769const SHARED_RECURSION_TRACKER = new PathTracker();
1770class DiscriminatedPathTracker {
1771 constructor() {
1772 this.entityPaths = Object.create(null, {
1773 [EntitiesKey]: { value: new Map() }
1774 });
1775 }
1776 getEntities(path, discriminator) {
1777 let currentPaths = this.entityPaths;
1778 for (const pathSegment of path) {
1779 currentPaths = currentPaths[pathSegment] =
1780 currentPaths[pathSegment] ||
1781 Object.create(null, { [EntitiesKey]: { value: new Map() } });
1782 }
1783 return getOrCreate(currentPaths[EntitiesKey], discriminator, () => new Set());
1784 }
1785}
1786
1787function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
1788 return Object.create(inheritedDescriptions, memberDescriptions);
1789}
1790const UnknownValue = Symbol('Unknown Value');
1791const UNKNOWN_EXPRESSION = {
1792 deoptimizePath: () => { },
1793 getLiteralValueAtPath: () => UnknownValue,
1794 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
1795 hasEffectsWhenAccessedAtPath: path => path.length > 0,
1796 hasEffectsWhenAssignedAtPath: path => path.length > 0,
1797 hasEffectsWhenCalledAtPath: () => true,
1798 include: () => { },
1799 includeCallArguments(context, args) {
1800 for (const arg of args) {
1801 arg.include(context, false);
1802 }
1803 },
1804 included: true,
1805 toString: () => '[[UNKNOWN]]'
1806};
1807const UNDEFINED_EXPRESSION = {
1808 deoptimizePath: () => { },
1809 getLiteralValueAtPath: () => undefined,
1810 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
1811 hasEffectsWhenAccessedAtPath: path => path.length > 0,
1812 hasEffectsWhenAssignedAtPath: path => path.length > 0,
1813 hasEffectsWhenCalledAtPath: () => true,
1814 include: () => { },
1815 includeCallArguments() { },
1816 included: true,
1817 toString: () => 'undefined'
1818};
1819const returnsUnknown = {
1820 value: {
1821 callsArgs: null,
1822 mutatesSelf: false,
1823 returns: null,
1824 returnsPrimitive: UNKNOWN_EXPRESSION
1825 }
1826};
1827const mutatesSelfReturnsUnknown = {
1828 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
1829};
1830const callsArgReturnsUnknown = {
1831 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
1832};
1833class UnknownArrayExpression {
1834 constructor() {
1835 this.included = false;
1836 }
1837 deoptimizePath() { }
1838 getLiteralValueAtPath() {
1839 return UnknownValue;
1840 }
1841 getReturnExpressionWhenCalledAtPath(path) {
1842 if (path.length === 1) {
1843 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
1844 }
1845 return UNKNOWN_EXPRESSION;
1846 }
1847 hasEffectsWhenAccessedAtPath(path) {
1848 return path.length > 1;
1849 }
1850 hasEffectsWhenAssignedAtPath(path) {
1851 return path.length > 1;
1852 }
1853 hasEffectsWhenCalledAtPath(path, callOptions, context) {
1854 if (path.length === 1) {
1855 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
1856 }
1857 return true;
1858 }
1859 include() {
1860 this.included = true;
1861 }
1862 includeCallArguments(context, args) {
1863 for (const arg of args) {
1864 arg.include(context, false);
1865 }
1866 }
1867 toString() {
1868 return '[[UNKNOWN ARRAY]]';
1869 }
1870}
1871const returnsArray = {
1872 value: {
1873 callsArgs: null,
1874 mutatesSelf: false,
1875 returns: UnknownArrayExpression,
1876 returnsPrimitive: null
1877 }
1878};
1879const mutatesSelfReturnsArray = {
1880 value: {
1881 callsArgs: null,
1882 mutatesSelf: true,
1883 returns: UnknownArrayExpression,
1884 returnsPrimitive: null
1885 }
1886};
1887const callsArgReturnsArray = {
1888 value: {
1889 callsArgs: [0],
1890 mutatesSelf: false,
1891 returns: UnknownArrayExpression,
1892 returnsPrimitive: null
1893 }
1894};
1895const callsArgMutatesSelfReturnsArray = {
1896 value: {
1897 callsArgs: [0],
1898 mutatesSelf: true,
1899 returns: UnknownArrayExpression,
1900 returnsPrimitive: null
1901 }
1902};
1903const UNKNOWN_LITERAL_BOOLEAN = {
1904 deoptimizePath: () => { },
1905 getLiteralValueAtPath: () => UnknownValue,
1906 getReturnExpressionWhenCalledAtPath: path => {
1907 if (path.length === 1) {
1908 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
1909 }
1910 return UNKNOWN_EXPRESSION;
1911 },
1912 hasEffectsWhenAccessedAtPath: path => path.length > 1,
1913 hasEffectsWhenAssignedAtPath: path => path.length > 0,
1914 hasEffectsWhenCalledAtPath: path => {
1915 if (path.length === 1) {
1916 const subPath = path[0];
1917 return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
1918 }
1919 return true;
1920 },
1921 include: () => { },
1922 includeCallArguments(context, args) {
1923 for (const arg of args) {
1924 arg.include(context, false);
1925 }
1926 },
1927 included: true,
1928 toString: () => '[[UNKNOWN BOOLEAN]]'
1929};
1930const returnsBoolean = {
1931 value: {
1932 callsArgs: null,
1933 mutatesSelf: false,
1934 returns: null,
1935 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
1936 }
1937};
1938const callsArgReturnsBoolean = {
1939 value: {
1940 callsArgs: [0],
1941 mutatesSelf: false,
1942 returns: null,
1943 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
1944 }
1945};
1946const UNKNOWN_LITERAL_NUMBER = {
1947 deoptimizePath: () => { },
1948 getLiteralValueAtPath: () => UnknownValue,
1949 getReturnExpressionWhenCalledAtPath: path => {
1950 if (path.length === 1) {
1951 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
1952 }
1953 return UNKNOWN_EXPRESSION;
1954 },
1955 hasEffectsWhenAccessedAtPath: path => path.length > 1,
1956 hasEffectsWhenAssignedAtPath: path => path.length > 0,
1957 hasEffectsWhenCalledAtPath: path => {
1958 if (path.length === 1) {
1959 const subPath = path[0];
1960 return typeof subPath !== 'string' || !literalNumberMembers[subPath];
1961 }
1962 return true;
1963 },
1964 include: () => { },
1965 includeCallArguments(context, args) {
1966 for (const arg of args) {
1967 arg.include(context, false);
1968 }
1969 },
1970 included: true,
1971 toString: () => '[[UNKNOWN NUMBER]]'
1972};
1973const returnsNumber = {
1974 value: {
1975 callsArgs: null,
1976 mutatesSelf: false,
1977 returns: null,
1978 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
1979 }
1980};
1981const mutatesSelfReturnsNumber = {
1982 value: {
1983 callsArgs: null,
1984 mutatesSelf: true,
1985 returns: null,
1986 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
1987 }
1988};
1989const callsArgReturnsNumber = {
1990 value: {
1991 callsArgs: [0],
1992 mutatesSelf: false,
1993 returns: null,
1994 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
1995 }
1996};
1997const UNKNOWN_LITERAL_STRING = {
1998 deoptimizePath: () => { },
1999 getLiteralValueAtPath: () => UnknownValue,
2000 getReturnExpressionWhenCalledAtPath: path => {
2001 if (path.length === 1) {
2002 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
2003 }
2004 return UNKNOWN_EXPRESSION;
2005 },
2006 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2007 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2008 hasEffectsWhenCalledAtPath: (path, callOptions, context) => {
2009 if (path.length === 1) {
2010 return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context);
2011 }
2012 return true;
2013 },
2014 include: () => { },
2015 includeCallArguments(context, args) {
2016 for (const arg of args) {
2017 arg.include(context, false);
2018 }
2019 },
2020 included: true,
2021 toString: () => '[[UNKNOWN STRING]]'
2022};
2023const returnsString = {
2024 value: {
2025 callsArgs: null,
2026 mutatesSelf: false,
2027 returns: null,
2028 returnsPrimitive: UNKNOWN_LITERAL_STRING
2029 }
2030};
2031class UnknownObjectExpression {
2032 constructor() {
2033 this.included = false;
2034 }
2035 deoptimizePath() { }
2036 getLiteralValueAtPath() {
2037 return UnknownValue;
2038 }
2039 getReturnExpressionWhenCalledAtPath(path) {
2040 if (path.length === 1) {
2041 return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
2042 }
2043 return UNKNOWN_EXPRESSION;
2044 }
2045 hasEffectsWhenAccessedAtPath(path) {
2046 return path.length > 1;
2047 }
2048 hasEffectsWhenAssignedAtPath(path) {
2049 return path.length > 1;
2050 }
2051 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2052 if (path.length === 1) {
2053 return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context);
2054 }
2055 return true;
2056 }
2057 include() {
2058 this.included = true;
2059 }
2060 includeCallArguments(context, args) {
2061 for (const arg of args) {
2062 arg.include(context, false);
2063 }
2064 }
2065 toString() {
2066 return '[[UNKNOWN OBJECT]]';
2067 }
2068}
2069const objectMembers = assembleMemberDescriptions({
2070 hasOwnProperty: returnsBoolean,
2071 isPrototypeOf: returnsBoolean,
2072 propertyIsEnumerable: returnsBoolean,
2073 toLocaleString: returnsString,
2074 toString: returnsString,
2075 valueOf: returnsUnknown
2076});
2077const arrayMembers = assembleMemberDescriptions({
2078 concat: returnsArray,
2079 copyWithin: mutatesSelfReturnsArray,
2080 every: callsArgReturnsBoolean,
2081 fill: mutatesSelfReturnsArray,
2082 filter: callsArgReturnsArray,
2083 find: callsArgReturnsUnknown,
2084 findIndex: callsArgReturnsNumber,
2085 forEach: callsArgReturnsUnknown,
2086 includes: returnsBoolean,
2087 indexOf: returnsNumber,
2088 join: returnsString,
2089 lastIndexOf: returnsNumber,
2090 map: callsArgReturnsArray,
2091 pop: mutatesSelfReturnsUnknown,
2092 push: mutatesSelfReturnsNumber,
2093 reduce: callsArgReturnsUnknown,
2094 reduceRight: callsArgReturnsUnknown,
2095 reverse: mutatesSelfReturnsArray,
2096 shift: mutatesSelfReturnsUnknown,
2097 slice: returnsArray,
2098 some: callsArgReturnsBoolean,
2099 sort: callsArgMutatesSelfReturnsArray,
2100 splice: mutatesSelfReturnsArray,
2101 unshift: mutatesSelfReturnsNumber
2102}, objectMembers);
2103const literalBooleanMembers = assembleMemberDescriptions({
2104 valueOf: returnsBoolean
2105}, objectMembers);
2106const literalNumberMembers = assembleMemberDescriptions({
2107 toExponential: returnsString,
2108 toFixed: returnsString,
2109 toLocaleString: returnsString,
2110 toPrecision: returnsString,
2111 valueOf: returnsNumber
2112}, objectMembers);
2113const literalStringMembers = assembleMemberDescriptions({
2114 charAt: returnsString,
2115 charCodeAt: returnsNumber,
2116 codePointAt: returnsNumber,
2117 concat: returnsString,
2118 endsWith: returnsBoolean,
2119 includes: returnsBoolean,
2120 indexOf: returnsNumber,
2121 lastIndexOf: returnsNumber,
2122 localeCompare: returnsNumber,
2123 match: returnsBoolean,
2124 normalize: returnsString,
2125 padEnd: returnsString,
2126 padStart: returnsString,
2127 repeat: returnsString,
2128 replace: {
2129 value: {
2130 callsArgs: [1],
2131 mutatesSelf: false,
2132 returns: null,
2133 returnsPrimitive: UNKNOWN_LITERAL_STRING
2134 }
2135 },
2136 search: returnsNumber,
2137 slice: returnsString,
2138 split: returnsArray,
2139 startsWith: returnsBoolean,
2140 substr: returnsString,
2141 substring: returnsString,
2142 toLocaleLowerCase: returnsString,
2143 toLocaleUpperCase: returnsString,
2144 toLowerCase: returnsString,
2145 toUpperCase: returnsString,
2146 trim: returnsString,
2147 valueOf: returnsString
2148}, objectMembers);
2149function getLiteralMembersForValue(value) {
2150 switch (typeof value) {
2151 case 'boolean':
2152 return literalBooleanMembers;
2153 case 'number':
2154 return literalNumberMembers;
2155 case 'string':
2156 return literalStringMembers;
2157 default:
2158 return Object.create(null);
2159 }
2160}
2161function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) {
2162 if (typeof memberName !== 'string' ||
2163 !members[memberName] ||
2164 (members[memberName].mutatesSelf && parentIncluded))
2165 return true;
2166 if (!members[memberName].callsArgs)
2167 return false;
2168 for (const argIndex of members[memberName].callsArgs) {
2169 if (callOptions.args[argIndex] &&
2170 callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
2171 args: NO_ARGS,
2172 withNew: false
2173 }, context))
2174 return true;
2175 }
2176 return false;
2177}
2178function getMemberReturnExpressionWhenCalled(members, memberName) {
2179 if (typeof memberName !== 'string' || !members[memberName])
2180 return UNKNOWN_EXPRESSION;
2181 return members[memberName].returnsPrimitive !== null
2182 ? members[memberName].returnsPrimitive
2183 : new members[memberName].returns();
2184}
2185
2186class Variable {
2187 constructor(name) {
2188 this.alwaysRendered = false;
2189 this.included = false;
2190 this.isId = false;
2191 this.isReassigned = false;
2192 this.renderBaseName = null;
2193 this.renderName = null;
2194 this.name = name;
2195 }
2196 /**
2197 * Binds identifiers that reference this variable to this variable.
2198 * Necessary to be able to change variable names.
2199 */
2200 addReference(_identifier) { }
2201 deoptimizePath(_path) { }
2202 getBaseVariableName() {
2203 return this.renderBaseName || this.renderName || this.name;
2204 }
2205 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2206 return UnknownValue;
2207 }
2208 getName() {
2209 const name = this.renderName || this.name;
2210 return this.renderBaseName
2211 ? `${this.renderBaseName}${RESERVED_NAMES[name] ? `['${name}']` : `.${name}`}`
2212 : name;
2213 }
2214 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
2215 return UNKNOWN_EXPRESSION;
2216 }
2217 hasEffectsWhenAccessedAtPath(path, _context) {
2218 return path.length > 0;
2219 }
2220 hasEffectsWhenAssignedAtPath(_path, _context) {
2221 return true;
2222 }
2223 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
2224 return true;
2225 }
2226 /**
2227 * Marks this variable as being part of the bundle, which is usually the case when one of
2228 * its identifiers becomes part of the bundle. Returns true if it has not been included
2229 * previously.
2230 * Once a variable is included, it should take care all its declarations are included.
2231 */
2232 include() {
2233 this.included = true;
2234 }
2235 includeCallArguments(context, args) {
2236 for (const arg of args) {
2237 arg.include(context, false);
2238 }
2239 }
2240 markCalledFromTryStatement() { }
2241 setRenderNames(baseName, name) {
2242 this.renderBaseName = baseName;
2243 this.renderName = name;
2244 }
2245}
2246
2247class ExternalVariable extends Variable {
2248 constructor(module, name) {
2249 super(name);
2250 this.module = module;
2251 this.isNamespace = name === '*';
2252 this.referenced = false;
2253 }
2254 addReference(identifier) {
2255 this.referenced = true;
2256 if (this.name === 'default' || this.name === '*') {
2257 this.module.suggestName(identifier.name);
2258 }
2259 }
2260 include() {
2261 if (!this.included) {
2262 this.included = true;
2263 this.module.used = true;
2264 }
2265 }
2266}
2267
2268const BLANK = Object.freeze(Object.create(null));
2269const EMPTY_OBJECT = Object.freeze({});
2270const EMPTY_ARRAY = Object.freeze([]);
2271
2272const 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(' ');
2273const 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(' ');
2274const blacklisted = new Set(reservedWords.concat(builtins));
2275const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2276const startsWithDigit = (str) => /\d/.test(str[0]);
2277function isLegal(str) {
2278 if (startsWithDigit(str) || blacklisted.has(str)) {
2279 return false;
2280 }
2281 return !illegalCharacters.test(str);
2282}
2283function makeLegal(str) {
2284 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2285 if (startsWithDigit(str) || blacklisted.has(str))
2286 str = `_${str}`;
2287 return str || '_';
2288}
2289
2290const absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
2291const relativePath = /^\.?\.\//;
2292function isAbsolute(path) {
2293 return absolutePath.test(path);
2294}
2295function isRelative(path) {
2296 return relativePath.test(path);
2297}
2298function normalize(path) {
2299 if (path.indexOf('\\') == -1)
2300 return path;
2301 return path.replace(/\\/g, '/');
2302}
2303
2304class ExternalModule {
2305 constructor(options, id, hasModuleSideEffects, meta) {
2306 this.options = options;
2307 this.id = id;
2308 this.defaultVariableName = '';
2309 this.dynamicImporters = [];
2310 this.importers = [];
2311 this.mostCommonSuggestion = 0;
2312 this.namespaceVariableName = '';
2313 this.reexported = false;
2314 this.renderPath = undefined;
2315 this.renormalizeRenderPath = false;
2316 this.used = false;
2317 this.variableName = '';
2318 this.execIndex = Infinity;
2319 this.suggestedVariableName = makeLegal(id.split(/[\\/]/).pop());
2320 this.nameSuggestions = Object.create(null);
2321 this.declarations = Object.create(null);
2322 this.exportedVariables = new Map();
2323 const module = this;
2324 this.info = {
2325 ast: null,
2326 code: null,
2327 dynamicallyImportedIds: EMPTY_ARRAY,
2328 get dynamicImporters() {
2329 return module.dynamicImporters.sort();
2330 },
2331 hasModuleSideEffects,
2332 id,
2333 implicitlyLoadedAfterOneOf: EMPTY_ARRAY,
2334 implicitlyLoadedBefore: EMPTY_ARRAY,
2335 importedIds: EMPTY_ARRAY,
2336 get importers() {
2337 return module.importers.sort();
2338 },
2339 isEntry: false,
2340 isExternal: true,
2341 meta
2342 };
2343 }
2344 getVariableForExportName(name) {
2345 let declaration = this.declarations[name];
2346 if (declaration)
2347 return declaration;
2348 this.declarations[name] = declaration = new ExternalVariable(this, name);
2349 this.exportedVariables.set(declaration, name);
2350 return declaration;
2351 }
2352 setRenderPath(options, inputBase) {
2353 this.renderPath =
2354 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2355 if (!this.renderPath) {
2356 if (!isAbsolute(this.id)) {
2357 this.renderPath = this.id;
2358 }
2359 else {
2360 this.renderPath = normalize(relative$1(inputBase, this.id));
2361 this.renormalizeRenderPath = true;
2362 }
2363 }
2364 return this.renderPath;
2365 }
2366 suggestName(name) {
2367 if (!this.nameSuggestions[name])
2368 this.nameSuggestions[name] = 0;
2369 this.nameSuggestions[name] += 1;
2370 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
2371 this.mostCommonSuggestion = this.nameSuggestions[name];
2372 this.suggestedVariableName = name;
2373 }
2374 }
2375 warnUnusedImports() {
2376 const unused = Object.keys(this.declarations).filter(name => {
2377 if (name === '*')
2378 return false;
2379 const declaration = this.declarations[name];
2380 return !declaration.included && !this.reexported && !declaration.referenced;
2381 });
2382 if (unused.length === 0)
2383 return;
2384 const names = unused.length === 1
2385 ? `'${unused[0]}' is`
2386 : `${unused
2387 .slice(0, -1)
2388 .map(name => `'${name}'`)
2389 .join(', ')} and '${unused.slice(-1)}' are`;
2390 this.options.onwarn({
2391 code: 'UNUSED_EXTERNAL_IMPORT',
2392 message: `${names} imported from external module '${this.id}' but never used`,
2393 names: unused,
2394 source: this.id
2395 });
2396 }
2397}
2398
2399function markModuleAndImpureDependenciesAsExecuted(baseModule) {
2400 baseModule.isExecuted = true;
2401 const modules = [baseModule];
2402 const visitedModules = new Set();
2403 for (const module of modules) {
2404 for (const dependency of [...module.dependencies, ...module.implicitlyLoadedBefore]) {
2405 if (!(dependency instanceof ExternalModule) &&
2406 !dependency.isExecuted &&
2407 (dependency.info.hasModuleSideEffects || module.implicitlyLoadedBefore.has(dependency)) &&
2408 !visitedModules.has(dependency.id)) {
2409 dependency.isExecuted = true;
2410 visitedModules.add(dependency.id);
2411 modules.push(dependency);
2412 }
2413 }
2414 }
2415}
2416
2417const BROKEN_FLOW_NONE = 0;
2418const BROKEN_FLOW_BREAK_CONTINUE = 1;
2419const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
2420function createInclusionContext() {
2421 return {
2422 brokenFlow: BROKEN_FLOW_NONE,
2423 includedCallArguments: new Set(),
2424 includedLabels: new Set()
2425 };
2426}
2427function createHasEffectsContext() {
2428 return {
2429 accessed: new PathTracker(),
2430 assigned: new PathTracker(),
2431 brokenFlow: BROKEN_FLOW_NONE,
2432 called: new DiscriminatedPathTracker(),
2433 ignore: {
2434 breaks: false,
2435 continues: false,
2436 labels: new Set(),
2437 returnAwaitYield: false
2438 },
2439 includedLabels: new Set(),
2440 instantiated: new DiscriminatedPathTracker(),
2441 replacedVariableInits: new Map()
2442 };
2443}
2444
2445// To avoid infinite recursions
2446const MAX_PATH_DEPTH = 7;
2447class LocalVariable extends Variable {
2448 constructor(name, declarator, init, context) {
2449 super(name);
2450 this.additionalInitializers = null;
2451 this.calledFromTryStatement = false;
2452 this.expressionsToBeDeoptimized = [];
2453 this.declarations = declarator ? [declarator] : [];
2454 this.init = init;
2455 this.deoptimizationTracker = context.deoptimizationTracker;
2456 this.module = context.module;
2457 }
2458 addDeclaration(identifier, init) {
2459 this.declarations.push(identifier);
2460 if (this.additionalInitializers === null) {
2461 this.additionalInitializers = this.init === null ? [] : [this.init];
2462 this.init = UNKNOWN_EXPRESSION;
2463 this.isReassigned = true;
2464 }
2465 if (init !== null) {
2466 this.additionalInitializers.push(init);
2467 }
2468 }
2469 consolidateInitializers() {
2470 if (this.additionalInitializers !== null) {
2471 for (const initializer of this.additionalInitializers) {
2472 initializer.deoptimizePath(UNKNOWN_PATH);
2473 }
2474 this.additionalInitializers = null;
2475 }
2476 }
2477 deoptimizePath(path) {
2478 if (path.length > MAX_PATH_DEPTH || this.isReassigned)
2479 return;
2480 const trackedEntities = this.deoptimizationTracker.getEntities(path);
2481 if (trackedEntities.has(this))
2482 return;
2483 trackedEntities.add(this);
2484 if (path.length === 0) {
2485 if (!this.isReassigned) {
2486 this.isReassigned = true;
2487 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
2488 this.expressionsToBeDeoptimized = [];
2489 for (const expression of expressionsToBeDeoptimized) {
2490 expression.deoptimizeCache();
2491 }
2492 if (this.init) {
2493 this.init.deoptimizePath(UNKNOWN_PATH);
2494 }
2495 }
2496 }
2497 else if (this.init) {
2498 this.init.deoptimizePath(path);
2499 }
2500 }
2501 getLiteralValueAtPath(path, recursionTracker, origin) {
2502 if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
2503 return UnknownValue;
2504 }
2505 const trackedEntities = recursionTracker.getEntities(path);
2506 if (trackedEntities.has(this.init)) {
2507 return UnknownValue;
2508 }
2509 this.expressionsToBeDeoptimized.push(origin);
2510 trackedEntities.add(this.init);
2511 const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
2512 trackedEntities.delete(this.init);
2513 return value;
2514 }
2515 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
2516 if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
2517 return UNKNOWN_EXPRESSION;
2518 }
2519 const trackedEntities = recursionTracker.getEntities(path);
2520 if (trackedEntities.has(this.init)) {
2521 return UNKNOWN_EXPRESSION;
2522 }
2523 this.expressionsToBeDeoptimized.push(origin);
2524 trackedEntities.add(this.init);
2525 const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
2526 trackedEntities.delete(this.init);
2527 return value;
2528 }
2529 hasEffectsWhenAccessedAtPath(path, context) {
2530 if (path.length === 0)
2531 return false;
2532 if (this.isReassigned || path.length > MAX_PATH_DEPTH)
2533 return true;
2534 const trackedExpressions = context.accessed.getEntities(path);
2535 if (trackedExpressions.has(this))
2536 return false;
2537 trackedExpressions.add(this);
2538 return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
2539 }
2540 hasEffectsWhenAssignedAtPath(path, context) {
2541 if (this.included || path.length > MAX_PATH_DEPTH)
2542 return true;
2543 if (path.length === 0)
2544 return false;
2545 if (this.isReassigned)
2546 return true;
2547 const trackedExpressions = context.assigned.getEntities(path);
2548 if (trackedExpressions.has(this))
2549 return false;
2550 trackedExpressions.add(this);
2551 return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
2552 }
2553 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2554 if (path.length > MAX_PATH_DEPTH || this.isReassigned)
2555 return true;
2556 const trackedExpressions = (callOptions.withNew
2557 ? context.instantiated
2558 : context.called).getEntities(path, callOptions);
2559 if (trackedExpressions.has(this))
2560 return false;
2561 trackedExpressions.add(this);
2562 return (this.init && this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
2563 }
2564 include() {
2565 if (!this.included) {
2566 this.included = true;
2567 if (!this.module.isExecuted) {
2568 markModuleAndImpureDependenciesAsExecuted(this.module);
2569 }
2570 for (const declaration of this.declarations) {
2571 // If node is a default export, it can save a tree-shaking run to include the full declaration now
2572 if (!declaration.included)
2573 declaration.include(createInclusionContext(), false);
2574 let node = declaration.parent;
2575 while (!node.included) {
2576 // We do not want to properly include parents in case they are part of a dead branch
2577 // in which case .include() might pull in more dead code
2578 node.included = true;
2579 if (node.type === Program)
2580 break;
2581 node = node.parent;
2582 }
2583 }
2584 }
2585 }
2586 includeCallArguments(context, args) {
2587 if (this.isReassigned || (this.init && context.includedCallArguments.has(this.init))) {
2588 for (const arg of args) {
2589 arg.include(context, false);
2590 }
2591 }
2592 else if (this.init) {
2593 context.includedCallArguments.add(this.init);
2594 this.init.includeCallArguments(context, args);
2595 context.includedCallArguments.delete(this.init);
2596 }
2597 }
2598 markCalledFromTryStatement() {
2599 this.calledFromTryStatement = true;
2600 }
2601}
2602
2603class Scope {
2604 constructor() {
2605 this.children = [];
2606 this.variables = new Map();
2607 }
2608 addDeclaration(identifier, context, init, _isHoisted) {
2609 const name = identifier.name;
2610 let variable = this.variables.get(name);
2611 if (variable) {
2612 variable.addDeclaration(identifier, init);
2613 }
2614 else {
2615 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
2616 this.variables.set(name, variable);
2617 }
2618 return variable;
2619 }
2620 contains(name) {
2621 return this.variables.has(name);
2622 }
2623 findVariable(_name) {
2624 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
2625 }
2626}
2627
2628class ChildScope extends Scope {
2629 constructor(parent) {
2630 super();
2631 this.accessedOutsideVariables = new Map();
2632 this.parent = parent;
2633 parent.children.push(this);
2634 }
2635 addAccessedDynamicImport(importExpression) {
2636 (this.accessedDynamicImports || (this.accessedDynamicImports = new Set())).add(importExpression);
2637 if (this.parent instanceof ChildScope) {
2638 this.parent.addAccessedDynamicImport(importExpression);
2639 }
2640 }
2641 addAccessedGlobals(globals, accessedGlobalsByScope) {
2642 const accessedGlobals = accessedGlobalsByScope.get(this) || new Set();
2643 for (const name of globals) {
2644 accessedGlobals.add(name);
2645 }
2646 accessedGlobalsByScope.set(this, accessedGlobals);
2647 if (this.parent instanceof ChildScope) {
2648 this.parent.addAccessedGlobals(globals, accessedGlobalsByScope);
2649 }
2650 }
2651 addNamespaceMemberAccess(name, variable) {
2652 this.accessedOutsideVariables.set(name, variable);
2653 this.parent.addNamespaceMemberAccess(name, variable);
2654 }
2655 addReturnExpression(expression) {
2656 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
2657 }
2658 addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope) {
2659 for (const variable of this.accessedOutsideVariables.values()) {
2660 if (variable.included) {
2661 usedNames.add(variable.getBaseVariableName());
2662 if (format === 'system' && exportNamesByVariable.has(variable)) {
2663 usedNames.add('exports');
2664 }
2665 }
2666 }
2667 const accessedGlobals = accessedGlobalsByScope.get(this);
2668 if (accessedGlobals) {
2669 for (const name of accessedGlobals) {
2670 usedNames.add(name);
2671 }
2672 }
2673 }
2674 contains(name) {
2675 return this.variables.has(name) || this.parent.contains(name);
2676 }
2677 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
2678 const usedNames = new Set();
2679 this.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
2680 if (this.accessedDynamicImports) {
2681 for (const importExpression of this.accessedDynamicImports) {
2682 if (importExpression.inlineNamespace) {
2683 usedNames.add(importExpression.inlineNamespace.getBaseVariableName());
2684 }
2685 }
2686 }
2687 for (const [name, variable] of this.variables) {
2688 if (variable.included || variable.alwaysRendered) {
2689 variable.setRenderNames(null, getSafeName(name, usedNames));
2690 }
2691 }
2692 for (const scope of this.children) {
2693 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
2694 }
2695 }
2696 findLexicalBoundary() {
2697 return this.parent.findLexicalBoundary();
2698 }
2699 findVariable(name) {
2700 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
2701 if (knownVariable) {
2702 return knownVariable;
2703 }
2704 const variable = this.parent.findVariable(name);
2705 this.accessedOutsideVariables.set(name, variable);
2706 return variable;
2707 }
2708}
2709
2710function getLocator$1(source, options) {
2711 if (options === void 0) { options = {}; }
2712 var offsetLine = options.offsetLine || 0;
2713 var offsetColumn = options.offsetColumn || 0;
2714 var originalLines = source.split('\n');
2715 var start = 0;
2716 var lineRanges = originalLines.map(function (line, i) {
2717 var end = start + line.length + 1;
2718 var range = { start: start, end: end, line: i };
2719 start = end;
2720 return range;
2721 });
2722 var i = 0;
2723 function rangeContains(range, index) {
2724 return range.start <= index && index < range.end;
2725 }
2726 function getLocation(range, index) {
2727 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
2728 }
2729 function locate(search, startIndex) {
2730 if (typeof search === 'string') {
2731 search = source.indexOf(search, startIndex || 0);
2732 }
2733 var range = lineRanges[i];
2734 var d = search >= range.end ? 1 : -1;
2735 while (range) {
2736 if (rangeContains(range, search))
2737 return getLocation(range, search);
2738 i += d;
2739 range = lineRanges[i];
2740 }
2741 }
2742 return locate;
2743}
2744function locate(source, search, options) {
2745 if (typeof options === 'number') {
2746 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
2747 }
2748 return getLocator$1(source, options)(search, options && options.startIndex);
2749}
2750
2751const keys = {
2752 Literal: [],
2753 Program: ['body']
2754};
2755function getAndCreateKeys(esTreeNode) {
2756 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
2757 return keys[esTreeNode.type];
2758}
2759
2760const INCLUDE_PARAMETERS = 'variables';
2761class NodeBase {
2762 constructor(esTreeNode, parent, parentScope) {
2763 this.included = false;
2764 this.esTreeNode = esTreeNode;
2765 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
2766 this.parent = parent;
2767 this.context = parent.context;
2768 this.createScope(parentScope);
2769 this.parseNode(esTreeNode);
2770 this.initialise();
2771 this.context.magicString.addSourcemapLocation(this.start);
2772 this.context.magicString.addSourcemapLocation(this.end);
2773 }
2774 /**
2775 * Override this to bind assignments to variables and do any initialisations that
2776 * require the scopes to be populated with variables.
2777 */
2778 bind() {
2779 for (const key of this.keys) {
2780 const value = this[key];
2781 if (value === null || key === 'annotations')
2782 continue;
2783 if (Array.isArray(value)) {
2784 for (const child of value) {
2785 if (child !== null)
2786 child.bind();
2787 }
2788 }
2789 else {
2790 value.bind();
2791 }
2792 }
2793 }
2794 /**
2795 * Override if this node should receive a different scope than the parent scope.
2796 */
2797 createScope(parentScope) {
2798 this.scope = parentScope;
2799 }
2800 declare(_kind, _init) {
2801 return [];
2802 }
2803 deoptimizePath(_path) { }
2804 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2805 return UnknownValue;
2806 }
2807 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
2808 return UNKNOWN_EXPRESSION;
2809 }
2810 hasEffects(context) {
2811 for (const key of this.keys) {
2812 const value = this[key];
2813 if (value === null || key === 'annotations')
2814 continue;
2815 if (Array.isArray(value)) {
2816 for (const child of value) {
2817 if (child !== null && child.hasEffects(context))
2818 return true;
2819 }
2820 }
2821 else if (value.hasEffects(context))
2822 return true;
2823 }
2824 return false;
2825 }
2826 hasEffectsWhenAccessedAtPath(path, _context) {
2827 return path.length > 0;
2828 }
2829 hasEffectsWhenAssignedAtPath(_path, _context) {
2830 return true;
2831 }
2832 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
2833 return true;
2834 }
2835 include(context, includeChildrenRecursively) {
2836 this.included = true;
2837 for (const key of this.keys) {
2838 const value = this[key];
2839 if (value === null || key === 'annotations')
2840 continue;
2841 if (Array.isArray(value)) {
2842 for (const child of value) {
2843 if (child !== null)
2844 child.include(context, includeChildrenRecursively);
2845 }
2846 }
2847 else {
2848 value.include(context, includeChildrenRecursively);
2849 }
2850 }
2851 }
2852 includeCallArguments(context, args) {
2853 for (const arg of args) {
2854 arg.include(context, false);
2855 }
2856 }
2857 includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
2858 this.include(context, includeChildrenRecursively);
2859 }
2860 /**
2861 * Override to perform special initialisation steps after the scope is initialised
2862 */
2863 initialise() { }
2864 insertSemicolon(code) {
2865 if (code.original[this.end - 1] !== ';') {
2866 code.appendLeft(this.end, ';');
2867 }
2868 }
2869 parseNode(esTreeNode) {
2870 for (const key of Object.keys(esTreeNode)) {
2871 // That way, we can override this function to add custom initialisation and then call super.parseNode
2872 if (this.hasOwnProperty(key))
2873 continue;
2874 const value = esTreeNode[key];
2875 if (typeof value !== 'object' || value === null || key === 'annotations') {
2876 this[key] = value;
2877 }
2878 else if (Array.isArray(value)) {
2879 this[key] = [];
2880 for (const child of value) {
2881 this[key].push(child === null
2882 ? null
2883 : new (this.context.nodeConstructors[child.type] ||
2884 this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
2885 }
2886 }
2887 else {
2888 this[key] = new (this.context.nodeConstructors[value.type] ||
2889 this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
2890 }
2891 }
2892 }
2893 render(code, options) {
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.render(code, options);
2902 }
2903 }
2904 else {
2905 value.render(code, options);
2906 }
2907 }
2908 }
2909 shouldBeIncluded(context) {
2910 return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
2911 }
2912 toString() {
2913 return this.context.code.slice(this.start, this.end);
2914 }
2915}
2916
2917class ClassNode extends NodeBase {
2918 createScope(parentScope) {
2919 this.scope = new ChildScope(parentScope);
2920 }
2921 hasEffectsWhenAccessedAtPath(path) {
2922 if (path.length <= 1)
2923 return false;
2924 return path.length > 2 || path[0] !== 'prototype';
2925 }
2926 hasEffectsWhenAssignedAtPath(path) {
2927 if (path.length <= 1)
2928 return false;
2929 return path.length > 2 || path[0] !== 'prototype';
2930 }
2931 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2932 if (!callOptions.withNew)
2933 return true;
2934 return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
2935 (this.superClass !== null &&
2936 this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
2937 }
2938 initialise() {
2939 if (this.id !== null) {
2940 this.id.declare('class', this);
2941 }
2942 }
2943}
2944
2945class ClassDeclaration extends ClassNode {
2946 initialise() {
2947 super.initialise();
2948 if (this.id !== null) {
2949 this.id.variable.isId = true;
2950 }
2951 }
2952 parseNode(esTreeNode) {
2953 if (esTreeNode.id !== null) {
2954 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope.parent);
2955 }
2956 super.parseNode(esTreeNode);
2957 }
2958 render(code, options) {
2959 if (options.format === 'system' &&
2960 this.id &&
2961 options.exportNamesByVariable.has(this.id.variable)) {
2962 code.appendLeft(this.end, `${options.compact ? '' : ' '}${getSystemExportStatement([this.id.variable], options)};`);
2963 }
2964 super.render(code, options);
2965 }
2966}
2967
2968class ArgumentsVariable extends LocalVariable {
2969 constructor(context) {
2970 super('arguments', null, UNKNOWN_EXPRESSION, context);
2971 }
2972 hasEffectsWhenAccessedAtPath(path) {
2973 return path.length > 1;
2974 }
2975 hasEffectsWhenAssignedAtPath() {
2976 return true;
2977 }
2978 hasEffectsWhenCalledAtPath() {
2979 return true;
2980 }
2981}
2982
2983class ThisVariable extends LocalVariable {
2984 constructor(context) {
2985 super('this', null, null, context);
2986 }
2987 getLiteralValueAtPath() {
2988 return UnknownValue;
2989 }
2990 hasEffectsWhenAccessedAtPath(path, context) {
2991 return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
2992 super.hasEffectsWhenAccessedAtPath(path, context));
2993 }
2994 hasEffectsWhenAssignedAtPath(path, context) {
2995 return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
2996 super.hasEffectsWhenAssignedAtPath(path, context));
2997 }
2998 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2999 return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
3000 super.hasEffectsWhenCalledAtPath(path, callOptions, context));
3001 }
3002 getInit(context) {
3003 return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
3004 }
3005}
3006
3007class SpreadElement extends NodeBase {
3008 bind() {
3009 super.bind();
3010 // Only properties of properties of the argument could become subject to reassignment
3011 // This will also reassign the return values of iterators
3012 this.argument.deoptimizePath([UnknownKey, UnknownKey]);
3013 }
3014}
3015
3016class ParameterScope extends ChildScope {
3017 constructor(parent, context) {
3018 super(parent);
3019 this.parameters = [];
3020 this.hasRest = false;
3021 this.context = context;
3022 this.hoistedBodyVarScope = new ChildScope(this);
3023 }
3024 /**
3025 * Adds a parameter to this scope. Parameters must be added in the correct
3026 * order, e.g. from left to right.
3027 */
3028 addParameterDeclaration(identifier) {
3029 const name = identifier.name;
3030 let variable = this.hoistedBodyVarScope.variables.get(name);
3031 if (variable) {
3032 variable.addDeclaration(identifier, null);
3033 }
3034 else {
3035 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
3036 }
3037 this.variables.set(name, variable);
3038 return variable;
3039 }
3040 addParameterVariables(parameters, hasRest) {
3041 this.parameters = parameters;
3042 for (const parameterList of parameters) {
3043 for (const parameter of parameterList) {
3044 parameter.alwaysRendered = true;
3045 }
3046 }
3047 this.hasRest = hasRest;
3048 }
3049 includeCallArguments(context, args) {
3050 let calledFromTryStatement = false;
3051 let argIncluded = false;
3052 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
3053 for (const checkedArg of args) {
3054 if (checkedArg instanceof SpreadElement) {
3055 for (const arg of args) {
3056 arg.include(context, false);
3057 }
3058 break;
3059 }
3060 }
3061 for (let index = args.length - 1; index >= 0; index--) {
3062 const paramVars = this.parameters[index] || restParam;
3063 const arg = args[index];
3064 if (paramVars) {
3065 calledFromTryStatement = false;
3066 for (const variable of paramVars) {
3067 if (variable.included) {
3068 argIncluded = true;
3069 }
3070 if (variable.calledFromTryStatement) {
3071 calledFromTryStatement = true;
3072 }
3073 }
3074 }
3075 if (!argIncluded && arg.shouldBeIncluded(context)) {
3076 argIncluded = true;
3077 }
3078 if (argIncluded) {
3079 arg.include(context, calledFromTryStatement);
3080 }
3081 }
3082 }
3083}
3084
3085class ReturnValueScope extends ParameterScope {
3086 constructor() {
3087 super(...arguments);
3088 this.returnExpression = null;
3089 this.returnExpressions = [];
3090 }
3091 addReturnExpression(expression) {
3092 this.returnExpressions.push(expression);
3093 }
3094 getReturnExpression() {
3095 if (this.returnExpression === null)
3096 this.updateReturnExpression();
3097 return this.returnExpression;
3098 }
3099 updateReturnExpression() {
3100 if (this.returnExpressions.length === 1) {
3101 this.returnExpression = this.returnExpressions[0];
3102 }
3103 else {
3104 this.returnExpression = UNKNOWN_EXPRESSION;
3105 for (const expression of this.returnExpressions) {
3106 expression.deoptimizePath(UNKNOWN_PATH);
3107 }
3108 }
3109 }
3110}
3111
3112class FunctionScope extends ReturnValueScope {
3113 constructor(parent, context) {
3114 super(parent, context);
3115 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
3116 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
3117 }
3118 findLexicalBoundary() {
3119 return this;
3120 }
3121 includeCallArguments(context, args) {
3122 super.includeCallArguments(context, args);
3123 if (this.argumentsVariable.included) {
3124 for (const arg of args) {
3125 if (!arg.included) {
3126 arg.include(context, false);
3127 }
3128 }
3129 }
3130 }
3131}
3132
3133function isReference(node, parent) {
3134 if (node.type === 'MemberExpression') {
3135 return !node.computed && isReference(node.object, node);
3136 }
3137 if (node.type === 'Identifier') {
3138 if (!parent)
3139 return true;
3140 switch (parent.type) {
3141 // disregard `bar` in `foo.bar`
3142 case 'MemberExpression': return parent.computed || node === parent.object;
3143 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
3144 case 'MethodDefinition': return parent.computed;
3145 // disregard the `foo` in `class {foo=bar}` but keep it in `class {[foo]=bar}` and `class {bar=foo}`
3146 case 'FieldDefinition': return parent.computed || node === parent.value;
3147 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
3148 case 'Property': return parent.computed || node === parent.value;
3149 // disregard the `bar` in `export { foo as bar }` or
3150 // the foo in `import { foo as bar }`
3151 case 'ExportSpecifier':
3152 case 'ImportSpecifier': return node === parent.local;
3153 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
3154 case 'LabeledStatement':
3155 case 'BreakStatement':
3156 case 'ContinueStatement': return false;
3157 default: return true;
3158 }
3159 }
3160 return false;
3161}
3162
3163const ValueProperties = Symbol('Value Properties');
3164const PURE = { pure: true };
3165const IMPURE = { pure: false };
3166// We use shortened variables to reduce file size here
3167/* OBJECT */
3168const O = {
3169 // @ts-ignore
3170 __proto__: null,
3171 [ValueProperties]: IMPURE
3172};
3173/* PURE FUNCTION */
3174const PF = {
3175 // @ts-ignore
3176 __proto__: null,
3177 [ValueProperties]: PURE
3178};
3179/* CONSTRUCTOR */
3180const C = {
3181 // @ts-ignore
3182 __proto__: null,
3183 [ValueProperties]: IMPURE,
3184 prototype: O
3185};
3186/* PURE CONSTRUCTOR */
3187const PC = {
3188 // @ts-ignore
3189 __proto__: null,
3190 [ValueProperties]: PURE,
3191 prototype: O
3192};
3193const ARRAY_TYPE = {
3194 // @ts-ignore
3195 __proto__: null,
3196 [ValueProperties]: PURE,
3197 from: PF,
3198 of: PF,
3199 prototype: O
3200};
3201const INTL_MEMBER = {
3202 // @ts-ignore
3203 __proto__: null,
3204 [ValueProperties]: PURE,
3205 supportedLocalesOf: PC
3206};
3207const knownGlobals = {
3208 // Placeholders for global objects to avoid shape mutations
3209 global: O,
3210 globalThis: O,
3211 self: O,
3212 window: O,
3213 // Common globals
3214 // @ts-ignore
3215 __proto__: null,
3216 [ValueProperties]: IMPURE,
3217 Array: {
3218 // @ts-ignore
3219 __proto__: null,
3220 [ValueProperties]: IMPURE,
3221 from: O,
3222 isArray: PF,
3223 of: PF,
3224 prototype: O
3225 },
3226 ArrayBuffer: {
3227 // @ts-ignore
3228 __proto__: null,
3229 [ValueProperties]: PURE,
3230 isView: PF,
3231 prototype: O
3232 },
3233 Atomics: O,
3234 BigInt: C,
3235 BigInt64Array: C,
3236 BigUint64Array: C,
3237 Boolean: PC,
3238 // @ts-ignore
3239 constructor: C,
3240 DataView: PC,
3241 Date: {
3242 // @ts-ignore
3243 __proto__: null,
3244 [ValueProperties]: PURE,
3245 now: PF,
3246 parse: PF,
3247 prototype: O,
3248 UTC: PF
3249 },
3250 decodeURI: PF,
3251 decodeURIComponent: PF,
3252 encodeURI: PF,
3253 encodeURIComponent: PF,
3254 Error: PC,
3255 escape: PF,
3256 eval: O,
3257 EvalError: PC,
3258 Float32Array: ARRAY_TYPE,
3259 Float64Array: ARRAY_TYPE,
3260 Function: C,
3261 // @ts-ignore
3262 hasOwnProperty: O,
3263 Infinity: O,
3264 Int16Array: ARRAY_TYPE,
3265 Int32Array: ARRAY_TYPE,
3266 Int8Array: ARRAY_TYPE,
3267 isFinite: PF,
3268 isNaN: PF,
3269 // @ts-ignore
3270 isPrototypeOf: O,
3271 JSON: O,
3272 Map: PC,
3273 Math: {
3274 // @ts-ignore
3275 __proto__: null,
3276 [ValueProperties]: IMPURE,
3277 abs: PF,
3278 acos: PF,
3279 acosh: PF,
3280 asin: PF,
3281 asinh: PF,
3282 atan: PF,
3283 atan2: PF,
3284 atanh: PF,
3285 cbrt: PF,
3286 ceil: PF,
3287 clz32: PF,
3288 cos: PF,
3289 cosh: PF,
3290 exp: PF,
3291 expm1: PF,
3292 floor: PF,
3293 fround: PF,
3294 hypot: PF,
3295 imul: PF,
3296 log: PF,
3297 log10: PF,
3298 log1p: PF,
3299 log2: PF,
3300 max: PF,
3301 min: PF,
3302 pow: PF,
3303 random: PF,
3304 round: PF,
3305 sign: PF,
3306 sin: PF,
3307 sinh: PF,
3308 sqrt: PF,
3309 tan: PF,
3310 tanh: PF,
3311 trunc: PF
3312 },
3313 NaN: O,
3314 Number: {
3315 // @ts-ignore
3316 __proto__: null,
3317 [ValueProperties]: PURE,
3318 isFinite: PF,
3319 isInteger: PF,
3320 isNaN: PF,
3321 isSafeInteger: PF,
3322 parseFloat: PF,
3323 parseInt: PF,
3324 prototype: O
3325 },
3326 Object: {
3327 // @ts-ignore
3328 __proto__: null,
3329 [ValueProperties]: PURE,
3330 create: PF,
3331 getNotifier: PF,
3332 getOwn: PF,
3333 getOwnPropertyDescriptor: PF,
3334 getOwnPropertyNames: PF,
3335 getOwnPropertySymbols: PF,
3336 getPrototypeOf: PF,
3337 is: PF,
3338 isExtensible: PF,
3339 isFrozen: PF,
3340 isSealed: PF,
3341 keys: PF,
3342 prototype: O
3343 },
3344 parseFloat: PF,
3345 parseInt: PF,
3346 Promise: {
3347 // @ts-ignore
3348 __proto__: null,
3349 [ValueProperties]: IMPURE,
3350 all: PF,
3351 prototype: O,
3352 race: PF,
3353 resolve: PF
3354 },
3355 // @ts-ignore
3356 propertyIsEnumerable: O,
3357 Proxy: O,
3358 RangeError: PC,
3359 ReferenceError: PC,
3360 Reflect: O,
3361 RegExp: PC,
3362 Set: PC,
3363 SharedArrayBuffer: C,
3364 String: {
3365 // @ts-ignore
3366 __proto__: null,
3367 [ValueProperties]: PURE,
3368 fromCharCode: PF,
3369 fromCodePoint: PF,
3370 prototype: O,
3371 raw: PF
3372 },
3373 Symbol: {
3374 // @ts-ignore
3375 __proto__: null,
3376 [ValueProperties]: PURE,
3377 for: PF,
3378 keyFor: PF,
3379 prototype: O
3380 },
3381 SyntaxError: PC,
3382 // @ts-ignore
3383 toLocaleString: O,
3384 // @ts-ignore
3385 toString: O,
3386 TypeError: PC,
3387 Uint16Array: ARRAY_TYPE,
3388 Uint32Array: ARRAY_TYPE,
3389 Uint8Array: ARRAY_TYPE,
3390 Uint8ClampedArray: ARRAY_TYPE,
3391 // Technically, this is a global, but it needs special handling
3392 // undefined: ?,
3393 unescape: PF,
3394 URIError: PC,
3395 // @ts-ignore
3396 valueOf: O,
3397 WeakMap: PC,
3398 WeakSet: PC,
3399 // Additional globals shared by Node and Browser that are not strictly part of the language
3400 clearInterval: C,
3401 clearTimeout: C,
3402 console: O,
3403 Intl: {
3404 // @ts-ignore
3405 __proto__: null,
3406 [ValueProperties]: IMPURE,
3407 Collator: INTL_MEMBER,
3408 DateTimeFormat: INTL_MEMBER,
3409 ListFormat: INTL_MEMBER,
3410 NumberFormat: INTL_MEMBER,
3411 PluralRules: INTL_MEMBER,
3412 RelativeTimeFormat: INTL_MEMBER
3413 },
3414 setInterval: C,
3415 setTimeout: C,
3416 TextDecoder: C,
3417 TextEncoder: C,
3418 URL: C,
3419 URLSearchParams: C,
3420 // Browser specific globals
3421 AbortController: C,
3422 AbortSignal: C,
3423 addEventListener: O,
3424 alert: O,
3425 AnalyserNode: C,
3426 Animation: C,
3427 AnimationEvent: C,
3428 applicationCache: O,
3429 ApplicationCache: C,
3430 ApplicationCacheErrorEvent: C,
3431 atob: O,
3432 Attr: C,
3433 Audio: C,
3434 AudioBuffer: C,
3435 AudioBufferSourceNode: C,
3436 AudioContext: C,
3437 AudioDestinationNode: C,
3438 AudioListener: C,
3439 AudioNode: C,
3440 AudioParam: C,
3441 AudioProcessingEvent: C,
3442 AudioScheduledSourceNode: C,
3443 AudioWorkletNode: C,
3444 BarProp: C,
3445 BaseAudioContext: C,
3446 BatteryManager: C,
3447 BeforeUnloadEvent: C,
3448 BiquadFilterNode: C,
3449 Blob: C,
3450 BlobEvent: C,
3451 blur: O,
3452 BroadcastChannel: C,
3453 btoa: O,
3454 ByteLengthQueuingStrategy: C,
3455 Cache: C,
3456 caches: O,
3457 CacheStorage: C,
3458 cancelAnimationFrame: O,
3459 cancelIdleCallback: O,
3460 CanvasCaptureMediaStreamTrack: C,
3461 CanvasGradient: C,
3462 CanvasPattern: C,
3463 CanvasRenderingContext2D: C,
3464 ChannelMergerNode: C,
3465 ChannelSplitterNode: C,
3466 CharacterData: C,
3467 clientInformation: O,
3468 ClipboardEvent: C,
3469 close: O,
3470 closed: O,
3471 CloseEvent: C,
3472 Comment: C,
3473 CompositionEvent: C,
3474 confirm: O,
3475 ConstantSourceNode: C,
3476 ConvolverNode: C,
3477 CountQueuingStrategy: C,
3478 createImageBitmap: O,
3479 Credential: C,
3480 CredentialsContainer: C,
3481 crypto: O,
3482 Crypto: C,
3483 CryptoKey: C,
3484 CSS: C,
3485 CSSConditionRule: C,
3486 CSSFontFaceRule: C,
3487 CSSGroupingRule: C,
3488 CSSImportRule: C,
3489 CSSKeyframeRule: C,
3490 CSSKeyframesRule: C,
3491 CSSMediaRule: C,
3492 CSSNamespaceRule: C,
3493 CSSPageRule: C,
3494 CSSRule: C,
3495 CSSRuleList: C,
3496 CSSStyleDeclaration: C,
3497 CSSStyleRule: C,
3498 CSSStyleSheet: C,
3499 CSSSupportsRule: C,
3500 CustomElementRegistry: C,
3501 customElements: O,
3502 CustomEvent: C,
3503 DataTransfer: C,
3504 DataTransferItem: C,
3505 DataTransferItemList: C,
3506 defaultstatus: O,
3507 defaultStatus: O,
3508 DelayNode: C,
3509 DeviceMotionEvent: C,
3510 DeviceOrientationEvent: C,
3511 devicePixelRatio: O,
3512 dispatchEvent: O,
3513 document: O,
3514 Document: C,
3515 DocumentFragment: C,
3516 DocumentType: C,
3517 DOMError: C,
3518 DOMException: C,
3519 DOMImplementation: C,
3520 DOMMatrix: C,
3521 DOMMatrixReadOnly: C,
3522 DOMParser: C,
3523 DOMPoint: C,
3524 DOMPointReadOnly: C,
3525 DOMQuad: C,
3526 DOMRect: C,
3527 DOMRectReadOnly: C,
3528 DOMStringList: C,
3529 DOMStringMap: C,
3530 DOMTokenList: C,
3531 DragEvent: C,
3532 DynamicsCompressorNode: C,
3533 Element: C,
3534 ErrorEvent: C,
3535 Event: C,
3536 EventSource: C,
3537 EventTarget: C,
3538 external: O,
3539 fetch: O,
3540 File: C,
3541 FileList: C,
3542 FileReader: C,
3543 find: O,
3544 focus: O,
3545 FocusEvent: C,
3546 FontFace: C,
3547 FontFaceSetLoadEvent: C,
3548 FormData: C,
3549 frames: O,
3550 GainNode: C,
3551 Gamepad: C,
3552 GamepadButton: C,
3553 GamepadEvent: C,
3554 getComputedStyle: O,
3555 getSelection: O,
3556 HashChangeEvent: C,
3557 Headers: C,
3558 history: O,
3559 History: C,
3560 HTMLAllCollection: C,
3561 HTMLAnchorElement: C,
3562 HTMLAreaElement: C,
3563 HTMLAudioElement: C,
3564 HTMLBaseElement: C,
3565 HTMLBodyElement: C,
3566 HTMLBRElement: C,
3567 HTMLButtonElement: C,
3568 HTMLCanvasElement: C,
3569 HTMLCollection: C,
3570 HTMLContentElement: C,
3571 HTMLDataElement: C,
3572 HTMLDataListElement: C,
3573 HTMLDetailsElement: C,
3574 HTMLDialogElement: C,
3575 HTMLDirectoryElement: C,
3576 HTMLDivElement: C,
3577 HTMLDListElement: C,
3578 HTMLDocument: C,
3579 HTMLElement: C,
3580 HTMLEmbedElement: C,
3581 HTMLFieldSetElement: C,
3582 HTMLFontElement: C,
3583 HTMLFormControlsCollection: C,
3584 HTMLFormElement: C,
3585 HTMLFrameElement: C,
3586 HTMLFrameSetElement: C,
3587 HTMLHeadElement: C,
3588 HTMLHeadingElement: C,
3589 HTMLHRElement: C,
3590 HTMLHtmlElement: C,
3591 HTMLIFrameElement: C,
3592 HTMLImageElement: C,
3593 HTMLInputElement: C,
3594 HTMLLabelElement: C,
3595 HTMLLegendElement: C,
3596 HTMLLIElement: C,
3597 HTMLLinkElement: C,
3598 HTMLMapElement: C,
3599 HTMLMarqueeElement: C,
3600 HTMLMediaElement: C,
3601 HTMLMenuElement: C,
3602 HTMLMetaElement: C,
3603 HTMLMeterElement: C,
3604 HTMLModElement: C,
3605 HTMLObjectElement: C,
3606 HTMLOListElement: C,
3607 HTMLOptGroupElement: C,
3608 HTMLOptionElement: C,
3609 HTMLOptionsCollection: C,
3610 HTMLOutputElement: C,
3611 HTMLParagraphElement: C,
3612 HTMLParamElement: C,
3613 HTMLPictureElement: C,
3614 HTMLPreElement: C,
3615 HTMLProgressElement: C,
3616 HTMLQuoteElement: C,
3617 HTMLScriptElement: C,
3618 HTMLSelectElement: C,
3619 HTMLShadowElement: C,
3620 HTMLSlotElement: C,
3621 HTMLSourceElement: C,
3622 HTMLSpanElement: C,
3623 HTMLStyleElement: C,
3624 HTMLTableCaptionElement: C,
3625 HTMLTableCellElement: C,
3626 HTMLTableColElement: C,
3627 HTMLTableElement: C,
3628 HTMLTableRowElement: C,
3629 HTMLTableSectionElement: C,
3630 HTMLTemplateElement: C,
3631 HTMLTextAreaElement: C,
3632 HTMLTimeElement: C,
3633 HTMLTitleElement: C,
3634 HTMLTrackElement: C,
3635 HTMLUListElement: C,
3636 HTMLUnknownElement: C,
3637 HTMLVideoElement: C,
3638 IDBCursor: C,
3639 IDBCursorWithValue: C,
3640 IDBDatabase: C,
3641 IDBFactory: C,
3642 IDBIndex: C,
3643 IDBKeyRange: C,
3644 IDBObjectStore: C,
3645 IDBOpenDBRequest: C,
3646 IDBRequest: C,
3647 IDBTransaction: C,
3648 IDBVersionChangeEvent: C,
3649 IdleDeadline: C,
3650 IIRFilterNode: C,
3651 Image: C,
3652 ImageBitmap: C,
3653 ImageBitmapRenderingContext: C,
3654 ImageCapture: C,
3655 ImageData: C,
3656 indexedDB: O,
3657 innerHeight: O,
3658 innerWidth: O,
3659 InputEvent: C,
3660 IntersectionObserver: C,
3661 IntersectionObserverEntry: C,
3662 isSecureContext: O,
3663 KeyboardEvent: C,
3664 KeyframeEffect: C,
3665 length: O,
3666 localStorage: O,
3667 location: O,
3668 Location: C,
3669 locationbar: O,
3670 matchMedia: O,
3671 MediaDeviceInfo: C,
3672 MediaDevices: C,
3673 MediaElementAudioSourceNode: C,
3674 MediaEncryptedEvent: C,
3675 MediaError: C,
3676 MediaKeyMessageEvent: C,
3677 MediaKeySession: C,
3678 MediaKeyStatusMap: C,
3679 MediaKeySystemAccess: C,
3680 MediaList: C,
3681 MediaQueryList: C,
3682 MediaQueryListEvent: C,
3683 MediaRecorder: C,
3684 MediaSettingsRange: C,
3685 MediaSource: C,
3686 MediaStream: C,
3687 MediaStreamAudioDestinationNode: C,
3688 MediaStreamAudioSourceNode: C,
3689 MediaStreamEvent: C,
3690 MediaStreamTrack: C,
3691 MediaStreamTrackEvent: C,
3692 menubar: O,
3693 MessageChannel: C,
3694 MessageEvent: C,
3695 MessagePort: C,
3696 MIDIAccess: C,
3697 MIDIConnectionEvent: C,
3698 MIDIInput: C,
3699 MIDIInputMap: C,
3700 MIDIMessageEvent: C,
3701 MIDIOutput: C,
3702 MIDIOutputMap: C,
3703 MIDIPort: C,
3704 MimeType: C,
3705 MimeTypeArray: C,
3706 MouseEvent: C,
3707 moveBy: O,
3708 moveTo: O,
3709 MutationEvent: C,
3710 MutationObserver: C,
3711 MutationRecord: C,
3712 name: O,
3713 NamedNodeMap: C,
3714 NavigationPreloadManager: C,
3715 navigator: O,
3716 Navigator: C,
3717 NetworkInformation: C,
3718 Node: C,
3719 NodeFilter: O,
3720 NodeIterator: C,
3721 NodeList: C,
3722 Notification: C,
3723 OfflineAudioCompletionEvent: C,
3724 OfflineAudioContext: C,
3725 offscreenBuffering: O,
3726 OffscreenCanvas: C,
3727 open: O,
3728 openDatabase: O,
3729 Option: C,
3730 origin: O,
3731 OscillatorNode: C,
3732 outerHeight: O,
3733 outerWidth: O,
3734 PageTransitionEvent: C,
3735 pageXOffset: O,
3736 pageYOffset: O,
3737 PannerNode: C,
3738 parent: O,
3739 Path2D: C,
3740 PaymentAddress: C,
3741 PaymentRequest: C,
3742 PaymentRequestUpdateEvent: C,
3743 PaymentResponse: C,
3744 performance: O,
3745 Performance: C,
3746 PerformanceEntry: C,
3747 PerformanceLongTaskTiming: C,
3748 PerformanceMark: C,
3749 PerformanceMeasure: C,
3750 PerformanceNavigation: C,
3751 PerformanceNavigationTiming: C,
3752 PerformanceObserver: C,
3753 PerformanceObserverEntryList: C,
3754 PerformancePaintTiming: C,
3755 PerformanceResourceTiming: C,
3756 PerformanceTiming: C,
3757 PeriodicWave: C,
3758 Permissions: C,
3759 PermissionStatus: C,
3760 personalbar: O,
3761 PhotoCapabilities: C,
3762 Plugin: C,
3763 PluginArray: C,
3764 PointerEvent: C,
3765 PopStateEvent: C,
3766 postMessage: O,
3767 Presentation: C,
3768 PresentationAvailability: C,
3769 PresentationConnection: C,
3770 PresentationConnectionAvailableEvent: C,
3771 PresentationConnectionCloseEvent: C,
3772 PresentationConnectionList: C,
3773 PresentationReceiver: C,
3774 PresentationRequest: C,
3775 print: O,
3776 ProcessingInstruction: C,
3777 ProgressEvent: C,
3778 PromiseRejectionEvent: C,
3779 prompt: O,
3780 PushManager: C,
3781 PushSubscription: C,
3782 PushSubscriptionOptions: C,
3783 queueMicrotask: O,
3784 RadioNodeList: C,
3785 Range: C,
3786 ReadableStream: C,
3787 RemotePlayback: C,
3788 removeEventListener: O,
3789 Request: C,
3790 requestAnimationFrame: O,
3791 requestIdleCallback: O,
3792 resizeBy: O,
3793 ResizeObserver: C,
3794 ResizeObserverEntry: C,
3795 resizeTo: O,
3796 Response: C,
3797 RTCCertificate: C,
3798 RTCDataChannel: C,
3799 RTCDataChannelEvent: C,
3800 RTCDtlsTransport: C,
3801 RTCIceCandidate: C,
3802 RTCIceTransport: C,
3803 RTCPeerConnection: C,
3804 RTCPeerConnectionIceEvent: C,
3805 RTCRtpReceiver: C,
3806 RTCRtpSender: C,
3807 RTCSctpTransport: C,
3808 RTCSessionDescription: C,
3809 RTCStatsReport: C,
3810 RTCTrackEvent: C,
3811 screen: O,
3812 Screen: C,
3813 screenLeft: O,
3814 ScreenOrientation: C,
3815 screenTop: O,
3816 screenX: O,
3817 screenY: O,
3818 ScriptProcessorNode: C,
3819 scroll: O,
3820 scrollbars: O,
3821 scrollBy: O,
3822 scrollTo: O,
3823 scrollX: O,
3824 scrollY: O,
3825 SecurityPolicyViolationEvent: C,
3826 Selection: C,
3827 ServiceWorker: C,
3828 ServiceWorkerContainer: C,
3829 ServiceWorkerRegistration: C,
3830 sessionStorage: O,
3831 ShadowRoot: C,
3832 SharedWorker: C,
3833 SourceBuffer: C,
3834 SourceBufferList: C,
3835 speechSynthesis: O,
3836 SpeechSynthesisEvent: C,
3837 SpeechSynthesisUtterance: C,
3838 StaticRange: C,
3839 status: O,
3840 statusbar: O,
3841 StereoPannerNode: C,
3842 stop: O,
3843 Storage: C,
3844 StorageEvent: C,
3845 StorageManager: C,
3846 styleMedia: O,
3847 StyleSheet: C,
3848 StyleSheetList: C,
3849 SubtleCrypto: C,
3850 SVGAElement: C,
3851 SVGAngle: C,
3852 SVGAnimatedAngle: C,
3853 SVGAnimatedBoolean: C,
3854 SVGAnimatedEnumeration: C,
3855 SVGAnimatedInteger: C,
3856 SVGAnimatedLength: C,
3857 SVGAnimatedLengthList: C,
3858 SVGAnimatedNumber: C,
3859 SVGAnimatedNumberList: C,
3860 SVGAnimatedPreserveAspectRatio: C,
3861 SVGAnimatedRect: C,
3862 SVGAnimatedString: C,
3863 SVGAnimatedTransformList: C,
3864 SVGAnimateElement: C,
3865 SVGAnimateMotionElement: C,
3866 SVGAnimateTransformElement: C,
3867 SVGAnimationElement: C,
3868 SVGCircleElement: C,
3869 SVGClipPathElement: C,
3870 SVGComponentTransferFunctionElement: C,
3871 SVGDefsElement: C,
3872 SVGDescElement: C,
3873 SVGDiscardElement: C,
3874 SVGElement: C,
3875 SVGEllipseElement: C,
3876 SVGFEBlendElement: C,
3877 SVGFEColorMatrixElement: C,
3878 SVGFEComponentTransferElement: C,
3879 SVGFECompositeElement: C,
3880 SVGFEConvolveMatrixElement: C,
3881 SVGFEDiffuseLightingElement: C,
3882 SVGFEDisplacementMapElement: C,
3883 SVGFEDistantLightElement: C,
3884 SVGFEDropShadowElement: C,
3885 SVGFEFloodElement: C,
3886 SVGFEFuncAElement: C,
3887 SVGFEFuncBElement: C,
3888 SVGFEFuncGElement: C,
3889 SVGFEFuncRElement: C,
3890 SVGFEGaussianBlurElement: C,
3891 SVGFEImageElement: C,
3892 SVGFEMergeElement: C,
3893 SVGFEMergeNodeElement: C,
3894 SVGFEMorphologyElement: C,
3895 SVGFEOffsetElement: C,
3896 SVGFEPointLightElement: C,
3897 SVGFESpecularLightingElement: C,
3898 SVGFESpotLightElement: C,
3899 SVGFETileElement: C,
3900 SVGFETurbulenceElement: C,
3901 SVGFilterElement: C,
3902 SVGForeignObjectElement: C,
3903 SVGGElement: C,
3904 SVGGeometryElement: C,
3905 SVGGradientElement: C,
3906 SVGGraphicsElement: C,
3907 SVGImageElement: C,
3908 SVGLength: C,
3909 SVGLengthList: C,
3910 SVGLinearGradientElement: C,
3911 SVGLineElement: C,
3912 SVGMarkerElement: C,
3913 SVGMaskElement: C,
3914 SVGMatrix: C,
3915 SVGMetadataElement: C,
3916 SVGMPathElement: C,
3917 SVGNumber: C,
3918 SVGNumberList: C,
3919 SVGPathElement: C,
3920 SVGPatternElement: C,
3921 SVGPoint: C,
3922 SVGPointList: C,
3923 SVGPolygonElement: C,
3924 SVGPolylineElement: C,
3925 SVGPreserveAspectRatio: C,
3926 SVGRadialGradientElement: C,
3927 SVGRect: C,
3928 SVGRectElement: C,
3929 SVGScriptElement: C,
3930 SVGSetElement: C,
3931 SVGStopElement: C,
3932 SVGStringList: C,
3933 SVGStyleElement: C,
3934 SVGSVGElement: C,
3935 SVGSwitchElement: C,
3936 SVGSymbolElement: C,
3937 SVGTextContentElement: C,
3938 SVGTextElement: C,
3939 SVGTextPathElement: C,
3940 SVGTextPositioningElement: C,
3941 SVGTitleElement: C,
3942 SVGTransform: C,
3943 SVGTransformList: C,
3944 SVGTSpanElement: C,
3945 SVGUnitTypes: C,
3946 SVGUseElement: C,
3947 SVGViewElement: C,
3948 TaskAttributionTiming: C,
3949 Text: C,
3950 TextEvent: C,
3951 TextMetrics: C,
3952 TextTrack: C,
3953 TextTrackCue: C,
3954 TextTrackCueList: C,
3955 TextTrackList: C,
3956 TimeRanges: C,
3957 toolbar: O,
3958 top: O,
3959 Touch: C,
3960 TouchEvent: C,
3961 TouchList: C,
3962 TrackEvent: C,
3963 TransitionEvent: C,
3964 TreeWalker: C,
3965 UIEvent: C,
3966 ValidityState: C,
3967 visualViewport: O,
3968 VisualViewport: C,
3969 VTTCue: C,
3970 WaveShaperNode: C,
3971 WebAssembly: O,
3972 WebGL2RenderingContext: C,
3973 WebGLActiveInfo: C,
3974 WebGLBuffer: C,
3975 WebGLContextEvent: C,
3976 WebGLFramebuffer: C,
3977 WebGLProgram: C,
3978 WebGLQuery: C,
3979 WebGLRenderbuffer: C,
3980 WebGLRenderingContext: C,
3981 WebGLSampler: C,
3982 WebGLShader: C,
3983 WebGLShaderPrecisionFormat: C,
3984 WebGLSync: C,
3985 WebGLTexture: C,
3986 WebGLTransformFeedback: C,
3987 WebGLUniformLocation: C,
3988 WebGLVertexArrayObject: C,
3989 WebSocket: C,
3990 WheelEvent: C,
3991 Window: C,
3992 Worker: C,
3993 WritableStream: C,
3994 XMLDocument: C,
3995 XMLHttpRequest: C,
3996 XMLHttpRequestEventTarget: C,
3997 XMLHttpRequestUpload: C,
3998 XMLSerializer: C,
3999 XPathEvaluator: C,
4000 XPathExpression: C,
4001 XPathResult: C,
4002 XSLTProcessor: C
4003};
4004for (const global of ['window', 'global', 'self', 'globalThis']) {
4005 knownGlobals[global] = knownGlobals;
4006}
4007function getGlobalAtPath(path) {
4008 let currentGlobal = knownGlobals;
4009 for (const pathSegment of path) {
4010 if (typeof pathSegment !== 'string') {
4011 return null;
4012 }
4013 currentGlobal = currentGlobal[pathSegment];
4014 if (!currentGlobal) {
4015 return null;
4016 }
4017 }
4018 return currentGlobal[ValueProperties];
4019}
4020function isPureGlobal(path) {
4021 const globalAtPath = getGlobalAtPath(path);
4022 return globalAtPath !== null && globalAtPath.pure;
4023}
4024function isGlobalMember(path) {
4025 if (path.length === 1) {
4026 return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
4027 }
4028 return getGlobalAtPath(path.slice(0, -1)) !== null;
4029}
4030
4031class GlobalVariable extends Variable {
4032 constructor() {
4033 super(...arguments);
4034 this.isReassigned = true;
4035 }
4036 hasEffectsWhenAccessedAtPath(path) {
4037 return !isGlobalMember([this.name, ...path]);
4038 }
4039 hasEffectsWhenCalledAtPath(path) {
4040 return !isPureGlobal([this.name, ...path]);
4041 }
4042}
4043
4044class Identifier$1 extends NodeBase {
4045 constructor() {
4046 super(...arguments);
4047 this.variable = null;
4048 this.bound = false;
4049 }
4050 addExportedVariables(variables, exportNamesByVariable) {
4051 if (this.variable !== null && exportNamesByVariable.has(this.variable)) {
4052 variables.push(this.variable);
4053 }
4054 }
4055 bind() {
4056 if (this.bound)
4057 return;
4058 this.bound = true;
4059 if (this.variable === null && isReference(this, this.parent)) {
4060 this.variable = this.scope.findVariable(this.name);
4061 this.variable.addReference(this);
4062 }
4063 if (this.variable !== null &&
4064 this.variable instanceof LocalVariable &&
4065 this.variable.additionalInitializers !== null) {
4066 this.variable.consolidateInitializers();
4067 }
4068 }
4069 declare(kind, init) {
4070 let variable;
4071 switch (kind) {
4072 case 'var':
4073 variable = this.scope.addDeclaration(this, this.context, init, true);
4074 break;
4075 case 'function':
4076 // in strict mode, functions are only hoisted within a scope but not across block scopes
4077 variable = this.scope.addDeclaration(this, this.context, init, false);
4078 break;
4079 case 'let':
4080 case 'const':
4081 case 'class':
4082 variable = this.scope.addDeclaration(this, this.context, init, false);
4083 break;
4084 case 'parameter':
4085 variable = this.scope.addParameterDeclaration(this);
4086 break;
4087 /* istanbul ignore next */
4088 default:
4089 /* istanbul ignore next */
4090 throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
4091 }
4092 return [(this.variable = variable)];
4093 }
4094 deoptimizePath(path) {
4095 if (!this.bound)
4096 this.bind();
4097 if (path.length === 0 && !this.scope.contains(this.name)) {
4098 this.disallowImportReassignment();
4099 }
4100 this.variable.deoptimizePath(path);
4101 }
4102 getLiteralValueAtPath(path, recursionTracker, origin) {
4103 if (!this.bound)
4104 this.bind();
4105 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
4106 }
4107 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
4108 if (!this.bound)
4109 this.bind();
4110 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
4111 }
4112 hasEffects() {
4113 return (this.context.options.treeshake.unknownGlobalSideEffects &&
4114 this.variable instanceof GlobalVariable &&
4115 this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
4116 }
4117 hasEffectsWhenAccessedAtPath(path, context) {
4118 return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
4119 }
4120 hasEffectsWhenAssignedAtPath(path, context) {
4121 return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
4122 }
4123 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4124 return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
4125 }
4126 include() {
4127 if (!this.included) {
4128 this.included = true;
4129 if (this.variable !== null) {
4130 this.context.includeVariable(this.variable);
4131 }
4132 }
4133 }
4134 includeCallArguments(context, args) {
4135 this.variable.includeCallArguments(context, args);
4136 }
4137 render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
4138 if (this.variable) {
4139 const name = this.variable.getName();
4140 if (name !== this.name) {
4141 code.overwrite(this.start, this.end, name, {
4142 contentOnly: true,
4143 storeName: true
4144 });
4145 if (isShorthandProperty) {
4146 code.prependRight(this.start, `${this.name}: `);
4147 }
4148 }
4149 // In strict mode, any variable named "eval" must be the actual "eval" function
4150 if (name === 'eval' &&
4151 renderedParentType === CallExpression &&
4152 isCalleeOfRenderedParent) {
4153 code.appendRight(this.start, '0, ');
4154 }
4155 }
4156 }
4157 disallowImportReassignment() {
4158 return this.context.error({
4159 code: 'ILLEGAL_REASSIGNMENT',
4160 message: `Illegal reassignment to import '${this.name}'`
4161 }, this.start);
4162 }
4163}
4164
4165class RestElement extends NodeBase {
4166 constructor() {
4167 super(...arguments);
4168 this.declarationInit = null;
4169 }
4170 addExportedVariables(variables, exportNamesByVariable) {
4171 this.argument.addExportedVariables(variables, exportNamesByVariable);
4172 }
4173 bind() {
4174 super.bind();
4175 if (this.declarationInit !== null) {
4176 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
4177 }
4178 }
4179 declare(kind, init) {
4180 this.declarationInit = init;
4181 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
4182 }
4183 deoptimizePath(path) {
4184 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
4185 }
4186 hasEffectsWhenAssignedAtPath(path, context) {
4187 return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
4188 }
4189}
4190
4191class FunctionNode extends NodeBase {
4192 constructor() {
4193 super(...arguments);
4194 this.isPrototypeDeoptimized = false;
4195 }
4196 createScope(parentScope) {
4197 this.scope = new FunctionScope(parentScope, this.context);
4198 }
4199 deoptimizePath(path) {
4200 if (path.length === 1) {
4201 if (path[0] === 'prototype') {
4202 this.isPrototypeDeoptimized = true;
4203 }
4204 else if (path[0] === UnknownKey) {
4205 this.isPrototypeDeoptimized = true;
4206 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
4207 // which means the return expression needs to be reassigned as well
4208 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
4209 }
4210 }
4211 }
4212 getReturnExpressionWhenCalledAtPath(path) {
4213 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
4214 }
4215 hasEffects() {
4216 return this.id !== null && this.id.hasEffects();
4217 }
4218 hasEffectsWhenAccessedAtPath(path) {
4219 if (path.length <= 1)
4220 return false;
4221 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
4222 }
4223 hasEffectsWhenAssignedAtPath(path) {
4224 if (path.length <= 1) {
4225 return false;
4226 }
4227 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
4228 }
4229 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4230 if (path.length > 0)
4231 return true;
4232 for (const param of this.params) {
4233 if (param.hasEffects(context))
4234 return true;
4235 }
4236 const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
4237 context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
4238 const { brokenFlow, ignore } = context;
4239 context.ignore = {
4240 breaks: false,
4241 continues: false,
4242 labels: new Set(),
4243 returnAwaitYield: true
4244 };
4245 if (this.body.hasEffects(context))
4246 return true;
4247 context.brokenFlow = brokenFlow;
4248 if (thisInit) {
4249 context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
4250 }
4251 else {
4252 context.replacedVariableInits.delete(this.scope.thisVariable);
4253 }
4254 context.ignore = ignore;
4255 return false;
4256 }
4257 include(context, includeChildrenRecursively) {
4258 this.included = true;
4259 if (this.id)
4260 this.id.include();
4261 const hasArguments = this.scope.argumentsVariable.included;
4262 for (const param of this.params) {
4263 if (!(param instanceof Identifier$1) || hasArguments) {
4264 param.include(context, includeChildrenRecursively);
4265 }
4266 }
4267 const { brokenFlow } = context;
4268 context.brokenFlow = BROKEN_FLOW_NONE;
4269 this.body.include(context, includeChildrenRecursively);
4270 context.brokenFlow = brokenFlow;
4271 }
4272 includeCallArguments(context, args) {
4273 this.scope.includeCallArguments(context, args);
4274 }
4275 initialise() {
4276 if (this.id !== null) {
4277 this.id.declare('function', this);
4278 }
4279 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
4280 this.body.addImplicitReturnExpressionToScope();
4281 }
4282 parseNode(esTreeNode) {
4283 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
4284 super.parseNode(esTreeNode);
4285 }
4286}
4287FunctionNode.prototype.preventChildBlockScope = true;
4288
4289class FunctionDeclaration extends FunctionNode {
4290 initialise() {
4291 super.initialise();
4292 if (this.id !== null) {
4293 this.id.variable.isId = true;
4294 }
4295 }
4296 parseNode(esTreeNode) {
4297 if (esTreeNode.id !== null) {
4298 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
4299 .parent);
4300 }
4301 super.parseNode(esTreeNode);
4302 }
4303}
4304
4305// The header ends at the first non-white-space after "default"
4306function getDeclarationStart(code, start) {
4307 return findNonWhiteSpace(code, findFirstOccurrenceOutsideComment(code, 'default', start) + 7);
4308}
4309function getIdInsertPosition(code, declarationKeyword, endMarker, start) {
4310 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
4311 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, endMarker, declarationEnd));
4312 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
4313 if (generatorStarPos === -1) {
4314 return declarationEnd;
4315 }
4316 return declarationEnd + generatorStarPos + 1;
4317}
4318class ExportDefaultDeclaration extends NodeBase {
4319 include(context, includeChildrenRecursively) {
4320 super.include(context, includeChildrenRecursively);
4321 if (includeChildrenRecursively) {
4322 this.context.includeVariable(this.variable);
4323 }
4324 }
4325 initialise() {
4326 const declaration = this.declaration;
4327 this.declarationName =
4328 (declaration.id && declaration.id.name) || this.declaration.name;
4329 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
4330 this.context.addExport(this);
4331 }
4332 render(code, options, nodeRenderOptions) {
4333 const { start, end } = nodeRenderOptions;
4334 const declarationStart = getDeclarationStart(code.original, this.start);
4335 if (this.declaration instanceof FunctionDeclaration) {
4336 this.renderNamedDeclaration(code, declarationStart, 'function', '(', this.declaration.id === null, options);
4337 }
4338 else if (this.declaration instanceof ClassDeclaration) {
4339 this.renderNamedDeclaration(code, declarationStart, 'class', '{', this.declaration.id === null, options);
4340 }
4341 else if (this.variable.getOriginalVariable() !== this.variable) {
4342 // Remove altogether to prevent re-declaring the same variable
4343 treeshakeNode(this, code, start, end);
4344 return;
4345 }
4346 else if (this.variable.included) {
4347 this.renderVariableDeclaration(code, declarationStart, options);
4348 }
4349 else {
4350 code.remove(this.start, declarationStart);
4351 this.declaration.render(code, options, {
4352 isCalleeOfRenderedParent: false,
4353 renderedParentType: ExpressionStatement
4354 });
4355 if (code.original[this.end - 1] !== ';') {
4356 code.appendLeft(this.end, ';');
4357 }
4358 return;
4359 }
4360 this.declaration.render(code, options);
4361 }
4362 renderNamedDeclaration(code, declarationStart, declarationKeyword, endMarker, needsId, options) {
4363 const name = this.variable.getName();
4364 // Remove `export default`
4365 code.remove(this.start, declarationStart);
4366 if (needsId) {
4367 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, endMarker, declarationStart), ` ${name}`);
4368 }
4369 if (options.format === 'system' &&
4370 this.declaration instanceof ClassDeclaration &&
4371 options.exportNamesByVariable.has(this.variable)) {
4372 code.appendLeft(this.end, ` ${getSystemExportStatement([this.variable], options)};`);
4373 }
4374 }
4375 renderVariableDeclaration(code, declarationStart, options) {
4376 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
4377 const systemExportNames = options.format === 'system' && options.exportNamesByVariable.get(this.variable);
4378 if (systemExportNames) {
4379 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = exports('${systemExportNames[0]}', `);
4380 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
4381 }
4382 else {
4383 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = `);
4384 if (!hasTrailingSemicolon) {
4385 code.appendLeft(this.end, ';');
4386 }
4387 }
4388 }
4389}
4390ExportDefaultDeclaration.prototype.needsBoundaries = true;
4391
4392class UndefinedVariable extends Variable {
4393 constructor() {
4394 super('undefined');
4395 }
4396 getLiteralValueAtPath() {
4397 return undefined;
4398 }
4399}
4400
4401class ExportDefaultVariable extends LocalVariable {
4402 constructor(name, exportDefaultDeclaration, context) {
4403 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
4404 this.hasId = false;
4405 // Not initialised during construction
4406 this.originalId = null;
4407 this.originalVariableAndDeclarationModules = null;
4408 const declaration = exportDefaultDeclaration.declaration;
4409 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
4410 declaration.id) {
4411 this.hasId = true;
4412 this.originalId = declaration.id;
4413 }
4414 else if (declaration instanceof Identifier$1) {
4415 this.originalId = declaration;
4416 }
4417 }
4418 addReference(identifier) {
4419 if (!this.hasId) {
4420 this.name = identifier.name;
4421 }
4422 }
4423 getAssignedVariableName() {
4424 return (this.originalId && this.originalId.name) || null;
4425 }
4426 getBaseVariableName() {
4427 const original = this.getOriginalVariable();
4428 if (original === this) {
4429 return super.getBaseVariableName();
4430 }
4431 else {
4432 return original.getBaseVariableName();
4433 }
4434 }
4435 getName() {
4436 const original = this.getOriginalVariable();
4437 if (original === this) {
4438 return super.getName();
4439 }
4440 else {
4441 return original.getName();
4442 }
4443 }
4444 getOriginalVariable() {
4445 return this.getOriginalVariableAndDeclarationModules().original;
4446 }
4447 getOriginalVariableAndDeclarationModules() {
4448 if (this.originalVariableAndDeclarationModules === null) {
4449 if (!this.originalId ||
4450 (!this.hasId &&
4451 (this.originalId.variable.isReassigned ||
4452 this.originalId.variable instanceof UndefinedVariable))) {
4453 this.originalVariableAndDeclarationModules = { modules: [], original: this };
4454 }
4455 else {
4456 const assignedOriginal = this.originalId.variable;
4457 if (assignedOriginal instanceof ExportDefaultVariable) {
4458 const { modules, original } = assignedOriginal.getOriginalVariableAndDeclarationModules();
4459 this.originalVariableAndDeclarationModules = {
4460 modules: modules.concat(this.module),
4461 original
4462 };
4463 }
4464 else {
4465 this.originalVariableAndDeclarationModules = {
4466 modules: [this.module],
4467 original: assignedOriginal
4468 };
4469 }
4470 }
4471 }
4472 return this.originalVariableAndDeclarationModules;
4473 }
4474}
4475
4476const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
4477
4478class ExportShimVariable extends Variable {
4479 constructor(module) {
4480 super(MISSING_EXPORT_SHIM_VARIABLE);
4481 this.module = module;
4482 }
4483}
4484
4485class NamespaceVariable extends Variable {
4486 constructor(context, syntheticNamedExports) {
4487 super(context.getModuleName());
4488 this.memberVariables = null;
4489 this.mergedNamespaces = [];
4490 this.referencedEarly = false;
4491 this.references = [];
4492 this.context = context;
4493 this.module = context.module;
4494 this.syntheticNamedExports = syntheticNamedExports;
4495 }
4496 addReference(identifier) {
4497 this.references.push(identifier);
4498 this.name = identifier.name;
4499 }
4500 // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
4501 // build fails due to an illegal namespace reassignment or MemberExpression already forwards
4502 // the reassignment to the right variable. This means we lost track of this variable and thus
4503 // need to reassign all exports.
4504 deoptimizePath() {
4505 const memberVariables = this.getMemberVariables();
4506 for (const key of Object.keys(memberVariables)) {
4507 memberVariables[key].deoptimizePath(UNKNOWN_PATH);
4508 }
4509 }
4510 getMemberVariables() {
4511 if (this.memberVariables) {
4512 return this.memberVariables;
4513 }
4514 const memberVariables = Object.create(null);
4515 for (const name of this.context.getExports().concat(this.context.getReexports())) {
4516 if (name[0] !== '*' && name !== this.module.syntheticNamedExports) {
4517 memberVariables[name] = this.context.traceExport(name);
4518 }
4519 }
4520 return (this.memberVariables = memberVariables);
4521 }
4522 include() {
4523 this.included = true;
4524 this.context.includeAllExports();
4525 }
4526 prepareNamespace(mergedNamespaces) {
4527 this.mergedNamespaces = mergedNamespaces;
4528 const moduleExecIndex = this.context.getModuleExecIndex();
4529 for (const identifier of this.references) {
4530 if (identifier.context.getModuleExecIndex() <= moduleExecIndex) {
4531 this.referencedEarly = true;
4532 break;
4533 }
4534 }
4535 }
4536 renderBlock(options) {
4537 const _ = options.compact ? '' : ' ';
4538 const n = options.compact ? '' : '\n';
4539 const t = options.indent;
4540 const memberVariables = this.getMemberVariables();
4541 const members = Object.keys(memberVariables).map(name => {
4542 const original = memberVariables[name];
4543 if (this.referencedEarly || original.isReassigned) {
4544 return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
4545 }
4546 const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
4547 return `${t}${safeName}: ${original.getName()}`;
4548 });
4549 if (options.namespaceToStringTag) {
4550 members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
4551 }
4552 const needsObjectAssign = this.mergedNamespaces.length > 0 || this.syntheticNamedExports;
4553 if (!needsObjectAssign)
4554 members.unshift(`${t}__proto__:${_}null`);
4555 let output = `{${n}${members.join(`,${n}`)}${n}}`;
4556 if (needsObjectAssign) {
4557 const assignmentArgs = ['/*#__PURE__*/Object.create(null)'];
4558 if (this.mergedNamespaces.length > 0) {
4559 assignmentArgs.push(...this.mergedNamespaces.map(variable => variable.getName()));
4560 }
4561 if (this.syntheticNamedExports) {
4562 assignmentArgs.push(this.module.getSyntheticNamespace().getName());
4563 }
4564 if (members.length > 0) {
4565 assignmentArgs.push(output);
4566 }
4567 output = `/*#__PURE__*/Object.assign(${assignmentArgs.join(`,${_}`)})`;
4568 }
4569 if (options.freeze) {
4570 output = `/*#__PURE__*/Object.freeze(${output})`;
4571 }
4572 const name = this.getName();
4573 output = `${options.varOrConst} ${name}${_}=${_}${output};`;
4574 if (options.format === 'system' && options.exportNamesByVariable.has(this)) {
4575 output += `${n}${getSystemExportStatement([this], options)};`;
4576 }
4577 return output;
4578 }
4579 renderFirst() {
4580 return this.referencedEarly;
4581 }
4582}
4583NamespaceVariable.prototype.isNamespace = true;
4584
4585class SyntheticNamedExportVariable extends Variable {
4586 constructor(context, name, syntheticNamespace) {
4587 super(name);
4588 this.context = context;
4589 this.module = context.module;
4590 this.syntheticNamespace = syntheticNamespace;
4591 }
4592 getBaseVariable() {
4593 let baseVariable = this.syntheticNamespace;
4594 if (baseVariable instanceof ExportDefaultVariable) {
4595 baseVariable = baseVariable.getOriginalVariable();
4596 }
4597 if (baseVariable instanceof SyntheticNamedExportVariable) {
4598 baseVariable = baseVariable.getBaseVariable();
4599 }
4600 return baseVariable;
4601 }
4602 getBaseVariableName() {
4603 return this.syntheticNamespace.getBaseVariableName();
4604 }
4605 getName() {
4606 const name = this.name;
4607 return `${this.syntheticNamespace.getName()}${getPropertyAccess(name)}`;
4608 }
4609 include() {
4610 if (!this.included) {
4611 this.included = true;
4612 this.context.includeVariable(this.syntheticNamespace);
4613 }
4614 }
4615 setRenderNames(baseName, name) {
4616 super.setRenderNames(baseName, name);
4617 }
4618}
4619const getPropertyAccess = (name) => {
4620 return !RESERVED_NAMES[name] && /^(?!\d)[\w$]+$/.test(name)
4621 ? `.${name}`
4622 : `[${JSON.stringify(name)}]`;
4623};
4624
4625const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
4626const INTEROP_DEFAULT_LEGACY_VARIABLE = '_interopDefaultLegacy';
4627const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
4628const INTEROP_NAMESPACE_DEFAULT_VARIABLE = '_interopNamespaceDefault';
4629const INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE = '_interopNamespaceDefaultOnly';
4630const defaultInteropHelpersByInteropType = {
4631 auto: INTEROP_DEFAULT_VARIABLE,
4632 default: null,
4633 defaultOnly: null,
4634 esModule: null,
4635 false: null,
4636 true: INTEROP_DEFAULT_LEGACY_VARIABLE
4637};
4638function isDefaultAProperty(interopType, externalLiveBindings) {
4639 return (interopType === 'esModule' ||
4640 (externalLiveBindings && (interopType === 'auto' || interopType === 'true')));
4641}
4642const namespaceInteropHelpersByInteropType = {
4643 auto: INTEROP_NAMESPACE_VARIABLE,
4644 default: INTEROP_NAMESPACE_DEFAULT_VARIABLE,
4645 defaultOnly: INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE,
4646 esModule: null,
4647 false: null,
4648 true: INTEROP_NAMESPACE_VARIABLE
4649};
4650function canDefaultBeTakenFromNamespace(interopType, externalLiveBindings) {
4651 return (isDefaultAProperty(interopType, externalLiveBindings) &&
4652 defaultInteropHelpersByInteropType[interopType] === INTEROP_DEFAULT_VARIABLE);
4653}
4654function getDefaultOnlyHelper() {
4655 return INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE;
4656}
4657function getHelpersBlock(usedHelpers, accessedGlobals, _, n, s, t, liveBindings, freeze, namespaceToStringTag) {
4658 return HELPER_NAMES.map(variable => usedHelpers.has(variable) || accessedGlobals.has(variable)
4659 ? HELPER_GENERATORS[variable](_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers)
4660 : '').join('');
4661}
4662const HELPER_GENERATORS = {
4663 [INTEROP_DEFAULT_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_VARIABLE}${_}(e)${_}{${_}return ` +
4664 `e${_}&&${_}e.__esModule${_}?${_}` +
4665 `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
4666 [INTEROP_DEFAULT_LEGACY_VARIABLE]: (_, n, s, _t, liveBindings) => `function ${INTEROP_DEFAULT_LEGACY_VARIABLE}${_}(e)${_}{${_}return ` +
4667 `e${_}&&${_}typeof e${_}===${_}'object'${_}&&${_}'default'${_}in e${_}?${_}` +
4668 `${liveBindings ? getDefaultLiveBinding(_) : getDefaultStatic(_)}${s}${_}}${n}${n}`,
4669 [INTEROP_NAMESPACE_VARIABLE]: (_, n, s, t, liveBindings, freeze, namespaceToStringTag, usedHelpers) => `function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
4670 (usedHelpers.has(INTEROP_NAMESPACE_DEFAULT_VARIABLE)
4671 ? `${t}return e${_}&&${_}e.__esModule${_}?${_}e${_}:${_}${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${s}${n}`
4672 : `${t}if${_}(e${_}&&${_}e.__esModule)${_}return e;${n}` +
4673 createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag)) +
4674 `}${n}${n}`,
4675 [INTEROP_NAMESPACE_DEFAULT_VARIABLE]: (_, n, _s, t, liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_VARIABLE}(e)${_}{${n}` +
4676 createNamespaceObject(_, n, t, t, liveBindings, freeze, namespaceToStringTag) +
4677 `}${n}${n}`,
4678 [INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE]: (_, n, _s, t, _liveBindings, freeze, namespaceToStringTag) => `function ${INTEROP_NAMESPACE_DEFAULT_ONLY_VARIABLE}(e)${_}{${n}` +
4679 `${t}return ${getFrozen(`{__proto__: null,${namespaceToStringTag ? `${_}[Symbol.toStringTag]:${_}'Module',` : ''}${_}'default':${_}e}`, freeze)};${n}` +
4680 `}${n}${n}`
4681};
4682function getDefaultLiveBinding(_) {
4683 return `e${_}:${_}{${_}'default':${_}e${_}}`;
4684}
4685function getDefaultStatic(_) {
4686 return `e['default']${_}:${_}e`;
4687}
4688function createNamespaceObject(_, n, t, i, liveBindings, freeze, namespaceToStringTag) {
4689 return (`${i}var n${_}=${_}${namespaceToStringTag
4690 ? `{__proto__:${_}null,${_}[Symbol.toStringTag]:${_}'Module'}`
4691 : 'Object.create(null)'};${n}` +
4692 `${i}if${_}(e)${_}{${n}` +
4693 `${i}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
4694 (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, i + t + t) +
4695 `${i}${t}});${n}` +
4696 `${i}}${n}` +
4697 `${i}n['default']${_}=${_}e;${n}` +
4698 `${i}return ${getFrozen('n', freeze)};${n}`);
4699}
4700function copyPropertyLiveBinding(_, n, t, i) {
4701 return (`${i}if${_}(k${_}!==${_}'default')${_}{${n}` +
4702 `${i}${t}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
4703 `${i}${t}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
4704 `${i}${t}${t}enumerable:${_}true,${n}` +
4705 `${i}${t}${t}get:${_}function${_}()${_}{${n}` +
4706 `${i}${t}${t}${t}return e[k];${n}` +
4707 `${i}${t}${t}}${n}` +
4708 `${i}${t}});${n}` +
4709 `${i}}${n}`);
4710}
4711function copyPropertyStatic(_, n, _t, i) {
4712 return `${i}n[k]${_}=${_}e[k];${n}`;
4713}
4714function getFrozen(fragment, freeze) {
4715 return freeze ? `Object.freeze(${fragment})` : fragment;
4716}
4717const HELPER_NAMES = Object.keys(HELPER_GENERATORS);
4718
4719function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, mechanism = 'return ') {
4720 const _ = compact ? '' : ' ';
4721 const n = compact ? '' : '\n';
4722 if (!namedExportsMode) {
4723 return `${n}${n}${mechanism}${getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings)};`;
4724 }
4725 let exportBlock = '';
4726 // star exports must always output first for precedence
4727 for (const { name, reexports } of dependencies) {
4728 if (reexports && namedExportsMode) {
4729 for (const specifier of reexports) {
4730 if (specifier.reexported === '*') {
4731 if (exportBlock)
4732 exportBlock += n;
4733 if (specifier.needsLiveBinding) {
4734 exportBlock +=
4735 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
4736 `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
4737 `${t}${t}enumerable:${_}true,${n}` +
4738 `${t}${t}get:${_}function${_}()${_}{${n}` +
4739 `${t}${t}${t}return ${name}[k];${n}` +
4740 `${t}${t}}${n}${t}});${n}});`;
4741 }
4742 else {
4743 exportBlock +=
4744 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
4745 `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
4746 }
4747 }
4748 }
4749 }
4750 }
4751 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
4752 if (reexports && namedExportsMode) {
4753 for (const specifier of reexports) {
4754 if (specifier.reexported !== '*') {
4755 const importName = getReexportedImportName(name, specifier.imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
4756 if (exportBlock)
4757 exportBlock += n;
4758 exportBlock +=
4759 specifier.imported !== '*' && specifier.needsLiveBinding
4760 ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
4761 `${t}enumerable:${_}true,${n}` +
4762 `${t}get:${_}function${_}()${_}{${n}` +
4763 `${t}${t}return ${importName};${n}${t}}${n}});`
4764 : `exports.${specifier.reexported}${_}=${_}${importName};`;
4765 }
4766 }
4767 }
4768 }
4769 for (const chunkExport of exports) {
4770 const lhs = `exports.${chunkExport.exported}`;
4771 const rhs = chunkExport.local;
4772 if (lhs !== rhs) {
4773 if (exportBlock)
4774 exportBlock += n;
4775 exportBlock += `${lhs}${_}=${_}${rhs};`;
4776 }
4777 }
4778 if (exportBlock) {
4779 return `${n}${n}${exportBlock}`;
4780 }
4781 return '';
4782}
4783function getSingleDefaultExport(exports, dependencies, interop, externalLiveBindings) {
4784 if (exports.length > 0) {
4785 return exports[0].local;
4786 }
4787 else {
4788 for (const { defaultVariableName, id, isChunk, name, namedExportsMode: depNamedExportsMode, namespaceVariableName, reexports } of dependencies) {
4789 if (reexports) {
4790 return getReexportedImportName(name, reexports[0].imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, id, externalLiveBindings);
4791 }
4792 }
4793 }
4794}
4795function getReexportedImportName(moduleVariableName, imported, depNamedExportsMode, isChunk, defaultVariableName, namespaceVariableName, interop, moduleId, externalLiveBindings) {
4796 if (imported === 'default') {
4797 if (!isChunk) {
4798 const moduleInterop = String(interop(moduleId));
4799 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
4800 ? defaultVariableName
4801 : moduleVariableName;
4802 return isDefaultAProperty(moduleInterop, externalLiveBindings)
4803 ? `${variableName}['default']`
4804 : variableName;
4805 }
4806 return depNamedExportsMode ? `${moduleVariableName}['default']` : moduleVariableName;
4807 }
4808 if (imported === '*') {
4809 return (isChunk
4810 ? !depNamedExportsMode
4811 : namespaceInteropHelpersByInteropType[String(interop(moduleId))])
4812 ? namespaceVariableName
4813 : moduleVariableName;
4814 }
4815 return `${moduleVariableName}.${imported}`;
4816}
4817function getEsModuleExport(_) {
4818 return `Object.defineProperty(exports,${_}'__esModule',${_}{${_}value:${_}true${_}});`;
4819}
4820function getNamespaceToStringExport(_) {
4821 return `exports[Symbol.toStringTag]${_}=${_}'Module';`;
4822}
4823function getNamespaceMarkers(hasNamedExports, addEsModule, addNamespaceToStringTag, _, n) {
4824 let namespaceMarkers = '';
4825 if (hasNamedExports) {
4826 if (addEsModule) {
4827 namespaceMarkers += getEsModuleExport(_);
4828 }
4829 if (addNamespaceToStringTag) {
4830 if (namespaceMarkers) {
4831 namespaceMarkers += n;
4832 }
4833 namespaceMarkers += getNamespaceToStringExport(_);
4834 }
4835 }
4836 return namespaceMarkers;
4837}
4838
4839function getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t) {
4840 const neededInteropHelpers = new Set();
4841 const interopStatements = [];
4842 const addInteropStatement = (helperVariableName, helper, dependencyVariableName) => {
4843 neededInteropHelpers.add(helper);
4844 interopStatements.push(`${varOrConst} ${helperVariableName}${_}=${_}/*#__PURE__*/${helper}(${dependencyVariableName});`);
4845 };
4846 for (const { defaultVariableName, imports, id, isChunk, name, namedExportsMode, namespaceVariableName, reexports } of dependencies) {
4847 if (isChunk) {
4848 for (const { imported, reexported } of [
4849 ...(imports || []),
4850 ...(reexports || [])
4851 ]) {
4852 if (imported === '*' && reexported !== '*') {
4853 if (!namedExportsMode) {
4854 addInteropStatement(namespaceVariableName, getDefaultOnlyHelper(), name);
4855 }
4856 break;
4857 }
4858 }
4859 }
4860 else {
4861 const moduleInterop = String(interop(id));
4862 let hasDefault = false;
4863 let hasNamespace = false;
4864 for (const { imported, reexported } of [
4865 ...(imports || []),
4866 ...(reexports || [])
4867 ]) {
4868 let helper;
4869 let variableName;
4870 if (imported === 'default') {
4871 if (!hasDefault) {
4872 hasDefault = true;
4873 if (defaultVariableName !== namespaceVariableName) {
4874 variableName = defaultVariableName;
4875 helper = defaultInteropHelpersByInteropType[moduleInterop];
4876 }
4877 }
4878 }
4879 else if (imported === '*' && reexported !== '*') {
4880 if (!hasNamespace) {
4881 hasNamespace = true;
4882 helper = namespaceInteropHelpersByInteropType[moduleInterop];
4883 variableName = namespaceVariableName;
4884 }
4885 }
4886 if (helper) {
4887 addInteropStatement(variableName, helper, name);
4888 }
4889 }
4890 }
4891 }
4892 return `${getHelpersBlock(neededInteropHelpers, accessedGlobals, _, n, s, t, externalLiveBindings, freeze, namespaceToStringTag)}${interopStatements.length > 0 ? `${interopStatements.join(n)}${n}${n}` : ''}`;
4893}
4894
4895const builtins$1 = {
4896 assert: true,
4897 buffer: true,
4898 console: true,
4899 constants: true,
4900 domain: true,
4901 events: true,
4902 http: true,
4903 https: true,
4904 os: true,
4905 path: true,
4906 process: true,
4907 punycode: true,
4908 querystring: true,
4909 stream: true,
4910 string_decoder: true,
4911 timers: true,
4912 tty: true,
4913 url: true,
4914 util: true,
4915 vm: true,
4916 zlib: true
4917};
4918function warnOnBuiltins(warn, dependencies) {
4919 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins$1);
4920 if (!externalBuiltins.length)
4921 return;
4922 const detail = externalBuiltins.length === 1
4923 ? `module ('${externalBuiltins[0]}')`
4924 : `modules (${externalBuiltins
4925 .slice(0, -1)
4926 .map(name => `'${name}'`)
4927 .join(', ')} and '${externalBuiltins.slice(-1)}')`;
4928 warn({
4929 code: 'MISSING_NODE_BUILTINS',
4930 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`,
4931 modules: externalBuiltins
4932 });
4933}
4934
4935// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
4936// The assumption is that this makes sense for all relative ids:
4937// https://requirejs.org/docs/api.html#jsfiles
4938function removeExtensionFromRelativeAmdId(id) {
4939 if (id[0] === '.' && id.endsWith('.js')) {
4940 return id.slice(0, -3);
4941 }
4942 return id;
4943}
4944function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst, warn }, { amd: { define: amdDefine, id: amdId }, compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
4945 warnOnBuiltins(warn, dependencies);
4946 const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
4947 const args = dependencies.map(m => m.name);
4948 const n = compact ? '' : '\n';
4949 const s = compact ? '' : ';';
4950 const _ = compact ? '' : ' ';
4951 if (namedExportsMode && hasExports) {
4952 args.unshift(`exports`);
4953 deps.unshift(`'exports'`);
4954 }
4955 if (accessedGlobals.has('require')) {
4956 args.unshift('require');
4957 deps.unshift(`'require'`);
4958 }
4959 if (accessedGlobals.has('module')) {
4960 args.unshift('module');
4961 deps.unshift(`'module'`);
4962 }
4963 const params = (amdId ? `'${amdId}',${_}` : ``) + (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
4964 const useStrict = strict ? `${_}'use strict';` : '';
4965 magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
4966 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
4967 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
4968 if (namespaceMarkers) {
4969 namespaceMarkers = n + n + namespaceMarkers;
4970 }
4971 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
4972 return magicString
4973 .indent(t)
4974 .prepend(`${amdDefine}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`)
4975 .append(`${n}${n}});`);
4976}
4977
4978function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryFacade, isModuleFacade, namedExportsMode, outro, varOrConst }, { compact, esModule, externalLiveBindings, freeze, interop, namespaceToStringTag, strict }) {
4979 const n = compact ? '' : '\n';
4980 const s = compact ? '' : ';';
4981 const _ = compact ? '' : ' ';
4982 const useStrict = strict ? `'use strict';${n}${n}` : '';
4983 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, isEntryFacade && esModule, isModuleFacade && namespaceToStringTag, _, n);
4984 if (namespaceMarkers) {
4985 namespaceMarkers += n + n;
4986 }
4987 const importBlock = getImportBlock(dependencies, compact, varOrConst, n, _);
4988 const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
4989 magicString.prepend(`${useStrict}${intro}${namespaceMarkers}${importBlock}${interopBlock}`);
4990 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings, `module.exports${_}=${_}`);
4991 return magicString.append(`${exportBlock}${outro}`);
4992}
4993function getImportBlock(dependencies, compact, varOrConst, n, _) {
4994 let importBlock = '';
4995 let definingVariable = false;
4996 for (const { id, name, reexports, imports } of dependencies) {
4997 if (!reexports && !imports) {
4998 if (importBlock) {
4999 importBlock += !compact || definingVariable ? `;${n}` : ',';
5000 }
5001 definingVariable = false;
5002 importBlock += `require('${id}')`;
5003 }
5004 else {
5005 importBlock +=
5006 compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
5007 definingVariable = true;
5008 importBlock += `${name}${_}=${_}require('${id}')`;
5009 }
5010 }
5011 if (importBlock) {
5012 return `${importBlock};${n}${n}`;
5013 }
5014 return '';
5015}
5016
5017function es(magicString, { intro, outro, dependencies, exports, varOrConst }, { compact }) {
5018 const _ = compact ? '' : ' ';
5019 const n = compact ? '' : '\n';
5020 const importBlock = getImportBlock$1(dependencies, _);
5021 if (importBlock.length > 0)
5022 intro += importBlock.join(n) + n + n;
5023 if (intro)
5024 magicString.prepend(intro);
5025 const exportBlock = getExportBlock$1(exports, _, varOrConst);
5026 if (exportBlock.length)
5027 magicString.append(n + n + exportBlock.join(n).trim());
5028 if (outro)
5029 magicString.append(outro);
5030 return magicString.trim();
5031}
5032function getImportBlock$1(dependencies, _) {
5033 const importBlock = [];
5034 for (const { id, reexports, imports, name } of dependencies) {
5035 if (!reexports && !imports) {
5036 importBlock.push(`import${_}'${id}';`);
5037 continue;
5038 }
5039 if (imports) {
5040 let defaultImport = null;
5041 let starImport = null;
5042 const importedNames = [];
5043 for (const specifier of imports) {
5044 if (specifier.imported === 'default') {
5045 defaultImport = specifier;
5046 }
5047 else if (specifier.imported === '*') {
5048 starImport = specifier;
5049 }
5050 else {
5051 importedNames.push(specifier);
5052 }
5053 }
5054 if (starImport) {
5055 importBlock.push(`import${_}*${_}as ${starImport.local} from${_}'${id}';`);
5056 }
5057 if (defaultImport && importedNames.length === 0) {
5058 importBlock.push(`import ${defaultImport.local} from${_}'${id}';`);
5059 }
5060 else if (importedNames.length > 0) {
5061 importBlock.push(`import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${importedNames
5062 .map(specifier => {
5063 if (specifier.imported === specifier.local) {
5064 return specifier.imported;
5065 }
5066 else {
5067 return `${specifier.imported} as ${specifier.local}`;
5068 }
5069 })
5070 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
5071 }
5072 }
5073 if (reexports) {
5074 let starExport = null;
5075 const namespaceReexports = [];
5076 const namedReexports = [];
5077 for (const specifier of reexports) {
5078 if (specifier.reexported === '*') {
5079 starExport = specifier;
5080 }
5081 else if (specifier.imported === '*') {
5082 namespaceReexports.push(specifier);
5083 }
5084 else {
5085 namedReexports.push(specifier);
5086 }
5087 }
5088 if (starExport) {
5089 importBlock.push(`export${_}*${_}from${_}'${id}';`);
5090 }
5091 if (namespaceReexports.length > 0) {
5092 if (!imports ||
5093 !imports.some(specifier => specifier.imported === '*' && specifier.local === name)) {
5094 importBlock.push(`import${_}*${_}as ${name} from${_}'${id}';`);
5095 }
5096 for (const specifier of namespaceReexports) {
5097 importBlock.push(`export${_}{${_}${name === specifier.reexported ? name : `${name} as ${specifier.reexported}`} };`);
5098 }
5099 }
5100 if (namedReexports.length > 0) {
5101 importBlock.push(`export${_}{${_}${namedReexports
5102 .map(specifier => {
5103 if (specifier.imported === specifier.reexported) {
5104 return specifier.imported;
5105 }
5106 else {
5107 return `${specifier.imported} as ${specifier.reexported}`;
5108 }
5109 })
5110 .join(`,${_}`)}${_}}${_}from${_}'${id}';`);
5111 }
5112 }
5113 }
5114 return importBlock;
5115}
5116function getExportBlock$1(exports, _, varOrConst) {
5117 const exportBlock = [];
5118 const exportDeclaration = [];
5119 for (const specifier of exports) {
5120 if (specifier.exported === 'default') {
5121 exportBlock.push(`export default ${specifier.local};`);
5122 }
5123 else {
5124 if (specifier.expression) {
5125 exportBlock.push(`${varOrConst} ${specifier.local}${_}=${_}${specifier.expression};`);
5126 }
5127 exportDeclaration.push(specifier.exported === specifier.local
5128 ? specifier.local
5129 : `${specifier.local} as ${specifier.exported}`);
5130 }
5131 }
5132 if (exportDeclaration.length) {
5133 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
5134 }
5135 return exportBlock;
5136}
5137
5138function spaces(i) {
5139 let result = '';
5140 while (i--)
5141 result += ' ';
5142 return result;
5143}
5144function tabsToSpaces(str) {
5145 return str.replace(/^\t+/, match => match.split('\t').join(' '));
5146}
5147function getCodeFrame(source, line, column) {
5148 let lines = source.split('\n');
5149 const frameStart = Math.max(0, line - 3);
5150 let frameEnd = Math.min(line + 2, lines.length);
5151 lines = lines.slice(frameStart, frameEnd);
5152 while (!/\S/.test(lines[lines.length - 1])) {
5153 lines.pop();
5154 frameEnd -= 1;
5155 }
5156 const digits = String(frameEnd).length;
5157 return lines
5158 .map((str, i) => {
5159 const isErrorLine = frameStart + i + 1 === line;
5160 let lineNum = String(i + frameStart + 1);
5161 while (lineNum.length < digits)
5162 lineNum = ` ${lineNum}`;
5163 if (isErrorLine) {
5164 const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
5165 return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
5166 }
5167 return `${lineNum}: ${tabsToSpaces(str)}`;
5168 })
5169 .join('\n');
5170}
5171
5172function sanitizeFileName(name) {
5173 return name.replace(/[\0?*]/g, '_');
5174}
5175
5176function getAliasName(id) {
5177 const base = basename(id);
5178 return base.substr(0, base.length - extname(id).length);
5179}
5180function relativeId(id) {
5181 if (typeof process === 'undefined' || !isAbsolute(id))
5182 return id;
5183 return relative$1(process.cwd(), id);
5184}
5185function isPlainPathFragment(name) {
5186 // not starting with "/", "./", "../"
5187 return (name[0] !== '/' &&
5188 !(name[0] === '.' && (name[1] === '/' || name[1] === '.')) &&
5189 sanitizeFileName(name) === name &&
5190 !isAbsolute(name));
5191}
5192
5193function error(base) {
5194 if (!(base instanceof Error))
5195 base = Object.assign(new Error(base.message), base);
5196 throw base;
5197}
5198function augmentCodeLocation(props, pos, source, id) {
5199 if (typeof pos === 'object') {
5200 const { line, column } = pos;
5201 props.loc = { file: id, line, column };
5202 }
5203 else {
5204 props.pos = pos;
5205 const { line, column } = locate(source, pos, { offsetLine: 1 });
5206 props.loc = { file: id, line, column };
5207 }
5208 if (props.frame === undefined) {
5209 const { line, column } = props.loc;
5210 props.frame = getCodeFrame(source, line, column);
5211 }
5212}
5213var Errors;
5214(function (Errors) {
5215 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
5216 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
5217 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
5218 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
5219 Errors["BAD_LOADER"] = "BAD_LOADER";
5220 Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
5221 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
5222 Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
5223 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
5224 Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
5225 Errors["INPUT_HOOK_IN_OUTPUT_PLUGIN"] = "INPUT_HOOK_IN_OUTPUT_PLUGIN";
5226 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
5227 Errors["INVALID_EXPORT_OPTION"] = "INVALID_EXPORT_OPTION";
5228 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
5229 Errors["INVALID_OPTION"] = "INVALID_OPTION";
5230 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
5231 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
5232 Errors["MISSING_IMPLICIT_DEPENDANT"] = "MISSING_IMPLICIT_DEPENDANT";
5233 Errors["MIXED_EXPORTS"] = "MIXED_EXPORTS";
5234 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
5235 Errors["NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE"] = "NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE";
5236 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
5237 Errors["PREFER_NAMED_EXPORTS"] = "PREFER_NAMED_EXPORTS";
5238 Errors["UNEXPECTED_NAMED_IMPORT"] = "UNEXPECTED_NAMED_IMPORT";
5239 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
5240 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
5241 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
5242 Errors["EXTERNAL_SYNTHETIC_EXPORTS"] = "EXTERNAL_SYNTHETIC_EXPORTS";
5243 Errors["SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT"] = "SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT";
5244})(Errors || (Errors = {}));
5245function errAssetNotFinalisedForFileName(name) {
5246 return {
5247 code: Errors.ASSET_NOT_FINALISED,
5248 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
5249 };
5250}
5251function errCannotEmitFromOptionsHook() {
5252 return {
5253 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
5254 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
5255 };
5256}
5257function errChunkNotGeneratedForFileName(name) {
5258 return {
5259 code: Errors.CHUNK_NOT_GENERATED,
5260 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
5261 };
5262}
5263function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
5264 return {
5265 code: Errors.ASSET_NOT_FOUND,
5266 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
5267 };
5268}
5269function errAssetSourceAlreadySet(name) {
5270 return {
5271 code: Errors.ASSET_SOURCE_ALREADY_SET,
5272 message: `Unable to set the source for asset "${name}", source already set.`
5273 };
5274}
5275function errNoAssetSourceSet(assetName) {
5276 return {
5277 code: Errors.ASSET_SOURCE_MISSING,
5278 message: `Plugin error creating asset "${assetName}" - no asset source set.`
5279 };
5280}
5281function errBadLoader(id) {
5282 return {
5283 code: Errors.BAD_LOADER,
5284 message: `Error loading ${relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
5285 };
5286}
5287function errDeprecation(deprecation) {
5288 return {
5289 code: Errors.DEPRECATED_FEATURE,
5290 ...(typeof deprecation === 'string' ? { message: deprecation } : deprecation)
5291 };
5292}
5293function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
5294 return {
5295 code: Errors.FILE_NOT_FOUND,
5296 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
5297 };
5298}
5299function errFileNameConflict(fileName) {
5300 return {
5301 code: Errors.FILE_NAME_CONFLICT,
5302 message: `The emitted file "${fileName}" overwrites a previously emitted file of the same name.`
5303 };
5304}
5305function errInputHookInOutputPlugin(pluginName, hookName) {
5306 return {
5307 code: Errors.INPUT_HOOK_IN_OUTPUT_PLUGIN,
5308 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.`
5309 };
5310}
5311function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
5312 return {
5313 code: Errors.INVALID_CHUNK,
5314 message: `Cannot assign ${relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
5315 };
5316}
5317function errInvalidExportOptionValue(optionValue) {
5318 return {
5319 code: Errors.INVALID_EXPORT_OPTION,
5320 message: `"output.exports" must be "default", "named", "none", "auto", or left unspecified (defaults to "auto"), received "${optionValue}"`,
5321 url: `https://rollupjs.org/guide/en/#outputexports`
5322 };
5323}
5324function errIncompatibleExportOptionValue(optionValue, keys, entryModule) {
5325 return {
5326 code: 'INVALID_EXPORT_OPTION',
5327 message: `"${optionValue}" was specified for "output.exports", but entry module "${relativeId(entryModule)}" has the following exports: ${keys.join(', ')}`
5328 };
5329}
5330function errInternalIdCannotBeExternal(source, importer) {
5331 return {
5332 code: Errors.INVALID_EXTERNAL_ID,
5333 message: `'${source}' is imported as an external by ${relativeId(importer)}, but is already an existing non-external module id.`
5334 };
5335}
5336function errInvalidOption(option, explanation) {
5337 return {
5338 code: Errors.INVALID_OPTION,
5339 message: `Invalid value for option "${option}" - ${explanation}.`
5340 };
5341}
5342function errInvalidRollupPhaseForAddWatchFile() {
5343 return {
5344 code: Errors.INVALID_ROLLUP_PHASE,
5345 message: `Cannot call addWatchFile after the build has finished.`
5346 };
5347}
5348function errInvalidRollupPhaseForChunkEmission() {
5349 return {
5350 code: Errors.INVALID_ROLLUP_PHASE,
5351 message: `Cannot emit chunks after module loading has finished.`
5352 };
5353}
5354function errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore) {
5355 return {
5356 code: Errors.MISSING_IMPLICIT_DEPENDANT,
5357 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" cannot be external.`
5358 };
5359}
5360function errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore) {
5361 return {
5362 code: Errors.MISSING_IMPLICIT_DEPENDANT,
5363 message: `Module "${relativeId(unresolvedId)}" that should be implicitly loaded before "${relativeId(implicitlyLoadedBefore)}" could not be resolved.`
5364 };
5365}
5366function errImplicitDependantIsNotIncluded(module) {
5367 const implicitDependencies = Array.from(module.implicitlyLoadedBefore, dependency => relativeId(dependency.id)).sort();
5368 return {
5369 code: Errors.MISSING_IMPLICIT_DEPENDANT,
5370 message: `Module "${relativeId(module.id)}" that should be implicitly loaded before "${implicitDependencies.length === 1
5371 ? implicitDependencies[0]
5372 : `${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.`
5373 };
5374}
5375function errMixedExport(facadeModuleId, name) {
5376 return {
5377 code: Errors.MIXED_EXPORTS,
5378 id: facadeModuleId,
5379 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`,
5380 url: `https://rollupjs.org/guide/en/#outputexports`
5381 };
5382}
5383function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
5384 return {
5385 code: Errors.NAMESPACE_CONFLICT,
5386 message: `Conflicting namespaces: ${relativeId(reexportingModule.id)} re-exports '${name}' from both ${relativeId(reexportingModule.exportsAll[name])} and ${relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
5387 name,
5388 reexporter: reexportingModule.id,
5389 sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
5390 };
5391}
5392function errNoTransformMapOrAstWithoutCode(pluginName) {
5393 return {
5394 code: Errors.NO_TRANSFORM_MAP_OR_AST_WITHOUT_CODE,
5395 message: `The plugin "${pluginName}" returned a "map" or "ast" without returning ` +
5396 'a "code". This will be ignored.'
5397 };
5398}
5399function errPreferNamedExports(facadeModuleId) {
5400 const file = relativeId(facadeModuleId);
5401 return {
5402 code: Errors.PREFER_NAMED_EXPORTS,
5403 id: facadeModuleId,
5404 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.`,
5405 url: `https://rollupjs.org/guide/en/#outputexports`
5406 };
5407}
5408function errUnexpectedNamedImport(id, imported, isReexport) {
5409 const importType = isReexport ? 'reexport' : 'import';
5410 return {
5411 code: Errors.UNEXPECTED_NAMED_IMPORT,
5412 id,
5413 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.`,
5414 url: 'https://rollupjs.org/guide/en/#outputinterop'
5415 };
5416}
5417function errUnexpectedNamespaceReexport(id) {
5418 return {
5419 code: Errors.UNEXPECTED_NAMED_IMPORT,
5420 id,
5421 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.`,
5422 url: 'https://rollupjs.org/guide/en/#outputinterop'
5423 };
5424}
5425function errEntryCannotBeExternal(unresolvedId) {
5426 return {
5427 code: Errors.UNRESOLVED_ENTRY,
5428 message: `Entry module cannot be external (${relativeId(unresolvedId)}).`
5429 };
5430}
5431function errUnresolvedEntry(unresolvedId) {
5432 return {
5433 code: Errors.UNRESOLVED_ENTRY,
5434 message: `Could not resolve entry module (${relativeId(unresolvedId)}).`
5435 };
5436}
5437function errUnresolvedImport(source, importer) {
5438 return {
5439 code: Errors.UNRESOLVED_IMPORT,
5440 message: `Could not resolve '${source}' from ${relativeId(importer)}`
5441 };
5442}
5443function errUnresolvedImportTreatedAsExternal(source, importer) {
5444 return {
5445 code: Errors.UNRESOLVED_IMPORT,
5446 importer: relativeId(importer),
5447 message: `'${source}' is imported by ${relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
5448 source,
5449 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
5450 };
5451}
5452function errExternalSyntheticExports(source, importer) {
5453 return {
5454 code: Errors.EXTERNAL_SYNTHETIC_EXPORTS,
5455 importer: relativeId(importer),
5456 message: `External '${source}' can not have 'syntheticNamedExports' enabled.`,
5457 source
5458 };
5459}
5460function errFailedValidation(message) {
5461 return {
5462 code: Errors.VALIDATION_ERROR,
5463 message
5464 };
5465}
5466function warnDeprecation(deprecation, activeDeprecation, options) {
5467 warnDeprecationWithOptions(deprecation, activeDeprecation, options.onwarn, options.strictDeprecations);
5468}
5469function warnDeprecationWithOptions(deprecation, activeDeprecation, warn, strictDeprecations) {
5470 if (activeDeprecation || strictDeprecations) {
5471 const warning = errDeprecation(deprecation);
5472 if (strictDeprecations) {
5473 return error(warning);
5474 }
5475 warn(warning);
5476 }
5477}
5478
5479// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
5480// if the property name isn't trivial
5481const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
5482function property(prop) {
5483 return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
5484}
5485function keypath(keypath) {
5486 return keypath
5487 .split('.')
5488 .map(property)
5489 .join('');
5490}
5491
5492function setupNamespace(name, root, globals, compact) {
5493 const _ = compact ? '' : ' ';
5494 const parts = name.split('.');
5495 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
5496 parts.pop();
5497 let acc = root;
5498 return (parts
5499 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
5500 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
5501}
5502function assignToDeepVariable(deepName, root, globals, compact, assignment) {
5503 const _ = compact ? '' : ' ';
5504 const parts = deepName.split('.');
5505 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
5506 const last = parts.pop();
5507 let acc = root;
5508 let deepAssignment = parts
5509 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
5510 .concat(`${acc}${property(last)}`)
5511 .join(`,${_}`)
5512 .concat(`${_}=${_}${assignment}`);
5513 if (parts.length > 0) {
5514 deepAssignment = `(${deepAssignment})`;
5515 }
5516 return deepAssignment;
5517}
5518
5519function trimEmptyImports(dependencies) {
5520 let i = dependencies.length;
5521 while (i--) {
5522 const { imports, reexports } = dependencies[i];
5523 if (imports || reexports) {
5524 return dependencies.slice(0, i + 1);
5525 }
5526 }
5527 return [];
5528}
5529
5530const thisProp = (name) => `this${keypath(name)}`;
5531function iife(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, { compact, esModule, extend, freeze, externalLiveBindings, globals, interop, name, namespaceToStringTag, strict }) {
5532 const _ = compact ? '' : ' ';
5533 const s = compact ? '' : ';';
5534 const n = compact ? '' : '\n';
5535 const isNamespaced = name && name.indexOf('.') !== -1;
5536 const useVariableAssignment = !extend && !isNamespaced;
5537 if (name && useVariableAssignment && !isLegal(name)) {
5538 return error({
5539 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
5540 message: `Given name "${name}" is not a legal JS identifier. If you need this, you can try "output.extend: true".`
5541 });
5542 }
5543 warnOnBuiltins(warn, dependencies);
5544 const external = trimEmptyImports(dependencies);
5545 const deps = external.map(dep => dep.globalName || 'null');
5546 const args = external.map(m => m.name);
5547 if (hasExports && !name) {
5548 warn({
5549 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
5550 message: `If you do not supply "output.name", you may not be able to access the exports of an IIFE bundle.`
5551 });
5552 }
5553 if (namedExportsMode && hasExports) {
5554 if (extend) {
5555 deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
5556 args.unshift('exports');
5557 }
5558 else {
5559 deps.unshift('{}');
5560 args.unshift('exports');
5561 }
5562 }
5563 const useStrict = strict ? `${t}'use strict';${n}` : '';
5564 const interopBlock = getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t);
5565 magicString.prepend(`${intro}${interopBlock}`);
5566 let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}${n}`;
5567 if (hasExports) {
5568 if (name && !(extend && namedExportsMode)) {
5569 wrapperIntro =
5570 (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
5571 `${_}=${_}${wrapperIntro}`;
5572 }
5573 if (isNamespaced) {
5574 wrapperIntro = setupNamespace(name, 'this', globals, compact) + wrapperIntro;
5575 }
5576 }
5577 let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
5578 if (hasExports && !extend && namedExportsMode) {
5579 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
5580 }
5581 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
5582 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
5583 if (namespaceMarkers) {
5584 namespaceMarkers = n + n + namespaceMarkers;
5585 }
5586 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
5587 return magicString.indent(t).prepend(wrapperIntro).append(wrapperOutro);
5588}
5589
5590function getStarExcludes({ dependencies, exports }) {
5591 const starExcludes = new Set(exports.map(expt => expt.exported));
5592 if (!starExcludes.has('default'))
5593 starExcludes.add('default');
5594 // also include reexport names
5595 for (const { reexports } of dependencies) {
5596 if (reexports) {
5597 for (const reexport of reexports) {
5598 if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
5599 starExcludes.add(reexport.reexported);
5600 }
5601 }
5602 }
5603 return starExcludes;
5604}
5605const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
5606 ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${[...starExcludes]
5607 .map(prop => `${prop}:${_}1`)
5608 .join(`,${_}`)}${_}};`
5609 : '';
5610const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
5611function getExportsBlock(exports, _, t, n) {
5612 if (exports.length === 0) {
5613 return '';
5614 }
5615 if (exports.length === 1) {
5616 return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
5617 }
5618 return (`${t}${t}${t}exports({${n}` +
5619 exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
5620 `${n}${t}${t}${t}});${n}${n}`);
5621}
5622const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5623 .filter(expt => expt.hoisted || expt.uninitialized)
5624 .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
5625const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5626 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
5627 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
5628const getSyntheticExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5629 .filter(expt => expt.expression)
5630 .map(expt => ({ name: expt.exported, value: expt.local })), _, t, n);
5631function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
5632 const n = options.compact ? '' : '\n';
5633 const _ = options.compact ? '' : ' ';
5634 const dependencyIds = dependencies.map(m => `'${m.id}'`);
5635 const importBindings = [];
5636 let starExcludes;
5637 const setters = [];
5638 for (const { imports, reexports } of dependencies) {
5639 const setter = [];
5640 if (imports) {
5641 for (const specifier of imports) {
5642 importBindings.push(specifier.local);
5643 if (specifier.imported === '*') {
5644 setter.push(`${specifier.local}${_}=${_}module;`);
5645 }
5646 else {
5647 setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
5648 }
5649 }
5650 }
5651 if (reexports) {
5652 let createdSetter = false;
5653 // bulk-reexport form
5654 if (reexports.length > 1 ||
5655 (reexports.length === 1 &&
5656 (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
5657 // star reexports
5658 for (const specifier of reexports) {
5659 if (specifier.reexported !== '*')
5660 continue;
5661 // need own exports list for deduping in star export case
5662 if (!starExcludes) {
5663 starExcludes = getStarExcludes({ dependencies, exports });
5664 }
5665 if (!createdSetter) {
5666 setter.push(`${varOrConst} _setter${_}=${_}{};`);
5667 createdSetter = true;
5668 }
5669 setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
5670 setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
5671 setter.push('}');
5672 }
5673 // star import reexport
5674 for (const specifier of reexports) {
5675 if (specifier.imported !== '*' || specifier.reexported === '*')
5676 continue;
5677 setter.push(`exports('${specifier.reexported}',${_}module);`);
5678 }
5679 // reexports
5680 for (const specifier of reexports) {
5681 if (specifier.reexported === '*' || specifier.imported === '*')
5682 continue;
5683 if (!createdSetter) {
5684 setter.push(`${varOrConst} _setter${_}=${_}{};`);
5685 createdSetter = true;
5686 }
5687 setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
5688 }
5689 if (createdSetter) {
5690 setter.push('exports(_setter);');
5691 }
5692 }
5693 else {
5694 // single reexport
5695 for (const specifier of reexports) {
5696 setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
5697 }
5698 }
5699 }
5700 setters.push(setter.join(`${n}${t}${t}${t}`));
5701 }
5702 const registeredName = options.name ? `'${options.name}',${_}` : '';
5703 const wrapperParams = accessedGlobals.has('module')
5704 ? `exports,${_}module`
5705 : hasExports
5706 ? 'exports'
5707 : '';
5708 let wrapperStart = `System.register(${registeredName}[` +
5709 dependencyIds.join(`,${_}`) +
5710 `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
5711 getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
5712 getImportBindingsBlock(importBindings, _, t, n) +
5713 `${n}${t}return${_}{${setters.length
5714 ? `${n}${t}${t}setters:${_}[${setters
5715 .map(s => s
5716 ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
5717 : options.systemNullSetters
5718 ? `null`
5719 : `function${_}()${_}{}`)
5720 .join(`,${_}`)}],`
5721 : ''}${n}`;
5722 wrapperStart +=
5723 `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
5724 getHoistedExportsBlock(exports, _, t, n);
5725 const wrapperEnd = `${n}${n}` +
5726 getSyntheticExportsBlock(exports, _, t, n) +
5727 getMissingExportsBlock(exports, _, t, n) +
5728 `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
5729 if (intro)
5730 magicString.prepend(intro);
5731 if (outro)
5732 magicString.append(outro);
5733 return magicString.indent(`${t}${t}${t}`).append(wrapperEnd).prepend(wrapperStart);
5734}
5735
5736function globalProp(name, globalVar) {
5737 if (!name)
5738 return 'null';
5739 return `${globalVar}${keypath(name)}`;
5740}
5741function safeAccess(name, globalVar, _) {
5742 const parts = name.split('.');
5743 let acc = globalVar;
5744 return parts.map(part => (acc += property(part))).join(`${_}&&${_}`);
5745}
5746function 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, namespaceToStringTag, globals, noConflict, strict }) {
5747 const _ = compact ? '' : ' ';
5748 const n = compact ? '' : '\n';
5749 const s = compact ? '' : ';';
5750 const factoryVar = compact ? 'f' : 'factory';
5751 const globalVar = compact ? 'g' : 'global';
5752 if (hasExports && !name) {
5753 return error({
5754 code: 'MISSING_NAME_OPTION_FOR_IIFE_EXPORT',
5755 message: 'You must supply "output.name" for UMD bundles that have exports so that the exports are accessible in environments without a module loader.'
5756 });
5757 }
5758 warnOnBuiltins(warn, dependencies);
5759 const amdDeps = dependencies.map(m => `'${m.id}'`);
5760 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
5761 const trimmedImports = trimEmptyImports(dependencies);
5762 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
5763 const factoryArgs = trimmedImports.map(m => m.name);
5764 if (namedExportsMode && (hasExports || noConflict)) {
5765 amdDeps.unshift(`'exports'`);
5766 cjsDeps.unshift(`exports`);
5767 globalDeps.unshift(assignToDeepVariable(name, globalVar, globals, compact, `${extend ? `${globalProp(name, globalVar)}${_}||${_}` : ''}{}`));
5768 factoryArgs.unshift('exports');
5769 }
5770 const amdParams = (amdId ? `'${amdId}',${_}` : ``) + (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
5771 const define = amdDefine;
5772 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
5773 const useStrict = strict ? `${_}'use strict';${n}` : ``;
5774 let iifeExport;
5775 if (noConflict) {
5776 const noConflictExportsVar = compact ? 'e' : 'exports';
5777 let factory;
5778 if (!namedExportsMode && hasExports) {
5779 factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(name, globalVar, globals, compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
5780 }
5781 else {
5782 const module = globalDeps.shift();
5783 factory =
5784 `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
5785 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
5786 }
5787 iifeExport =
5788 `(function${_}()${_}{${n}` +
5789 `${t}${t}var current${_}=${_}${safeAccess(name, globalVar, _)};${n}` +
5790 `${t}${t}${factory}${n}` +
5791 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
5792 `${globalProp(name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${compact ? '' : '; '}};${n}` +
5793 `${t}}())`;
5794 }
5795 else {
5796 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
5797 if (!namedExportsMode && hasExports) {
5798 iifeExport = assignToDeepVariable(name, globalVar, globals, compact, iifeExport);
5799 }
5800 }
5801 const iifeNeedsGlobal = hasExports || (noConflict && namedExportsMode) || globalDeps.length > 0;
5802 const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
5803 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
5804 const iifeStart = iifeNeedsGlobal
5805 ? `(${globalVar}${_}=${_}typeof globalThis${_}!==${_}'undefined'${_}?${_}globalThis${_}:${_}${globalVar}${_}||${_}self,${_}`
5806 : '';
5807 const iifeEnd = iifeNeedsGlobal ? ')' : '';
5808 const cjsIntro = iifeNeedsGlobal
5809 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
5810 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
5811 : '';
5812 // factory function should be wrapped by parentheses to avoid lazy parsing
5813 const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
5814 cjsIntro +
5815 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
5816 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
5817 `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
5818 const wrapperOutro = n + n + '})));';
5819 magicString.prepend(`${intro}${getInteropBlock(dependencies, varOrConst, interop, externalLiveBindings, freeze, namespaceToStringTag, accessedGlobals, _, n, s, t)}`);
5820 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, externalLiveBindings);
5821 let namespaceMarkers = getNamespaceMarkers(namedExportsMode && hasExports, esModule, namespaceToStringTag, _, n);
5822 if (namespaceMarkers) {
5823 namespaceMarkers = n + n + namespaceMarkers;
5824 }
5825 magicString.append(`${exportBlock}${namespaceMarkers}${outro}`);
5826 return magicString.trim().indent(t).append(wrapperOutro).prepend(wrapperIntro);
5827}
5828
5829var finalisers = { system, amd, cjs, es, iife, umd };
5830
5831const extractors = {
5832 ArrayPattern(names, param) {
5833 for (const element of param.elements) {
5834 if (element)
5835 extractors[element.type](names, element);
5836 }
5837 },
5838 AssignmentPattern(names, param) {
5839 extractors[param.left.type](names, param.left);
5840 },
5841 Identifier(names, param) {
5842 names.push(param.name);
5843 },
5844 MemberExpression() { },
5845 ObjectPattern(names, param) {
5846 for (const prop of param.properties) {
5847 if (prop.type === 'RestElement') {
5848 extractors.RestElement(names, prop);
5849 }
5850 else {
5851 extractors[prop.value.type](names, prop.value);
5852 }
5853 }
5854 },
5855 RestElement(names, param) {
5856 extractors[param.argument.type](names, param.argument);
5857 }
5858};
5859const extractAssignedNames = function extractAssignedNames(param) {
5860 const names = [];
5861 extractors[param.type](names, param);
5862 return names;
5863};
5864
5865class ExportAllDeclaration extends NodeBase {
5866 hasEffects() {
5867 return false;
5868 }
5869 initialise() {
5870 this.context.addExport(this);
5871 }
5872 render(code, _options, nodeRenderOptions) {
5873 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
5874 }
5875}
5876ExportAllDeclaration.prototype.needsBoundaries = true;
5877
5878class ArrayExpression extends NodeBase {
5879 bind() {
5880 super.bind();
5881 for (const element of this.elements) {
5882 if (element !== null)
5883 element.deoptimizePath(UNKNOWN_PATH);
5884 }
5885 }
5886 getReturnExpressionWhenCalledAtPath(path) {
5887 if (path.length !== 1)
5888 return UNKNOWN_EXPRESSION;
5889 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
5890 }
5891 hasEffectsWhenAccessedAtPath(path) {
5892 return path.length > 1;
5893 }
5894 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5895 if (path.length === 1) {
5896 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
5897 }
5898 return true;
5899 }
5900}
5901
5902class ArrayPattern extends NodeBase {
5903 addExportedVariables(variables, exportNamesByVariable) {
5904 for (const element of this.elements) {
5905 if (element !== null) {
5906 element.addExportedVariables(variables, exportNamesByVariable);
5907 }
5908 }
5909 }
5910 declare(kind) {
5911 const variables = [];
5912 for (const element of this.elements) {
5913 if (element !== null) {
5914 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
5915 }
5916 }
5917 return variables;
5918 }
5919 deoptimizePath(path) {
5920 if (path.length === 0) {
5921 for (const element of this.elements) {
5922 if (element !== null) {
5923 element.deoptimizePath(path);
5924 }
5925 }
5926 }
5927 }
5928 hasEffectsWhenAssignedAtPath(path, context) {
5929 if (path.length > 0)
5930 return true;
5931 for (const element of this.elements) {
5932 if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
5933 return true;
5934 }
5935 return false;
5936 }
5937}
5938
5939class BlockScope extends ChildScope {
5940 addDeclaration(identifier, context, init, isHoisted) {
5941 if (isHoisted) {
5942 return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, isHoisted);
5943 }
5944 else {
5945 return super.addDeclaration(identifier, context, init, false);
5946 }
5947 }
5948}
5949
5950class ExpressionStatement$1 extends NodeBase {
5951 initialise() {
5952 if (this.directive &&
5953 this.directive !== 'use strict' &&
5954 this.parent.type === Program) {
5955 this.context.warn(
5956 // This is necessary, because either way (deleting or not) can lead to errors.
5957 {
5958 code: 'MODULE_LEVEL_DIRECTIVE',
5959 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
5960 }, this.start);
5961 }
5962 }
5963 render(code, options) {
5964 super.render(code, options);
5965 if (this.included)
5966 this.insertSemicolon(code);
5967 }
5968 shouldBeIncluded(context) {
5969 if (this.directive && this.directive !== 'use strict')
5970 return this.parent.type !== Program;
5971 return super.shouldBeIncluded(context);
5972 }
5973}
5974
5975class BlockStatement$1 extends NodeBase {
5976 constructor() {
5977 super(...arguments);
5978 this.directlyIncluded = false;
5979 }
5980 addImplicitReturnExpressionToScope() {
5981 const lastStatement = this.body[this.body.length - 1];
5982 if (!lastStatement || lastStatement.type !== ReturnStatement) {
5983 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
5984 }
5985 }
5986 createScope(parentScope) {
5987 this.scope = this.parent.preventChildBlockScope
5988 ? parentScope
5989 : new BlockScope(parentScope);
5990 }
5991 hasEffects(context) {
5992 if (this.deoptimizeBody)
5993 return true;
5994 for (const node of this.body) {
5995 if (node.hasEffects(context))
5996 return true;
5997 if (context.brokenFlow)
5998 break;
5999 }
6000 return false;
6001 }
6002 include(context, includeChildrenRecursively) {
6003 if (!this.deoptimizeBody || !this.directlyIncluded) {
6004 this.included = true;
6005 this.directlyIncluded = true;
6006 if (this.deoptimizeBody)
6007 includeChildrenRecursively = true;
6008 for (const node of this.body) {
6009 if (includeChildrenRecursively || node.shouldBeIncluded(context))
6010 node.include(context, includeChildrenRecursively);
6011 }
6012 }
6013 }
6014 initialise() {
6015 const firstBodyStatement = this.body[0];
6016 this.deoptimizeBody =
6017 firstBodyStatement instanceof ExpressionStatement$1 &&
6018 firstBodyStatement.directive === 'use asm';
6019 }
6020 render(code, options) {
6021 if (this.body.length) {
6022 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
6023 }
6024 else {
6025 super.render(code, options);
6026 }
6027 }
6028}
6029
6030class ArrowFunctionExpression$1 extends NodeBase {
6031 createScope(parentScope) {
6032 this.scope = new ReturnValueScope(parentScope, this.context);
6033 }
6034 deoptimizePath(path) {
6035 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
6036 // which means the return expression needs to be reassigned
6037 if (path.length === 1 && path[0] === UnknownKey) {
6038 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
6039 }
6040 }
6041 getReturnExpressionWhenCalledAtPath(path) {
6042 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
6043 }
6044 hasEffects() {
6045 return false;
6046 }
6047 hasEffectsWhenAccessedAtPath(path) {
6048 return path.length > 1;
6049 }
6050 hasEffectsWhenAssignedAtPath(path) {
6051 return path.length > 1;
6052 }
6053 hasEffectsWhenCalledAtPath(path, _callOptions, context) {
6054 if (path.length > 0)
6055 return true;
6056 for (const param of this.params) {
6057 if (param.hasEffects(context))
6058 return true;
6059 }
6060 const { ignore, brokenFlow } = context;
6061 context.ignore = {
6062 breaks: false,
6063 continues: false,
6064 labels: new Set(),
6065 returnAwaitYield: true
6066 };
6067 if (this.body.hasEffects(context))
6068 return true;
6069 context.ignore = ignore;
6070 context.brokenFlow = brokenFlow;
6071 return false;
6072 }
6073 include(context, includeChildrenRecursively) {
6074 this.included = true;
6075 for (const param of this.params) {
6076 if (!(param instanceof Identifier$1)) {
6077 param.include(context, includeChildrenRecursively);
6078 }
6079 }
6080 const { brokenFlow } = context;
6081 context.brokenFlow = BROKEN_FLOW_NONE;
6082 this.body.include(context, includeChildrenRecursively);
6083 context.brokenFlow = brokenFlow;
6084 }
6085 includeCallArguments(context, args) {
6086 this.scope.includeCallArguments(context, args);
6087 }
6088 initialise() {
6089 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
6090 if (this.body instanceof BlockStatement$1) {
6091 this.body.addImplicitReturnExpressionToScope();
6092 }
6093 else {
6094 this.scope.addReturnExpression(this.body);
6095 }
6096 }
6097 parseNode(esTreeNode) {
6098 if (esTreeNode.body.type === BlockStatement) {
6099 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
6100 }
6101 super.parseNode(esTreeNode);
6102 }
6103}
6104ArrowFunctionExpression$1.prototype.preventChildBlockScope = true;
6105
6106class AssignmentExpression extends NodeBase {
6107 constructor() {
6108 super(...arguments);
6109 this.deoptimized = false;
6110 }
6111 hasEffects(context) {
6112 if (!this.deoptimized)
6113 this.applyDeoptimizations();
6114 return (this.right.hasEffects(context) ||
6115 this.left.hasEffects(context) ||
6116 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
6117 }
6118 hasEffectsWhenAccessedAtPath(path, context) {
6119 return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
6120 }
6121 include(context, includeChildrenRecursively) {
6122 if (!this.deoptimized)
6123 this.applyDeoptimizations();
6124 this.included = true;
6125 this.left.include(context, includeChildrenRecursively);
6126 this.right.include(context, includeChildrenRecursively);
6127 }
6128 render(code, options) {
6129 this.left.render(code, options);
6130 this.right.render(code, options);
6131 if (options.format === 'system') {
6132 const exportNames = this.left.variable && options.exportNamesByVariable.get(this.left.variable);
6133 if (this.left.type === 'Identifier' && exportNames) {
6134 const _ = options.compact ? '' : ' ';
6135 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
6136 const operation = this.operator.length > 1 ? `${exportNames[0]}${_}${this.operator.slice(0, -1)}${_}` : '';
6137 code.overwrite(operatorPos, findNonWhiteSpace(code.original, operatorPos + this.operator.length), `=${_}${exportNames.length === 1
6138 ? `exports('${exportNames[0]}',${_}`
6139 : getSystemExportFunctionLeft([this.left.variable], false, options)}${operation}`);
6140 code.appendLeft(this.right.end, ')');
6141 }
6142 else {
6143 const systemPatternExports = [];
6144 this.left.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
6145 if (systemPatternExports.length > 0) {
6146 code.prependRight(this.start, getSystemExportFunctionLeft(systemPatternExports, true, options));
6147 code.appendLeft(this.end, ')');
6148 }
6149 }
6150 }
6151 }
6152 applyDeoptimizations() {
6153 this.deoptimized = true;
6154 this.left.deoptimizePath(EMPTY_PATH);
6155 this.right.deoptimizePath(UNKNOWN_PATH);
6156 }
6157}
6158
6159class AssignmentPattern extends NodeBase {
6160 addExportedVariables(variables, exportNamesByVariable) {
6161 this.left.addExportedVariables(variables, exportNamesByVariable);
6162 }
6163 bind() {
6164 super.bind();
6165 this.left.deoptimizePath(EMPTY_PATH);
6166 this.right.deoptimizePath(UNKNOWN_PATH);
6167 }
6168 declare(kind, init) {
6169 return this.left.declare(kind, init);
6170 }
6171 deoptimizePath(path) {
6172 path.length === 0 && this.left.deoptimizePath(path);
6173 }
6174 hasEffectsWhenAssignedAtPath(path, context) {
6175 return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
6176 }
6177 render(code, options, { isShorthandProperty } = BLANK) {
6178 this.left.render(code, options, { isShorthandProperty });
6179 this.right.render(code, options);
6180 }
6181}
6182
6183class AwaitExpression extends NodeBase {
6184 hasEffects(context) {
6185 return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
6186 }
6187 include(context, includeChildrenRecursively) {
6188 if (!this.included) {
6189 this.included = true;
6190 checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
6191 let parent = this.parent;
6192 do {
6193 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression$1)
6194 break checkTopLevelAwait;
6195 } while ((parent = parent.parent));
6196 this.context.usesTopLevelAwait = true;
6197 }
6198 }
6199 this.argument.include(context, includeChildrenRecursively);
6200 }
6201}
6202
6203const binaryOperators = {
6204 '!=': (left, right) => left != right,
6205 '!==': (left, right) => left !== right,
6206 '%': (left, right) => left % right,
6207 '&': (left, right) => left & right,
6208 '*': (left, right) => left * right,
6209 // At the moment, "**" will be transpiled to Math.pow
6210 '**': (left, right) => left ** right,
6211 '+': (left, right) => left + right,
6212 '-': (left, right) => left - right,
6213 '/': (left, right) => left / right,
6214 '<': (left, right) => left < right,
6215 '<<': (left, right) => left << right,
6216 '<=': (left, right) => left <= right,
6217 '==': (left, right) => left == right,
6218 '===': (left, right) => left === right,
6219 '>': (left, right) => left > right,
6220 '>=': (left, right) => left >= right,
6221 '>>': (left, right) => left >> right,
6222 '>>>': (left, right) => left >>> right,
6223 '^': (left, right) => left ^ right,
6224 in: () => UnknownValue,
6225 instanceof: () => UnknownValue,
6226 '|': (left, right) => left | right
6227};
6228class BinaryExpression extends NodeBase {
6229 deoptimizeCache() { }
6230 getLiteralValueAtPath(path, recursionTracker, origin) {
6231 if (path.length > 0)
6232 return UnknownValue;
6233 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6234 if (leftValue === UnknownValue)
6235 return UnknownValue;
6236 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6237 if (rightValue === UnknownValue)
6238 return UnknownValue;
6239 const operatorFn = binaryOperators[this.operator];
6240 if (!operatorFn)
6241 return UnknownValue;
6242 return operatorFn(leftValue, rightValue);
6243 }
6244 hasEffects(context) {
6245 // support some implicit type coercion runtime errors
6246 if (this.operator === '+' &&
6247 this.parent instanceof ExpressionStatement$1 &&
6248 this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this) === '')
6249 return true;
6250 return super.hasEffects(context);
6251 }
6252 hasEffectsWhenAccessedAtPath(path) {
6253 return path.length > 1;
6254 }
6255}
6256
6257class BreakStatement extends NodeBase {
6258 hasEffects(context) {
6259 if (this.label) {
6260 if (!context.ignore.labels.has(this.label.name))
6261 return true;
6262 context.includedLabels.add(this.label.name);
6263 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
6264 }
6265 else {
6266 if (!context.ignore.breaks)
6267 return true;
6268 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
6269 }
6270 return false;
6271 }
6272 include(context) {
6273 this.included = true;
6274 if (this.label) {
6275 this.label.include();
6276 context.includedLabels.add(this.label.name);
6277 }
6278 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
6279 }
6280}
6281
6282class Literal extends NodeBase {
6283 getLiteralValueAtPath(path) {
6284 if (path.length > 0 ||
6285 // unknown literals can also be null but do not start with an "n"
6286 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
6287 typeof this.value === 'bigint' ||
6288 // to support shims for regular expressions
6289 this.context.code.charCodeAt(this.start) === 47) {
6290 return UnknownValue;
6291 }
6292 return this.value;
6293 }
6294 getReturnExpressionWhenCalledAtPath(path) {
6295 if (path.length !== 1)
6296 return UNKNOWN_EXPRESSION;
6297 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
6298 }
6299 hasEffectsWhenAccessedAtPath(path) {
6300 if (this.value === null) {
6301 return path.length > 0;
6302 }
6303 return path.length > 1;
6304 }
6305 hasEffectsWhenAssignedAtPath(path) {
6306 return path.length > 0;
6307 }
6308 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6309 if (path.length === 1) {
6310 return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
6311 }
6312 return true;
6313 }
6314 initialise() {
6315 this.members = getLiteralMembersForValue(this.value);
6316 }
6317 parseNode(esTreeNode) {
6318 this.value = esTreeNode.value;
6319 this.regex = esTreeNode.regex;
6320 super.parseNode(esTreeNode);
6321 }
6322 render(code) {
6323 if (typeof this.value === 'string') {
6324 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
6325 }
6326 }
6327}
6328
6329function getResolvablePropertyKey(memberExpression) {
6330 return memberExpression.computed
6331 ? getResolvableComputedPropertyKey(memberExpression.property)
6332 : memberExpression.property.name;
6333}
6334function getResolvableComputedPropertyKey(propertyKey) {
6335 if (propertyKey instanceof Literal) {
6336 return String(propertyKey.value);
6337 }
6338 return null;
6339}
6340function getPathIfNotComputed(memberExpression) {
6341 const nextPathKey = memberExpression.propertyKey;
6342 const object = memberExpression.object;
6343 if (typeof nextPathKey === 'string') {
6344 if (object instanceof Identifier$1) {
6345 return [
6346 { key: object.name, pos: object.start },
6347 { key: nextPathKey, pos: memberExpression.property.start }
6348 ];
6349 }
6350 if (object instanceof MemberExpression) {
6351 const parentPath = getPathIfNotComputed(object);
6352 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
6353 }
6354 }
6355 return null;
6356}
6357function getStringFromPath(path) {
6358 let pathString = path[0].key;
6359 for (let index = 1; index < path.length; index++) {
6360 pathString += '.' + path[index].key;
6361 }
6362 return pathString;
6363}
6364class MemberExpression extends NodeBase {
6365 constructor() {
6366 super(...arguments);
6367 this.variable = null;
6368 this.bound = false;
6369 this.expressionsToBeDeoptimized = [];
6370 this.replacement = null;
6371 this.wasPathDeoptimizedWhileOptimized = false;
6372 }
6373 addExportedVariables() { }
6374 bind() {
6375 if (this.bound)
6376 return;
6377 this.bound = true;
6378 const path = getPathIfNotComputed(this);
6379 const baseVariable = path && this.scope.findVariable(path[0].key);
6380 if (baseVariable && baseVariable.isNamespace) {
6381 const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
6382 if (!resolvedVariable) {
6383 super.bind();
6384 }
6385 else if (typeof resolvedVariable === 'string') {
6386 this.replacement = resolvedVariable;
6387 }
6388 else {
6389 if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
6390 resolvedVariable.module.suggestName(path[0].key);
6391 }
6392 this.variable = resolvedVariable;
6393 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
6394 }
6395 }
6396 else {
6397 super.bind();
6398 // ensure the propertyKey is set for the tree-shaking passes
6399 this.getPropertyKey();
6400 }
6401 }
6402 deoptimizeCache() {
6403 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6404 this.expressionsToBeDeoptimized = [];
6405 this.propertyKey = UnknownKey;
6406 if (this.wasPathDeoptimizedWhileOptimized) {
6407 this.object.deoptimizePath(UNKNOWN_PATH);
6408 }
6409 for (const expression of expressionsToBeDeoptimized) {
6410 expression.deoptimizeCache();
6411 }
6412 }
6413 deoptimizePath(path) {
6414 if (!this.bound)
6415 this.bind();
6416 if (path.length === 0)
6417 this.disallowNamespaceReassignment();
6418 if (this.variable) {
6419 this.variable.deoptimizePath(path);
6420 }
6421 else {
6422 const propertyKey = this.getPropertyKey();
6423 if (propertyKey === UnknownKey) {
6424 this.object.deoptimizePath(UNKNOWN_PATH);
6425 }
6426 else {
6427 this.wasPathDeoptimizedWhileOptimized = true;
6428 this.object.deoptimizePath([propertyKey, ...path]);
6429 }
6430 }
6431 }
6432 getLiteralValueAtPath(path, recursionTracker, origin) {
6433 if (!this.bound)
6434 this.bind();
6435 if (this.variable !== null) {
6436 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
6437 }
6438 this.expressionsToBeDeoptimized.push(origin);
6439 return this.object.getLiteralValueAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
6440 }
6441 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6442 if (!this.bound)
6443 this.bind();
6444 if (this.variable !== null) {
6445 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6446 }
6447 this.expressionsToBeDeoptimized.push(origin);
6448 return this.object.getReturnExpressionWhenCalledAtPath([this.getPropertyKey(), ...path], recursionTracker, origin);
6449 }
6450 hasEffects(context) {
6451 return (this.property.hasEffects(context) ||
6452 this.object.hasEffects(context) ||
6453 (this.context.options.treeshake.propertyReadSideEffects &&
6454 this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
6455 }
6456 hasEffectsWhenAccessedAtPath(path, context) {
6457 if (path.length === 0)
6458 return false;
6459 if (this.variable !== null) {
6460 return this.variable.hasEffectsWhenAccessedAtPath(path, context);
6461 }
6462 return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
6463 }
6464 hasEffectsWhenAssignedAtPath(path, context) {
6465 if (this.variable !== null) {
6466 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
6467 }
6468 return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
6469 }
6470 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6471 if (this.variable !== null) {
6472 return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
6473 }
6474 return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
6475 }
6476 include(context, includeChildrenRecursively) {
6477 if (!this.included) {
6478 this.included = true;
6479 if (this.variable !== null) {
6480 this.context.includeVariable(this.variable);
6481 }
6482 }
6483 this.object.include(context, includeChildrenRecursively);
6484 this.property.include(context, includeChildrenRecursively);
6485 }
6486 includeCallArguments(context, args) {
6487 if (this.variable) {
6488 this.variable.includeCallArguments(context, args);
6489 }
6490 else {
6491 super.includeCallArguments(context, args);
6492 }
6493 }
6494 initialise() {
6495 this.propertyKey = getResolvablePropertyKey(this);
6496 }
6497 render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
6498 const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
6499 if (this.variable || this.replacement) {
6500 let replacement = this.variable ? this.variable.getName() : this.replacement;
6501 if (isCalleeOfDifferentParent)
6502 replacement = '0, ' + replacement;
6503 code.overwrite(this.start, this.end, replacement, {
6504 contentOnly: true,
6505 storeName: true
6506 });
6507 }
6508 else {
6509 if (isCalleeOfDifferentParent) {
6510 code.appendRight(this.start, '0, ');
6511 }
6512 super.render(code, options);
6513 }
6514 }
6515 disallowNamespaceReassignment() {
6516 if (this.object instanceof Identifier$1) {
6517 const variable = this.scope.findVariable(this.object.name);
6518 if (variable.isNamespace) {
6519 if (this.variable) {
6520 this.context.includeVariable(this.variable);
6521 }
6522 this.context.warn({
6523 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
6524 message: `Illegal reassignment to import '${this.object.name}'`
6525 }, this.start);
6526 }
6527 }
6528 }
6529 getPropertyKey() {
6530 if (this.propertyKey === null) {
6531 this.propertyKey = UnknownKey;
6532 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
6533 return (this.propertyKey = value === UnknownValue ? UnknownKey : String(value));
6534 }
6535 return this.propertyKey;
6536 }
6537 resolveNamespaceVariables(baseVariable, path) {
6538 if (path.length === 0)
6539 return baseVariable;
6540 if (!baseVariable.isNamespace)
6541 return null;
6542 const exportName = path[0].key;
6543 const variable = baseVariable instanceof ExternalVariable
6544 ? baseVariable.module.getVariableForExportName(exportName)
6545 : baseVariable.context.traceExport(exportName);
6546 if (!variable) {
6547 const fileName = baseVariable instanceof ExternalVariable
6548 ? baseVariable.module.id
6549 : baseVariable.context.fileName;
6550 this.context.warn({
6551 code: 'MISSING_EXPORT',
6552 exporter: relativeId(fileName),
6553 importer: relativeId(this.context.fileName),
6554 message: `'${exportName}' is not exported by '${relativeId(fileName)}'`,
6555 missing: exportName,
6556 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
6557 }, path[0].pos);
6558 return 'undefined';
6559 }
6560 return this.resolveNamespaceVariables(variable, path.slice(1));
6561 }
6562}
6563
6564class CallExpression$1 extends NodeBase {
6565 constructor() {
6566 super(...arguments);
6567 this.expressionsToBeDeoptimized = [];
6568 this.returnExpression = null;
6569 this.wasPathDeoptmizedWhileOptimized = false;
6570 }
6571 bind() {
6572 super.bind();
6573 if (this.callee instanceof Identifier$1) {
6574 const variable = this.scope.findVariable(this.callee.name);
6575 if (variable.isNamespace) {
6576 this.context.warn({
6577 code: 'CANNOT_CALL_NAMESPACE',
6578 message: `Cannot call a namespace ('${this.callee.name}')`
6579 }, this.start);
6580 }
6581 if (this.callee.name === 'eval') {
6582 this.context.warn({
6583 code: 'EVAL',
6584 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
6585 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
6586 }, this.start);
6587 }
6588 }
6589 // ensure the returnExpression is set for the tree-shaking passes
6590 this.getReturnExpression(SHARED_RECURSION_TRACKER);
6591 // This deoptimizes "this" for non-namespace calls until we have a better solution
6592 if (this.callee instanceof MemberExpression && !this.callee.variable) {
6593 this.callee.object.deoptimizePath(UNKNOWN_PATH);
6594 }
6595 for (const argument of this.arguments) {
6596 // This will make sure all properties of parameters behave as "unknown"
6597 argument.deoptimizePath(UNKNOWN_PATH);
6598 }
6599 }
6600 deoptimizeCache() {
6601 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
6602 this.returnExpression = null;
6603 const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
6604 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6605 if (returnExpression !== UNKNOWN_EXPRESSION) {
6606 // We need to replace here because is possible new expressions are added
6607 // while we are deoptimizing the old ones
6608 this.expressionsToBeDeoptimized = [];
6609 if (this.wasPathDeoptmizedWhileOptimized) {
6610 returnExpression.deoptimizePath(UNKNOWN_PATH);
6611 this.wasPathDeoptmizedWhileOptimized = false;
6612 }
6613 }
6614 for (const expression of expressionsToBeDeoptimized) {
6615 expression.deoptimizeCache();
6616 }
6617 }
6618 }
6619 deoptimizePath(path) {
6620 if (path.length === 0)
6621 return;
6622 const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
6623 if (trackedEntities.has(this))
6624 return;
6625 trackedEntities.add(this);
6626 const returnExpression = this.getReturnExpression(SHARED_RECURSION_TRACKER);
6627 if (returnExpression !== UNKNOWN_EXPRESSION) {
6628 this.wasPathDeoptmizedWhileOptimized = true;
6629 returnExpression.deoptimizePath(path);
6630 }
6631 }
6632 getLiteralValueAtPath(path, recursionTracker, origin) {
6633 const returnExpression = this.getReturnExpression(recursionTracker);
6634 if (returnExpression === UNKNOWN_EXPRESSION) {
6635 return UnknownValue;
6636 }
6637 const trackedEntities = recursionTracker.getEntities(path);
6638 if (trackedEntities.has(returnExpression)) {
6639 return UnknownValue;
6640 }
6641 this.expressionsToBeDeoptimized.push(origin);
6642 trackedEntities.add(returnExpression);
6643 const value = returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
6644 trackedEntities.delete(returnExpression);
6645 return value;
6646 }
6647 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6648 const returnExpression = this.getReturnExpression(recursionTracker);
6649 if (this.returnExpression === UNKNOWN_EXPRESSION) {
6650 return UNKNOWN_EXPRESSION;
6651 }
6652 const trackedEntities = recursionTracker.getEntities(path);
6653 if (trackedEntities.has(returnExpression)) {
6654 return UNKNOWN_EXPRESSION;
6655 }
6656 this.expressionsToBeDeoptimized.push(origin);
6657 trackedEntities.add(returnExpression);
6658 const value = returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6659 trackedEntities.delete(returnExpression);
6660 return value;
6661 }
6662 hasEffects(context) {
6663 for (const argument of this.arguments) {
6664 if (argument.hasEffects(context))
6665 return true;
6666 }
6667 if (this.context.options.treeshake.annotations &&
6668 this.annotatedPure)
6669 return false;
6670 return (this.callee.hasEffects(context) ||
6671 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
6672 }
6673 hasEffectsWhenAccessedAtPath(path, context) {
6674 if (path.length === 0)
6675 return false;
6676 const trackedExpressions = context.accessed.getEntities(path);
6677 if (trackedExpressions.has(this))
6678 return false;
6679 trackedExpressions.add(this);
6680 return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
6681 }
6682 hasEffectsWhenAssignedAtPath(path, context) {
6683 if (path.length === 0)
6684 return true;
6685 const trackedExpressions = context.assigned.getEntities(path);
6686 if (trackedExpressions.has(this))
6687 return false;
6688 trackedExpressions.add(this);
6689 return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
6690 }
6691 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6692 const trackedExpressions = (callOptions.withNew
6693 ? context.instantiated
6694 : context.called).getEntities(path, callOptions);
6695 if (trackedExpressions.has(this))
6696 return false;
6697 trackedExpressions.add(this);
6698 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
6699 }
6700 include(context, includeChildrenRecursively) {
6701 if (includeChildrenRecursively) {
6702 super.include(context, includeChildrenRecursively);
6703 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
6704 this.callee instanceof Identifier$1 &&
6705 this.callee.variable) {
6706 this.callee.variable.markCalledFromTryStatement();
6707 }
6708 }
6709 else {
6710 this.included = true;
6711 this.callee.include(context, false);
6712 }
6713 this.callee.includeCallArguments(context, this.arguments);
6714 if (!this.returnExpression.included) {
6715 this.returnExpression.include(context, false);
6716 }
6717 }
6718 initialise() {
6719 this.callOptions = {
6720 args: this.arguments,
6721 withNew: false
6722 };
6723 }
6724 render(code, options, { renderedParentType } = BLANK) {
6725 this.callee.render(code, options);
6726 if (this.arguments.length > 0) {
6727 if (this.arguments[this.arguments.length - 1].included) {
6728 for (const arg of this.arguments) {
6729 arg.render(code, options);
6730 }
6731 }
6732 else {
6733 let lastIncludedIndex = this.arguments.length - 2;
6734 while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
6735 lastIncludedIndex--;
6736 }
6737 if (lastIncludedIndex >= 0) {
6738 for (let index = 0; index <= lastIncludedIndex; index++) {
6739 this.arguments[index].render(code, options);
6740 }
6741 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
6742 }
6743 else {
6744 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
6745 }
6746 }
6747 }
6748 if (renderedParentType === ExpressionStatement &&
6749 this.callee.type === FunctionExpression) {
6750 code.appendRight(this.start, '(');
6751 code.prependLeft(this.end, ')');
6752 }
6753 }
6754 getReturnExpression(recursionTracker) {
6755 if (this.returnExpression === null) {
6756 this.returnExpression = UNKNOWN_EXPRESSION;
6757 return (this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this));
6758 }
6759 return this.returnExpression;
6760 }
6761}
6762
6763class CatchScope extends ParameterScope {
6764 addDeclaration(identifier, context, init, isHoisted) {
6765 if (isHoisted) {
6766 return this.parent.addDeclaration(identifier, context, init, isHoisted);
6767 }
6768 else {
6769 return super.addDeclaration(identifier, context, init, false);
6770 }
6771 }
6772}
6773
6774class CatchClause extends NodeBase {
6775 createScope(parentScope) {
6776 this.scope = new CatchScope(parentScope, this.context);
6777 }
6778 initialise() {
6779 if (this.param) {
6780 this.param.declare('parameter', UNKNOWN_EXPRESSION);
6781 }
6782 }
6783 parseNode(esTreeNode) {
6784 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
6785 super.parseNode(esTreeNode);
6786 }
6787}
6788CatchClause.prototype.preventChildBlockScope = true;
6789
6790class ChainExpression extends NodeBase {
6791}
6792
6793class ClassBodyScope extends ChildScope {
6794 findLexicalBoundary() {
6795 return this;
6796 }
6797}
6798
6799class MethodDefinition extends NodeBase {
6800 hasEffects(context) {
6801 return this.key.hasEffects(context);
6802 }
6803 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6804 return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
6805 }
6806}
6807
6808class ClassBody extends NodeBase {
6809 createScope(parentScope) {
6810 this.scope = new ClassBodyScope(parentScope);
6811 }
6812 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6813 if (path.length > 0)
6814 return true;
6815 return (this.classConstructor !== null &&
6816 this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
6817 }
6818 initialise() {
6819 for (const method of this.body) {
6820 if (method instanceof MethodDefinition && method.kind === 'constructor') {
6821 this.classConstructor = method;
6822 return;
6823 }
6824 }
6825 this.classConstructor = null;
6826 }
6827}
6828
6829class ClassExpression extends ClassNode {
6830}
6831
6832class MultiExpression {
6833 constructor(expressions) {
6834 this.included = false;
6835 this.expressions = expressions;
6836 }
6837 deoptimizePath(path) {
6838 for (const expression of this.expressions) {
6839 expression.deoptimizePath(path);
6840 }
6841 }
6842 getLiteralValueAtPath() {
6843 return UnknownValue;
6844 }
6845 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6846 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
6847 }
6848 hasEffectsWhenAccessedAtPath(path, context) {
6849 for (const expression of this.expressions) {
6850 if (expression.hasEffectsWhenAccessedAtPath(path, context))
6851 return true;
6852 }
6853 return false;
6854 }
6855 hasEffectsWhenAssignedAtPath(path, context) {
6856 for (const expression of this.expressions) {
6857 if (expression.hasEffectsWhenAssignedAtPath(path, context))
6858 return true;
6859 }
6860 return false;
6861 }
6862 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6863 for (const expression of this.expressions) {
6864 if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
6865 return true;
6866 }
6867 return false;
6868 }
6869 include(context, includeChildrenRecursively) {
6870 // This is only relevant to include values that do not have an AST representation,
6871 // such as UnknownArrayExpression. Thus we only need to include them once.
6872 for (const expression of this.expressions) {
6873 if (!expression.included) {
6874 expression.include(context, includeChildrenRecursively);
6875 }
6876 }
6877 }
6878 includeCallArguments() { }
6879}
6880
6881class ConditionalExpression extends NodeBase {
6882 constructor() {
6883 super(...arguments);
6884 this.expressionsToBeDeoptimized = [];
6885 this.isBranchResolutionAnalysed = false;
6886 this.usedBranch = null;
6887 this.wasPathDeoptimizedWhileOptimized = false;
6888 }
6889 bind() {
6890 super.bind();
6891 // ensure the usedBranch is set for the tree-shaking passes
6892 this.getUsedBranch();
6893 }
6894 deoptimizeCache() {
6895 if (this.usedBranch !== null) {
6896 const unusedBranch = this.usedBranch === this.consequent ? this.alternate : this.consequent;
6897 this.usedBranch = null;
6898 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
6899 this.expressionsToBeDeoptimized = [];
6900 if (this.wasPathDeoptimizedWhileOptimized) {
6901 unusedBranch.deoptimizePath(UNKNOWN_PATH);
6902 }
6903 for (const expression of expressionsToBeDeoptimized) {
6904 expression.deoptimizeCache();
6905 }
6906 }
6907 }
6908 deoptimizePath(path) {
6909 if (path.length > 0) {
6910 const usedBranch = this.getUsedBranch();
6911 if (usedBranch === null) {
6912 this.consequent.deoptimizePath(path);
6913 this.alternate.deoptimizePath(path);
6914 }
6915 else {
6916 this.wasPathDeoptimizedWhileOptimized = true;
6917 usedBranch.deoptimizePath(path);
6918 }
6919 }
6920 }
6921 getLiteralValueAtPath(path, recursionTracker, origin) {
6922 const usedBranch = this.getUsedBranch();
6923 if (usedBranch === null)
6924 return UnknownValue;
6925 this.expressionsToBeDeoptimized.push(origin);
6926 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
6927 }
6928 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6929 const usedBranch = this.getUsedBranch();
6930 if (usedBranch === null)
6931 return new MultiExpression([
6932 this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
6933 this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
6934 ]);
6935 this.expressionsToBeDeoptimized.push(origin);
6936 return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6937 }
6938 hasEffects(context) {
6939 if (this.test.hasEffects(context))
6940 return true;
6941 if (this.usedBranch === null) {
6942 return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
6943 }
6944 return this.usedBranch.hasEffects(context);
6945 }
6946 hasEffectsWhenAccessedAtPath(path, context) {
6947 if (path.length === 0)
6948 return false;
6949 if (this.usedBranch === null) {
6950 return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
6951 this.alternate.hasEffectsWhenAccessedAtPath(path, context));
6952 }
6953 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
6954 }
6955 hasEffectsWhenAssignedAtPath(path, context) {
6956 if (path.length === 0)
6957 return true;
6958 if (this.usedBranch === null) {
6959 return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
6960 this.alternate.hasEffectsWhenAssignedAtPath(path, context));
6961 }
6962 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
6963 }
6964 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6965 if (this.usedBranch === null) {
6966 return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
6967 this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
6968 }
6969 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
6970 }
6971 include(context, includeChildrenRecursively) {
6972 this.included = true;
6973 if (includeChildrenRecursively ||
6974 this.test.shouldBeIncluded(context) ||
6975 this.usedBranch === null) {
6976 this.test.include(context, includeChildrenRecursively);
6977 this.consequent.include(context, includeChildrenRecursively);
6978 this.alternate.include(context, includeChildrenRecursively);
6979 }
6980 else {
6981 this.usedBranch.include(context, includeChildrenRecursively);
6982 }
6983 }
6984 includeCallArguments(context, args) {
6985 if (this.usedBranch === null) {
6986 this.consequent.includeCallArguments(context, args);
6987 this.alternate.includeCallArguments(context, args);
6988 }
6989 else {
6990 this.usedBranch.includeCallArguments(context, args);
6991 }
6992 }
6993 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
6994 if (!this.test.included) {
6995 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
6996 const inclusionStart = (this.consequent.included
6997 ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
6998 : colonPos) + 1;
6999 if (preventASI) {
7000 removeLineBreaks(code, inclusionStart, this.usedBranch.start);
7001 }
7002 code.remove(this.start, inclusionStart);
7003 if (this.consequent.included) {
7004 code.remove(colonPos, this.end);
7005 }
7006 removeAnnotations(this, code);
7007 this.usedBranch.render(code, options, {
7008 isCalleeOfRenderedParent: renderedParentType
7009 ? isCalleeOfRenderedParent
7010 : this.parent.callee === this,
7011 preventASI: true,
7012 renderedParentType: renderedParentType || this.parent.type
7013 });
7014 }
7015 else {
7016 super.render(code, options);
7017 }
7018 }
7019 getUsedBranch() {
7020 if (this.isBranchResolutionAnalysed) {
7021 return this.usedBranch;
7022 }
7023 this.isBranchResolutionAnalysed = true;
7024 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
7025 return testValue === UnknownValue
7026 ? null
7027 : (this.usedBranch = testValue ? this.consequent : this.alternate);
7028 }
7029}
7030
7031class ContinueStatement extends NodeBase {
7032 hasEffects(context) {
7033 if (this.label) {
7034 if (!context.ignore.labels.has(this.label.name))
7035 return true;
7036 context.includedLabels.add(this.label.name);
7037 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
7038 }
7039 else {
7040 if (!context.ignore.continues)
7041 return true;
7042 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
7043 }
7044 return false;
7045 }
7046 include(context) {
7047 this.included = true;
7048 if (this.label) {
7049 this.label.include();
7050 context.includedLabels.add(this.label.name);
7051 }
7052 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
7053 }
7054}
7055
7056class DoWhileStatement extends NodeBase {
7057 hasEffects(context) {
7058 if (this.test.hasEffects(context))
7059 return true;
7060 const { brokenFlow, ignore: { breaks, continues } } = context;
7061 context.ignore.breaks = true;
7062 context.ignore.continues = true;
7063 if (this.body.hasEffects(context))
7064 return true;
7065 context.ignore.breaks = breaks;
7066 context.ignore.continues = continues;
7067 context.brokenFlow = brokenFlow;
7068 return false;
7069 }
7070 include(context, includeChildrenRecursively) {
7071 this.included = true;
7072 this.test.include(context, includeChildrenRecursively);
7073 const { brokenFlow } = context;
7074 this.body.include(context, includeChildrenRecursively);
7075 context.brokenFlow = brokenFlow;
7076 }
7077}
7078
7079class EmptyStatement extends NodeBase {
7080 hasEffects() {
7081 return false;
7082 }
7083}
7084
7085class ExportNamedDeclaration extends NodeBase {
7086 bind() {
7087 // Do not bind specifiers
7088 if (this.declaration !== null)
7089 this.declaration.bind();
7090 }
7091 hasEffects(context) {
7092 return this.declaration !== null && this.declaration.hasEffects(context);
7093 }
7094 initialise() {
7095 this.context.addExport(this);
7096 }
7097 render(code, options, nodeRenderOptions) {
7098 const { start, end } = nodeRenderOptions;
7099 if (this.declaration === null) {
7100 code.remove(start, end);
7101 }
7102 else {
7103 code.remove(this.start, this.declaration.start);
7104 this.declaration.render(code, options, { start, end });
7105 }
7106 }
7107}
7108ExportNamedDeclaration.prototype.needsBoundaries = true;
7109
7110class ExportSpecifier extends NodeBase {
7111}
7112
7113class FieldDefinition extends NodeBase {
7114 hasEffects(context) {
7115 return (this.key.hasEffects(context) ||
7116 (this.static && this.value !== null && this.value.hasEffects(context)));
7117 }
7118}
7119
7120class ForInStatement extends NodeBase {
7121 bind() {
7122 this.left.bind();
7123 this.left.deoptimizePath(EMPTY_PATH);
7124 this.right.bind();
7125 this.body.bind();
7126 }
7127 createScope(parentScope) {
7128 this.scope = new BlockScope(parentScope);
7129 }
7130 hasEffects(context) {
7131 if ((this.left &&
7132 (this.left.hasEffects(context) ||
7133 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
7134 (this.right && this.right.hasEffects(context)))
7135 return true;
7136 const { brokenFlow, ignore: { breaks, continues } } = context;
7137 context.ignore.breaks = true;
7138 context.ignore.continues = true;
7139 if (this.body.hasEffects(context))
7140 return true;
7141 context.ignore.breaks = breaks;
7142 context.ignore.continues = continues;
7143 context.brokenFlow = brokenFlow;
7144 return false;
7145 }
7146 include(context, includeChildrenRecursively) {
7147 this.included = true;
7148 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
7149 this.left.deoptimizePath(EMPTY_PATH);
7150 this.right.include(context, includeChildrenRecursively);
7151 const { brokenFlow } = context;
7152 this.body.include(context, includeChildrenRecursively);
7153 context.brokenFlow = brokenFlow;
7154 }
7155 render(code, options) {
7156 this.left.render(code, options, NO_SEMICOLON);
7157 this.right.render(code, options, NO_SEMICOLON);
7158 // handle no space between "in" and the right side
7159 if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
7160 code.prependLeft(this.right.start, ' ');
7161 }
7162 this.body.render(code, options);
7163 }
7164}
7165
7166class ForOfStatement extends NodeBase {
7167 bind() {
7168 this.left.bind();
7169 this.left.deoptimizePath(EMPTY_PATH);
7170 this.right.bind();
7171 this.body.bind();
7172 }
7173 createScope(parentScope) {
7174 this.scope = new BlockScope(parentScope);
7175 }
7176 hasEffects() {
7177 // Placeholder until proper Symbol.Iterator support
7178 return true;
7179 }
7180 include(context, includeChildrenRecursively) {
7181 this.included = true;
7182 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
7183 this.left.deoptimizePath(EMPTY_PATH);
7184 this.right.include(context, includeChildrenRecursively);
7185 const { brokenFlow } = context;
7186 this.body.include(context, includeChildrenRecursively);
7187 context.brokenFlow = brokenFlow;
7188 }
7189 render(code, options) {
7190 this.left.render(code, options, NO_SEMICOLON);
7191 this.right.render(code, options, NO_SEMICOLON);
7192 // handle no space between "of" and the right side
7193 if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
7194 code.prependLeft(this.right.start, ' ');
7195 }
7196 this.body.render(code, options);
7197 }
7198}
7199
7200class ForStatement extends NodeBase {
7201 createScope(parentScope) {
7202 this.scope = new BlockScope(parentScope);
7203 }
7204 hasEffects(context) {
7205 if ((this.init && this.init.hasEffects(context)) ||
7206 (this.test && this.test.hasEffects(context)) ||
7207 (this.update && this.update.hasEffects(context)))
7208 return true;
7209 const { brokenFlow, ignore: { breaks, continues } } = context;
7210 context.ignore.breaks = true;
7211 context.ignore.continues = true;
7212 if (this.body.hasEffects(context))
7213 return true;
7214 context.ignore.breaks = breaks;
7215 context.ignore.continues = continues;
7216 context.brokenFlow = brokenFlow;
7217 return false;
7218 }
7219 include(context, includeChildrenRecursively) {
7220 this.included = true;
7221 if (this.init)
7222 this.init.include(context, includeChildrenRecursively);
7223 if (this.test)
7224 this.test.include(context, includeChildrenRecursively);
7225 const { brokenFlow } = context;
7226 if (this.update)
7227 this.update.include(context, includeChildrenRecursively);
7228 this.body.include(context, includeChildrenRecursively);
7229 context.brokenFlow = brokenFlow;
7230 }
7231 render(code, options) {
7232 if (this.init)
7233 this.init.render(code, options, NO_SEMICOLON);
7234 if (this.test)
7235 this.test.render(code, options, NO_SEMICOLON);
7236 if (this.update)
7237 this.update.render(code, options, NO_SEMICOLON);
7238 this.body.render(code, options);
7239 }
7240}
7241
7242class FunctionExpression$1 extends FunctionNode {
7243}
7244
7245class TrackingScope extends BlockScope {
7246 constructor() {
7247 super(...arguments);
7248 this.hoistedDeclarations = [];
7249 }
7250 addDeclaration(identifier, context, init, isHoisted) {
7251 this.hoistedDeclarations.push(identifier);
7252 return this.parent.addDeclaration(identifier, context, init, isHoisted);
7253 }
7254}
7255
7256const unset = Symbol('unset');
7257class IfStatement extends NodeBase {
7258 constructor() {
7259 super(...arguments);
7260 this.testValue = unset;
7261 }
7262 deoptimizeCache() {
7263 this.testValue = UnknownValue;
7264 }
7265 hasEffects(context) {
7266 if (this.test.hasEffects(context)) {
7267 return true;
7268 }
7269 const testValue = this.getTestValue();
7270 if (testValue === UnknownValue) {
7271 const { brokenFlow } = context;
7272 if (this.consequent.hasEffects(context))
7273 return true;
7274 const consequentBrokenFlow = context.brokenFlow;
7275 context.brokenFlow = brokenFlow;
7276 if (this.alternate === null)
7277 return false;
7278 if (this.alternate.hasEffects(context))
7279 return true;
7280 context.brokenFlow =
7281 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
7282 return false;
7283 }
7284 return testValue
7285 ? this.consequent.hasEffects(context)
7286 : this.alternate !== null && this.alternate.hasEffects(context);
7287 }
7288 include(context, includeChildrenRecursively) {
7289 this.included = true;
7290 if (includeChildrenRecursively) {
7291 this.includeRecursively(includeChildrenRecursively, context);
7292 }
7293 else {
7294 const testValue = this.getTestValue();
7295 if (testValue === UnknownValue) {
7296 this.includeUnknownTest(context);
7297 }
7298 else {
7299 this.includeKnownTest(context, testValue);
7300 }
7301 }
7302 }
7303 parseNode(esTreeNode) {
7304 this.consequentScope = new TrackingScope(this.scope);
7305 this.consequent = new (this.context.nodeConstructors[esTreeNode.consequent.type] ||
7306 this.context.nodeConstructors.UnknownNode)(esTreeNode.consequent, this, this.consequentScope);
7307 if (esTreeNode.alternate) {
7308 this.alternateScope = new TrackingScope(this.scope);
7309 this.alternate = new (this.context.nodeConstructors[esTreeNode.alternate.type] ||
7310 this.context.nodeConstructors.UnknownNode)(esTreeNode.alternate, this, this.alternateScope);
7311 }
7312 super.parseNode(esTreeNode);
7313 }
7314 render(code, options) {
7315 // Note that unknown test values are always included
7316 const testValue = this.getTestValue();
7317 const hoistedDeclarations = [];
7318 const includesIfElse = this.test.included;
7319 const noTreeshake = !this.context.options.treeshake;
7320 if (includesIfElse) {
7321 this.test.render(code, options);
7322 }
7323 else {
7324 removeAnnotations(this, code);
7325 code.remove(this.start, this.consequent.start);
7326 }
7327 if (this.consequent.included && (noTreeshake || testValue === UnknownValue || testValue)) {
7328 this.consequent.render(code, options);
7329 }
7330 else {
7331 code.overwrite(this.consequent.start, this.consequent.end, includesIfElse ? ';' : '');
7332 hoistedDeclarations.push(...this.consequentScope.hoistedDeclarations);
7333 }
7334 if (this.alternate) {
7335 if (this.alternate.included && (noTreeshake || testValue === UnknownValue || !testValue)) {
7336 if (includesIfElse) {
7337 if (code.original.charCodeAt(this.alternate.start - 1) === 101) {
7338 code.prependLeft(this.alternate.start, ' ');
7339 }
7340 }
7341 else {
7342 code.remove(this.consequent.end, this.alternate.start);
7343 }
7344 this.alternate.render(code, options);
7345 }
7346 else {
7347 if (includesIfElse && this.shouldKeepAlternateBranch()) {
7348 code.overwrite(this.alternate.start, this.end, ';');
7349 }
7350 else {
7351 code.remove(this.consequent.end, this.end);
7352 }
7353 hoistedDeclarations.push(...this.alternateScope.hoistedDeclarations);
7354 }
7355 }
7356 this.renderHoistedDeclarations(hoistedDeclarations, code);
7357 }
7358 getTestValue() {
7359 if (this.testValue === unset) {
7360 return (this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
7361 }
7362 return this.testValue;
7363 }
7364 includeKnownTest(context, testValue) {
7365 if (this.test.shouldBeIncluded(context)) {
7366 this.test.include(context, false);
7367 }
7368 if (testValue && this.consequent.shouldBeIncluded(context)) {
7369 this.consequent.include(context, false);
7370 }
7371 if (this.alternate !== null && !testValue && this.alternate.shouldBeIncluded(context)) {
7372 this.alternate.include(context, false);
7373 }
7374 }
7375 includeRecursively(includeChildrenRecursively, context) {
7376 this.test.include(context, includeChildrenRecursively);
7377 this.consequent.include(context, includeChildrenRecursively);
7378 if (this.alternate !== null) {
7379 this.alternate.include(context, includeChildrenRecursively);
7380 }
7381 }
7382 includeUnknownTest(context) {
7383 this.test.include(context, false);
7384 const { brokenFlow } = context;
7385 let consequentBrokenFlow = BROKEN_FLOW_NONE;
7386 if (this.consequent.shouldBeIncluded(context)) {
7387 this.consequent.include(context, false);
7388 consequentBrokenFlow = context.brokenFlow;
7389 context.brokenFlow = brokenFlow;
7390 }
7391 if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
7392 this.alternate.include(context, false);
7393 context.brokenFlow =
7394 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
7395 }
7396 }
7397 renderHoistedDeclarations(hoistedDeclarations, code) {
7398 const hoistedVars = [
7399 ...new Set(hoistedDeclarations.map(identifier => {
7400 const variable = identifier.variable;
7401 return variable.included ? variable.getName() : '';
7402 }))
7403 ]
7404 .filter(Boolean)
7405 .join(', ');
7406 if (hoistedVars) {
7407 const parentType = this.parent.type;
7408 const needsBraces = parentType !== Program && parentType !== BlockStatement;
7409 code.prependRight(this.start, `${needsBraces ? '{ ' : ''}var ${hoistedVars}; `);
7410 if (needsBraces) {
7411 code.appendLeft(this.end, ` }`);
7412 }
7413 }
7414 }
7415 shouldKeepAlternateBranch() {
7416 let currentParent = this.parent;
7417 do {
7418 if (currentParent instanceof IfStatement && currentParent.alternate) {
7419 return true;
7420 }
7421 if (currentParent instanceof BlockStatement$1) {
7422 return false;
7423 }
7424 currentParent = currentParent.parent;
7425 } while (currentParent);
7426 return false;
7427 }
7428}
7429
7430class ImportDeclaration extends NodeBase {
7431 bind() { }
7432 hasEffects() {
7433 return false;
7434 }
7435 initialise() {
7436 this.context.addImport(this);
7437 }
7438 render(code, _options, nodeRenderOptions) {
7439 code.remove(nodeRenderOptions.start, nodeRenderOptions.end);
7440 }
7441}
7442ImportDeclaration.prototype.needsBoundaries = true;
7443
7444class ImportDefaultSpecifier$1 extends NodeBase {
7445}
7446
7447class ImportExpression extends NodeBase {
7448 constructor() {
7449 super(...arguments);
7450 this.inlineNamespace = null;
7451 this.mechanism = null;
7452 this.resolution = null;
7453 }
7454 hasEffects() {
7455 return true;
7456 }
7457 include(context, includeChildrenRecursively) {
7458 if (!this.included) {
7459 this.included = true;
7460 this.context.includeDynamicImport(this);
7461 this.scope.addAccessedDynamicImport(this);
7462 }
7463 this.source.include(context, includeChildrenRecursively);
7464 }
7465 initialise() {
7466 this.context.addDynamicImport(this);
7467 }
7468 render(code, options) {
7469 if (this.inlineNamespace) {
7470 const _ = options.compact ? '' : ' ';
7471 const s = options.compact ? '' : ';';
7472 code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
7473 return;
7474 }
7475 if (this.mechanism) {
7476 code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, this.mechanism.left);
7477 code.overwrite(this.end - 1, this.end, this.mechanism.right);
7478 }
7479 this.source.render(code, options);
7480 }
7481 renderFinalResolution(code, resolution, namespaceExportName, options) {
7482 code.overwrite(this.source.start, this.source.end, resolution);
7483 if (namespaceExportName) {
7484 const _ = options.compact ? '' : ' ';
7485 const s = options.compact ? '' : ';';
7486 code.prependLeft(this.end, `.then(function${_}(n)${_}{${_}return n.${namespaceExportName}${s}${_}})`);
7487 }
7488 }
7489 setExternalResolution(exportMode, resolution, options, pluginDriver, accessedGlobalsByScope) {
7490 this.resolution = resolution;
7491 const accessedGlobals = [...(accessedImportGlobals[options.format] || [])];
7492 let helper;
7493 ({ helper, mechanism: this.mechanism } = this.getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver));
7494 if (helper) {
7495 accessedGlobals.push(helper);
7496 }
7497 if (accessedGlobals.length > 0) {
7498 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
7499 }
7500 }
7501 setInternalResolution(inlineNamespace) {
7502 this.inlineNamespace = inlineNamespace;
7503 }
7504 getDynamicImportMechanismAndHelper(resolution, exportMode, options, pluginDriver) {
7505 const mechanism = pluginDriver.hookFirstSync('renderDynamicImport', [
7506 {
7507 customResolution: typeof this.resolution === 'string' ? this.resolution : null,
7508 format: options.format,
7509 moduleId: this.context.module.id,
7510 targetModuleId: this.resolution && typeof this.resolution !== 'string' ? this.resolution.id : null
7511 }
7512 ]);
7513 if (mechanism) {
7514 return { helper: null, mechanism };
7515 }
7516 switch (options.format) {
7517 case 'cjs': {
7518 const _ = options.compact ? '' : ' ';
7519 const s = options.compact ? '' : ';';
7520 const leftStart = `Promise.resolve().then(function${_}()${_}{${_}return`;
7521 const helper = this.getInteropHelper(resolution, exportMode, options.interop);
7522 return {
7523 helper,
7524 mechanism: helper
7525 ? {
7526 left: `${leftStart} /*#__PURE__*/${helper}(require(`,
7527 right: `))${s}${_}})`
7528 }
7529 : {
7530 left: `${leftStart} require(`,
7531 right: `)${s}${_}})`
7532 }
7533 };
7534 }
7535 case 'amd': {
7536 const _ = options.compact ? '' : ' ';
7537 const resolve = options.compact ? 'c' : 'resolve';
7538 const reject = options.compact ? 'e' : 'reject';
7539 const helper = this.getInteropHelper(resolution, exportMode, options.interop);
7540 const resolveNamespace = helper
7541 ? `function${_}(m)${_}{${_}${resolve}(/*#__PURE__*/${helper}(m));${_}}`
7542 : resolve;
7543 return {
7544 helper,
7545 mechanism: {
7546 left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
7547 right: `],${_}${resolveNamespace},${_}${reject})${_}})`
7548 }
7549 };
7550 }
7551 case 'system':
7552 return {
7553 helper: null,
7554 mechanism: {
7555 left: 'module.import(',
7556 right: ')'
7557 }
7558 };
7559 case 'es':
7560 if (options.dynamicImportFunction) {
7561 return {
7562 helper: null,
7563 mechanism: {
7564 left: `${options.dynamicImportFunction}(`,
7565 right: ')'
7566 }
7567 };
7568 }
7569 }
7570 return { helper: null, mechanism: null };
7571 }
7572 getInteropHelper(resolution, exportMode, interop) {
7573 return exportMode === 'external'
7574 ? namespaceInteropHelpersByInteropType[String(interop(resolution instanceof ExternalModule ? resolution.id : null))]
7575 : exportMode === 'default'
7576 ? getDefaultOnlyHelper()
7577 : null;
7578 }
7579}
7580const accessedImportGlobals = {
7581 amd: ['require'],
7582 cjs: ['require'],
7583 system: ['module']
7584};
7585
7586class ImportNamespaceSpecifier$1 extends NodeBase {
7587}
7588
7589class ImportSpecifier extends NodeBase {
7590}
7591
7592class LabeledStatement extends NodeBase {
7593 hasEffects(context) {
7594 const brokenFlow = context.brokenFlow;
7595 context.ignore.labels.add(this.label.name);
7596 if (this.body.hasEffects(context))
7597 return true;
7598 context.ignore.labels.delete(this.label.name);
7599 if (context.includedLabels.has(this.label.name)) {
7600 context.includedLabels.delete(this.label.name);
7601 context.brokenFlow = brokenFlow;
7602 }
7603 return false;
7604 }
7605 include(context, includeChildrenRecursively) {
7606 this.included = true;
7607 const brokenFlow = context.brokenFlow;
7608 this.body.include(context, includeChildrenRecursively);
7609 if (includeChildrenRecursively || context.includedLabels.has(this.label.name)) {
7610 this.label.include();
7611 context.includedLabels.delete(this.label.name);
7612 context.brokenFlow = brokenFlow;
7613 }
7614 }
7615 render(code, options) {
7616 if (this.label.included) {
7617 this.label.render(code, options);
7618 }
7619 else {
7620 code.remove(this.start, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1);
7621 }
7622 this.body.render(code, options);
7623 }
7624}
7625
7626class LogicalExpression extends NodeBase {
7627 constructor() {
7628 super(...arguments);
7629 // We collect deoptimization information if usedBranch !== null
7630 this.expressionsToBeDeoptimized = [];
7631 this.isBranchResolutionAnalysed = false;
7632 this.unusedBranch = null;
7633 this.usedBranch = null;
7634 this.wasPathDeoptimizedWhileOptimized = false;
7635 }
7636 bind() {
7637 super.bind();
7638 // ensure the usedBranch is set for the tree-shaking passes
7639 this.getUsedBranch();
7640 }
7641 deoptimizeCache() {
7642 if (this.usedBranch !== null) {
7643 this.usedBranch = null;
7644 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized;
7645 this.expressionsToBeDeoptimized = [];
7646 if (this.wasPathDeoptimizedWhileOptimized) {
7647 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
7648 }
7649 for (const expression of expressionsToBeDeoptimized) {
7650 expression.deoptimizeCache();
7651 }
7652 }
7653 }
7654 deoptimizePath(path) {
7655 const usedBranch = this.getUsedBranch();
7656 if (usedBranch === null) {
7657 this.left.deoptimizePath(path);
7658 this.right.deoptimizePath(path);
7659 }
7660 else {
7661 this.wasPathDeoptimizedWhileOptimized = true;
7662 usedBranch.deoptimizePath(path);
7663 }
7664 }
7665 getLiteralValueAtPath(path, recursionTracker, origin) {
7666 const usedBranch = this.getUsedBranch();
7667 if (usedBranch === null)
7668 return UnknownValue;
7669 this.expressionsToBeDeoptimized.push(origin);
7670 return usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
7671 }
7672 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
7673 const usedBranch = this.getUsedBranch();
7674 if (usedBranch === null)
7675 return new MultiExpression([
7676 this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
7677 this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
7678 ]);
7679 this.expressionsToBeDeoptimized.push(origin);
7680 return usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
7681 }
7682 hasEffects(context) {
7683 if (this.left.hasEffects(context)) {
7684 return true;
7685 }
7686 if (this.usedBranch !== this.left) {
7687 return this.right.hasEffects(context);
7688 }
7689 return false;
7690 }
7691 hasEffectsWhenAccessedAtPath(path, context) {
7692 if (path.length === 0)
7693 return false;
7694 if (this.usedBranch === null) {
7695 return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
7696 this.right.hasEffectsWhenAccessedAtPath(path, context));
7697 }
7698 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
7699 }
7700 hasEffectsWhenAssignedAtPath(path, context) {
7701 if (path.length === 0)
7702 return true;
7703 if (this.usedBranch === null) {
7704 return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
7705 this.right.hasEffectsWhenAssignedAtPath(path, context));
7706 }
7707 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
7708 }
7709 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7710 if (this.usedBranch === null) {
7711 return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
7712 this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
7713 }
7714 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
7715 }
7716 include(context, includeChildrenRecursively) {
7717 this.included = true;
7718 if (includeChildrenRecursively ||
7719 (this.usedBranch === this.right && this.left.shouldBeIncluded(context)) ||
7720 this.usedBranch === null) {
7721 this.left.include(context, includeChildrenRecursively);
7722 this.right.include(context, includeChildrenRecursively);
7723 }
7724 else {
7725 this.usedBranch.include(context, includeChildrenRecursively);
7726 }
7727 }
7728 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
7729 if (!this.left.included || !this.right.included) {
7730 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
7731 if (this.right.included) {
7732 code.remove(this.start, operatorPos + 2);
7733 if (preventASI) {
7734 removeLineBreaks(code, operatorPos + 2, this.right.start);
7735 }
7736 }
7737 else {
7738 code.remove(operatorPos, this.end);
7739 }
7740 removeAnnotations(this, code);
7741 this.usedBranch.render(code, options, {
7742 isCalleeOfRenderedParent: renderedParentType
7743 ? isCalleeOfRenderedParent
7744 : this.parent.callee === this,
7745 preventASI,
7746 renderedParentType: renderedParentType || this.parent.type
7747 });
7748 }
7749 else {
7750 this.left.render(code, options, { preventASI });
7751 this.right.render(code, options);
7752 }
7753 }
7754 getUsedBranch() {
7755 if (!this.isBranchResolutionAnalysed) {
7756 this.isBranchResolutionAnalysed = true;
7757 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
7758 if (leftValue === UnknownValue) {
7759 return null;
7760 }
7761 else {
7762 if ((this.operator === '||' && leftValue) ||
7763 (this.operator === '&&' && !leftValue) ||
7764 (this.operator === '??' && leftValue != null)) {
7765 this.usedBranch = this.left;
7766 this.unusedBranch = this.right;
7767 }
7768 else {
7769 this.usedBranch = this.right;
7770 this.unusedBranch = this.left;
7771 }
7772 }
7773 }
7774 return this.usedBranch;
7775 }
7776}
7777
7778const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
7779const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
7780const FILE_PREFIX = 'ROLLUP_FILE_URL_';
7781class MetaProperty extends NodeBase {
7782 addAccessedGlobals(format, accessedGlobalsByScope) {
7783 const metaProperty = this.metaProperty;
7784 const accessedGlobals = (metaProperty &&
7785 (metaProperty.startsWith(FILE_PREFIX) ||
7786 metaProperty.startsWith(ASSET_PREFIX) ||
7787 metaProperty.startsWith(CHUNK_PREFIX))
7788 ? accessedFileUrlGlobals
7789 : accessedMetaUrlGlobals)[format];
7790 if (accessedGlobals.length > 0) {
7791 this.scope.addAccessedGlobals(accessedGlobals, accessedGlobalsByScope);
7792 }
7793 }
7794 getReferencedFileName(outputPluginDriver) {
7795 const metaProperty = this.metaProperty;
7796 if (metaProperty && metaProperty.startsWith(FILE_PREFIX)) {
7797 return outputPluginDriver.getFileName(metaProperty.substr(FILE_PREFIX.length));
7798 }
7799 return null;
7800 }
7801 hasEffects() {
7802 return false;
7803 }
7804 hasEffectsWhenAccessedAtPath(path) {
7805 return path.length > 1;
7806 }
7807 include() {
7808 if (!this.included) {
7809 this.included = true;
7810 if (this.meta.name === 'import') {
7811 this.context.addImportMeta(this);
7812 const parent = this.parent;
7813 this.metaProperty =
7814 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
7815 ? parent.propertyKey
7816 : null;
7817 }
7818 }
7819 }
7820 renderFinalMechanism(code, chunkId, format, outputPluginDriver) {
7821 var _a;
7822 const parent = this.parent;
7823 const metaProperty = this.metaProperty;
7824 if (metaProperty &&
7825 (metaProperty.startsWith(FILE_PREFIX) ||
7826 metaProperty.startsWith(ASSET_PREFIX) ||
7827 metaProperty.startsWith(CHUNK_PREFIX))) {
7828 let referenceId = null;
7829 let assetReferenceId = null;
7830 let chunkReferenceId = null;
7831 let fileName;
7832 if (metaProperty.startsWith(FILE_PREFIX)) {
7833 referenceId = metaProperty.substr(FILE_PREFIX.length);
7834 fileName = outputPluginDriver.getFileName(referenceId);
7835 }
7836 else if (metaProperty.startsWith(ASSET_PREFIX)) {
7837 warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
7838 assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
7839 fileName = outputPluginDriver.getFileName(assetReferenceId);
7840 }
7841 else {
7842 warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, true, this.context.options);
7843 chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
7844 fileName = outputPluginDriver.getFileName(chunkReferenceId);
7845 }
7846 const relativePath = normalize(relative$1(dirname(chunkId), fileName));
7847 let replacement;
7848 if (assetReferenceId !== null) {
7849 replacement = outputPluginDriver.hookFirstSync('resolveAssetUrl', [
7850 {
7851 assetFileName: fileName,
7852 chunkId,
7853 format,
7854 moduleId: this.context.module.id,
7855 relativeAssetPath: relativePath
7856 }
7857 ]);
7858 }
7859 if (!replacement) {
7860 replacement =
7861 outputPluginDriver.hookFirstSync('resolveFileUrl', [
7862 {
7863 assetReferenceId,
7864 chunkId,
7865 chunkReferenceId,
7866 fileName,
7867 format,
7868 moduleId: this.context.module.id,
7869 referenceId: referenceId || assetReferenceId || chunkReferenceId,
7870 relativePath
7871 }
7872 ]) || relativeUrlMechanisms[format](relativePath);
7873 }
7874 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
7875 return;
7876 }
7877 const replacement = outputPluginDriver.hookFirstSync('resolveImportMeta', [
7878 metaProperty,
7879 {
7880 chunkId,
7881 format,
7882 moduleId: this.context.module.id
7883 }
7884 ]) || ((_a = importMetaMechanisms[format]) === null || _a === void 0 ? void 0 : _a.call(importMetaMechanisms, metaProperty, chunkId));
7885 if (typeof replacement === 'string') {
7886 if (parent instanceof MemberExpression) {
7887 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
7888 }
7889 else {
7890 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
7891 }
7892 }
7893 }
7894}
7895const accessedMetaUrlGlobals = {
7896 amd: ['document', 'module', 'URL'],
7897 cjs: ['document', 'require', 'URL'],
7898 es: [],
7899 iife: ['document', 'URL'],
7900 system: ['module'],
7901 umd: ['document', 'require', 'URL']
7902};
7903const accessedFileUrlGlobals = {
7904 amd: ['document', 'require', 'URL'],
7905 cjs: ['document', 'require', 'URL'],
7906 es: [],
7907 iife: ['document', 'URL'],
7908 system: ['module', 'URL'],
7909 umd: ['document', 'require', 'URL']
7910};
7911const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
7912const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
7913const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
7914 const urlMechanism = getUrl(chunkId);
7915 return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
7916};
7917const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
7918const relativeUrlMechanisms = {
7919 amd: relativePath => {
7920 if (relativePath[0] !== '.')
7921 relativePath = './' + relativePath;
7922 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
7923 },
7924 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
7925 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
7926 iife: relativePath => getRelativeUrlFromDocument(relativePath),
7927 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
7928 umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
7929};
7930const importMetaMechanisms = {
7931 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
7932 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
7933 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
7934 system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
7935 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
7936};
7937
7938class NewExpression extends NodeBase {
7939 bind() {
7940 super.bind();
7941 for (const argument of this.arguments) {
7942 // This will make sure all properties of parameters behave as "unknown"
7943 argument.deoptimizePath(UNKNOWN_PATH);
7944 }
7945 }
7946 hasEffects(context) {
7947 for (const argument of this.arguments) {
7948 if (argument.hasEffects(context))
7949 return true;
7950 }
7951 if (this.context.options.treeshake.annotations &&
7952 this.annotatedPure)
7953 return false;
7954 return (this.callee.hasEffects(context) ||
7955 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
7956 }
7957 hasEffectsWhenAccessedAtPath(path) {
7958 return path.length > 1;
7959 }
7960 initialise() {
7961 this.callOptions = {
7962 args: this.arguments,
7963 withNew: true
7964 };
7965 }
7966}
7967
7968class ObjectExpression extends NodeBase {
7969 constructor() {
7970 super(...arguments);
7971 this.deoptimizedPaths = new Set();
7972 // We collect deoptimization information if we can resolve a computed property access
7973 this.expressionsToBeDeoptimized = new Map();
7974 this.hasUnknownDeoptimizedProperty = false;
7975 this.propertyMap = null;
7976 this.unmatchablePropertiesRead = [];
7977 this.unmatchablePropertiesWrite = [];
7978 }
7979 bind() {
7980 super.bind();
7981 // ensure the propertyMap is set for the tree-shaking passes
7982 this.getPropertyMap();
7983 }
7984 // We could also track this per-property but this would quickly become much more complex
7985 deoptimizeCache() {
7986 if (!this.hasUnknownDeoptimizedProperty)
7987 this.deoptimizeAllProperties();
7988 }
7989 deoptimizePath(path) {
7990 if (this.hasUnknownDeoptimizedProperty)
7991 return;
7992 const propertyMap = this.getPropertyMap();
7993 const key = path[0];
7994 if (path.length === 1) {
7995 if (typeof key !== 'string') {
7996 this.deoptimizeAllProperties();
7997 return;
7998 }
7999 if (!this.deoptimizedPaths.has(key)) {
8000 this.deoptimizedPaths.add(key);
8001 // we only deoptimizeCache exact matches as in all other cases,
8002 // we do not return a literal value or return expression
8003 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
8004 if (expressionsToBeDeoptimized) {
8005 for (const expression of expressionsToBeDeoptimized) {
8006 expression.deoptimizeCache();
8007 }
8008 }
8009 }
8010 }
8011 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
8012 for (const property of typeof key === 'string'
8013 ? propertyMap[key]
8014 ? propertyMap[key].propertiesRead
8015 : []
8016 : this.properties) {
8017 property.deoptimizePath(subPath);
8018 }
8019 }
8020 getLiteralValueAtPath(path, recursionTracker, origin) {
8021 const propertyMap = this.getPropertyMap();
8022 const key = path[0];
8023 if (path.length === 0 ||
8024 this.hasUnknownDeoptimizedProperty ||
8025 typeof key !== 'string' ||
8026 this.deoptimizedPaths.has(key)) {
8027 return UnknownValue;
8028 }
8029 if (path.length === 1 &&
8030 !propertyMap[key] &&
8031 !objectMembers[key] &&
8032 this.unmatchablePropertiesRead.length === 0) {
8033 getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
8034 return undefined;
8035 }
8036 if (!propertyMap[key] ||
8037 propertyMap[key].exactMatchRead === null ||
8038 propertyMap[key].propertiesRead.length > 1) {
8039 return UnknownValue;
8040 }
8041 getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
8042 return propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
8043 }
8044 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
8045 const propertyMap = this.getPropertyMap();
8046 const key = path[0];
8047 if (path.length === 0 ||
8048 this.hasUnknownDeoptimizedProperty ||
8049 typeof key !== 'string' ||
8050 this.deoptimizedPaths.has(key)) {
8051 return UNKNOWN_EXPRESSION;
8052 }
8053 if (path.length === 1 &&
8054 objectMembers[key] &&
8055 this.unmatchablePropertiesRead.length === 0 &&
8056 (!propertyMap[key] || propertyMap[key].exactMatchRead === null)) {
8057 return getMemberReturnExpressionWhenCalled(objectMembers, key);
8058 }
8059 if (!propertyMap[key] ||
8060 propertyMap[key].exactMatchRead === null ||
8061 propertyMap[key].propertiesRead.length > 1) {
8062 return UNKNOWN_EXPRESSION;
8063 }
8064 getOrCreate(this.expressionsToBeDeoptimized, key, () => []).push(origin);
8065 return propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
8066 }
8067 hasEffectsWhenAccessedAtPath(path, context) {
8068 if (path.length === 0)
8069 return false;
8070 const key = path[0];
8071 const propertyMap = this.propertyMap;
8072 if (path.length > 1 &&
8073 (this.hasUnknownDeoptimizedProperty ||
8074 typeof key !== 'string' ||
8075 this.deoptimizedPaths.has(key) ||
8076 !propertyMap[key] ||
8077 propertyMap[key].exactMatchRead === null))
8078 return true;
8079 const subPath = path.slice(1);
8080 for (const property of typeof key !== 'string'
8081 ? this.properties
8082 : propertyMap[key]
8083 ? propertyMap[key].propertiesRead
8084 : []) {
8085 if (property.hasEffectsWhenAccessedAtPath(subPath, context))
8086 return true;
8087 }
8088 return false;
8089 }
8090 hasEffectsWhenAssignedAtPath(path, context) {
8091 const key = path[0];
8092 const propertyMap = this.propertyMap;
8093 if (path.length > 1 &&
8094 (this.hasUnknownDeoptimizedProperty ||
8095 this.deoptimizedPaths.has(key) ||
8096 !propertyMap[key] ||
8097 propertyMap[key].exactMatchRead === null)) {
8098 return true;
8099 }
8100 const subPath = path.slice(1);
8101 for (const property of typeof key !== 'string'
8102 ? this.properties
8103 : path.length > 1
8104 ? propertyMap[key].propertiesRead
8105 : propertyMap[key]
8106 ? propertyMap[key].propertiesWrite
8107 : []) {
8108 if (property.hasEffectsWhenAssignedAtPath(subPath, context))
8109 return true;
8110 }
8111 return false;
8112 }
8113 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8114 const key = path[0];
8115 if (typeof key !== 'string' ||
8116 this.hasUnknownDeoptimizedProperty ||
8117 this.deoptimizedPaths.has(key) ||
8118 (this.propertyMap[key]
8119 ? !this.propertyMap[key].exactMatchRead
8120 : path.length > 1 || !objectMembers[key])) {
8121 return true;
8122 }
8123 const subPath = path.slice(1);
8124 if (this.propertyMap[key]) {
8125 for (const property of this.propertyMap[key].propertiesRead) {
8126 if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
8127 return true;
8128 }
8129 }
8130 if (path.length === 1 && objectMembers[key])
8131 return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
8132 return false;
8133 }
8134 render(code, options, { renderedParentType } = BLANK) {
8135 super.render(code, options);
8136 if (renderedParentType === ExpressionStatement ||
8137 renderedParentType === ArrowFunctionExpression) {
8138 code.appendRight(this.start, '(');
8139 code.prependLeft(this.end, ')');
8140 }
8141 }
8142 deoptimizeAllProperties() {
8143 this.hasUnknownDeoptimizedProperty = true;
8144 for (const property of this.properties) {
8145 property.deoptimizePath(UNKNOWN_PATH);
8146 }
8147 for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
8148 for (const expression of expressionsToBeDeoptimized) {
8149 expression.deoptimizeCache();
8150 }
8151 }
8152 }
8153 getPropertyMap() {
8154 if (this.propertyMap !== null) {
8155 return this.propertyMap;
8156 }
8157 const propertyMap = (this.propertyMap = Object.create(null));
8158 for (let index = this.properties.length - 1; index >= 0; index--) {
8159 const property = this.properties[index];
8160 if (property instanceof SpreadElement) {
8161 this.unmatchablePropertiesRead.push(property);
8162 continue;
8163 }
8164 const isWrite = property.kind !== 'get';
8165 const isRead = property.kind !== 'set';
8166 let key;
8167 if (property.computed) {
8168 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this);
8169 if (keyValue === UnknownValue) {
8170 if (isRead) {
8171 this.unmatchablePropertiesRead.push(property);
8172 }
8173 else {
8174 this.unmatchablePropertiesWrite.push(property);
8175 }
8176 continue;
8177 }
8178 key = String(keyValue);
8179 }
8180 else if (property.key instanceof Identifier$1) {
8181 key = property.key.name;
8182 }
8183 else {
8184 key = String(property.key.value);
8185 }
8186 const propertyMapProperty = propertyMap[key];
8187 if (!propertyMapProperty) {
8188 propertyMap[key] = {
8189 exactMatchRead: isRead ? property : null,
8190 exactMatchWrite: isWrite ? property : null,
8191 propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
8192 propertiesWrite: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
8193 };
8194 continue;
8195 }
8196 if (isRead && propertyMapProperty.exactMatchRead === null) {
8197 propertyMapProperty.exactMatchRead = property;
8198 propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
8199 }
8200 if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
8201 propertyMapProperty.exactMatchWrite = property;
8202 propertyMapProperty.propertiesWrite.push(property, ...this.unmatchablePropertiesWrite);
8203 }
8204 }
8205 return propertyMap;
8206 }
8207}
8208
8209class ObjectPattern extends NodeBase {
8210 addExportedVariables(variables, exportNamesByVariable) {
8211 for (const property of this.properties) {
8212 if (property.type === Property) {
8213 property.value.addExportedVariables(variables, exportNamesByVariable);
8214 }
8215 else {
8216 property.argument.addExportedVariables(variables, exportNamesByVariable);
8217 }
8218 }
8219 }
8220 declare(kind, init) {
8221 const variables = [];
8222 for (const property of this.properties) {
8223 variables.push(...property.declare(kind, init));
8224 }
8225 return variables;
8226 }
8227 deoptimizePath(path) {
8228 if (path.length === 0) {
8229 for (const property of this.properties) {
8230 property.deoptimizePath(path);
8231 }
8232 }
8233 }
8234 hasEffectsWhenAssignedAtPath(path, context) {
8235 if (path.length > 0)
8236 return true;
8237 for (const property of this.properties) {
8238 if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
8239 return true;
8240 }
8241 return false;
8242 }
8243}
8244
8245class PrivateName extends NodeBase {
8246}
8247
8248class Program$1 extends NodeBase {
8249 constructor() {
8250 super(...arguments);
8251 this.hasCachedEffect = false;
8252 }
8253 hasEffects(context) {
8254 // We are caching here to later more efficiently identify side-effect-free modules
8255 if (this.hasCachedEffect)
8256 return true;
8257 for (const node of this.body) {
8258 if (node.hasEffects(context)) {
8259 return (this.hasCachedEffect = true);
8260 }
8261 }
8262 return false;
8263 }
8264 include(context, includeChildrenRecursively) {
8265 this.included = true;
8266 for (const node of this.body) {
8267 if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
8268 node.include(context, includeChildrenRecursively);
8269 }
8270 }
8271 }
8272 render(code, options) {
8273 if (this.body.length) {
8274 renderStatementList(this.body, code, this.start, this.end, options);
8275 }
8276 else {
8277 super.render(code, options);
8278 }
8279 }
8280}
8281
8282class Property$1 extends NodeBase {
8283 constructor() {
8284 super(...arguments);
8285 this.declarationInit = null;
8286 this.returnExpression = null;
8287 }
8288 bind() {
8289 super.bind();
8290 if (this.kind === 'get') {
8291 // ensure the returnExpression is set for the tree-shaking passes
8292 this.getReturnExpression();
8293 }
8294 if (this.declarationInit !== null) {
8295 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
8296 }
8297 }
8298 declare(kind, init) {
8299 this.declarationInit = init;
8300 return this.value.declare(kind, UNKNOWN_EXPRESSION);
8301 }
8302 // As getter properties directly receive their values from function expressions that always
8303 // have a fixed return value, there is no known situation where a getter is deoptimized.
8304 deoptimizeCache() { }
8305 deoptimizePath(path) {
8306 if (this.kind === 'get') {
8307 this.getReturnExpression().deoptimizePath(path);
8308 }
8309 else {
8310 this.value.deoptimizePath(path);
8311 }
8312 }
8313 getLiteralValueAtPath(path, recursionTracker, origin) {
8314 if (this.kind === 'get') {
8315 return this.getReturnExpression().getLiteralValueAtPath(path, recursionTracker, origin);
8316 }
8317 return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
8318 }
8319 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
8320 if (this.kind === 'get') {
8321 return this.getReturnExpression().getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8322 }
8323 return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8324 }
8325 hasEffects(context) {
8326 return this.key.hasEffects(context) || this.value.hasEffects(context);
8327 }
8328 hasEffectsWhenAccessedAtPath(path, context) {
8329 if (this.kind === 'get') {
8330 const trackedExpressions = context.accessed.getEntities(path);
8331 if (trackedExpressions.has(this))
8332 return false;
8333 trackedExpressions.add(this);
8334 return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
8335 (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
8336 }
8337 return this.value.hasEffectsWhenAccessedAtPath(path, context);
8338 }
8339 hasEffectsWhenAssignedAtPath(path, context) {
8340 if (this.kind === 'get') {
8341 const trackedExpressions = context.assigned.getEntities(path);
8342 if (trackedExpressions.has(this))
8343 return false;
8344 trackedExpressions.add(this);
8345 return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
8346 }
8347 if (this.kind === 'set') {
8348 const trackedExpressions = context.assigned.getEntities(path);
8349 if (trackedExpressions.has(this))
8350 return false;
8351 trackedExpressions.add(this);
8352 return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
8353 }
8354 return this.value.hasEffectsWhenAssignedAtPath(path, context);
8355 }
8356 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8357 if (this.kind === 'get') {
8358 const trackedExpressions = (callOptions.withNew
8359 ? context.instantiated
8360 : context.called).getEntities(path, callOptions);
8361 if (trackedExpressions.has(this))
8362 return false;
8363 trackedExpressions.add(this);
8364 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
8365 }
8366 return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
8367 }
8368 initialise() {
8369 this.accessorCallOptions = {
8370 args: NO_ARGS,
8371 withNew: false
8372 };
8373 }
8374 render(code, options) {
8375 if (!this.shorthand) {
8376 this.key.render(code, options);
8377 }
8378 this.value.render(code, options, { isShorthandProperty: this.shorthand });
8379 }
8380 getReturnExpression() {
8381 if (this.returnExpression === null) {
8382 this.returnExpression = UNKNOWN_EXPRESSION;
8383 return (this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, SHARED_RECURSION_TRACKER, this));
8384 }
8385 return this.returnExpression;
8386 }
8387}
8388
8389class ReturnStatement$1 extends NodeBase {
8390 hasEffects(context) {
8391 if (!context.ignore.returnAwaitYield ||
8392 (this.argument !== null && this.argument.hasEffects(context)))
8393 return true;
8394 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8395 return false;
8396 }
8397 include(context, includeChildrenRecursively) {
8398 this.included = true;
8399 if (this.argument) {
8400 this.argument.include(context, includeChildrenRecursively);
8401 }
8402 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8403 }
8404 initialise() {
8405 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
8406 }
8407 render(code, options) {
8408 if (this.argument) {
8409 this.argument.render(code, options, { preventASI: true });
8410 if (this.argument.start === this.start + 6 /* 'return'.length */) {
8411 code.prependLeft(this.start + 6, ' ');
8412 }
8413 }
8414 }
8415}
8416
8417class SequenceExpression extends NodeBase {
8418 deoptimizePath(path) {
8419 if (path.length > 0)
8420 this.expressions[this.expressions.length - 1].deoptimizePath(path);
8421 }
8422 getLiteralValueAtPath(path, recursionTracker, origin) {
8423 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
8424 }
8425 hasEffects(context) {
8426 for (const expression of this.expressions) {
8427 if (expression.hasEffects(context))
8428 return true;
8429 }
8430 return false;
8431 }
8432 hasEffectsWhenAccessedAtPath(path, context) {
8433 return (path.length > 0 &&
8434 this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
8435 }
8436 hasEffectsWhenAssignedAtPath(path, context) {
8437 return (path.length === 0 ||
8438 this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
8439 }
8440 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8441 return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
8442 }
8443 include(context, includeChildrenRecursively) {
8444 this.included = true;
8445 for (let i = 0; i < this.expressions.length - 1; i++) {
8446 const node = this.expressions[i];
8447 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8448 node.include(context, includeChildrenRecursively);
8449 }
8450 this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
8451 }
8452 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
8453 let includedNodes = 0;
8454 for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
8455 if (!node.included) {
8456 treeshakeNode(node, code, start, end);
8457 continue;
8458 }
8459 includedNodes++;
8460 if (includedNodes === 1 && preventASI) {
8461 removeLineBreaks(code, start, node.start);
8462 }
8463 if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
8464 node.render(code, options, {
8465 isCalleeOfRenderedParent: renderedParentType
8466 ? isCalleeOfRenderedParent
8467 : this.parent.callee === this,
8468 renderedParentType: renderedParentType || this.parent.type
8469 });
8470 }
8471 else {
8472 node.render(code, options);
8473 }
8474 }
8475 }
8476}
8477
8478class Super extends NodeBase {
8479}
8480
8481class SwitchCase extends NodeBase {
8482 hasEffects(context) {
8483 if (this.test && this.test.hasEffects(context))
8484 return true;
8485 for (const node of this.consequent) {
8486 if (context.brokenFlow)
8487 break;
8488 if (node.hasEffects(context))
8489 return true;
8490 }
8491 return false;
8492 }
8493 include(context, includeChildrenRecursively) {
8494 this.included = true;
8495 if (this.test)
8496 this.test.include(context, includeChildrenRecursively);
8497 for (const node of this.consequent) {
8498 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8499 node.include(context, includeChildrenRecursively);
8500 }
8501 }
8502 render(code, options, nodeRenderOptions) {
8503 if (this.consequent.length) {
8504 this.test && this.test.render(code, options);
8505 const testEnd = this.test
8506 ? this.test.end
8507 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
8508 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
8509 renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
8510 }
8511 else {
8512 super.render(code, options);
8513 }
8514 }
8515}
8516SwitchCase.prototype.needsBoundaries = true;
8517
8518class SwitchStatement extends NodeBase {
8519 createScope(parentScope) {
8520 this.scope = new BlockScope(parentScope);
8521 }
8522 hasEffects(context) {
8523 if (this.discriminant.hasEffects(context))
8524 return true;
8525 const { brokenFlow, ignore: { breaks } } = context;
8526 let minBrokenFlow = Infinity;
8527 context.ignore.breaks = true;
8528 for (const switchCase of this.cases) {
8529 if (switchCase.hasEffects(context))
8530 return true;
8531 minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
8532 context.brokenFlow = brokenFlow;
8533 }
8534 if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8535 context.brokenFlow = minBrokenFlow;
8536 }
8537 context.ignore.breaks = breaks;
8538 return false;
8539 }
8540 include(context, includeChildrenRecursively) {
8541 this.included = true;
8542 this.discriminant.include(context, includeChildrenRecursively);
8543 const { brokenFlow } = context;
8544 let minBrokenFlow = Infinity;
8545 let isCaseIncluded = includeChildrenRecursively ||
8546 (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
8547 for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
8548 const switchCase = this.cases[caseIndex];
8549 if (switchCase.included) {
8550 isCaseIncluded = true;
8551 }
8552 if (!isCaseIncluded) {
8553 const hasEffectsContext = createHasEffectsContext();
8554 hasEffectsContext.ignore.breaks = true;
8555 isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
8556 }
8557 if (isCaseIncluded) {
8558 switchCase.include(context, includeChildrenRecursively);
8559 minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
8560 context.brokenFlow = brokenFlow;
8561 }
8562 else {
8563 minBrokenFlow = brokenFlow;
8564 }
8565 }
8566 if (isCaseIncluded &&
8567 this.defaultCase !== null &&
8568 !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8569 context.brokenFlow = minBrokenFlow;
8570 }
8571 }
8572 initialise() {
8573 for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
8574 if (this.cases[caseIndex].test === null) {
8575 this.defaultCase = caseIndex;
8576 return;
8577 }
8578 }
8579 this.defaultCase = null;
8580 }
8581 render(code, options) {
8582 this.discriminant.render(code, options);
8583 if (this.cases.length > 0) {
8584 renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
8585 }
8586 }
8587}
8588
8589class TaggedTemplateExpression extends NodeBase {
8590 bind() {
8591 super.bind();
8592 if (this.tag.type === Identifier) {
8593 const name = this.tag.name;
8594 const variable = this.scope.findVariable(name);
8595 if (variable.isNamespace) {
8596 this.context.warn({
8597 code: 'CANNOT_CALL_NAMESPACE',
8598 message: `Cannot call a namespace ('${name}')`,
8599 }, this.start);
8600 }
8601 if (name === 'eval') {
8602 this.context.warn({
8603 code: 'EVAL',
8604 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
8605 url: 'https://rollupjs.org/guide/en/#avoiding-eval',
8606 }, this.start);
8607 }
8608 }
8609 }
8610 hasEffects(context) {
8611 return (super.hasEffects(context) ||
8612 this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
8613 }
8614 initialise() {
8615 this.callOptions = {
8616 args: NO_ARGS,
8617 withNew: false,
8618 };
8619 }
8620}
8621
8622class TemplateElement extends NodeBase {
8623 bind() { }
8624 hasEffects() {
8625 return false;
8626 }
8627 include() {
8628 this.included = true;
8629 }
8630 parseNode(esTreeNode) {
8631 this.value = esTreeNode.value;
8632 super.parseNode(esTreeNode);
8633 }
8634 render() { }
8635}
8636
8637class TemplateLiteral extends NodeBase {
8638 getLiteralValueAtPath(path) {
8639 if (path.length > 0 || this.quasis.length !== 1) {
8640 return UnknownValue;
8641 }
8642 return this.quasis[0].value.cooked;
8643 }
8644 render(code, options) {
8645 code.indentExclusionRanges.push([this.start, this.end]);
8646 super.render(code, options);
8647 }
8648}
8649
8650class ModuleScope extends ChildScope {
8651 constructor(parent, context) {
8652 super(parent);
8653 this.context = context;
8654 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
8655 }
8656 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
8657 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
8658 this.variables.set('default', variable);
8659 return variable;
8660 }
8661 addNamespaceMemberAccess() { }
8662 deconflict(format, exportNamesByVariable, accessedGlobalsByScope) {
8663 // all module level variables are already deconflicted when deconflicting the chunk
8664 for (const scope of this.children)
8665 scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
8666 }
8667 findLexicalBoundary() {
8668 return this;
8669 }
8670 findVariable(name) {
8671 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
8672 if (knownVariable) {
8673 return knownVariable;
8674 }
8675 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
8676 if (variable instanceof GlobalVariable) {
8677 this.accessedOutsideVariables.set(name, variable);
8678 }
8679 return variable;
8680 }
8681}
8682
8683class ThisExpression extends NodeBase {
8684 bind() {
8685 super.bind();
8686 this.variable = this.scope.findVariable('this');
8687 }
8688 hasEffectsWhenAccessedAtPath(path, context) {
8689 return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
8690 }
8691 hasEffectsWhenAssignedAtPath(path, context) {
8692 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
8693 }
8694 initialise() {
8695 this.alias =
8696 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
8697 if (this.alias === 'undefined') {
8698 this.context.warn({
8699 code: 'THIS_IS_UNDEFINED',
8700 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
8701 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
8702 }, this.start);
8703 }
8704 }
8705 render(code) {
8706 if (this.alias !== null) {
8707 code.overwrite(this.start, this.end, this.alias, {
8708 contentOnly: false,
8709 storeName: true
8710 });
8711 }
8712 }
8713}
8714
8715class ThrowStatement extends NodeBase {
8716 hasEffects() {
8717 return true;
8718 }
8719 include(context, includeChildrenRecursively) {
8720 this.included = true;
8721 this.argument.include(context, includeChildrenRecursively);
8722 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8723 }
8724 render(code, options) {
8725 this.argument.render(code, options, { preventASI: true });
8726 if (this.argument.start === this.start + 5 /* 'throw'.length */) {
8727 code.prependLeft(this.start + 5, ' ');
8728 }
8729 }
8730}
8731
8732class TryStatement extends NodeBase {
8733 constructor() {
8734 super(...arguments);
8735 this.directlyIncluded = false;
8736 }
8737 hasEffects(context) {
8738 return ((this.context.options.treeshake.tryCatchDeoptimization
8739 ? this.block.body.length > 0
8740 : this.block.hasEffects(context)) ||
8741 (this.finalizer !== null && this.finalizer.hasEffects(context)));
8742 }
8743 include(context, includeChildrenRecursively) {
8744 var _a;
8745 const tryCatchDeoptimization = (_a = this.context.options.treeshake) === null || _a === void 0 ? void 0 : _a.tryCatchDeoptimization;
8746 const { brokenFlow } = context;
8747 if (!this.directlyIncluded || !tryCatchDeoptimization) {
8748 this.included = true;
8749 this.directlyIncluded = true;
8750 this.block.include(context, tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
8751 context.brokenFlow = brokenFlow;
8752 }
8753 if (this.handler !== null) {
8754 this.handler.include(context, includeChildrenRecursively);
8755 context.brokenFlow = brokenFlow;
8756 }
8757 if (this.finalizer !== null) {
8758 this.finalizer.include(context, includeChildrenRecursively);
8759 }
8760 }
8761}
8762
8763const unaryOperators = {
8764 '!': value => !value,
8765 '+': value => +value,
8766 '-': value => -value,
8767 delete: () => UnknownValue,
8768 typeof: value => typeof value,
8769 void: () => undefined,
8770 '~': value => ~value
8771};
8772class UnaryExpression extends NodeBase {
8773 bind() {
8774 super.bind();
8775 if (this.operator === 'delete') {
8776 this.argument.deoptimizePath(EMPTY_PATH);
8777 }
8778 }
8779 getLiteralValueAtPath(path, recursionTracker, origin) {
8780 if (path.length > 0)
8781 return UnknownValue;
8782 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8783 if (argumentValue === UnknownValue)
8784 return UnknownValue;
8785 return unaryOperators[this.operator](argumentValue);
8786 }
8787 hasEffects(context) {
8788 if (this.operator === 'typeof' && this.argument instanceof Identifier$1)
8789 return false;
8790 return (this.argument.hasEffects(context) ||
8791 (this.operator === 'delete' &&
8792 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
8793 }
8794 hasEffectsWhenAccessedAtPath(path) {
8795 if (this.operator === 'void') {
8796 return path.length > 0;
8797 }
8798 return path.length > 1;
8799 }
8800}
8801
8802class UnknownNode extends NodeBase {
8803 hasEffects() {
8804 return true;
8805 }
8806 include(context) {
8807 super.include(context, true);
8808 }
8809}
8810
8811class UpdateExpression extends NodeBase {
8812 bind() {
8813 super.bind();
8814 this.argument.deoptimizePath(EMPTY_PATH);
8815 if (this.argument instanceof Identifier$1) {
8816 const variable = this.scope.findVariable(this.argument.name);
8817 variable.isReassigned = true;
8818 }
8819 }
8820 hasEffects(context) {
8821 return (this.argument.hasEffects(context) ||
8822 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
8823 }
8824 hasEffectsWhenAccessedAtPath(path) {
8825 return path.length > 1;
8826 }
8827 render(code, options) {
8828 this.argument.render(code, options);
8829 if (options.format === 'system') {
8830 const variable = this.argument.variable;
8831 const exportNames = options.exportNamesByVariable.get(variable);
8832 if (exportNames && exportNames.length) {
8833 const _ = options.compact ? '' : ' ';
8834 const name = variable.getName();
8835 if (this.prefix) {
8836 if (exportNames.length === 1) {
8837 code.overwrite(this.start, this.end, `exports('${exportNames[0]}',${_}${this.operator}${name})`);
8838 }
8839 else {
8840 code.overwrite(this.start, this.end, `(${this.operator}${name},${_}${getSystemExportStatement([variable], options)},${_}${name})`);
8841 }
8842 }
8843 else if (exportNames.length > 1) {
8844 code.overwrite(this.start, this.end, `${getSystemExportFunctionLeft([variable], false, options)}${this.operator}${name})`);
8845 }
8846 else {
8847 let op;
8848 switch (this.operator) {
8849 case '++':
8850 op = `${name}${_}+${_}1`;
8851 break;
8852 case '--':
8853 op = `${name}${_}-${_}1`;
8854 break;
8855 }
8856 code.overwrite(this.start, this.end, `(exports('${exportNames[0]}',${_}${op}),${_}${name}${this.operator})`);
8857 }
8858 }
8859 }
8860 }
8861}
8862
8863function isReassignedExportsMember(variable, exportNamesByVariable) {
8864 return (variable.renderBaseName !== null && exportNamesByVariable.has(variable) && variable.isReassigned);
8865}
8866function areAllDeclarationsIncludedAndNotExported(declarations, exportNamesByVariable) {
8867 for (const declarator of declarations) {
8868 if (!declarator.included)
8869 return false;
8870 if (declarator.id.type === Identifier) {
8871 if (exportNamesByVariable.has(declarator.id.variable))
8872 return false;
8873 }
8874 else {
8875 const exportedVariables = [];
8876 declarator.id.addExportedVariables(exportedVariables, exportNamesByVariable);
8877 if (exportedVariables.length > 0)
8878 return false;
8879 }
8880 }
8881 return true;
8882}
8883class VariableDeclaration extends NodeBase {
8884 deoptimizePath() {
8885 for (const declarator of this.declarations) {
8886 declarator.deoptimizePath(EMPTY_PATH);
8887 }
8888 }
8889 hasEffectsWhenAssignedAtPath() {
8890 return false;
8891 }
8892 include(context, includeChildrenRecursively) {
8893 this.included = true;
8894 for (const declarator of this.declarations) {
8895 if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
8896 declarator.include(context, includeChildrenRecursively);
8897 }
8898 }
8899 includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
8900 this.included = true;
8901 for (const declarator of this.declarations) {
8902 declarator.include(context, includeChildrenRecursively);
8903 }
8904 }
8905 initialise() {
8906 for (const declarator of this.declarations) {
8907 declarator.declareDeclarator(this.kind);
8908 }
8909 }
8910 render(code, options, nodeRenderOptions = BLANK) {
8911 if (areAllDeclarationsIncludedAndNotExported(this.declarations, options.exportNamesByVariable)) {
8912 for (const declarator of this.declarations) {
8913 declarator.render(code, options);
8914 }
8915 if (!nodeRenderOptions.isNoStatement &&
8916 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
8917 code.appendLeft(this.end, ';');
8918 }
8919 }
8920 else {
8921 this.renderReplacedDeclarations(code, options, nodeRenderOptions);
8922 }
8923 }
8924 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports, options) {
8925 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
8926 code.remove(this.end - 1, this.end);
8927 }
8928 if (addSemicolon) {
8929 separatorString += ';';
8930 }
8931 if (lastSeparatorPos !== null) {
8932 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
8933 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
8934 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
8935 actualContentEnd--;
8936 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
8937 actualContentEnd--;
8938 }
8939 }
8940 if (actualContentEnd === lastSeparatorPos + 1) {
8941 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
8942 }
8943 else {
8944 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
8945 code.remove(actualContentEnd, renderedContentEnd);
8946 }
8947 }
8948 else {
8949 code.appendLeft(renderedContentEnd, separatorString);
8950 }
8951 if (systemPatternExports.length > 0) {
8952 code.appendLeft(renderedContentEnd, ` ${getSystemExportStatement(systemPatternExports, options)};`);
8953 }
8954 }
8955 renderReplacedDeclarations(code, options, { start = this.start, end = this.end, isNoStatement }) {
8956 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
8957 let actualContentEnd, renderedContentEnd;
8958 if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
8959 renderedContentEnd = this.start + this.kind.length;
8960 }
8961 else {
8962 renderedContentEnd = separatedNodes[0].start;
8963 }
8964 let lastSeparatorPos = renderedContentEnd - 1;
8965 code.remove(this.start, lastSeparatorPos);
8966 let isInDeclaration = false;
8967 let hasRenderedContent = false;
8968 let separatorString = '', leadingString, nextSeparatorString;
8969 const systemPatternExports = [];
8970 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
8971 if (!node.included ||
8972 (node.id instanceof Identifier$1 &&
8973 isReassignedExportsMember(node.id.variable, options.exportNamesByVariable) &&
8974 node.init === null)) {
8975 code.remove(start, end);
8976 continue;
8977 }
8978 leadingString = '';
8979 nextSeparatorString = '';
8980 if (node.id instanceof Identifier$1 &&
8981 isReassignedExportsMember(node.id.variable, options.exportNamesByVariable)) {
8982 if (hasRenderedContent) {
8983 separatorString += ';';
8984 }
8985 isInDeclaration = false;
8986 }
8987 else {
8988 if (options.format === 'system' && node.init !== null) {
8989 if (node.id.type !== Identifier) {
8990 node.id.addExportedVariables(systemPatternExports, options.exportNamesByVariable);
8991 }
8992 else {
8993 const exportNames = options.exportNamesByVariable.get(node.id.variable);
8994 if (exportNames) {
8995 const _ = options.compact ? '' : ' ';
8996 const operatorPos = findFirstOccurrenceOutsideComment(code.original, '=', node.id.end);
8997 code.prependLeft(findNonWhiteSpace(code.original, operatorPos + 1), exportNames.length === 1
8998 ? `exports('${exportNames[0]}',${_}`
8999 : getSystemExportFunctionLeft([node.id.variable], false, options));
9000 nextSeparatorString += ')';
9001 }
9002 }
9003 }
9004 if (isInDeclaration) {
9005 separatorString += ',';
9006 }
9007 else {
9008 if (hasRenderedContent) {
9009 separatorString += ';';
9010 }
9011 leadingString += `${this.kind} `;
9012 isInDeclaration = true;
9013 }
9014 }
9015 if (renderedContentEnd === lastSeparatorPos + 1) {
9016 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
9017 }
9018 else {
9019 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
9020 code.appendLeft(renderedContentEnd, leadingString);
9021 }
9022 node.render(code, options);
9023 actualContentEnd = contentEnd;
9024 renderedContentEnd = end;
9025 hasRenderedContent = true;
9026 lastSeparatorPos = separator;
9027 separatorString = nextSeparatorString;
9028 }
9029 if (hasRenderedContent) {
9030 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports, options);
9031 }
9032 else {
9033 code.remove(start, end);
9034 }
9035 }
9036}
9037
9038class VariableDeclarator extends NodeBase {
9039 declareDeclarator(kind) {
9040 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
9041 }
9042 deoptimizePath(path) {
9043 this.id.deoptimizePath(path);
9044 }
9045}
9046
9047class WhileStatement extends NodeBase {
9048 hasEffects(context) {
9049 if (this.test.hasEffects(context))
9050 return true;
9051 const { brokenFlow, ignore: { breaks, continues } } = context;
9052 context.ignore.breaks = true;
9053 context.ignore.continues = true;
9054 if (this.body.hasEffects(context))
9055 return true;
9056 context.ignore.breaks = breaks;
9057 context.ignore.continues = continues;
9058 context.brokenFlow = brokenFlow;
9059 return false;
9060 }
9061 include(context, includeChildrenRecursively) {
9062 this.included = true;
9063 this.test.include(context, includeChildrenRecursively);
9064 const { brokenFlow } = context;
9065 this.body.include(context, includeChildrenRecursively);
9066 context.brokenFlow = brokenFlow;
9067 }
9068}
9069
9070class YieldExpression extends NodeBase {
9071 bind() {
9072 super.bind();
9073 if (this.argument !== null) {
9074 this.argument.deoptimizePath(UNKNOWN_PATH);
9075 }
9076 }
9077 hasEffects(context) {
9078 return (!context.ignore.returnAwaitYield ||
9079 (this.argument !== null && this.argument.hasEffects(context)));
9080 }
9081 render(code, options) {
9082 if (this.argument) {
9083 this.argument.render(code, options, { preventASI: true });
9084 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
9085 code.prependLeft(this.start + 5, ' ');
9086 }
9087 }
9088 }
9089}
9090
9091const nodeConstructors = {
9092 ArrayExpression,
9093 ArrayPattern,
9094 ArrowFunctionExpression: ArrowFunctionExpression$1,
9095 AssignmentExpression,
9096 AssignmentPattern,
9097 AwaitExpression,
9098 BinaryExpression,
9099 BlockStatement: BlockStatement$1,
9100 BreakStatement,
9101 CallExpression: CallExpression$1,
9102 CatchClause,
9103 ChainExpression,
9104 ClassBody,
9105 ClassDeclaration,
9106 ClassExpression,
9107 ConditionalExpression,
9108 ContinueStatement,
9109 DoWhileStatement,
9110 EmptyStatement,
9111 ExportAllDeclaration,
9112 ExportDefaultDeclaration,
9113 ExportNamedDeclaration,
9114 ExportSpecifier,
9115 ExpressionStatement: ExpressionStatement$1,
9116 FieldDefinition,
9117 ForInStatement,
9118 ForOfStatement,
9119 ForStatement,
9120 FunctionDeclaration,
9121 FunctionExpression: FunctionExpression$1,
9122 Identifier: Identifier$1,
9123 IfStatement,
9124 ImportDeclaration,
9125 ImportDefaultSpecifier: ImportDefaultSpecifier$1,
9126 ImportExpression,
9127 ImportNamespaceSpecifier: ImportNamespaceSpecifier$1,
9128 ImportSpecifier,
9129 LabeledStatement,
9130 Literal,
9131 LogicalExpression,
9132 MemberExpression,
9133 MetaProperty,
9134 MethodDefinition,
9135 NewExpression,
9136 ObjectExpression,
9137 ObjectPattern,
9138 PrivateName,
9139 Program: Program$1,
9140 Property: Property$1,
9141 RestElement,
9142 ReturnStatement: ReturnStatement$1,
9143 SequenceExpression,
9144 SpreadElement,
9145 Super,
9146 SwitchCase,
9147 SwitchStatement,
9148 TaggedTemplateExpression,
9149 TemplateElement,
9150 TemplateLiteral,
9151 ThisExpression,
9152 ThrowStatement,
9153 TryStatement,
9154 UnaryExpression,
9155 UnknownNode,
9156 UpdateExpression,
9157 VariableDeclaration,
9158 VariableDeclarator,
9159 WhileStatement,
9160 YieldExpression
9161};
9162
9163function getId(m) {
9164 return m.id;
9165}
9166
9167function getOriginalLocation(sourcemapChain, location) {
9168 // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
9169 const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
9170 while (filteredSourcemapChain.length > 0) {
9171 const sourcemap = filteredSourcemapChain.pop();
9172 const line = sourcemap.mappings[location.line - 1];
9173 let locationFound = false;
9174 if (line !== undefined) {
9175 for (const segment of line) {
9176 if (segment[0] >= location.column) {
9177 if (segment.length === 1)
9178 break;
9179 location = {
9180 column: segment[3],
9181 line: segment[2] + 1,
9182 name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
9183 source: sourcemap.sources[segment[1]]
9184 };
9185 locationFound = true;
9186 break;
9187 }
9188 }
9189 }
9190 if (!locationFound) {
9191 throw new Error("Can't resolve original location of error.");
9192 }
9193 }
9194 return location;
9195}
9196
9197// AST walker module for Mozilla Parser API compatible trees
9198
9199function skipThrough(node, st, c) { c(node, st); }
9200function ignore(_node, _st, _c) {}
9201
9202// Node walkers.
9203
9204var base$1 = {};
9205
9206base$1.Program = base$1.BlockStatement = function (node, st, c) {
9207 for (var i = 0, list = node.body; i < list.length; i += 1)
9208 {
9209 var stmt = list[i];
9210
9211 c(stmt, st, "Statement");
9212 }
9213};
9214base$1.Statement = skipThrough;
9215base$1.EmptyStatement = ignore;
9216base$1.ExpressionStatement = base$1.ParenthesizedExpression = base$1.ChainExpression =
9217 function (node, st, c) { return c(node.expression, st, "Expression"); };
9218base$1.IfStatement = function (node, st, c) {
9219 c(node.test, st, "Expression");
9220 c(node.consequent, st, "Statement");
9221 if (node.alternate) { c(node.alternate, st, "Statement"); }
9222};
9223base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
9224base$1.BreakStatement = base$1.ContinueStatement = ignore;
9225base$1.WithStatement = function (node, st, c) {
9226 c(node.object, st, "Expression");
9227 c(node.body, st, "Statement");
9228};
9229base$1.SwitchStatement = function (node, st, c) {
9230 c(node.discriminant, st, "Expression");
9231 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
9232 var cs = list$1[i$1];
9233
9234 if (cs.test) { c(cs.test, st, "Expression"); }
9235 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
9236 {
9237 var cons = list[i];
9238
9239 c(cons, st, "Statement");
9240 }
9241 }
9242};
9243base$1.SwitchCase = function (node, st, c) {
9244 if (node.test) { c(node.test, st, "Expression"); }
9245 for (var i = 0, list = node.consequent; i < list.length; i += 1)
9246 {
9247 var cons = list[i];
9248
9249 c(cons, st, "Statement");
9250 }
9251};
9252base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
9253 if (node.argument) { c(node.argument, st, "Expression"); }
9254};
9255base$1.ThrowStatement = base$1.SpreadElement =
9256 function (node, st, c) { return c(node.argument, st, "Expression"); };
9257base$1.TryStatement = function (node, st, c) {
9258 c(node.block, st, "Statement");
9259 if (node.handler) { c(node.handler, st); }
9260 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
9261};
9262base$1.CatchClause = function (node, st, c) {
9263 if (node.param) { c(node.param, st, "Pattern"); }
9264 c(node.body, st, "Statement");
9265};
9266base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
9267 c(node.test, st, "Expression");
9268 c(node.body, st, "Statement");
9269};
9270base$1.ForStatement = function (node, st, c) {
9271 if (node.init) { c(node.init, st, "ForInit"); }
9272 if (node.test) { c(node.test, st, "Expression"); }
9273 if (node.update) { c(node.update, st, "Expression"); }
9274 c(node.body, st, "Statement");
9275};
9276base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
9277 c(node.left, st, "ForInit");
9278 c(node.right, st, "Expression");
9279 c(node.body, st, "Statement");
9280};
9281base$1.ForInit = function (node, st, c) {
9282 if (node.type === "VariableDeclaration") { c(node, st); }
9283 else { c(node, st, "Expression"); }
9284};
9285base$1.DebuggerStatement = ignore;
9286
9287base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
9288base$1.VariableDeclaration = function (node, st, c) {
9289 for (var i = 0, list = node.declarations; i < list.length; i += 1)
9290 {
9291 var decl = list[i];
9292
9293 c(decl, st);
9294 }
9295};
9296base$1.VariableDeclarator = function (node, st, c) {
9297 c(node.id, st, "Pattern");
9298 if (node.init) { c(node.init, st, "Expression"); }
9299};
9300
9301base$1.Function = function (node, st, c) {
9302 if (node.id) { c(node.id, st, "Pattern"); }
9303 for (var i = 0, list = node.params; i < list.length; i += 1)
9304 {
9305 var param = list[i];
9306
9307 c(param, st, "Pattern");
9308 }
9309 c(node.body, st, node.expression ? "Expression" : "Statement");
9310};
9311
9312base$1.Pattern = function (node, st, c) {
9313 if (node.type === "Identifier")
9314 { c(node, st, "VariablePattern"); }
9315 else if (node.type === "MemberExpression")
9316 { c(node, st, "MemberPattern"); }
9317 else
9318 { c(node, st); }
9319};
9320base$1.VariablePattern = ignore;
9321base$1.MemberPattern = skipThrough;
9322base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
9323base$1.ArrayPattern = function (node, st, c) {
9324 for (var i = 0, list = node.elements; i < list.length; i += 1) {
9325 var elt = list[i];
9326
9327 if (elt) { c(elt, st, "Pattern"); }
9328 }
9329};
9330base$1.ObjectPattern = function (node, st, c) {
9331 for (var i = 0, list = node.properties; i < list.length; i += 1) {
9332 var prop = list[i];
9333
9334 if (prop.type === "Property") {
9335 if (prop.computed) { c(prop.key, st, "Expression"); }
9336 c(prop.value, st, "Pattern");
9337 } else if (prop.type === "RestElement") {
9338 c(prop.argument, st, "Pattern");
9339 }
9340 }
9341};
9342
9343base$1.Expression = skipThrough;
9344base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
9345base$1.ArrayExpression = function (node, st, c) {
9346 for (var i = 0, list = node.elements; i < list.length; i += 1) {
9347 var elt = list[i];
9348
9349 if (elt) { c(elt, st, "Expression"); }
9350 }
9351};
9352base$1.ObjectExpression = function (node, st, c) {
9353 for (var i = 0, list = node.properties; i < list.length; i += 1)
9354 {
9355 var prop = list[i];
9356
9357 c(prop, st);
9358 }
9359};
9360base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
9361base$1.SequenceExpression = function (node, st, c) {
9362 for (var i = 0, list = node.expressions; i < list.length; i += 1)
9363 {
9364 var expr = list[i];
9365
9366 c(expr, st, "Expression");
9367 }
9368};
9369base$1.TemplateLiteral = function (node, st, c) {
9370 for (var i = 0, list = node.quasis; i < list.length; i += 1)
9371 {
9372 var quasi = list[i];
9373
9374 c(quasi, st);
9375 }
9376
9377 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
9378 {
9379 var expr = list$1[i$1];
9380
9381 c(expr, st, "Expression");
9382 }
9383};
9384base$1.TemplateElement = ignore;
9385base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
9386 c(node.argument, st, "Expression");
9387};
9388base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
9389 c(node.left, st, "Expression");
9390 c(node.right, st, "Expression");
9391};
9392base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
9393 c(node.left, st, "Pattern");
9394 c(node.right, st, "Expression");
9395};
9396base$1.ConditionalExpression = function (node, st, c) {
9397 c(node.test, st, "Expression");
9398 c(node.consequent, st, "Expression");
9399 c(node.alternate, st, "Expression");
9400};
9401base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
9402 c(node.callee, st, "Expression");
9403 if (node.arguments)
9404 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
9405 {
9406 var arg = list[i];
9407
9408 c(arg, st, "Expression");
9409 } }
9410};
9411base$1.MemberExpression = function (node, st, c) {
9412 c(node.object, st, "Expression");
9413 if (node.computed) { c(node.property, st, "Expression"); }
9414};
9415base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
9416 if (node.declaration)
9417 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
9418 if (node.source) { c(node.source, st, "Expression"); }
9419};
9420base$1.ExportAllDeclaration = function (node, st, c) {
9421 if (node.exported)
9422 { c(node.exported, st); }
9423 c(node.source, st, "Expression");
9424};
9425base$1.ImportDeclaration = function (node, st, c) {
9426 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
9427 {
9428 var spec = list[i];
9429
9430 c(spec, st);
9431 }
9432 c(node.source, st, "Expression");
9433};
9434base$1.ImportExpression = function (node, st, c) {
9435 c(node.source, st, "Expression");
9436};
9437base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
9438
9439base$1.TaggedTemplateExpression = function (node, st, c) {
9440 c(node.tag, st, "Expression");
9441 c(node.quasi, st, "Expression");
9442};
9443base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
9444base$1.Class = function (node, st, c) {
9445 if (node.id) { c(node.id, st, "Pattern"); }
9446 if (node.superClass) { c(node.superClass, st, "Expression"); }
9447 c(node.body, st);
9448};
9449base$1.ClassBody = function (node, st, c) {
9450 for (var i = 0, list = node.body; i < list.length; i += 1)
9451 {
9452 var elt = list[i];
9453
9454 c(elt, st);
9455 }
9456};
9457base$1.MethodDefinition = base$1.Property = function (node, st, c) {
9458 if (node.computed) { c(node.key, st, "Expression"); }
9459 c(node.value, st, "Expression");
9460};
9461
9462// @ts-ignore
9463// patch up acorn-walk until class-fields are officially supported
9464base$1.FieldDefinition = function (node, st, c) {
9465 if (node.computed) {
9466 c(node.key, st, 'Expression');
9467 }
9468 if (node.value) {
9469 c(node.value, st, 'Expression');
9470 }
9471};
9472function handlePureAnnotationsOfNode(node, state, type = node.type) {
9473 let commentNode = state.commentNodes[state.commentIndex];
9474 while (commentNode && node.start >= commentNode.end) {
9475 markPureNode(node, commentNode);
9476 commentNode = state.commentNodes[++state.commentIndex];
9477 }
9478 if (commentNode && commentNode.end <= node.end) {
9479 base$1[type](node, state, handlePureAnnotationsOfNode);
9480 }
9481}
9482function markPureNode(node, comment) {
9483 if (node.annotations) {
9484 node.annotations.push(comment);
9485 }
9486 else {
9487 node.annotations = [comment];
9488 }
9489 if (node.type === 'ExpressionStatement') {
9490 node = node.expression;
9491 }
9492 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
9493 node.annotatedPure = true;
9494 }
9495}
9496const pureCommentRegex = /[@#]__PURE__/;
9497const isPureComment = (comment) => pureCommentRegex.test(comment.text);
9498function markPureCallExpressions(comments, esTreeAst) {
9499 handlePureAnnotationsOfNode(esTreeAst, {
9500 commentIndex: 0,
9501 commentNodes: comments.filter(isPureComment)
9502 });
9503}
9504
9505// this looks ridiculous, but it prevents sourcemap tooling from mistaking
9506// this for an actual sourceMappingURL
9507let SOURCEMAPPING_URL = 'sourceMa';
9508SOURCEMAPPING_URL += 'ppingURL';
9509const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
9510
9511const NOOP = () => { };
9512let getStartTime = () => [0, 0];
9513let getElapsedTime = () => 0;
9514let getMemory = () => 0;
9515let timers = {};
9516const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
9517function setTimeHelpers() {
9518 if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
9519 getStartTime = process.hrtime.bind(process);
9520 getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
9521 }
9522 else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
9523 getStartTime = () => [performance.now(), 0];
9524 getElapsedTime = previous => performance.now() - previous[0];
9525 }
9526 if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
9527 getMemory = () => process.memoryUsage().heapUsed;
9528 }
9529}
9530function getPersistedLabel(label, level) {
9531 switch (level) {
9532 case 1:
9533 return `# ${label}`;
9534 case 2:
9535 return `## ${label}`;
9536 case 3:
9537 return label;
9538 default:
9539 return `${' '.repeat(level - 4)}- ${label}`;
9540 }
9541}
9542function timeStartImpl(label, level = 3) {
9543 label = getPersistedLabel(label, level);
9544 if (!timers.hasOwnProperty(label)) {
9545 timers[label] = {
9546 memory: 0,
9547 startMemory: undefined,
9548 startTime: undefined,
9549 time: 0,
9550 totalMemory: 0
9551 };
9552 }
9553 const currentMemory = getMemory();
9554 timers[label].startTime = getStartTime();
9555 timers[label].startMemory = currentMemory;
9556}
9557function timeEndImpl(label, level = 3) {
9558 label = getPersistedLabel(label, level);
9559 if (timers.hasOwnProperty(label)) {
9560 const currentMemory = getMemory();
9561 timers[label].time += getElapsedTime(timers[label].startTime);
9562 timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
9563 timers[label].memory += currentMemory - timers[label].startMemory;
9564 }
9565}
9566function getTimings() {
9567 const newTimings = {};
9568 for (const label of Object.keys(timers)) {
9569 newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
9570 }
9571 return newTimings;
9572}
9573let timeStart = NOOP, timeEnd = NOOP;
9574const TIMED_PLUGIN_HOOKS = {
9575 load: true,
9576 resolveDynamicImport: true,
9577 resolveId: true,
9578 transform: true
9579};
9580function getPluginWithTimers(plugin, index) {
9581 const timedPlugin = {};
9582 for (const hook of Object.keys(plugin)) {
9583 if (TIMED_PLUGIN_HOOKS[hook] === true) {
9584 let timerLabel = `plugin ${index}`;
9585 if (plugin.name) {
9586 timerLabel += ` (${plugin.name})`;
9587 }
9588 timerLabel += ` - ${hook}`;
9589 timedPlugin[hook] = function () {
9590 timeStart(timerLabel, 4);
9591 const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
9592 timeEnd(timerLabel, 4);
9593 if (result && typeof result.then === 'function') {
9594 timeStart(`${timerLabel} (async)`, 4);
9595 result.then(() => timeEnd(`${timerLabel} (async)`, 4));
9596 }
9597 return result;
9598 };
9599 }
9600 else {
9601 timedPlugin[hook] = plugin[hook];
9602 }
9603 }
9604 return timedPlugin;
9605}
9606function initialiseTimers(inputOptions) {
9607 if (inputOptions.perf) {
9608 timers = {};
9609 setTimeHelpers();
9610 timeStart = timeStartImpl;
9611 timeEnd = timeEndImpl;
9612 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
9613 }
9614 else {
9615 timeStart = NOOP;
9616 timeEnd = NOOP;
9617 }
9618}
9619
9620function tryParse(module, Parser, acornOptions) {
9621 try {
9622 return Parser.parse(module.info.code, {
9623 ...acornOptions,
9624 onComment: (block, text, start, end) => module.comments.push({ block, text, start, end })
9625 });
9626 }
9627 catch (err) {
9628 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
9629 if (module.id.endsWith('.json')) {
9630 message += ' (Note that you need @rollup/plugin-json to import JSON files)';
9631 }
9632 else if (!module.id.endsWith('.js')) {
9633 message += ' (Note that you need plugins to import files that are not JavaScript)';
9634 }
9635 return module.error({
9636 code: 'PARSE_ERROR',
9637 message,
9638 parserError: err
9639 }, err.pos);
9640 }
9641}
9642function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
9643 return importingModule.error({
9644 code: 'MISSING_EXPORT',
9645 message: `'${exportName}' is not exported by ${relativeId(importedModule)}, imported by ${relativeId(importingModule.id)}`,
9646 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
9647 }, importerStart);
9648}
9649const MISSING_EXPORT_SHIM_DESCRIPTION = {
9650 identifier: null,
9651 localName: MISSING_EXPORT_SHIM_VARIABLE
9652};
9653function getVariableForExportNameRecursive(target, name, isExportAllSearch, searchedNamesAndModules = new Map()) {
9654 const searchedModules = searchedNamesAndModules.get(name);
9655 if (searchedModules) {
9656 if (searchedModules.has(target)) {
9657 return null;
9658 }
9659 searchedModules.add(target);
9660 }
9661 else {
9662 searchedNamesAndModules.set(name, new Set([target]));
9663 }
9664 return target.getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules);
9665}
9666class Module {
9667 constructor(graph, id, options, isEntry, hasModuleSideEffects, syntheticNamedExports, meta) {
9668 this.graph = graph;
9669 this.id = id;
9670 this.options = options;
9671 this.syntheticNamedExports = syntheticNamedExports;
9672 this.ast = null;
9673 this.chunkFileNames = new Set();
9674 this.chunkName = null;
9675 this.comments = [];
9676 this.dependencies = new Set();
9677 this.dynamicDependencies = new Set();
9678 this.dynamicImporters = [];
9679 this.dynamicImports = [];
9680 this.execIndex = Infinity;
9681 this.exportAllSources = new Set();
9682 this.exports = Object.create(null);
9683 this.exportsAll = Object.create(null);
9684 this.implicitlyLoadedAfter = new Set();
9685 this.implicitlyLoadedBefore = new Set();
9686 this.importDescriptions = Object.create(null);
9687 this.importers = [];
9688 this.importMetas = [];
9689 this.imports = new Set();
9690 this.includedDynamicImporters = [];
9691 this.isExecuted = false;
9692 this.isUserDefinedEntryPoint = false;
9693 this.preserveSignature = this.options.preserveEntrySignatures;
9694 this.reexportDescriptions = Object.create(null);
9695 this.sources = new Set();
9696 this.userChunkNames = new Set();
9697 this.usesTopLevelAwait = false;
9698 this.allExportNames = null;
9699 this.exportAllModules = [];
9700 this.exportNamesByVariable = null;
9701 this.exportShimVariable = new ExportShimVariable(this);
9702 this.relevantDependencies = null;
9703 this.syntheticExports = new Map();
9704 this.syntheticNamespace = null;
9705 this.transformDependencies = [];
9706 this.transitiveReexports = null;
9707 this.excludeFromSourcemap = /\0/.test(id);
9708 this.context = options.moduleContext(id);
9709 const module = this;
9710 this.info = {
9711 ast: null,
9712 code: null,
9713 get dynamicallyImportedIds() {
9714 const dynamicallyImportedIds = [];
9715 for (const { resolution } of module.dynamicImports) {
9716 if (resolution instanceof Module || resolution instanceof ExternalModule) {
9717 dynamicallyImportedIds.push(resolution.id);
9718 }
9719 }
9720 return dynamicallyImportedIds;
9721 },
9722 get dynamicImporters() {
9723 return module.dynamicImporters.sort();
9724 },
9725 hasModuleSideEffects,
9726 id,
9727 get implicitlyLoadedAfterOneOf() {
9728 return Array.from(module.implicitlyLoadedAfter, getId);
9729 },
9730 get implicitlyLoadedBefore() {
9731 return Array.from(module.implicitlyLoadedBefore, getId);
9732 },
9733 get importedIds() {
9734 return Array.from(module.sources, source => module.resolvedIds[source].id);
9735 },
9736 get importers() {
9737 return module.importers.sort();
9738 },
9739 isEntry,
9740 isExternal: false,
9741 meta
9742 };
9743 }
9744 basename() {
9745 const base = basename(this.id);
9746 const ext = extname(this.id);
9747 return makeLegal(ext ? base.slice(0, -ext.length) : base);
9748 }
9749 bindReferences() {
9750 this.ast.bind();
9751 }
9752 error(props, pos) {
9753 this.addLocationToLogProps(props, pos);
9754 return error(props);
9755 }
9756 getAllExportNames() {
9757 if (this.allExportNames) {
9758 return this.allExportNames;
9759 }
9760 const allExportNames = (this.allExportNames = new Set());
9761 for (const name of Object.keys(this.exports)) {
9762 allExportNames.add(name);
9763 }
9764 for (const name of Object.keys(this.reexportDescriptions)) {
9765 allExportNames.add(name);
9766 }
9767 for (const module of this.exportAllModules) {
9768 if (module instanceof ExternalModule) {
9769 allExportNames.add(`*${module.id}`);
9770 continue;
9771 }
9772 for (const name of module.getAllExportNames()) {
9773 if (name !== 'default')
9774 allExportNames.add(name);
9775 }
9776 }
9777 return allExportNames;
9778 }
9779 getDependenciesToBeIncluded() {
9780 if (this.relevantDependencies)
9781 return this.relevantDependencies;
9782 const relevantDependencies = new Set();
9783 const additionalSideEffectModules = new Set();
9784 const possibleDependencies = new Set(this.dependencies);
9785 let dependencyVariables = this.imports;
9786 if (this.info.isEntry ||
9787 this.includedDynamicImporters.length > 0 ||
9788 this.namespace.included ||
9789 this.implicitlyLoadedAfter.size > 0) {
9790 dependencyVariables = new Set(dependencyVariables);
9791 for (const exportName of [...this.getReexports(), ...this.getExports()]) {
9792 dependencyVariables.add(this.getVariableForExportName(exportName));
9793 }
9794 }
9795 for (let variable of dependencyVariables) {
9796 if (variable instanceof SyntheticNamedExportVariable) {
9797 variable = variable.getBaseVariable();
9798 }
9799 else if (variable instanceof ExportDefaultVariable) {
9800 const { modules, original } = variable.getOriginalVariableAndDeclarationModules();
9801 variable = original;
9802 for (const module of modules) {
9803 additionalSideEffectModules.add(module);
9804 possibleDependencies.add(module);
9805 }
9806 }
9807 relevantDependencies.add(variable.module);
9808 }
9809 if (this.options.treeshake && this.info.hasModuleSideEffects !== 'no-treeshake') {
9810 for (const dependency of possibleDependencies) {
9811 if (!(dependency.info.hasModuleSideEffects ||
9812 additionalSideEffectModules.has(dependency)) ||
9813 relevantDependencies.has(dependency)) {
9814 continue;
9815 }
9816 if (dependency instanceof ExternalModule || dependency.hasEffects()) {
9817 relevantDependencies.add(dependency);
9818 }
9819 else {
9820 for (const transitiveDependency of dependency.dependencies) {
9821 possibleDependencies.add(transitiveDependency);
9822 }
9823 }
9824 }
9825 }
9826 else {
9827 for (const dependency of this.dependencies) {
9828 relevantDependencies.add(dependency);
9829 }
9830 }
9831 return (this.relevantDependencies = relevantDependencies);
9832 }
9833 getExportNamesByVariable() {
9834 if (this.exportNamesByVariable) {
9835 return this.exportNamesByVariable;
9836 }
9837 const exportNamesByVariable = new Map();
9838 for (const exportName of this.getAllExportNames()) {
9839 if (exportName === this.syntheticNamedExports)
9840 continue;
9841 let tracedVariable = this.getVariableForExportName(exportName);
9842 if (tracedVariable instanceof ExportDefaultVariable) {
9843 tracedVariable = tracedVariable.getOriginalVariable();
9844 }
9845 if (!tracedVariable ||
9846 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
9847 continue;
9848 }
9849 const existingExportNames = exportNamesByVariable.get(tracedVariable);
9850 if (existingExportNames) {
9851 existingExportNames.push(exportName);
9852 }
9853 else {
9854 exportNamesByVariable.set(tracedVariable, [exportName]);
9855 }
9856 }
9857 return (this.exportNamesByVariable = exportNamesByVariable);
9858 }
9859 getExports() {
9860 return Object.keys(this.exports);
9861 }
9862 getReexports() {
9863 if (this.transitiveReexports) {
9864 return this.transitiveReexports;
9865 }
9866 // to avoid infinite recursion when using circular `export * from X`
9867 this.transitiveReexports = [];
9868 const reexports = new Set();
9869 for (const name in this.reexportDescriptions) {
9870 reexports.add(name);
9871 }
9872 for (const module of this.exportAllModules) {
9873 if (module instanceof ExternalModule) {
9874 reexports.add(`*${module.id}`);
9875 }
9876 else {
9877 for (const name of [...module.getReexports(), ...module.getExports()]) {
9878 if (name !== 'default')
9879 reexports.add(name);
9880 }
9881 }
9882 }
9883 return (this.transitiveReexports = [...reexports]);
9884 }
9885 getRenderedExports() {
9886 // only direct exports are counted here, not reexports at all
9887 const renderedExports = [];
9888 const removedExports = [];
9889 for (const exportName in this.exports) {
9890 const variable = this.getVariableForExportName(exportName);
9891 (variable && variable.included ? renderedExports : removedExports).push(exportName);
9892 }
9893 return { renderedExports, removedExports };
9894 }
9895 getSyntheticNamespace() {
9896 if (this.syntheticNamespace === null) {
9897 this.syntheticNamespace = undefined;
9898 this.syntheticNamespace = this.getVariableForExportName(typeof this.syntheticNamedExports === 'string' ? this.syntheticNamedExports : 'default');
9899 }
9900 if (!this.syntheticNamespace) {
9901 return error({
9902 code: Errors.SYNTHETIC_NAMED_EXPORTS_NEED_NAMESPACE_EXPORT,
9903 id: this.id,
9904 message: `Module "${relativeId(this.id)}" that is marked with 'syntheticNamedExports: ${JSON.stringify(this.syntheticNamedExports)}' needs ${typeof this.syntheticNamedExports === 'string' && this.syntheticNamedExports !== 'default'
9905 ? `an export named "${this.syntheticNamedExports}"`
9906 : 'a default export'}.`
9907 });
9908 }
9909 return this.syntheticNamespace;
9910 }
9911 getVariableForExportName(name, isExportAllSearch, searchedNamesAndModules) {
9912 if (name[0] === '*') {
9913 if (name.length === 1) {
9914 return this.namespace;
9915 }
9916 else {
9917 // export * from 'external'
9918 const module = this.graph.modulesById.get(name.slice(1));
9919 return module.getVariableForExportName('*');
9920 }
9921 }
9922 // export { foo } from './other'
9923 const reexportDeclaration = this.reexportDescriptions[name];
9924 if (reexportDeclaration) {
9925 const declaration = getVariableForExportNameRecursive(reexportDeclaration.module, reexportDeclaration.localName, false, searchedNamesAndModules);
9926 if (!declaration) {
9927 return handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
9928 }
9929 return declaration;
9930 }
9931 const exportDeclaration = this.exports[name];
9932 if (exportDeclaration) {
9933 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
9934 return this.exportShimVariable;
9935 }
9936 const name = exportDeclaration.localName;
9937 return this.traceVariable(name);
9938 }
9939 if (name !== 'default') {
9940 for (const module of this.exportAllModules) {
9941 const declaration = getVariableForExportNameRecursive(module, name, true, searchedNamesAndModules);
9942 if (declaration)
9943 return declaration;
9944 }
9945 }
9946 // we don't want to create shims when we are just
9947 // probing export * modules for exports
9948 if (!isExportAllSearch) {
9949 if (this.syntheticNamedExports) {
9950 let syntheticExport = this.syntheticExports.get(name);
9951 if (!syntheticExport) {
9952 const syntheticNamespace = this.getSyntheticNamespace();
9953 syntheticExport = new SyntheticNamedExportVariable(this.astContext, name, syntheticNamespace);
9954 this.syntheticExports.set(name, syntheticExport);
9955 return syntheticExport;
9956 }
9957 return syntheticExport;
9958 }
9959 if (this.options.shimMissingExports) {
9960 this.shimMissingExport(name);
9961 return this.exportShimVariable;
9962 }
9963 }
9964 return null;
9965 }
9966 hasEffects() {
9967 return (this.info.hasModuleSideEffects === 'no-treeshake' ||
9968 (this.ast.included && this.ast.hasEffects(createHasEffectsContext())));
9969 }
9970 include() {
9971 const context = createInclusionContext();
9972 if (this.ast.shouldBeIncluded(context))
9973 this.ast.include(context, false);
9974 }
9975 includeAllExports(includeNamespaceMembers) {
9976 if (!this.isExecuted) {
9977 this.graph.needsTreeshakingPass = true;
9978 markModuleAndImpureDependenciesAsExecuted(this);
9979 }
9980 for (const exportName of this.getExports()) {
9981 if (includeNamespaceMembers || exportName !== this.syntheticNamedExports) {
9982 const variable = this.getVariableForExportName(exportName);
9983 variable.deoptimizePath(UNKNOWN_PATH);
9984 if (!variable.included) {
9985 variable.include();
9986 this.graph.needsTreeshakingPass = true;
9987 }
9988 }
9989 }
9990 for (const name of this.getReexports()) {
9991 const variable = this.getVariableForExportName(name);
9992 variable.deoptimizePath(UNKNOWN_PATH);
9993 if (!variable.included) {
9994 variable.include();
9995 this.graph.needsTreeshakingPass = true;
9996 }
9997 if (variable instanceof ExternalVariable) {
9998 variable.module.reexported = true;
9999 }
10000 }
10001 if (includeNamespaceMembers) {
10002 this.namespace.prepareNamespace(this.includeAndGetAdditionalMergedNamespaces());
10003 }
10004 }
10005 includeAllInBundle() {
10006 this.ast.include(createInclusionContext(), true);
10007 }
10008 isIncluded() {
10009 return this.ast.included || this.namespace.included;
10010 }
10011 linkImports() {
10012 this.addModulesToImportDescriptions(this.importDescriptions);
10013 this.addModulesToImportDescriptions(this.reexportDescriptions);
10014 for (const name in this.exports) {
10015 if (name !== 'default') {
10016 this.exportsAll[name] = this.id;
10017 }
10018 }
10019 const externalExportAllModules = [];
10020 for (const source of this.exportAllSources) {
10021 const module = this.graph.modulesById.get(this.resolvedIds[source].id);
10022 if (module instanceof ExternalModule) {
10023 externalExportAllModules.push(module);
10024 continue;
10025 }
10026 this.exportAllModules.push(module);
10027 for (const name in module.exportsAll) {
10028 if (name in this.exportsAll) {
10029 this.options.onwarn(errNamespaceConflict(name, this, module));
10030 }
10031 else {
10032 this.exportsAll[name] = module.exportsAll[name];
10033 }
10034 }
10035 }
10036 this.exportAllModules.push(...externalExportAllModules);
10037 }
10038 render(options) {
10039 const magicString = this.magicString.clone();
10040 this.ast.render(magicString, options);
10041 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
10042 return magicString;
10043 }
10044 setSource({ alwaysRemovedCode, ast, code, customTransformCache, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles, ...moduleOptions }) {
10045 this.info.code = code;
10046 this.originalCode = originalCode;
10047 this.originalSourcemap = originalSourcemap;
10048 this.sourcemapChain = sourcemapChain;
10049 if (transformFiles) {
10050 this.transformFiles = transformFiles;
10051 }
10052 this.transformDependencies = transformDependencies;
10053 this.customTransformCache = customTransformCache;
10054 this.updateOptions(moduleOptions);
10055 timeStart('generate ast', 3);
10056 this.alwaysRemovedCode = alwaysRemovedCode || [];
10057 if (!ast) {
10058 ast = tryParse(this, this.graph.acornParser, this.options.acorn);
10059 for (const comment of this.comments) {
10060 if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
10061 this.alwaysRemovedCode.push([comment.start, comment.end]);
10062 }
10063 }
10064 markPureCallExpressions(this.comments, ast);
10065 }
10066 timeEnd('generate ast', 3);
10067 this.resolvedIds = resolvedIds || Object.create(null);
10068 // By default, `id` is the file name. Custom resolvers and loaders
10069 // can change that, but it makes sense to use it for the source file name
10070 const fileName = this.id;
10071 this.magicString = new MagicString(code, {
10072 filename: (this.excludeFromSourcemap ? null : fileName),
10073 indentExclusionRanges: []
10074 });
10075 for (const [start, end] of this.alwaysRemovedCode) {
10076 this.magicString.remove(start, end);
10077 }
10078 timeStart('analyse ast', 3);
10079 this.astContext = {
10080 addDynamicImport: this.addDynamicImport.bind(this),
10081 addExport: this.addExport.bind(this),
10082 addImport: this.addImport.bind(this),
10083 addImportMeta: this.addImportMeta.bind(this),
10084 code,
10085 deoptimizationTracker: this.graph.deoptimizationTracker,
10086 error: this.error.bind(this),
10087 fileName,
10088 getExports: this.getExports.bind(this),
10089 getModuleExecIndex: () => this.execIndex,
10090 getModuleName: this.basename.bind(this),
10091 getReexports: this.getReexports.bind(this),
10092 importDescriptions: this.importDescriptions,
10093 includeAllExports: () => this.includeAllExports(true),
10094 includeDynamicImport: this.includeDynamicImport.bind(this),
10095 includeVariable: this.includeVariable.bind(this),
10096 magicString: this.magicString,
10097 module: this,
10098 moduleContext: this.context,
10099 nodeConstructors,
10100 options: this.options,
10101 traceExport: this.getVariableForExportName.bind(this),
10102 traceVariable: this.traceVariable.bind(this),
10103 usesTopLevelAwait: false,
10104 warn: this.warn.bind(this)
10105 };
10106 this.scope = new ModuleScope(this.graph.scope, this.astContext);
10107 this.namespace = new NamespaceVariable(this.astContext, this.syntheticNamedExports);
10108 this.ast = new Program$1(ast, { type: 'Module', context: this.astContext }, this.scope);
10109 this.info.ast = ast;
10110 timeEnd('analyse ast', 3);
10111 }
10112 toJSON() {
10113 return {
10114 alwaysRemovedCode: this.alwaysRemovedCode,
10115 ast: this.ast.esTreeNode,
10116 code: this.info.code,
10117 customTransformCache: this.customTransformCache,
10118 dependencies: Array.from(this.dependencies, getId),
10119 id: this.id,
10120 meta: this.info.meta,
10121 moduleSideEffects: this.info.hasModuleSideEffects,
10122 originalCode: this.originalCode,
10123 originalSourcemap: this.originalSourcemap,
10124 resolvedIds: this.resolvedIds,
10125 sourcemapChain: this.sourcemapChain,
10126 syntheticNamedExports: this.syntheticNamedExports,
10127 transformDependencies: this.transformDependencies,
10128 transformFiles: this.transformFiles
10129 };
10130 }
10131 traceVariable(name) {
10132 const localVariable = this.scope.variables.get(name);
10133 if (localVariable) {
10134 return localVariable;
10135 }
10136 if (name in this.importDescriptions) {
10137 const importDeclaration = this.importDescriptions[name];
10138 const otherModule = importDeclaration.module;
10139 if (otherModule instanceof Module && importDeclaration.name === '*') {
10140 return otherModule.namespace;
10141 }
10142 const declaration = otherModule.getVariableForExportName(importDeclaration.name);
10143 if (!declaration) {
10144 return handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
10145 }
10146 return declaration;
10147 }
10148 return null;
10149 }
10150 updateOptions({ meta, moduleSideEffects, syntheticNamedExports }) {
10151 if (moduleSideEffects != null) {
10152 this.info.hasModuleSideEffects = moduleSideEffects;
10153 }
10154 if (syntheticNamedExports != null) {
10155 this.syntheticNamedExports = syntheticNamedExports;
10156 }
10157 if (meta != null) {
10158 this.info.meta = { ...this.info.meta, ...meta };
10159 }
10160 }
10161 warn(props, pos) {
10162 this.addLocationToLogProps(props, pos);
10163 this.options.onwarn(props);
10164 }
10165 addDynamicImport(node) {
10166 let argument = node.source;
10167 if (argument instanceof TemplateLiteral) {
10168 if (argument.quasis.length === 1 && argument.quasis[0].value.cooked) {
10169 argument = argument.quasis[0].value.cooked;
10170 }
10171 }
10172 else if (argument instanceof Literal && typeof argument.value === 'string') {
10173 argument = argument.value;
10174 }
10175 this.dynamicImports.push({ node, resolution: null, argument });
10176 }
10177 addExport(node) {
10178 if (node instanceof ExportDefaultDeclaration) {
10179 // export default foo;
10180 this.exports.default = {
10181 identifier: node.variable.getAssignedVariableName(),
10182 localName: 'default'
10183 };
10184 }
10185 else if (node instanceof ExportAllDeclaration) {
10186 const source = node.source.value;
10187 this.sources.add(source);
10188 if (node.exported) {
10189 // export * as name from './other'
10190 const name = node.exported.name;
10191 this.reexportDescriptions[name] = {
10192 localName: '*',
10193 module: null,
10194 source,
10195 start: node.start
10196 };
10197 }
10198 else {
10199 // export * from './other'
10200 this.exportAllSources.add(source);
10201 }
10202 }
10203 else if (node.source instanceof Literal) {
10204 // export { name } from './other'
10205 const source = node.source.value;
10206 this.sources.add(source);
10207 for (const specifier of node.specifiers) {
10208 const name = specifier.exported.name;
10209 this.reexportDescriptions[name] = {
10210 localName: specifier.local.name,
10211 module: null,
10212 source,
10213 start: specifier.start
10214 };
10215 }
10216 }
10217 else if (node.declaration) {
10218 const declaration = node.declaration;
10219 if (declaration instanceof VariableDeclaration) {
10220 // export var { foo, bar } = ...
10221 // export var foo = 1, bar = 2;
10222 for (const declarator of declaration.declarations) {
10223 for (const localName of extractAssignedNames(declarator.id)) {
10224 this.exports[localName] = { identifier: null, localName };
10225 }
10226 }
10227 }
10228 else {
10229 // export function foo () {}
10230 const localName = declaration.id.name;
10231 this.exports[localName] = { identifier: null, localName };
10232 }
10233 }
10234 else {
10235 // export { foo, bar, baz }
10236 for (const specifier of node.specifiers) {
10237 const localName = specifier.local.name;
10238 const exportedName = specifier.exported.name;
10239 this.exports[exportedName] = { identifier: null, localName };
10240 }
10241 }
10242 }
10243 addImport(node) {
10244 const source = node.source.value;
10245 this.sources.add(source);
10246 for (const specifier of node.specifiers) {
10247 const isDefault = specifier.type === ImportDefaultSpecifier;
10248 const isNamespace = specifier.type === ImportNamespaceSpecifier;
10249 const name = isDefault
10250 ? 'default'
10251 : isNamespace
10252 ? '*'
10253 : specifier.imported.name;
10254 this.importDescriptions[specifier.local.name] = {
10255 module: null,
10256 name,
10257 source,
10258 start: specifier.start
10259 };
10260 }
10261 }
10262 addImportMeta(node) {
10263 this.importMetas.push(node);
10264 }
10265 addLocationToLogProps(props, pos) {
10266 props.id = this.id;
10267 props.pos = pos;
10268 let code = this.info.code;
10269 let { column, line } = locate(code, pos, { offsetLine: 1 });
10270 try {
10271 ({ column, line } = getOriginalLocation(this.sourcemapChain, { column, line }));
10272 code = this.originalCode;
10273 }
10274 catch (e) {
10275 this.options.onwarn({
10276 code: 'SOURCEMAP_ERROR',
10277 id: this.id,
10278 loc: {
10279 column,
10280 file: this.id,
10281 line
10282 },
10283 message: `Error when using sourcemap for reporting an error: ${e.message}`,
10284 pos
10285 });
10286 }
10287 augmentCodeLocation(props, { column, line }, code, this.id);
10288 }
10289 addModulesToImportDescriptions(importDescription) {
10290 for (const name of Object.keys(importDescription)) {
10291 const specifier = importDescription[name];
10292 const id = this.resolvedIds[specifier.source].id;
10293 specifier.module = this.graph.modulesById.get(id);
10294 }
10295 }
10296 includeAndGetAdditionalMergedNamespaces() {
10297 const mergedNamespaces = [];
10298 for (const module of this.exportAllModules) {
10299 if (module instanceof ExternalModule) {
10300 const externalVariable = module.getVariableForExportName('*');
10301 externalVariable.include();
10302 this.imports.add(externalVariable);
10303 mergedNamespaces.push(externalVariable);
10304 }
10305 else if (module.syntheticNamedExports) {
10306 const syntheticNamespace = module.getSyntheticNamespace();
10307 syntheticNamespace.include();
10308 this.imports.add(syntheticNamespace);
10309 mergedNamespaces.push(syntheticNamespace);
10310 }
10311 }
10312 return mergedNamespaces;
10313 }
10314 includeDynamicImport(node) {
10315 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
10316 if (resolution instanceof Module) {
10317 resolution.includedDynamicImporters.push(this);
10318 resolution.includeAllExports(true);
10319 }
10320 }
10321 includeVariable(variable) {
10322 const variableModule = variable.module;
10323 if (!variable.included) {
10324 variable.include();
10325 this.graph.needsTreeshakingPass = true;
10326 }
10327 if (variableModule && variableModule !== this) {
10328 this.imports.add(variable);
10329 }
10330 }
10331 shimMissingExport(name) {
10332 this.options.onwarn({
10333 code: 'SHIMMED_EXPORT',
10334 exporter: relativeId(this.id),
10335 exportName: name,
10336 message: `Missing export "${name}" has been shimmed in module ${relativeId(this.id)}.`
10337 });
10338 this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
10339 }
10340}
10341
10342class Source {
10343 constructor(filename, content) {
10344 this.isOriginal = true;
10345 this.filename = filename;
10346 this.content = content;
10347 }
10348 traceSegment(line, column, name) {
10349 return { line, column, name, source: this };
10350 }
10351}
10352class Link {
10353 constructor(map, sources) {
10354 this.sources = sources;
10355 this.names = map.names;
10356 this.mappings = map.mappings;
10357 }
10358 traceMappings() {
10359 const sources = [];
10360 const sourcesContent = [];
10361 const names = [];
10362 const mappings = [];
10363 for (const line of this.mappings) {
10364 const tracedLine = [];
10365 for (const segment of line) {
10366 if (segment.length == 1)
10367 continue;
10368 const source = this.sources[segment[1]];
10369 if (!source)
10370 continue;
10371 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
10372 if (traced) {
10373 // newer sources are more likely to be used, so search backwards.
10374 let sourceIndex = sources.lastIndexOf(traced.source.filename);
10375 if (sourceIndex === -1) {
10376 sourceIndex = sources.length;
10377 sources.push(traced.source.filename);
10378 sourcesContent[sourceIndex] = traced.source.content;
10379 }
10380 else if (sourcesContent[sourceIndex] == null) {
10381 sourcesContent[sourceIndex] = traced.source.content;
10382 }
10383 else if (traced.source.content != null &&
10384 sourcesContent[sourceIndex] !== traced.source.content) {
10385 return error({
10386 message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
10387 });
10388 }
10389 const tracedSegment = [
10390 segment[0],
10391 sourceIndex,
10392 traced.line,
10393 traced.column
10394 ];
10395 if (traced.name) {
10396 let nameIndex = names.indexOf(traced.name);
10397 if (nameIndex === -1) {
10398 nameIndex = names.length;
10399 names.push(traced.name);
10400 }
10401 tracedSegment[4] = nameIndex;
10402 }
10403 tracedLine.push(tracedSegment);
10404 }
10405 }
10406 mappings.push(tracedLine);
10407 }
10408 return { sources, sourcesContent, names, mappings };
10409 }
10410 traceSegment(line, column, name) {
10411 const segments = this.mappings[line];
10412 if (!segments)
10413 return null;
10414 // binary search through segments for the given column
10415 let i = 0;
10416 let j = segments.length - 1;
10417 while (i <= j) {
10418 const m = (i + j) >> 1;
10419 const segment = segments[m];
10420 if (segment[0] === column) {
10421 if (segment.length == 1)
10422 return null;
10423 const source = this.sources[segment[1]];
10424 if (!source)
10425 return null;
10426 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
10427 }
10428 if (segment[0] > column) {
10429 j = m - 1;
10430 }
10431 else {
10432 i = m + 1;
10433 }
10434 }
10435 return null;
10436 }
10437}
10438function getLinkMap(warn) {
10439 return function linkMap(source, map) {
10440 if (map.mappings) {
10441 return new Link(map, [source]);
10442 }
10443 warn({
10444 code: 'SOURCEMAP_BROKEN',
10445 message: `Sourcemap is likely to be incorrect: a plugin (${map.plugin}) was used to transform ` +
10446 "files, but didn't generate a sourcemap for the transformation. Consult the plugin " +
10447 'documentation for help',
10448 plugin: map.plugin,
10449 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
10450 });
10451 return new Link({
10452 mappings: [],
10453 names: []
10454 }, [source]);
10455 };
10456}
10457function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
10458 let source;
10459 if (!originalSourcemap) {
10460 source = new Source(id, originalCode);
10461 }
10462 else {
10463 const sources = originalSourcemap.sources;
10464 const sourcesContent = originalSourcemap.sourcesContent || [];
10465 const directory = dirname(id) || '.';
10466 const sourceRoot = originalSourcemap.sourceRoot || '.';
10467 const baseSources = sources.map((source, i) => new Source(resolve(directory, sourceRoot, source), sourcesContent[i]));
10468 source = new Link(originalSourcemap, baseSources);
10469 }
10470 return sourcemapChain.reduce(linkMap, source);
10471}
10472function collapseSourcemaps(file, map, modules, bundleSourcemapChain, excludeContent, warn) {
10473 const linkMap = getLinkMap(warn);
10474 const moduleSources = modules
10475 .filter(module => !module.excludeFromSourcemap)
10476 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
10477 // DecodedSourceMap (from magic-string) uses a number[] instead of the more
10478 // correct SourceMapSegment tuples. Cast it here to gain type safety.
10479 let source = new Link(map, moduleSources);
10480 source = bundleSourcemapChain.reduce(linkMap, source);
10481 let { sources, sourcesContent, names, mappings } = source.traceMappings();
10482 if (file) {
10483 const directory = dirname(file);
10484 sources = sources.map((source) => relative$1(directory, source));
10485 file = basename(file);
10486 }
10487 sourcesContent = (excludeContent ? null : sourcesContent);
10488 return new SourceMap({ file, sources, sourcesContent, names, mappings });
10489}
10490function collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn) {
10491 if (!sourcemapChain.length) {
10492 return originalSourcemap;
10493 }
10494 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(warn));
10495 const map = source.traceMappings();
10496 return { version: 3, ...map };
10497}
10498
10499const createHash = () => createHash$1('sha256');
10500
10501const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
10502 amd: deconflictImportsOther,
10503 cjs: deconflictImportsOther,
10504 es: deconflictImportsEsmOrSystem,
10505 iife: deconflictImportsOther,
10506 system: deconflictImportsEsmOrSystem,
10507 umd: deconflictImportsOther
10508};
10509function deconflictChunk(modules, dependenciesToBeDeconflicted, imports, usedNames, format, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports, exportNamesByVariable, accessedGlobalsByScope, includedNamespaces) {
10510 for (const module of modules) {
10511 module.scope.addUsedOutsideNames(usedNames, format, exportNamesByVariable, accessedGlobalsByScope);
10512 }
10513 deconflictTopLevelVariables(usedNames, modules, includedNamespaces);
10514 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependenciesToBeDeconflicted, interop, preserveModules, externalLiveBindings, chunkByModule, syntheticExports);
10515 for (const module of modules) {
10516 module.scope.deconflict(format, exportNamesByVariable, accessedGlobalsByScope);
10517 }
10518}
10519function deconflictImportsEsmOrSystem(usedNames, imports, dependenciesToBeDeconflicted, _interop, preserveModules, _externalLiveBindings, chunkByModule, syntheticExports) {
10520 // This is needed for namespace reexports
10521 for (const dependency of dependenciesToBeDeconflicted.dependencies) {
10522 if (preserveModules || dependency instanceof ExternalModule) {
10523 dependency.variableName = getSafeName(dependency.suggestedVariableName, usedNames);
10524 }
10525 }
10526 for (const variable of imports) {
10527 const module = variable.module;
10528 const name = variable.name;
10529 if (variable.isNamespace && (preserveModules || module instanceof ExternalModule)) {
10530 variable.setRenderNames(null, (module instanceof ExternalModule ? module : chunkByModule.get(module)).variableName);
10531 }
10532 else if (module instanceof ExternalModule && name === 'default') {
10533 variable.setRenderNames(null, getSafeName([...module.exportedVariables].some(([exportedVariable, exportedName]) => exportedName === '*' && exportedVariable.included)
10534 ? module.suggestedVariableName + '__default'
10535 : module.suggestedVariableName, usedNames));
10536 }
10537 else {
10538 variable.setRenderNames(null, getSafeName(name, usedNames));
10539 }
10540 }
10541 for (const variable of syntheticExports) {
10542 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
10543 }
10544}
10545function deconflictImportsOther(usedNames, imports, { deconflictedDefault, deconflictedNamespace, dependencies }, interop, preserveModules, externalLiveBindings, chunkByModule) {
10546 for (const chunkOrExternalModule of dependencies) {
10547 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.suggestedVariableName, usedNames);
10548 }
10549 for (const externalModuleOrChunk of deconflictedNamespace) {
10550 externalModuleOrChunk.namespaceVariableName = getSafeName(`${externalModuleOrChunk.suggestedVariableName}__namespace`, usedNames);
10551 }
10552 for (const externalModule of deconflictedDefault) {
10553 if (deconflictedNamespace.has(externalModule) &&
10554 canDefaultBeTakenFromNamespace(String(interop(externalModule.id)), externalLiveBindings)) {
10555 externalModule.defaultVariableName = externalModule.namespaceVariableName;
10556 }
10557 else {
10558 externalModule.defaultVariableName = getSafeName(`${externalModule.suggestedVariableName}__default`, usedNames);
10559 }
10560 }
10561 for (const variable of imports) {
10562 const module = variable.module;
10563 if (module instanceof ExternalModule) {
10564 const name = variable.name;
10565 if (name === 'default') {
10566 const moduleInterop = String(interop(module.id));
10567 const variableName = defaultInteropHelpersByInteropType[moduleInterop]
10568 ? module.defaultVariableName
10569 : module.variableName;
10570 if (isDefaultAProperty(moduleInterop, externalLiveBindings)) {
10571 variable.setRenderNames(variableName, 'default');
10572 }
10573 else {
10574 variable.setRenderNames(null, variableName);
10575 }
10576 }
10577 else if (name === '*') {
10578 variable.setRenderNames(null, namespaceInteropHelpersByInteropType[String(interop(module.id))]
10579 ? module.namespaceVariableName
10580 : module.variableName);
10581 }
10582 else {
10583 // if the second parameter is `null`, it uses its "name" for the property name
10584 variable.setRenderNames(module.variableName, null);
10585 }
10586 }
10587 else {
10588 const chunk = chunkByModule.get(module);
10589 if (preserveModules && variable.isNamespace) {
10590 variable.setRenderNames(null, chunk.exportMode === 'default' ? chunk.namespaceVariableName : chunk.variableName);
10591 }
10592 else if (chunk.exportMode === 'default') {
10593 variable.setRenderNames(null, chunk.variableName);
10594 }
10595 else {
10596 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
10597 }
10598 }
10599 }
10600}
10601function deconflictTopLevelVariables(usedNames, modules, includedNamespaces) {
10602 for (const module of modules) {
10603 for (const variable of module.scope.variables.values()) {
10604 if (variable.included &&
10605 // this will only happen for exports in some formats
10606 !(variable.renderBaseName ||
10607 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
10608 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
10609 }
10610 }
10611 if (includedNamespaces.has(module)) {
10612 const namespace = module.namespace;
10613 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
10614 }
10615 }
10616}
10617
10618const needsEscapeRegEx = /[\\'\r\n\u2028\u2029]/;
10619const quoteNewlineRegEx = /(['\r\n\u2028\u2029])/g;
10620const backSlashRegEx = /\\/g;
10621function escapeId(id) {
10622 if (!id.match(needsEscapeRegEx))
10623 return id;
10624 return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
10625}
10626
10627const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
10628function sortByExecutionOrder(units) {
10629 units.sort(compareExecIndex);
10630}
10631function analyseModuleExecution(entryModules) {
10632 let nextExecIndex = 0;
10633 const cyclePaths = [];
10634 const analysedModules = new Set();
10635 const dynamicImports = new Set();
10636 const parents = new Map();
10637 const orderedModules = [];
10638 const analyseModule = (module) => {
10639 if (module instanceof Module) {
10640 for (const dependency of module.dependencies) {
10641 if (parents.has(dependency)) {
10642 if (!analysedModules.has(dependency)) {
10643 cyclePaths.push(getCyclePath(dependency, module, parents));
10644 }
10645 continue;
10646 }
10647 parents.set(dependency, module);
10648 analyseModule(dependency);
10649 }
10650 for (const dependency of module.implicitlyLoadedBefore) {
10651 dynamicImports.add(dependency);
10652 }
10653 for (const { resolution } of module.dynamicImports) {
10654 if (resolution instanceof Module) {
10655 dynamicImports.add(resolution);
10656 }
10657 }
10658 orderedModules.push(module);
10659 }
10660 module.execIndex = nextExecIndex++;
10661 analysedModules.add(module);
10662 };
10663 for (const curEntry of entryModules) {
10664 if (!parents.has(curEntry)) {
10665 parents.set(curEntry, null);
10666 analyseModule(curEntry);
10667 }
10668 }
10669 for (const curEntry of dynamicImports) {
10670 if (!parents.has(curEntry)) {
10671 parents.set(curEntry, null);
10672 analyseModule(curEntry);
10673 }
10674 }
10675 return { orderedModules, cyclePaths };
10676}
10677function getCyclePath(module, parent, parents) {
10678 const path = [relativeId(module.id)];
10679 let nextModule = parent;
10680 while (nextModule !== module) {
10681 path.push(relativeId(nextModule.id));
10682 nextModule = parents.get(nextModule);
10683 }
10684 path.push(path[0]);
10685 path.reverse();
10686 return path;
10687}
10688
10689function assignExportsToMangledNames(exports, exportsByName, exportNamesByVariable) {
10690 let nameIndex = 0;
10691 for (const variable of exports) {
10692 let exportName = variable.name[0];
10693 if (exportsByName[exportName]) {
10694 do {
10695 exportName = toBase64(++nameIndex);
10696 // skip past leading number identifiers
10697 if (exportName.charCodeAt(0) === 49 /* '1' */) {
10698 nameIndex += 9 * 64 ** (exportName.length - 1);
10699 exportName = toBase64(nameIndex);
10700 }
10701 } while (RESERVED_NAMES[exportName] || exportsByName[exportName]);
10702 }
10703 exportsByName[exportName] = variable;
10704 exportNamesByVariable.set(variable, [exportName]);
10705 }
10706}
10707function assignExportsToNames(exports, exportsByName, exportNamesByVariable) {
10708 for (const variable of exports) {
10709 let nameIndex = 0;
10710 let exportName = variable.name;
10711 while (exportsByName[exportName]) {
10712 exportName = variable.name + '$' + ++nameIndex;
10713 }
10714 exportsByName[exportName] = variable;
10715 exportNamesByVariable.set(variable, [exportName]);
10716 }
10717}
10718
10719function getExportMode(chunk, { exports: exportMode, name, format }, unsetOptions, facadeModuleId, warn) {
10720 const exportKeys = chunk.getExportNames();
10721 if (exportMode === 'default') {
10722 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
10723 return error(errIncompatibleExportOptionValue('default', exportKeys, facadeModuleId));
10724 }
10725 }
10726 else if (exportMode === 'none' && exportKeys.length) {
10727 return error(errIncompatibleExportOptionValue('none', exportKeys, facadeModuleId));
10728 }
10729 if (exportMode === 'auto') {
10730 if (exportKeys.length === 0) {
10731 exportMode = 'none';
10732 }
10733 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
10734 if (format === 'cjs' && unsetOptions.has('exports')) {
10735 warn(errPreferNamedExports(facadeModuleId));
10736 }
10737 exportMode = 'default';
10738 }
10739 else {
10740 if (format !== 'es' && exportKeys.indexOf('default') !== -1) {
10741 warn(errMixedExport(facadeModuleId, name));
10742 }
10743 exportMode = 'named';
10744 }
10745 }
10746 return exportMode;
10747}
10748
10749function guessIndentString(code) {
10750 const lines = code.split('\n');
10751 const tabbed = lines.filter(line => /^\t+/.test(line));
10752 const spaced = lines.filter(line => /^ {2,}/.test(line));
10753 if (tabbed.length === 0 && spaced.length === 0) {
10754 return null;
10755 }
10756 // More lines tabbed than spaced? Assume tabs, and
10757 // default to tabs in the case of a tie (or nothing
10758 // to go on)
10759 if (tabbed.length >= spaced.length) {
10760 return '\t';
10761 }
10762 // Otherwise, we need to guess the multiple
10763 const min = spaced.reduce((previous, current) => {
10764 const numSpaces = /^ +/.exec(current)[0].length;
10765 return Math.min(numSpaces, previous);
10766 }, Infinity);
10767 return new Array(min + 1).join(' ');
10768}
10769function getIndentString(modules, options) {
10770 if (options.indent !== true)
10771 return options.indent;
10772 for (let i = 0; i < modules.length; i++) {
10773 const indent = guessIndentString(modules[i].originalCode);
10774 if (indent !== null)
10775 return indent;
10776 }
10777 return '\t';
10778}
10779
10780function decodedSourcemap(map) {
10781 if (!map)
10782 return null;
10783 if (typeof map === 'string') {
10784 map = JSON.parse(map);
10785 }
10786 if (map.mappings === '') {
10787 return {
10788 mappings: [],
10789 names: [],
10790 sources: [],
10791 version: 3
10792 };
10793 }
10794 let mappings;
10795 if (typeof map.mappings === 'string') {
10796 mappings = decode(map.mappings);
10797 }
10798 else {
10799 mappings = map.mappings;
10800 }
10801 return { ...map, mappings };
10802}
10803
10804function renderChunk({ code, options, outputPluginDriver, renderChunk, sourcemapChain }) {
10805 const renderChunkReducer = (code, result, plugin) => {
10806 if (result == null)
10807 return code;
10808 if (typeof result === 'string')
10809 result = {
10810 code: result,
10811 map: undefined
10812 };
10813 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
10814 if (result.map !== null) {
10815 const map = decodedSourcemap(result.map);
10816 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
10817 }
10818 return result.code;
10819 };
10820 return outputPluginDriver.hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer);
10821}
10822
10823function renderNamePattern(pattern, patternName, replacements, getFileInfo) {
10824 if (typeof pattern === 'function') {
10825 pattern = pattern(getFileInfo());
10826 }
10827 if (!isPlainPathFragment(pattern))
10828 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
10829 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
10830 if (!replacements.hasOwnProperty(type)) {
10831 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
10832 }
10833 const replacement = replacements[type]();
10834 if (!isPlainPathFragment(replacement))
10835 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
10836 return replacement;
10837 });
10838}
10839function makeUnique(name, existingNames) {
10840 const existingNamesLowercase = new Set(Object.keys(existingNames).map(key => key.toLowerCase()));
10841 if (!existingNamesLowercase.has(name.toLocaleLowerCase()))
10842 return name;
10843 const ext = extname(name);
10844 name = name.substr(0, name.length - ext.length);
10845 let uniqueName, uniqueIndex = 1;
10846 while (existingNamesLowercase.has((uniqueName = name + ++uniqueIndex + ext).toLowerCase()))
10847 ;
10848 return uniqueName;
10849}
10850
10851const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
10852function getGlobalName(module, globals, hasExports, warn) {
10853 const globalName = typeof globals === 'function' ? globals(module.id) : globals[module.id];
10854 if (globalName) {
10855 return globalName;
10856 }
10857 if (hasExports) {
10858 warn({
10859 code: 'MISSING_GLOBAL_NAME',
10860 guess: module.variableName,
10861 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
10862 source: module.id
10863 });
10864 return module.variableName;
10865 }
10866}
10867class Chunk$1 {
10868 constructor(orderedModules, inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, manualChunkAlias) {
10869 this.orderedModules = orderedModules;
10870 this.inputOptions = inputOptions;
10871 this.outputOptions = outputOptions;
10872 this.unsetOptions = unsetOptions;
10873 this.pluginDriver = pluginDriver;
10874 this.modulesById = modulesById;
10875 this.chunkByModule = chunkByModule;
10876 this.facadeChunkByModule = facadeChunkByModule;
10877 this.includedNamespaces = includedNamespaces;
10878 this.manualChunkAlias = manualChunkAlias;
10879 this.entryModules = [];
10880 this.exportMode = 'named';
10881 this.facadeModule = null;
10882 this.id = null;
10883 this.namespaceVariableName = '';
10884 this.variableName = '';
10885 this.accessedGlobalsByScope = new Map();
10886 this.dependencies = new Set();
10887 this.dynamicDependencies = new Set();
10888 this.dynamicEntryModules = [];
10889 this.exportNamesByVariable = new Map();
10890 this.exports = new Set();
10891 this.exportsByName = Object.create(null);
10892 this.fileName = null;
10893 this.implicitEntryModules = [];
10894 this.implicitlyLoadedBefore = new Set();
10895 this.imports = new Set();
10896 this.indentString = undefined;
10897 this.isEmpty = true;
10898 this.name = null;
10899 this.needsExportsShim = false;
10900 this.renderedDependencies = null;
10901 this.renderedExports = null;
10902 this.renderedHash = undefined;
10903 this.renderedModules = Object.create(null);
10904 this.renderedModuleSources = new Map();
10905 this.renderedSource = null;
10906 this.sortedExportNames = null;
10907 this.strictFacade = false;
10908 this.usedModules = undefined;
10909 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
10910 const chunkModules = new Set(orderedModules);
10911 for (const module of orderedModules) {
10912 if (module.namespace.included) {
10913 includedNamespaces.add(module);
10914 }
10915 if (this.isEmpty && module.isIncluded()) {
10916 this.isEmpty = false;
10917 }
10918 if (module.info.isEntry || outputOptions.preserveModules) {
10919 this.entryModules.push(module);
10920 }
10921 for (const importer of module.includedDynamicImporters) {
10922 if (!chunkModules.has(importer)) {
10923 this.dynamicEntryModules.push(module);
10924 // Modules with synthetic exports need an artificial namespace for dynamic imports
10925 if (module.syntheticNamedExports && !outputOptions.preserveModules) {
10926 includedNamespaces.add(module);
10927 this.exports.add(module.namespace);
10928 }
10929 }
10930 }
10931 if (module.implicitlyLoadedAfter.size > 0) {
10932 this.implicitEntryModules.push(module);
10933 }
10934 }
10935 this.suggestedVariableName = makeLegal(this.generateVariableName());
10936 }
10937 static generateFacade(inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, facadedModule, facadeName) {
10938 const chunk = new Chunk$1([], inputOptions, outputOptions, unsetOptions, pluginDriver, modulesById, chunkByModule, facadeChunkByModule, includedNamespaces, null);
10939 chunk.assignFacadeName(facadeName, facadedModule);
10940 if (!facadeChunkByModule.has(facadedModule)) {
10941 facadeChunkByModule.set(facadedModule, chunk);
10942 }
10943 for (const dependency of facadedModule.getDependenciesToBeIncluded()) {
10944 chunk.dependencies.add(dependency instanceof Module ? chunkByModule.get(dependency) : dependency);
10945 }
10946 if (!chunk.dependencies.has(chunkByModule.get(facadedModule)) &&
10947 facadedModule.info.hasModuleSideEffects &&
10948 facadedModule.hasEffects()) {
10949 chunk.dependencies.add(chunkByModule.get(facadedModule));
10950 }
10951 chunk.ensureReexportsAreAvailableForModule(facadedModule);
10952 chunk.facadeModule = facadedModule;
10953 chunk.strictFacade = true;
10954 return chunk;
10955 }
10956 canModuleBeFacade(module, exposedVariables) {
10957 const moduleExportNamesByVariable = module.getExportNamesByVariable();
10958 for (const exposedVariable of this.exports) {
10959 if (!moduleExportNamesByVariable.has(exposedVariable)) {
10960 if (moduleExportNamesByVariable.size === 0 &&
10961 module.isUserDefinedEntryPoint &&
10962 module.preserveSignature === 'strict' &&
10963 this.unsetOptions.has('preserveEntrySignatures')) {
10964 this.inputOptions.onwarn({
10965 code: 'EMPTY_FACADE',
10966 id: module.id,
10967 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.`,
10968 url: 'https://rollupjs.org/guide/en/#preserveentrysignatures'
10969 });
10970 }
10971 return false;
10972 }
10973 }
10974 for (const exposedVariable of exposedVariables) {
10975 if (!(moduleExportNamesByVariable.has(exposedVariable) || exposedVariable.module === module)) {
10976 return false;
10977 }
10978 }
10979 return true;
10980 }
10981 generateExports() {
10982 this.sortedExportNames = null;
10983 const remainingExports = new Set(this.exports);
10984 if (this.facadeModule !== null &&
10985 (this.facadeModule.preserveSignature !== false || this.strictFacade)) {
10986 const exportNamesByVariable = this.facadeModule.getExportNamesByVariable();
10987 for (const [variable, exportNames] of exportNamesByVariable) {
10988 this.exportNamesByVariable.set(variable, [...exportNames]);
10989 for (const exportName of exportNames) {
10990 this.exportsByName[exportName] = variable;
10991 }
10992 remainingExports.delete(variable);
10993 }
10994 }
10995 if (this.outputOptions.minifyInternalExports) {
10996 assignExportsToMangledNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
10997 }
10998 else {
10999 assignExportsToNames(remainingExports, this.exportsByName, this.exportNamesByVariable);
11000 }
11001 if (this.outputOptions.preserveModules || (this.facadeModule && this.facadeModule.info.isEntry))
11002 this.exportMode = getExportMode(this, this.outputOptions, this.unsetOptions, this.facadeModule.id, this.inputOptions.onwarn);
11003 }
11004 generateFacades() {
11005 var _a;
11006 const facades = [];
11007 const entryModules = new Set([...this.entryModules, ...this.implicitEntryModules]);
11008 const exposedVariables = new Set(this.dynamicEntryModules.map(module => module.namespace));
11009 for (const module of entryModules) {
11010 if (module.preserveSignature) {
11011 for (const exportedVariable of module.getExportNamesByVariable().keys()) {
11012 exposedVariables.add(exportedVariable);
11013 }
11014 }
11015 }
11016 for (const module of entryModules) {
11017 const requiredFacades = Array.from(module.userChunkNames, name => ({
11018 name
11019 }));
11020 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
11021 requiredFacades.push({});
11022 }
11023 requiredFacades.push(...Array.from(module.chunkFileNames, fileName => ({ fileName })));
11024 if (requiredFacades.length === 0) {
11025 requiredFacades.push({});
11026 }
11027 if (!this.facadeModule) {
11028 const needsStrictFacade = module.preserveSignature === 'strict' ||
11029 (module.preserveSignature === 'exports-only' &&
11030 module.getExportNamesByVariable().size !== 0);
11031 if (!needsStrictFacade ||
11032 this.outputOptions.preserveModules ||
11033 this.canModuleBeFacade(module, exposedVariables)) {
11034 this.facadeModule = module;
11035 this.facadeChunkByModule.set(module, this);
11036 if (module.preserveSignature) {
11037 this.strictFacade = needsStrictFacade;
11038 this.ensureReexportsAreAvailableForModule(module);
11039 }
11040 this.assignFacadeName(requiredFacades.shift(), module);
11041 }
11042 }
11043 for (const facadeName of requiredFacades) {
11044 facades.push(Chunk$1.generateFacade(this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.modulesById, this.chunkByModule, this.facadeChunkByModule, this.includedNamespaces, module, facadeName));
11045 }
11046 }
11047 for (const module of this.dynamicEntryModules) {
11048 if (module.syntheticNamedExports)
11049 continue;
11050 if (!this.facadeModule && this.canModuleBeFacade(module, exposedVariables)) {
11051 this.facadeModule = module;
11052 this.facadeChunkByModule.set(module, this);
11053 this.strictFacade = true;
11054 this.assignFacadeName({}, module);
11055 }
11056 else if (this.facadeModule === module &&
11057 !this.strictFacade &&
11058 this.canModuleBeFacade(module, exposedVariables)) {
11059 this.strictFacade = true;
11060 }
11061 else if (!((_a = this.facadeChunkByModule.get(module)) === null || _a === void 0 ? void 0 : _a.strictFacade)) {
11062 this.includedNamespaces.add(module);
11063 this.exports.add(module.namespace);
11064 }
11065 }
11066 return facades;
11067 }
11068 generateId(addons, options, existingNames, includeHash) {
11069 if (this.fileName !== null) {
11070 return this.fileName;
11071 }
11072 const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
11073 ? [options.entryFileNames, 'output.entryFileNames']
11074 : [options.chunkFileNames, 'output.chunkFileNames'];
11075 return makeUnique(renderNamePattern(pattern, patternName, {
11076 format: () => options.format,
11077 hash: () => includeHash
11078 ? this.computeContentHashWithDependencies(addons, options, existingNames)
11079 : '[hash]',
11080 name: () => this.getChunkName()
11081 }, this.getChunkInfo.bind(this)), existingNames);
11082 }
11083 generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames, unsetOptions) {
11084 const id = this.orderedModules[0].id;
11085 const sanitizedId = sanitizeFileName(id);
11086 let path;
11087 if (isAbsolute(id)) {
11088 const extension = extname(id);
11089 const pattern = unsetOptions.has('entryFileNames')
11090 ? NON_ASSET_EXTENSIONS.includes(extension)
11091 ? '[name].js'
11092 : '[name][extname].js'
11093 : options.entryFileNames;
11094 const currentDir = dirname(sanitizedId);
11095 const fileName = renderNamePattern(pattern, 'output.entryFileNames', {
11096 ext: () => extension.substr(1),
11097 extname: () => extension,
11098 format: () => options.format,
11099 name: () => this.getChunkName()
11100 }, this.getChunkInfo.bind(this));
11101 const currentPath = `${currentDir}/${fileName}`;
11102 const { preserveModulesRoot } = options;
11103 if (preserveModulesRoot && currentPath.startsWith(preserveModulesRoot)) {
11104 path = currentPath.slice(preserveModulesRoot.length).replace(/^[\\/]/, '');
11105 }
11106 else {
11107 path = relative(preserveModulesRelativeDir, currentPath);
11108 }
11109 }
11110 else {
11111 path = `_virtual/${basename(sanitizedId)}`;
11112 }
11113 return makeUnique(normalize(path), existingNames);
11114 }
11115 getChunkInfo() {
11116 const facadeModule = this.facadeModule;
11117 const getChunkName = this.getChunkName.bind(this);
11118 return {
11119 exports: this.getExportNames(),
11120 facadeModuleId: facadeModule && facadeModule.id,
11121 isDynamicEntry: this.dynamicEntryModules.length > 0,
11122 isEntry: facadeModule !== null && facadeModule.info.isEntry,
11123 isImplicitEntry: this.implicitEntryModules.length > 0,
11124 modules: this.renderedModules,
11125 get name() {
11126 return getChunkName();
11127 },
11128 type: 'chunk'
11129 };
11130 }
11131 getChunkInfoWithFileNames() {
11132 return Object.assign(this.getChunkInfo(), {
11133 code: undefined,
11134 dynamicImports: Array.from(this.dynamicDependencies, getId),
11135 fileName: this.id,
11136 implicitlyLoadedBefore: Array.from(this.implicitlyLoadedBefore, getId),
11137 importedBindings: this.getImportedBindingsPerDependency(),
11138 imports: Array.from(this.dependencies, getId),
11139 map: undefined,
11140 referencedFiles: this.getReferencedFiles()
11141 });
11142 }
11143 getChunkName() {
11144 return this.name || (this.name = sanitizeFileName(this.getFallbackChunkName()));
11145 }
11146 getExportNames() {
11147 return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportsByName).sort()));
11148 }
11149 getRenderedHash() {
11150 if (this.renderedHash)
11151 return this.renderedHash;
11152 const hash = createHash();
11153 const hashAugmentation = this.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [this.getChunkInfo()], (augmentation, pluginHash) => {
11154 if (pluginHash) {
11155 augmentation += pluginHash;
11156 }
11157 return augmentation;
11158 });
11159 hash.update(hashAugmentation);
11160 hash.update(this.renderedSource.toString());
11161 hash.update(this.getExportNames()
11162 .map(exportName => {
11163 const variable = this.exportsByName[exportName];
11164 return `${relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
11165 })
11166 .join(','));
11167 return (this.renderedHash = hash.digest('hex'));
11168 }
11169 getVariableExportName(variable) {
11170 if (this.outputOptions.preserveModules && variable instanceof NamespaceVariable) {
11171 return '*';
11172 }
11173 return this.exportNamesByVariable.get(variable)[0];
11174 }
11175 link() {
11176 for (const module of this.orderedModules) {
11177 this.addDependenciesToChunk(module.getDependenciesToBeIncluded(), this.dependencies);
11178 this.addDependenciesToChunk(module.dynamicDependencies, this.dynamicDependencies);
11179 this.addDependenciesToChunk(module.implicitlyLoadedBefore, this.implicitlyLoadedBefore);
11180 this.setUpChunkImportsAndExportsForModule(module);
11181 }
11182 }
11183 // prerender allows chunk hashes and names to be generated before finalizing
11184 preRender(options, inputBase) {
11185 const magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
11186 this.usedModules = [];
11187 this.indentString = getIndentString(this.orderedModules, options);
11188 const n = options.compact ? '' : '\n';
11189 const _ = options.compact ? '' : ' ';
11190 const renderOptions = {
11191 compact: options.compact,
11192 dynamicImportFunction: options.dynamicImportFunction,
11193 exportNamesByVariable: this.exportNamesByVariable,
11194 format: options.format,
11195 freeze: options.freeze,
11196 indent: this.indentString,
11197 namespaceToStringTag: options.namespaceToStringTag,
11198 outputPluginDriver: this.pluginDriver,
11199 varOrConst: options.preferConst ? 'const' : 'var'
11200 };
11201 // for static and dynamic entry points, inline the execution list to avoid loading latency
11202 if (options.hoistTransitiveImports &&
11203 !this.outputOptions.preserveModules &&
11204 this.facadeModule !== null) {
11205 for (const dep of this.dependencies) {
11206 if (dep instanceof Chunk$1)
11207 this.inlineChunkDependencies(dep);
11208 }
11209 }
11210 const sortedDependencies = [...this.dependencies];
11211 sortByExecutionOrder(sortedDependencies);
11212 this.dependencies = new Set(sortedDependencies);
11213 this.prepareDynamicImportsAndImportMetas();
11214 this.setIdentifierRenderResolutions(options);
11215 let hoistedSource = '';
11216 const renderedModules = this.renderedModules;
11217 for (const module of this.orderedModules) {
11218 let renderedLength = 0;
11219 if (module.isIncluded() || this.includedNamespaces.has(module)) {
11220 const source = module.render(renderOptions).trim();
11221 renderedLength = source.length();
11222 if (renderedLength) {
11223 if (options.compact && source.lastLine().indexOf('//') !== -1)
11224 source.append('\n');
11225 this.renderedModuleSources.set(module, source);
11226 magicString.addSource(source);
11227 this.usedModules.push(module);
11228 }
11229 const namespace = module.namespace;
11230 if (this.includedNamespaces.has(module) && !this.outputOptions.preserveModules) {
11231 const rendered = namespace.renderBlock(renderOptions);
11232 if (namespace.renderFirst())
11233 hoistedSource += n + rendered;
11234 else
11235 magicString.addSource(new MagicString(rendered));
11236 }
11237 }
11238 const { renderedExports, removedExports } = module.getRenderedExports();
11239 renderedModules[module.id] = {
11240 originalLength: module.originalCode.length,
11241 removedExports,
11242 renderedExports,
11243 renderedLength
11244 };
11245 }
11246 if (hoistedSource)
11247 magicString.prepend(hoistedSource + n + n);
11248 if (this.needsExportsShim) {
11249 magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
11250 }
11251 if (options.compact) {
11252 this.renderedSource = magicString;
11253 }
11254 else {
11255 this.renderedSource = magicString.trim();
11256 }
11257 this.renderedHash = undefined;
11258 if (this.isEmpty && this.getExportNames().length === 0 && this.dependencies.size === 0) {
11259 const chunkName = this.getChunkName();
11260 this.inputOptions.onwarn({
11261 chunkName,
11262 code: 'EMPTY_BUNDLE',
11263 message: `Generated an empty chunk: "${chunkName}"`
11264 });
11265 }
11266 this.setExternalRenderPaths(options, inputBase);
11267 this.renderedDependencies = this.getChunkDependencyDeclarations(options);
11268 this.renderedExports =
11269 this.exportMode === 'none' ? [] : this.getChunkExportDeclarations(options.format);
11270 }
11271 async render(options, addons, outputChunk) {
11272 timeStart('render format', 2);
11273 const format = options.format;
11274 const finalise = finalisers[format];
11275 if (options.dynamicImportFunction && format !== 'es') {
11276 this.inputOptions.onwarn({
11277 code: 'INVALID_OPTION',
11278 message: '"output.dynamicImportFunction" is ignored for formats other than "es".'
11279 });
11280 }
11281 // populate ids in the rendered declarations only here
11282 // as chunk ids known only after prerender
11283 for (const dependency of this.dependencies) {
11284 const renderedDependency = this.renderedDependencies.get(dependency);
11285 if (dependency instanceof ExternalModule) {
11286 const originalId = dependency.renderPath;
11287 renderedDependency.id = escapeId(dependency.renormalizeRenderPath ? this.getRelativePath(originalId, false) : originalId);
11288 }
11289 else {
11290 renderedDependency.namedExportsMode = dependency.exportMode !== 'default';
11291 renderedDependency.id = escapeId(this.getRelativePath(dependency.id, false));
11292 }
11293 }
11294 this.finaliseDynamicImports(options);
11295 this.finaliseImportMetas(format);
11296 const hasExports = this.renderedExports.length !== 0 ||
11297 [...this.renderedDependencies.values()].some(dep => (dep.reexports && dep.reexports.length !== 0));
11298 let usesTopLevelAwait = false;
11299 const accessedGlobals = new Set();
11300 for (const module of this.orderedModules) {
11301 if (module.usesTopLevelAwait) {
11302 usesTopLevelAwait = true;
11303 }
11304 const accessedGlobalVariables = this.accessedGlobalsByScope.get(module.scope);
11305 if (accessedGlobalVariables) {
11306 for (const name of accessedGlobalVariables) {
11307 accessedGlobals.add(name);
11308 }
11309 }
11310 }
11311 if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
11312 return error({
11313 code: 'INVALID_TLA_FORMAT',
11314 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
11315 });
11316 }
11317 const magicString = finalise(this.renderedSource, {
11318 accessedGlobals,
11319 dependencies: [...this.renderedDependencies.values()],
11320 exports: this.renderedExports,
11321 hasExports,
11322 indentString: this.indentString,
11323 intro: addons.intro,
11324 isEntryFacade: this.outputOptions.preserveModules ||
11325 (this.facadeModule !== null && this.facadeModule.info.isEntry),
11326 isModuleFacade: this.facadeModule !== null,
11327 namedExportsMode: this.exportMode !== 'default',
11328 outro: addons.outro,
11329 usesTopLevelAwait,
11330 varOrConst: options.preferConst ? 'const' : 'var',
11331 warn: this.inputOptions.onwarn
11332 }, options);
11333 if (addons.banner)
11334 magicString.prepend(addons.banner);
11335 if (addons.footer)
11336 magicString.append(addons.footer);
11337 const prevCode = magicString.toString();
11338 timeEnd('render format', 2);
11339 let map = null;
11340 const chunkSourcemapChain = [];
11341 let code = await renderChunk({
11342 code: prevCode,
11343 options,
11344 outputPluginDriver: this.pluginDriver,
11345 renderChunk: outputChunk,
11346 sourcemapChain: chunkSourcemapChain
11347 });
11348 if (options.sourcemap) {
11349 timeStart('sourcemap', 2);
11350 let file;
11351 if (options.file)
11352 file = resolve(options.sourcemapFile || options.file);
11353 else if (options.dir)
11354 file = resolve(options.dir, this.id);
11355 else
11356 file = resolve(this.id);
11357 const decodedMap = magicString.generateDecodedMap({});
11358 map = collapseSourcemaps(file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources, this.inputOptions.onwarn);
11359 map.sources = map.sources
11360 .map(sourcePath => {
11361 const { sourcemapPathTransform } = options;
11362 if (sourcemapPathTransform) {
11363 const newSourcePath = sourcemapPathTransform(sourcePath, `${file}.map`);
11364 if (typeof newSourcePath !== 'string') {
11365 error(errFailedValidation(`sourcemapPathTransform function must return a string.`));
11366 }
11367 return newSourcePath;
11368 }
11369 return sourcePath;
11370 })
11371 .map(normalize);
11372 timeEnd('sourcemap', 2);
11373 }
11374 if (!options.compact && code[code.length - 1] !== '\n')
11375 code += '\n';
11376 return { code, map };
11377 }
11378 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
11379 for (const module of moduleDependencies) {
11380 if (module instanceof Module) {
11381 const chunk = this.chunkByModule.get(module);
11382 if (chunk && chunk !== this) {
11383 chunkDependencies.add(chunk);
11384 }
11385 }
11386 else {
11387 chunkDependencies.add(module);
11388 }
11389 }
11390 }
11391 assignFacadeName({ fileName, name }, facadedModule) {
11392 if (fileName) {
11393 this.fileName = fileName;
11394 }
11395 else {
11396 this.name = sanitizeFileName(name || facadedModule.chunkName || getAliasName(facadedModule.id));
11397 }
11398 }
11399 computeContentHashWithDependencies(addons, options, existingNames) {
11400 const hash = createHash();
11401 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
11402 hash.update(options.format);
11403 const dependenciesForHashing = new Set([this]);
11404 for (const current of dependenciesForHashing) {
11405 if (current instanceof ExternalModule) {
11406 hash.update(':' + current.renderPath);
11407 }
11408 else {
11409 hash.update(current.getRenderedHash());
11410 hash.update(current.generateId(addons, options, existingNames, false));
11411 }
11412 if (current instanceof ExternalModule)
11413 continue;
11414 for (const dependency of [...current.dependencies, ...current.dynamicDependencies]) {
11415 dependenciesForHashing.add(dependency);
11416 }
11417 }
11418 return hash.digest('hex').substr(0, 8);
11419 }
11420 ensureReexportsAreAvailableForModule(module) {
11421 const map = module.getExportNamesByVariable();
11422 for (const exportedVariable of map.keys()) {
11423 const isSynthetic = exportedVariable instanceof SyntheticNamedExportVariable;
11424 const importedVariable = isSynthetic
11425 ? exportedVariable.getBaseVariable()
11426 : exportedVariable;
11427 if (!(importedVariable instanceof NamespaceVariable && this.outputOptions.preserveModules)) {
11428 const exportingModule = importedVariable.module;
11429 if (exportingModule instanceof Module) {
11430 const chunk = this.chunkByModule.get(exportingModule);
11431 if (chunk && chunk !== this) {
11432 chunk.exports.add(importedVariable);
11433 if (isSynthetic) {
11434 this.imports.add(importedVariable);
11435 }
11436 }
11437 }
11438 }
11439 }
11440 }
11441 finaliseDynamicImports(options) {
11442 const stripKnownJsExtensions = options.format === 'amd';
11443 for (const [module, code] of this.renderedModuleSources) {
11444 for (const { node, resolution } of module.dynamicImports) {
11445 const chunk = this.chunkByModule.get(resolution);
11446 const facadeChunk = this.facadeChunkByModule.get(resolution);
11447 if (!resolution || !node.included || chunk === this) {
11448 continue;
11449 }
11450 const renderedResolution = resolution instanceof Module
11451 ? `'${this.getRelativePath((facadeChunk || chunk).id, stripKnownJsExtensions)}'`
11452 : resolution instanceof ExternalModule
11453 ? `'${resolution.renormalizeRenderPath
11454 ? this.getRelativePath(resolution.renderPath, stripKnownJsExtensions)
11455 : resolution.renderPath}'`
11456 : resolution;
11457 node.renderFinalResolution(code, renderedResolution, resolution instanceof Module &&
11458 !(facadeChunk === null || facadeChunk === void 0 ? void 0 : facadeChunk.strictFacade) &&
11459 chunk.exportNamesByVariable.get(resolution.namespace)[0], options);
11460 }
11461 }
11462 }
11463 finaliseImportMetas(format) {
11464 for (const [module, code] of this.renderedModuleSources) {
11465 for (const importMeta of module.importMetas) {
11466 importMeta.renderFinalMechanism(code, this.id, format, this.pluginDriver);
11467 }
11468 }
11469 }
11470 generateVariableName() {
11471 if (this.manualChunkAlias) {
11472 return this.manualChunkAlias;
11473 }
11474 const moduleForNaming = this.entryModules[0] ||
11475 this.implicitEntryModules[0] ||
11476 this.dynamicEntryModules[0] ||
11477 this.orderedModules[this.orderedModules.length - 1];
11478 if (moduleForNaming) {
11479 return moduleForNaming.chunkName || getAliasName(moduleForNaming.id);
11480 }
11481 return 'chunk';
11482 }
11483 getChunkDependencyDeclarations(options) {
11484 const importSpecifiers = this.getImportSpecifiers();
11485 const reexportSpecifiers = this.getReexportSpecifiers();
11486 const dependencyDeclaration = new Map();
11487 for (const dep of this.dependencies) {
11488 const imports = importSpecifiers.get(dep) || null;
11489 const reexports = reexportSpecifiers.get(dep) || null;
11490 const namedExportsMode = dep instanceof ExternalModule || dep.exportMode !== 'default';
11491 dependencyDeclaration.set(dep, {
11492 defaultVariableName: dep.defaultVariableName,
11493 globalName: (dep instanceof ExternalModule &&
11494 (options.format === 'umd' || options.format === 'iife') &&
11495 getGlobalName(dep, options.globals, (imports || reexports) !== null, this.inputOptions.onwarn)),
11496 id: undefined,
11497 imports,
11498 isChunk: dep instanceof Chunk$1,
11499 name: dep.variableName,
11500 namedExportsMode,
11501 namespaceVariableName: dep.namespaceVariableName,
11502 reexports
11503 });
11504 }
11505 return dependencyDeclaration;
11506 }
11507 getChunkExportDeclarations(format) {
11508 const exports = [];
11509 for (const exportName of this.getExportNames()) {
11510 if (exportName[0] === '*')
11511 continue;
11512 const variable = this.exportsByName[exportName];
11513 if (!(variable instanceof SyntheticNamedExportVariable)) {
11514 const module = variable.module;
11515 if (module && this.chunkByModule.get(module) !== this)
11516 continue;
11517 }
11518 let expression = null;
11519 let hoisted = false;
11520 let uninitialized = false;
11521 let local = variable.getName();
11522 if (variable instanceof LocalVariable) {
11523 if (variable.init === UNDEFINED_EXPRESSION) {
11524 uninitialized = true;
11525 }
11526 for (const declaration of variable.declarations) {
11527 if (declaration.parent instanceof FunctionDeclaration ||
11528 (declaration instanceof ExportDefaultDeclaration &&
11529 declaration.declaration instanceof FunctionDeclaration)) {
11530 hoisted = true;
11531 break;
11532 }
11533 }
11534 }
11535 else if (variable instanceof SyntheticNamedExportVariable) {
11536 expression = local;
11537 if (format === 'es' && exportName !== 'default') {
11538 local = variable.renderName;
11539 }
11540 }
11541 exports.push({
11542 exported: exportName,
11543 expression,
11544 hoisted,
11545 local,
11546 uninitialized
11547 });
11548 }
11549 return exports;
11550 }
11551 getDependenciesToBeDeconflicted(addNonNamespacesAndInteropHelpers, addDependenciesWithoutBindings, interop) {
11552 const dependencies = new Set();
11553 const deconflictedDefault = new Set();
11554 const deconflictedNamespace = new Set();
11555 for (const variable of [...this.exportNamesByVariable.keys(), ...this.imports]) {
11556 if (addNonNamespacesAndInteropHelpers || variable.isNamespace) {
11557 const module = variable.module;
11558 if (module instanceof ExternalModule) {
11559 dependencies.add(module);
11560 if (addNonNamespacesAndInteropHelpers) {
11561 if (variable.name === 'default') {
11562 if (defaultInteropHelpersByInteropType[String(interop(module.id))]) {
11563 deconflictedDefault.add(module);
11564 }
11565 }
11566 else if (variable.name === '*') {
11567 if (namespaceInteropHelpersByInteropType[String(interop(module.id))]) {
11568 deconflictedNamespace.add(module);
11569 }
11570 }
11571 }
11572 }
11573 else {
11574 const chunk = this.chunkByModule.get(module);
11575 if (chunk !== this) {
11576 dependencies.add(chunk);
11577 if (addNonNamespacesAndInteropHelpers &&
11578 chunk.exportMode === 'default' &&
11579 variable.isNamespace) {
11580 deconflictedNamespace.add(chunk);
11581 }
11582 }
11583 }
11584 }
11585 }
11586 if (addDependenciesWithoutBindings) {
11587 for (const dependency of this.dependencies) {
11588 dependencies.add(dependency);
11589 }
11590 }
11591 return { deconflictedDefault, deconflictedNamespace, dependencies };
11592 }
11593 getFallbackChunkName() {
11594 if (this.manualChunkAlias) {
11595 return this.manualChunkAlias;
11596 }
11597 if (this.fileName) {
11598 return getAliasName(this.fileName);
11599 }
11600 return getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
11601 }
11602 getImportedBindingsPerDependency() {
11603 const importSpecifiers = {};
11604 for (const [dependency, declaration] of this.renderedDependencies) {
11605 const specifiers = new Set();
11606 if (declaration.imports) {
11607 for (const { imported } of declaration.imports) {
11608 specifiers.add(imported);
11609 }
11610 }
11611 if (declaration.reexports) {
11612 for (const { imported } of declaration.reexports) {
11613 specifiers.add(imported);
11614 }
11615 }
11616 importSpecifiers[dependency.id] = [...specifiers];
11617 }
11618 return importSpecifiers;
11619 }
11620 getImportSpecifiers() {
11621 const { interop } = this.outputOptions;
11622 const importsByDependency = new Map();
11623 for (const variable of this.imports) {
11624 const module = variable.module;
11625 let dependency;
11626 let imported;
11627 if (module instanceof ExternalModule) {
11628 dependency = module;
11629 imported = variable.name;
11630 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
11631 return error(errUnexpectedNamedImport(module.id, imported, false));
11632 }
11633 }
11634 else {
11635 dependency = this.chunkByModule.get(module);
11636 imported = dependency.getVariableExportName(variable);
11637 }
11638 getOrCreate(importsByDependency, dependency, () => []).push({
11639 imported,
11640 local: variable.getName()
11641 });
11642 }
11643 return importsByDependency;
11644 }
11645 getReexportSpecifiers() {
11646 const { externalLiveBindings, interop } = this.outputOptions;
11647 const reexportSpecifiers = new Map();
11648 for (let exportName of this.getExportNames()) {
11649 let dependency;
11650 let imported;
11651 let needsLiveBinding = false;
11652 if (exportName[0] === '*') {
11653 const id = exportName.substr(1);
11654 if (interop(id) === 'defaultOnly') {
11655 this.inputOptions.onwarn(errUnexpectedNamespaceReexport(id));
11656 }
11657 needsLiveBinding = externalLiveBindings;
11658 dependency = this.modulesById.get(id);
11659 imported = exportName = '*';
11660 }
11661 else {
11662 const variable = this.exportsByName[exportName];
11663 if (variable instanceof SyntheticNamedExportVariable)
11664 continue;
11665 const module = variable.module;
11666 if (module instanceof Module) {
11667 dependency = this.chunkByModule.get(module);
11668 if (dependency === this)
11669 continue;
11670 imported = dependency.getVariableExportName(variable);
11671 needsLiveBinding = variable.isReassigned;
11672 }
11673 else {
11674 dependency = module;
11675 imported = variable.name;
11676 if (imported !== 'default' && imported !== '*' && interop(module.id) === 'defaultOnly') {
11677 return error(errUnexpectedNamedImport(module.id, imported, true));
11678 }
11679 needsLiveBinding =
11680 externalLiveBindings &&
11681 (imported !== 'default' || isDefaultAProperty(String(interop(module.id)), true));
11682 }
11683 }
11684 getOrCreate(reexportSpecifiers, dependency, () => []).push({
11685 imported,
11686 needsLiveBinding,
11687 reexported: exportName
11688 });
11689 }
11690 return reexportSpecifiers;
11691 }
11692 getReferencedFiles() {
11693 const referencedFiles = [];
11694 for (const module of this.orderedModules) {
11695 for (const meta of module.importMetas) {
11696 const fileName = meta.getReferencedFileName(this.pluginDriver);
11697 if (fileName) {
11698 referencedFiles.push(fileName);
11699 }
11700 }
11701 }
11702 return referencedFiles;
11703 }
11704 getRelativePath(targetPath, stripJsExtension) {
11705 let relativePath = normalize(relative(dirname(this.id), targetPath));
11706 if (stripJsExtension && relativePath.endsWith('.js')) {
11707 relativePath = relativePath.slice(0, -3);
11708 }
11709 if (relativePath === '..')
11710 return '../../' + basename(targetPath);
11711 if (relativePath === '')
11712 return '../' + basename(targetPath);
11713 return relativePath.startsWith('../') ? relativePath : './' + relativePath;
11714 }
11715 inlineChunkDependencies(chunk) {
11716 for (const dep of chunk.dependencies) {
11717 if (this.dependencies.has(dep))
11718 continue;
11719 this.dependencies.add(dep);
11720 if (dep instanceof Chunk$1) {
11721 this.inlineChunkDependencies(dep);
11722 }
11723 }
11724 }
11725 prepareDynamicImportsAndImportMetas() {
11726 var _a;
11727 const accessedGlobalsByScope = this.accessedGlobalsByScope;
11728 for (const module of this.orderedModules) {
11729 for (const { node, resolution } of module.dynamicImports) {
11730 if (node.included) {
11731 if (resolution instanceof Module) {
11732 const chunk = this.chunkByModule.get(resolution);
11733 if (chunk === this) {
11734 node.setInternalResolution(resolution.namespace);
11735 }
11736 else {
11737 node.setExternalResolution(((_a = this.facadeChunkByModule.get(resolution)) === null || _a === void 0 ? void 0 : _a.exportMode) || chunk.exportMode, resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
11738 }
11739 }
11740 else {
11741 node.setExternalResolution('external', resolution, this.outputOptions, this.pluginDriver, accessedGlobalsByScope);
11742 }
11743 }
11744 }
11745 for (const importMeta of module.importMetas) {
11746 importMeta.addAccessedGlobals(this.outputOptions.format, accessedGlobalsByScope);
11747 }
11748 }
11749 }
11750 setExternalRenderPaths(options, inputBase) {
11751 for (const dependency of [...this.dependencies, ...this.dynamicDependencies]) {
11752 if (dependency instanceof ExternalModule) {
11753 dependency.setRenderPath(options, inputBase);
11754 }
11755 }
11756 }
11757 setIdentifierRenderResolutions({ format, interop }) {
11758 const syntheticExports = new Set();
11759 for (const exportName of this.getExportNames()) {
11760 const exportVariable = this.exportsByName[exportName];
11761 if (exportVariable instanceof ExportShimVariable) {
11762 this.needsExportsShim = true;
11763 }
11764 if (format !== 'es' &&
11765 format !== 'system' &&
11766 exportVariable.isReassigned &&
11767 !exportVariable.isId) {
11768 exportVariable.setRenderNames('exports', exportName);
11769 }
11770 else if (exportVariable instanceof SyntheticNamedExportVariable) {
11771 syntheticExports.add(exportVariable);
11772 }
11773 else {
11774 exportVariable.setRenderNames(null, null);
11775 }
11776 }
11777 const usedNames = new Set();
11778 if (this.needsExportsShim) {
11779 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
11780 }
11781 switch (format) {
11782 case 'system':
11783 usedNames.add('module').add('exports');
11784 break;
11785 case 'es':
11786 break;
11787 case 'cjs':
11788 usedNames.add('module').add('require').add('__filename').add('__dirname');
11789 // fallthrough
11790 default:
11791 usedNames.add('exports');
11792 for (const helper of HELPER_NAMES) {
11793 usedNames.add(helper);
11794 }
11795 }
11796 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);
11797 }
11798 setUpChunkImportsAndExportsForModule(module) {
11799 const moduleImports = new Set(module.imports);
11800 // when we are not preserving modules, we need to make all namespace variables available for
11801 // rendering the namespace object
11802 if (!this.outputOptions.preserveModules) {
11803 if (this.includedNamespaces.has(module)) {
11804 const memberVariables = module.namespace.getMemberVariables();
11805 for (const name of Object.keys(memberVariables)) {
11806 moduleImports.add(memberVariables[name]);
11807 }
11808 }
11809 }
11810 for (let variable of moduleImports) {
11811 if (variable instanceof ExportDefaultVariable) {
11812 variable = variable.getOriginalVariable();
11813 }
11814 if (variable instanceof SyntheticNamedExportVariable) {
11815 variable = variable.getBaseVariable();
11816 }
11817 const chunk = this.chunkByModule.get(variable.module);
11818 if (chunk !== this) {
11819 this.imports.add(variable);
11820 if (!(variable instanceof NamespaceVariable && this.outputOptions.preserveModules) &&
11821 variable.module instanceof Module) {
11822 chunk.exports.add(variable);
11823 }
11824 }
11825 }
11826 if (this.includedNamespaces.has(module) ||
11827 (module.info.isEntry && module.preserveSignature !== false) ||
11828 module.includedDynamicImporters.some(importer => this.chunkByModule.get(importer) !== this)) {
11829 this.ensureReexportsAreAvailableForModule(module);
11830 }
11831 for (const { node, resolution } of module.dynamicImports) {
11832 if (node.included &&
11833 resolution instanceof Module &&
11834 this.chunkByModule.get(resolution) === this &&
11835 !this.includedNamespaces.has(resolution)) {
11836 this.includedNamespaces.add(resolution);
11837 this.ensureReexportsAreAvailableForModule(resolution);
11838 }
11839 }
11840 }
11841}
11842
11843const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
11844const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
11845async function createAddons(options, outputPluginDriver) {
11846 try {
11847 let [banner, footer, intro, outro] = await Promise.all([
11848 outputPluginDriver.hookReduceValue('banner', options.banner(), [], concatSep),
11849 outputPluginDriver.hookReduceValue('footer', options.footer(), [], concatSep),
11850 outputPluginDriver.hookReduceValue('intro', options.intro(), [], concatDblSep),
11851 outputPluginDriver.hookReduceValue('outro', options.outro(), [], concatDblSep)
11852 ]);
11853 if (intro)
11854 intro += '\n\n';
11855 if (outro)
11856 outro = `\n\n${outro}`;
11857 if (banner.length)
11858 banner += '\n';
11859 if (footer.length)
11860 footer = '\n' + footer;
11861 return { intro, outro, banner, footer };
11862 }
11863 catch (err) {
11864 return error({
11865 code: 'ADDON_ERROR',
11866 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
11867\tError Message: ${err.message}`
11868 });
11869 }
11870}
11871
11872function getChunkAssignments(entryModules, manualChunkAliasByEntry) {
11873 const chunkDefinitions = [];
11874 const modulesInManualChunks = new Set(manualChunkAliasByEntry.keys());
11875 const manualChunkModulesByAlias = Object.create(null);
11876 for (const [entry, alias] of manualChunkAliasByEntry) {
11877 const chunkModules = (manualChunkModulesByAlias[alias] =
11878 manualChunkModulesByAlias[alias] || []);
11879 addStaticDependenciesToManualChunk(entry, chunkModules, modulesInManualChunks);
11880 }
11881 for (const [alias, modules] of Object.entries(manualChunkModulesByAlias)) {
11882 chunkDefinitions.push({ alias, modules });
11883 }
11884 const assignedEntryPointsByModule = new Map();
11885 const { dependentEntryPointsByModule, dynamicEntryModules } = analyzeModuleGraph(entryModules);
11886 const dynamicallyDependentEntryPointsByDynamicEntry = getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules);
11887 const staticEntries = new Set(entryModules);
11888 function assignEntryToStaticDependencies(entry, dynamicDependentEntryPoints) {
11889 const modulesToHandle = new Set([entry]);
11890 for (const module of modulesToHandle) {
11891 const assignedEntryPoints = getOrCreate(assignedEntryPointsByModule, module, () => new Set());
11892 if (dynamicDependentEntryPoints &&
11893 areEntryPointsContainedOrDynamicallyDependent(dynamicDependentEntryPoints, dependentEntryPointsByModule.get(module))) {
11894 continue;
11895 }
11896 else {
11897 assignedEntryPoints.add(entry);
11898 }
11899 for (const dependency of module.getDependenciesToBeIncluded()) {
11900 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
11901 modulesToHandle.add(dependency);
11902 }
11903 }
11904 }
11905 }
11906 function areEntryPointsContainedOrDynamicallyDependent(entryPoints, containedIn) {
11907 const entriesToCheck = new Set(entryPoints);
11908 for (const entry of entriesToCheck) {
11909 if (!containedIn.has(entry)) {
11910 if (staticEntries.has(entry))
11911 return false;
11912 const dynamicallyDependentEntryPoints = dynamicallyDependentEntryPointsByDynamicEntry.get(entry);
11913 for (const dependentEntry of dynamicallyDependentEntryPoints) {
11914 entriesToCheck.add(dependentEntry);
11915 }
11916 }
11917 }
11918 return true;
11919 }
11920 for (const entry of entryModules) {
11921 if (!modulesInManualChunks.has(entry)) {
11922 assignEntryToStaticDependencies(entry, null);
11923 }
11924 }
11925 for (const entry of dynamicEntryModules) {
11926 if (!modulesInManualChunks.has(entry)) {
11927 assignEntryToStaticDependencies(entry, dynamicallyDependentEntryPointsByDynamicEntry.get(entry));
11928 }
11929 }
11930 chunkDefinitions.push(...createChunks([...entryModules, ...dynamicEntryModules], assignedEntryPointsByModule));
11931 return chunkDefinitions;
11932}
11933function addStaticDependenciesToManualChunk(entry, manualChunkModules, modulesInManualChunks) {
11934 const modulesToHandle = new Set([entry]);
11935 for (const module of modulesToHandle) {
11936 modulesInManualChunks.add(module);
11937 manualChunkModules.push(module);
11938 for (const dependency of module.dependencies) {
11939 if (!(dependency instanceof ExternalModule || modulesInManualChunks.has(dependency))) {
11940 modulesToHandle.add(dependency);
11941 }
11942 }
11943 }
11944}
11945function analyzeModuleGraph(entryModules) {
11946 const dynamicEntryModules = new Set();
11947 const dependentEntryPointsByModule = new Map();
11948 const entriesToHandle = new Set(entryModules);
11949 for (const currentEntry of entriesToHandle) {
11950 const modulesToHandle = new Set([currentEntry]);
11951 for (const module of modulesToHandle) {
11952 getOrCreate(dependentEntryPointsByModule, module, () => new Set()).add(currentEntry);
11953 for (const dependency of module.getDependenciesToBeIncluded()) {
11954 if (!(dependency instanceof ExternalModule)) {
11955 modulesToHandle.add(dependency);
11956 }
11957 }
11958 for (const { resolution } of module.dynamicImports) {
11959 if (resolution instanceof Module && resolution.includedDynamicImporters.length > 0) {
11960 dynamicEntryModules.add(resolution);
11961 entriesToHandle.add(resolution);
11962 }
11963 }
11964 for (const dependency of module.implicitlyLoadedBefore) {
11965 dynamicEntryModules.add(dependency);
11966 entriesToHandle.add(dependency);
11967 }
11968 }
11969 }
11970 return { dependentEntryPointsByModule, dynamicEntryModules };
11971}
11972function getDynamicDependentEntryPoints(dependentEntryPointsByModule, dynamicEntryModules) {
11973 const dynamicallyDependentEntryPointsByDynamicEntry = new Map();
11974 for (const dynamicEntry of dynamicEntryModules) {
11975 const dynamicDependentEntryPoints = getOrCreate(dynamicallyDependentEntryPointsByDynamicEntry, dynamicEntry, () => new Set());
11976 for (const importer of [
11977 ...dynamicEntry.includedDynamicImporters,
11978 ...dynamicEntry.implicitlyLoadedAfter
11979 ]) {
11980 for (const entryPoint of dependentEntryPointsByModule.get(importer)) {
11981 dynamicDependentEntryPoints.add(entryPoint);
11982 }
11983 }
11984 }
11985 return dynamicallyDependentEntryPointsByDynamicEntry;
11986}
11987function createChunks(allEntryPoints, assignedEntryPointsByModule) {
11988 const chunkModules = Object.create(null);
11989 for (const [module, assignedEntryPoints] of assignedEntryPointsByModule) {
11990 let chunkSignature = '';
11991 for (const entry of allEntryPoints) {
11992 chunkSignature += assignedEntryPoints.has(entry) ? 'X' : '_';
11993 }
11994 const chunk = chunkModules[chunkSignature];
11995 if (chunk) {
11996 chunk.push(module);
11997 }
11998 else {
11999 chunkModules[chunkSignature] = [module];
12000 }
12001 }
12002 return Object.keys(chunkModules).map(chunkSignature => ({
12003 alias: null,
12004 modules: chunkModules[chunkSignature]
12005 }));
12006}
12007
12008// ported from https://github.com/substack/node-commondir
12009function commondir(files) {
12010 if (files.length === 0)
12011 return '/';
12012 if (files.length === 1)
12013 return dirname(files[0]);
12014 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
12015 const pathSegements = file.split(/\/+|\\+/);
12016 let i;
12017 for (i = 0; commonSegments[i] === pathSegements[i] &&
12018 i < Math.min(commonSegments.length, pathSegements.length); i++)
12019 ;
12020 return commonSegments.slice(0, i);
12021 }, files[0].split(/\/+|\\+/));
12022 // Windows correctly handles paths with forward-slashes
12023 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
12024}
12025
12026var BuildPhase;
12027(function (BuildPhase) {
12028 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
12029 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
12030 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
12031})(BuildPhase || (BuildPhase = {}));
12032
12033function generateAssetFileName(name, source, output) {
12034 const emittedName = name || 'asset';
12035 return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
12036 hash() {
12037 const hash = createHash();
12038 hash.update(emittedName);
12039 hash.update(':');
12040 hash.update(source);
12041 return hash.digest('hex').substr(0, 8);
12042 },
12043 ext: () => extname(emittedName).substr(1),
12044 extname: () => extname(emittedName),
12045 name: () => emittedName.substr(0, emittedName.length - extname(emittedName).length)
12046 }, () => ({ name, source, type: 'asset' })), output.bundle);
12047}
12048function reserveFileNameInBundle(fileName, bundle, warn) {
12049 if (fileName in bundle) {
12050 warn(errFileNameConflict(fileName));
12051 }
12052 bundle[fileName] = FILE_PLACEHOLDER;
12053}
12054const FILE_PLACEHOLDER = {
12055 type: 'placeholder'
12056};
12057function hasValidType(emittedFile) {
12058 return (emittedFile &&
12059 (emittedFile.type === 'asset' ||
12060 emittedFile.type === 'chunk'));
12061}
12062function hasValidName(emittedFile) {
12063 const validatedName = emittedFile.fileName || emittedFile.name;
12064 return (!validatedName || (typeof validatedName === 'string' && isPlainPathFragment(validatedName)));
12065}
12066function getValidSource(source, emittedFile, fileReferenceId) {
12067 if (!(typeof source === 'string' || source instanceof Uint8Array)) {
12068 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
12069 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.`));
12070 }
12071 return source;
12072}
12073function getAssetFileName(file, referenceId) {
12074 if (typeof file.fileName !== 'string') {
12075 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
12076 }
12077 return file.fileName;
12078}
12079function getChunkFileName(file, facadeChunkByModule) {
12080 var _a;
12081 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));
12082 if (!fileName)
12083 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
12084 return fileName;
12085}
12086class FileEmitter {
12087 constructor(graph, options, baseFileEmitter) {
12088 this.graph = graph;
12089 this.options = options;
12090 this.facadeChunkByModule = null;
12091 this.output = null;
12092 this.assertAssetsFinalized = () => {
12093 for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
12094 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
12095 return error(errNoAssetSourceSet(emittedFile.name || referenceId));
12096 }
12097 };
12098 this.emitFile = (emittedFile) => {
12099 if (!hasValidType(emittedFile)) {
12100 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile && emittedFile.type}".`));
12101 }
12102 if (!hasValidName(emittedFile)) {
12103 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}".`));
12104 }
12105 if (emittedFile.type === 'chunk') {
12106 return this.emitChunk(emittedFile);
12107 }
12108 else {
12109 return this.emitAsset(emittedFile);
12110 }
12111 };
12112 this.getFileName = (fileReferenceId) => {
12113 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
12114 if (!emittedFile)
12115 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
12116 if (emittedFile.type === 'chunk') {
12117 return getChunkFileName(emittedFile, this.facadeChunkByModule);
12118 }
12119 else {
12120 return getAssetFileName(emittedFile, fileReferenceId);
12121 }
12122 };
12123 this.setAssetSource = (referenceId, requestedSource) => {
12124 const consumedFile = this.filesByReferenceId.get(referenceId);
12125 if (!consumedFile)
12126 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
12127 if (consumedFile.type !== 'asset') {
12128 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
12129 }
12130 if (consumedFile.source !== undefined) {
12131 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
12132 }
12133 const source = getValidSource(requestedSource, consumedFile, referenceId);
12134 if (this.output) {
12135 this.finalizeAsset(consumedFile, source, referenceId, this.output);
12136 }
12137 else {
12138 consumedFile.source = source;
12139 }
12140 };
12141 this.setOutputBundle = (outputBundle, assetFileNames, facadeChunkByModule) => {
12142 this.output = {
12143 assetFileNames,
12144 bundle: outputBundle
12145 };
12146 this.facadeChunkByModule = facadeChunkByModule;
12147 for (const emittedFile of this.filesByReferenceId.values()) {
12148 if (emittedFile.fileName) {
12149 reserveFileNameInBundle(emittedFile.fileName, this.output.bundle, this.options.onwarn);
12150 }
12151 }
12152 for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
12153 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
12154 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
12155 }
12156 }
12157 };
12158 this.filesByReferenceId = baseFileEmitter
12159 ? new Map(baseFileEmitter.filesByReferenceId)
12160 : new Map();
12161 }
12162 assignReferenceId(file, idBase) {
12163 let referenceId;
12164 do {
12165 const hash = createHash();
12166 if (referenceId) {
12167 hash.update(referenceId);
12168 }
12169 else {
12170 hash.update(idBase);
12171 }
12172 referenceId = hash.digest('hex').substr(0, 8);
12173 } while (this.filesByReferenceId.has(referenceId));
12174 this.filesByReferenceId.set(referenceId, file);
12175 return referenceId;
12176 }
12177 emitAsset(emittedAsset) {
12178 const source = typeof emittedAsset.source !== 'undefined'
12179 ? getValidSource(emittedAsset.source, emittedAsset, null)
12180 : undefined;
12181 const consumedAsset = {
12182 fileName: emittedAsset.fileName,
12183 name: emittedAsset.name,
12184 source,
12185 type: 'asset'
12186 };
12187 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
12188 if (this.output) {
12189 if (emittedAsset.fileName) {
12190 reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle, this.options.onwarn);
12191 }
12192 if (source !== undefined) {
12193 this.finalizeAsset(consumedAsset, source, referenceId, this.output);
12194 }
12195 }
12196 return referenceId;
12197 }
12198 emitChunk(emittedChunk) {
12199 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
12200 return error(errInvalidRollupPhaseForChunkEmission());
12201 }
12202 if (typeof emittedChunk.id !== 'string') {
12203 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
12204 }
12205 const consumedChunk = {
12206 fileName: emittedChunk.fileName,
12207 module: null,
12208 name: emittedChunk.name || emittedChunk.id,
12209 type: 'chunk'
12210 };
12211 this.graph.moduleLoader
12212 .emitChunk(emittedChunk)
12213 .then(module => (consumedChunk.module = module))
12214 .catch(() => {
12215 // Avoid unhandled Promise rejection as the error will be thrown later
12216 // once module loading has finished
12217 });
12218 return this.assignReferenceId(consumedChunk, emittedChunk.id);
12219 }
12220 finalizeAsset(consumedFile, source, referenceId, output) {
12221 const fileName = consumedFile.fileName ||
12222 findExistingAssetFileNameWithSource(output.bundle, source) ||
12223 generateAssetFileName(consumedFile.name, source, output);
12224 // We must not modify the original assets to avoid interaction between outputs
12225 const assetWithFileName = { ...consumedFile, source, fileName };
12226 this.filesByReferenceId.set(referenceId, assetWithFileName);
12227 const options = this.options;
12228 output.bundle[fileName] = {
12229 fileName,
12230 name: consumedFile.name,
12231 get isAsset() {
12232 warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', true, options);
12233 return true;
12234 },
12235 source,
12236 type: 'asset'
12237 };
12238 }
12239}
12240function findExistingAssetFileNameWithSource(bundle, source) {
12241 for (const fileName of Object.keys(bundle)) {
12242 const outputFile = bundle[fileName];
12243 if (outputFile.type === 'asset' && areSourcesEqual(source, outputFile.source))
12244 return fileName;
12245 }
12246 return null;
12247}
12248function areSourcesEqual(sourceA, sourceB) {
12249 if (typeof sourceA === 'string') {
12250 return sourceA === sourceB;
12251 }
12252 if (typeof sourceB === 'string') {
12253 return false;
12254 }
12255 if ('equals' in sourceA) {
12256 return sourceA.equals(sourceB);
12257 }
12258 if (sourceA.length !== sourceB.length) {
12259 return false;
12260 }
12261 for (let index = 0; index < sourceA.length; index++) {
12262 if (sourceA[index] !== sourceB[index]) {
12263 return false;
12264 }
12265 }
12266 return true;
12267}
12268
12269class Bundle$1 {
12270 constructor(outputOptions, unsetOptions, inputOptions, pluginDriver, graph) {
12271 this.outputOptions = outputOptions;
12272 this.unsetOptions = unsetOptions;
12273 this.inputOptions = inputOptions;
12274 this.pluginDriver = pluginDriver;
12275 this.graph = graph;
12276 this.facadeChunkByModule = new Map();
12277 this.includedNamespaces = new Set();
12278 }
12279 async generate(isWrite) {
12280 timeStart('GENERATE', 1);
12281 const outputBundle = Object.create(null);
12282 this.pluginDriver.setOutputBundle(outputBundle, this.outputOptions.assetFileNames, this.facadeChunkByModule);
12283 try {
12284 await this.pluginDriver.hookParallel('renderStart', [this.outputOptions, this.inputOptions]);
12285 timeStart('generate chunks', 2);
12286 const chunks = await this.generateChunks();
12287 if (chunks.length > 1) {
12288 validateOptionsForMultiChunkOutput(this.outputOptions);
12289 }
12290 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
12291 timeEnd('generate chunks', 2);
12292 timeStart('render modules', 2);
12293 // We need to create addons before prerender because at the moment, there
12294 // can be no async code between prerender and render due to internal state
12295 const addons = await createAddons(this.outputOptions, this.pluginDriver);
12296 this.prerenderChunks(chunks, inputBase);
12297 timeEnd('render modules', 2);
12298 await this.addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle);
12299 }
12300 catch (error) {
12301 await this.pluginDriver.hookParallel('renderError', [error]);
12302 throw error;
12303 }
12304 await this.pluginDriver.hookSeq('generateBundle', [
12305 this.outputOptions,
12306 outputBundle,
12307 isWrite
12308 ]);
12309 this.finaliseAssets(outputBundle);
12310 timeEnd('GENERATE', 1);
12311 return outputBundle;
12312 }
12313 async addFinalizedChunksToBundle(chunks, inputBase, addons, outputBundle) {
12314 this.assignChunkIds(chunks, inputBase, addons, outputBundle);
12315 for (const chunk of chunks) {
12316 outputBundle[chunk.id] = chunk.getChunkInfoWithFileNames();
12317 }
12318 await Promise.all(chunks.map(async (chunk) => {
12319 const outputChunk = outputBundle[chunk.id];
12320 Object.assign(outputChunk, await chunk.render(this.outputOptions, addons, outputChunk));
12321 }));
12322 }
12323 async addManualChunks(manualChunks) {
12324 const manualChunkAliasByEntry = new Map();
12325 const chunkEntries = await Promise.all(Object.keys(manualChunks).map(async (alias) => ({
12326 alias,
12327 entries: await this.graph.moduleLoader.addAdditionalModules(manualChunks[alias])
12328 })));
12329 for (const { alias, entries } of chunkEntries) {
12330 for (const entry of entries) {
12331 addModuleToManualChunk(alias, entry, manualChunkAliasByEntry);
12332 }
12333 }
12334 return manualChunkAliasByEntry;
12335 }
12336 assignChunkIds(chunks, inputBase, addons, bundle) {
12337 const entryChunks = [];
12338 const otherChunks = [];
12339 for (const chunk of chunks) {
12340 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
12341 ? entryChunks
12342 : otherChunks).push(chunk);
12343 }
12344 // make sure entry chunk names take precedence with regard to deconflicting
12345 const chunksForNaming = entryChunks.concat(otherChunks);
12346 for (const chunk of chunksForNaming) {
12347 if (this.outputOptions.file) {
12348 chunk.id = basename(this.outputOptions.file);
12349 }
12350 else if (this.outputOptions.preserveModules) {
12351 chunk.id = chunk.generateIdPreserveModules(inputBase, this.outputOptions, bundle, this.unsetOptions);
12352 }
12353 else {
12354 chunk.id = chunk.generateId(addons, this.outputOptions, bundle, true);
12355 }
12356 bundle[chunk.id] = FILE_PLACEHOLDER;
12357 }
12358 }
12359 assignManualChunks(getManualChunk) {
12360 const manualChunkAliasByEntry = new Map();
12361 const manualChunksApi = {
12362 getModuleIds: () => this.graph.modulesById.keys(),
12363 getModuleInfo: this.graph.getModuleInfo
12364 };
12365 for (const module of this.graph.modulesById.values()) {
12366 if (module instanceof Module) {
12367 const manualChunkAlias = getManualChunk(module.id, manualChunksApi);
12368 if (typeof manualChunkAlias === 'string') {
12369 addModuleToManualChunk(manualChunkAlias, module, manualChunkAliasByEntry);
12370 }
12371 }
12372 }
12373 return manualChunkAliasByEntry;
12374 }
12375 finaliseAssets(outputBundle) {
12376 for (const key of Object.keys(outputBundle)) {
12377 const file = outputBundle[key];
12378 if (!file.type) {
12379 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);
12380 file.type = 'asset';
12381 }
12382 }
12383 this.pluginDriver.finaliseAssets();
12384 }
12385 async generateChunks() {
12386 const { manualChunks } = this.outputOptions;
12387 const manualChunkAliasByEntry = typeof manualChunks === 'object'
12388 ? await this.addManualChunks(manualChunks)
12389 : this.assignManualChunks(manualChunks);
12390 const chunks = [];
12391 const chunkByModule = new Map();
12392 for (const { alias, modules } of this.outputOptions.inlineDynamicImports
12393 ? [{ alias: null, modules: getIncludedModules(this.graph.modulesById) }]
12394 : this.outputOptions.preserveModules
12395 ? getIncludedModules(this.graph.modulesById).map(module => ({
12396 alias: null,
12397 modules: [module]
12398 }))
12399 : getChunkAssignments(this.graph.entryModules, manualChunkAliasByEntry)) {
12400 sortByExecutionOrder(modules);
12401 const chunk = new Chunk$1(modules, this.inputOptions, this.outputOptions, this.unsetOptions, this.pluginDriver, this.graph.modulesById, chunkByModule, this.facadeChunkByModule, this.includedNamespaces, alias);
12402 chunks.push(chunk);
12403 for (const module of modules) {
12404 chunkByModule.set(module, chunk);
12405 }
12406 }
12407 for (const chunk of chunks) {
12408 chunk.link();
12409 }
12410 const facades = [];
12411 for (const chunk of chunks) {
12412 facades.push(...chunk.generateFacades());
12413 }
12414 return [...chunks, ...facades];
12415 }
12416 prerenderChunks(chunks, inputBase) {
12417 for (const chunk of chunks) {
12418 chunk.generateExports();
12419 }
12420 for (const chunk of chunks) {
12421 chunk.preRender(this.outputOptions, inputBase);
12422 }
12423 }
12424}
12425function getAbsoluteEntryModulePaths(chunks) {
12426 const absoluteEntryModulePaths = [];
12427 for (const chunk of chunks) {
12428 for (const entryModule of chunk.entryModules) {
12429 if (isAbsolute(entryModule.id)) {
12430 absoluteEntryModulePaths.push(entryModule.id);
12431 }
12432 }
12433 }
12434 return absoluteEntryModulePaths;
12435}
12436function validateOptionsForMultiChunkOutput(outputOptions) {
12437 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
12438 return error({
12439 code: 'INVALID_OPTION',
12440 message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
12441 });
12442 if (typeof outputOptions.file === 'string')
12443 return error({
12444 code: 'INVALID_OPTION',
12445 message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file". ' +
12446 'To inline dynamic imports, set the "inlineDynamicImports" option.'
12447 });
12448 if (outputOptions.sourcemapFile)
12449 return error({
12450 code: 'INVALID_OPTION',
12451 message: '"output.sourcemapFile" is only supported for single-file builds.'
12452 });
12453}
12454function getIncludedModules(modulesById) {
12455 return [...modulesById.values()].filter(module => module instanceof Module &&
12456 (module.isIncluded() || module.info.isEntry || module.includedDynamicImporters.length > 0));
12457}
12458function addModuleToManualChunk(alias, module, manualChunkAliasByEntry) {
12459 const existingAlias = manualChunkAliasByEntry.get(module);
12460 if (typeof existingAlias === 'string' && existingAlias !== alias) {
12461 return error(errCannotAssignModuleToChunk(module.id, alias, existingAlias));
12462 }
12463 manualChunkAliasByEntry.set(module, alias);
12464}
12465
12466// Reserved word lists for various dialects of the language
12467
12468var reservedWords$1 = {
12469 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",
12470 5: "class enum extends super const export import",
12471 6: "enum",
12472 strict: "implements interface let package private protected public static yield",
12473 strictBind: "eval arguments"
12474};
12475
12476// And the keywords
12477
12478var 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";
12479
12480var keywords = {
12481 5: ecma5AndLessKeywords,
12482 "5module": ecma5AndLessKeywords + " export import",
12483 6: ecma5AndLessKeywords + " const class extends export import super"
12484};
12485
12486var keywordRelationalOperator = /^in(stanceof)?$/;
12487
12488// ## Character categories
12489
12490// Big ugly regular expressions that match characters in the
12491// whitespace, identifier, and identifier-start categories. These
12492// are only applied when a character is found to actually have a
12493// code point above 128.
12494// Generated by `bin/generate-identifier-regex.js`.
12495var 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";
12496var 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";
12497
12498var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
12499var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
12500
12501nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
12502
12503// These are a run-length and offset encoded representation of the
12504// >0xffff code points that are a valid part of identifiers. The
12505// offset starts at 0x10000, and each pair of numbers represents an
12506// offset to the next range, and then a size of the range. They were
12507// generated by bin/generate-identifier-regex.js
12508
12509// eslint-disable-next-line comma-spacing
12510var 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];
12511
12512// eslint-disable-next-line comma-spacing
12513var 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];
12514
12515// This has a complexity linear to the value of the code. The
12516// assumption is that looking up astral identifier characters is
12517// rare.
12518function isInAstralSet(code, set) {
12519 var pos = 0x10000;
12520 for (var i = 0; i < set.length; i += 2) {
12521 pos += set[i];
12522 if (pos > code) { return false }
12523 pos += set[i + 1];
12524 if (pos >= code) { return true }
12525 }
12526}
12527
12528// Test whether a given character code starts an identifier.
12529
12530function isIdentifierStart(code, astral) {
12531 if (code < 65) { return code === 36 }
12532 if (code < 91) { return true }
12533 if (code < 97) { return code === 95 }
12534 if (code < 123) { return true }
12535 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code)) }
12536 if (astral === false) { return false }
12537 return isInAstralSet(code, astralIdentifierStartCodes)
12538}
12539
12540// Test whether a given character is part of an identifier.
12541
12542function isIdentifierChar(code, astral) {
12543 if (code < 48) { return code === 36 }
12544 if (code < 58) { return true }
12545 if (code < 65) { return false }
12546 if (code < 91) { return true }
12547 if (code < 97) { return code === 95 }
12548 if (code < 123) { return true }
12549 if (code <= 0xffff) { return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code)) }
12550 if (astral === false) { return false }
12551 return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes)
12552}
12553
12554// ## Token types
12555
12556// The assignment of fine-grained, information-carrying type objects
12557// allows the tokenizer to store the information it has about a
12558// token in a way that is very cheap for the parser to look up.
12559
12560// All token type variables start with an underscore, to make them
12561// easy to recognize.
12562
12563// The `beforeExpr` property is used to disambiguate between regular
12564// expressions and divisions. It is set on all token types that can
12565// be followed by an expression (thus, a slash after them would be a
12566// regular expression).
12567//
12568// The `startsExpr` property is used to check if the token ends a
12569// `yield` expression. It is set on all token types that either can
12570// directly start an expression (like a quotation mark) or can
12571// continue an expression (like the body of a string).
12572//
12573// `isLoop` marks a keyword as starting a loop, which is important
12574// to know when parsing a label, in order to allow or disallow
12575// continue jumps to that label.
12576
12577var TokenType = function TokenType(label, conf) {
12578 if ( conf === void 0 ) conf = {};
12579
12580 this.label = label;
12581 this.keyword = conf.keyword;
12582 this.beforeExpr = !!conf.beforeExpr;
12583 this.startsExpr = !!conf.startsExpr;
12584 this.isLoop = !!conf.isLoop;
12585 this.isAssign = !!conf.isAssign;
12586 this.prefix = !!conf.prefix;
12587 this.postfix = !!conf.postfix;
12588 this.binop = conf.binop || null;
12589 this.updateContext = null;
12590};
12591
12592function binop(name, prec) {
12593 return new TokenType(name, {beforeExpr: true, binop: prec})
12594}
12595var beforeExpr = {beforeExpr: true}, startsExpr = {startsExpr: true};
12596
12597// Map keyword names to token types.
12598
12599var keywords$1 = {};
12600
12601// Succinct definitions of keyword token types
12602function kw(name, options) {
12603 if ( options === void 0 ) options = {};
12604
12605 options.keyword = name;
12606 return keywords$1[name] = new TokenType(name, options)
12607}
12608
12609var types = {
12610 num: new TokenType("num", startsExpr),
12611 regexp: new TokenType("regexp", startsExpr),
12612 string: new TokenType("string", startsExpr),
12613 name: new TokenType("name", startsExpr),
12614 eof: new TokenType("eof"),
12615
12616 // Punctuation token types.
12617 bracketL: new TokenType("[", {beforeExpr: true, startsExpr: true}),
12618 bracketR: new TokenType("]"),
12619 braceL: new TokenType("{", {beforeExpr: true, startsExpr: true}),
12620 braceR: new TokenType("}"),
12621 parenL: new TokenType("(", {beforeExpr: true, startsExpr: true}),
12622 parenR: new TokenType(")"),
12623 comma: new TokenType(",", beforeExpr),
12624 semi: new TokenType(";", beforeExpr),
12625 colon: new TokenType(":", beforeExpr),
12626 dot: new TokenType("."),
12627 question: new TokenType("?", beforeExpr),
12628 questionDot: new TokenType("?."),
12629 arrow: new TokenType("=>", beforeExpr),
12630 template: new TokenType("template"),
12631 invalidTemplate: new TokenType("invalidTemplate"),
12632 ellipsis: new TokenType("...", beforeExpr),
12633 backQuote: new TokenType("`", startsExpr),
12634 dollarBraceL: new TokenType("${", {beforeExpr: true, startsExpr: true}),
12635
12636 // Operators. These carry several kinds of properties to help the
12637 // parser use them properly (the presence of these properties is
12638 // what categorizes them as operators).
12639 //
12640 // `binop`, when present, specifies that this operator is a binary
12641 // operator, and will refer to its precedence.
12642 //
12643 // `prefix` and `postfix` mark the operator as a prefix or postfix
12644 // unary operator.
12645 //
12646 // `isAssign` marks all of `=`, `+=`, `-=` etcetera, which act as
12647 // binary operators with a very low precedence, that should result
12648 // in AssignmentExpression nodes.
12649
12650 eq: new TokenType("=", {beforeExpr: true, isAssign: true}),
12651 assign: new TokenType("_=", {beforeExpr: true, isAssign: true}),
12652 incDec: new TokenType("++/--", {prefix: true, postfix: true, startsExpr: true}),
12653 prefix: new TokenType("!/~", {beforeExpr: true, prefix: true, startsExpr: true}),
12654 logicalOR: binop("||", 1),
12655 logicalAND: binop("&&", 2),
12656 bitwiseOR: binop("|", 3),
12657 bitwiseXOR: binop("^", 4),
12658 bitwiseAND: binop("&", 5),
12659 equality: binop("==/!=/===/!==", 6),
12660 relational: binop("</>/<=/>=", 7),
12661 bitShift: binop("<</>>/>>>", 8),
12662 plusMin: new TokenType("+/-", {beforeExpr: true, binop: 9, prefix: true, startsExpr: true}),
12663 modulo: binop("%", 10),
12664 star: binop("*", 10),
12665 slash: binop("/", 10),
12666 starstar: new TokenType("**", {beforeExpr: true}),
12667 coalesce: binop("??", 1),
12668
12669 // Keyword token types.
12670 _break: kw("break"),
12671 _case: kw("case", beforeExpr),
12672 _catch: kw("catch"),
12673 _continue: kw("continue"),
12674 _debugger: kw("debugger"),
12675 _default: kw("default", beforeExpr),
12676 _do: kw("do", {isLoop: true, beforeExpr: true}),
12677 _else: kw("else", beforeExpr),
12678 _finally: kw("finally"),
12679 _for: kw("for", {isLoop: true}),
12680 _function: kw("function", startsExpr),
12681 _if: kw("if"),
12682 _return: kw("return", beforeExpr),
12683 _switch: kw("switch"),
12684 _throw: kw("throw", beforeExpr),
12685 _try: kw("try"),
12686 _var: kw("var"),
12687 _const: kw("const"),
12688 _while: kw("while", {isLoop: true}),
12689 _with: kw("with"),
12690 _new: kw("new", {beforeExpr: true, startsExpr: true}),
12691 _this: kw("this", startsExpr),
12692 _super: kw("super", startsExpr),
12693 _class: kw("class", startsExpr),
12694 _extends: kw("extends", beforeExpr),
12695 _export: kw("export"),
12696 _import: kw("import", startsExpr),
12697 _null: kw("null", startsExpr),
12698 _true: kw("true", startsExpr),
12699 _false: kw("false", startsExpr),
12700 _in: kw("in", {beforeExpr: true, binop: 7}),
12701 _instanceof: kw("instanceof", {beforeExpr: true, binop: 7}),
12702 _typeof: kw("typeof", {beforeExpr: true, prefix: true, startsExpr: true}),
12703 _void: kw("void", {beforeExpr: true, prefix: true, startsExpr: true}),
12704 _delete: kw("delete", {beforeExpr: true, prefix: true, startsExpr: true})
12705};
12706
12707// Matches a whole line break (where CRLF is considered a single
12708// line break). Used to count lines.
12709
12710var lineBreak = /\r\n?|\n|\u2028|\u2029/;
12711var lineBreakG = new RegExp(lineBreak.source, "g");
12712
12713function isNewLine(code, ecma2019String) {
12714 return code === 10 || code === 13 || (!ecma2019String && (code === 0x2028 || code === 0x2029))
12715}
12716
12717var nonASCIIwhitespace = /[\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
12718
12719var skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
12720
12721var ref = Object.prototype;
12722var hasOwnProperty = ref.hasOwnProperty;
12723var toString$1 = ref.toString;
12724
12725// Checks if an object has a property.
12726
12727function has(obj, propName) {
12728 return hasOwnProperty.call(obj, propName)
12729}
12730
12731var isArray = Array.isArray || (function (obj) { return (
12732 toString$1.call(obj) === "[object Array]"
12733); });
12734
12735function wordsRegexp(words) {
12736 return new RegExp("^(?:" + words.replace(/ /g, "|") + ")$")
12737}
12738
12739// These are used when `options.locations` is on, for the
12740// `startLoc` and `endLoc` properties.
12741
12742var Position = function Position(line, col) {
12743 this.line = line;
12744 this.column = col;
12745};
12746
12747Position.prototype.offset = function offset (n) {
12748 return new Position(this.line, this.column + n)
12749};
12750
12751var SourceLocation = function SourceLocation(p, start, end) {
12752 this.start = start;
12753 this.end = end;
12754 if (p.sourceFile !== null) { this.source = p.sourceFile; }
12755};
12756
12757// The `getLineInfo` function is mostly useful when the
12758// `locations` option is off (for performance reasons) and you
12759// want to find the line/column position for a given character
12760// offset. `input` should be the code string that the offset refers
12761// into.
12762
12763function getLineInfo(input, offset) {
12764 for (var line = 1, cur = 0;;) {
12765 lineBreakG.lastIndex = cur;
12766 var match = lineBreakG.exec(input);
12767 if (match && match.index < offset) {
12768 ++line;
12769 cur = match.index + match[0].length;
12770 } else {
12771 return new Position(line, offset - cur)
12772 }
12773 }
12774}
12775
12776// A second argument must be given to configure the parser process.
12777// These options are recognized (only `ecmaVersion` is required):
12778
12779var defaultOptions = {
12780 // `ecmaVersion` indicates the ECMAScript version to parse. Must be
12781 // either 3, 5, 6 (or 2015), 7 (2016), 8 (2017), 9 (2018), 10
12782 // (2019), 11 (2020), 12 (2021), or `"latest"` (the latest version
12783 // the library supports). This influences support for strict mode,
12784 // the set of reserved words, and support for new syntax features.
12785 ecmaVersion: null,
12786 // `sourceType` indicates the mode the code should be parsed in.
12787 // Can be either `"script"` or `"module"`. This influences global
12788 // strict mode and parsing of `import` and `export` declarations.
12789 sourceType: "script",
12790 // `onInsertedSemicolon` can be a callback that will be called
12791 // when a semicolon is automatically inserted. It will be passed
12792 // the position of the comma as an offset, and if `locations` is
12793 // enabled, it is given the location as a `{line, column}` object
12794 // as second argument.
12795 onInsertedSemicolon: null,
12796 // `onTrailingComma` is similar to `onInsertedSemicolon`, but for
12797 // trailing commas.
12798 onTrailingComma: null,
12799 // By default, reserved words are only enforced if ecmaVersion >= 5.
12800 // Set `allowReserved` to a boolean value to explicitly turn this on
12801 // an off. When this option has the value "never", reserved words
12802 // and keywords can also not be used as property names.
12803 allowReserved: null,
12804 // When enabled, a return at the top level is not considered an
12805 // error.
12806 allowReturnOutsideFunction: false,
12807 // When enabled, import/export statements are not constrained to
12808 // appearing at the top of the program.
12809 allowImportExportEverywhere: false,
12810 // When enabled, await identifiers are allowed to appear at the top-level scope,
12811 // but they are still not allowed in non-async functions.
12812 allowAwaitOutsideFunction: false,
12813 // When enabled, hashbang directive in the beginning of file
12814 // is allowed and treated as a line comment.
12815 allowHashBang: false,
12816 // When `locations` is on, `loc` properties holding objects with
12817 // `start` and `end` properties in `{line, column}` form (with
12818 // line being 1-based and column 0-based) will be attached to the
12819 // nodes.
12820 locations: false,
12821 // A function can be passed as `onToken` option, which will
12822 // cause Acorn to call that function with object in the same
12823 // format as tokens returned from `tokenizer().getToken()`. Note
12824 // that you are not allowed to call the parser from the
12825 // callback—that will corrupt its internal state.
12826 onToken: null,
12827 // A function can be passed as `onComment` option, which will
12828 // cause Acorn to call that function with `(block, text, start,
12829 // end)` parameters whenever a comment is skipped. `block` is a
12830 // boolean indicating whether this is a block (`/* */`) comment,
12831 // `text` is the content of the comment, and `start` and `end` are
12832 // character offsets that denote the start and end of the comment.
12833 // When the `locations` option is on, two more parameters are
12834 // passed, the full `{line, column}` locations of the start and
12835 // end of the comments. Note that you are not allowed to call the
12836 // parser from the callback—that will corrupt its internal state.
12837 onComment: null,
12838 // Nodes have their start and end characters offsets recorded in
12839 // `start` and `end` properties (directly on the node, rather than
12840 // the `loc` object, which holds line/column data. To also add a
12841 // [semi-standardized][range] `range` property holding a `[start,
12842 // end]` array with the same numbers, set the `ranges` option to
12843 // `true`.
12844 //
12845 // [range]: https://bugzilla.mozilla.org/show_bug.cgi?id=745678
12846 ranges: false,
12847 // It is possible to parse multiple files into a single AST by
12848 // passing the tree produced by parsing the first file as
12849 // `program` option in subsequent parses. This will add the
12850 // toplevel forms of the parsed file to the `Program` (top) node
12851 // of an existing parse tree.
12852 program: null,
12853 // When `locations` is on, you can pass this to record the source
12854 // file in every node's `loc` object.
12855 sourceFile: null,
12856 // This value, if given, is stored in every node, whether
12857 // `locations` is on or off.
12858 directSourceFile: null,
12859 // When enabled, parenthesized expressions are represented by
12860 // (non-standard) ParenthesizedExpression nodes
12861 preserveParens: false
12862};
12863
12864// Interpret and default an options object
12865
12866var warnedAboutEcmaVersion = false;
12867
12868function getOptions(opts) {
12869 var options = {};
12870
12871 for (var opt in defaultOptions)
12872 { options[opt] = opts && has(opts, opt) ? opts[opt] : defaultOptions[opt]; }
12873
12874 if (options.ecmaVersion === "latest") {
12875 options.ecmaVersion = 1e8;
12876 } else if (options.ecmaVersion == null) {
12877 if (!warnedAboutEcmaVersion && typeof console === "object" && console.warn) {
12878 warnedAboutEcmaVersion = true;
12879 console.warn("Since Acorn 8.0.0, options.ecmaVersion is required.\nDefaulting to 2020, but this will stop working in the future.");
12880 }
12881 options.ecmaVersion = 11;
12882 } else if (options.ecmaVersion >= 2015) {
12883 options.ecmaVersion -= 2009;
12884 }
12885
12886 if (options.allowReserved == null)
12887 { options.allowReserved = options.ecmaVersion < 5; }
12888
12889 if (isArray(options.onToken)) {
12890 var tokens = options.onToken;
12891 options.onToken = function (token) { return tokens.push(token); };
12892 }
12893 if (isArray(options.onComment))
12894 { options.onComment = pushComment(options, options.onComment); }
12895
12896 return options
12897}
12898
12899function pushComment(options, array) {
12900 return function(block, text, start, end, startLoc, endLoc) {
12901 var comment = {
12902 type: block ? "Block" : "Line",
12903 value: text,
12904 start: start,
12905 end: end
12906 };
12907 if (options.locations)
12908 { comment.loc = new SourceLocation(this, startLoc, endLoc); }
12909 if (options.ranges)
12910 { comment.range = [start, end]; }
12911 array.push(comment);
12912 }
12913}
12914
12915// Each scope gets a bitset that may contain these flags
12916var
12917 SCOPE_TOP = 1,
12918 SCOPE_FUNCTION = 2,
12919 SCOPE_VAR = SCOPE_TOP | SCOPE_FUNCTION,
12920 SCOPE_ASYNC = 4,
12921 SCOPE_GENERATOR = 8,
12922 SCOPE_ARROW = 16,
12923 SCOPE_SIMPLE_CATCH = 32,
12924 SCOPE_SUPER = 64,
12925 SCOPE_DIRECT_SUPER = 128;
12926
12927function functionFlags(async, generator) {
12928 return SCOPE_FUNCTION | (async ? SCOPE_ASYNC : 0) | (generator ? SCOPE_GENERATOR : 0)
12929}
12930
12931// Used in checkLVal* and declareName to determine the type of a binding
12932var
12933 BIND_NONE = 0, // Not a binding
12934 BIND_VAR = 1, // Var-style binding
12935 BIND_LEXICAL = 2, // Let- or const-style binding
12936 BIND_FUNCTION = 3, // Function declaration
12937 BIND_SIMPLE_CATCH = 4, // Simple (identifier pattern) catch binding
12938 BIND_OUTSIDE = 5; // Special case for function names as bound inside the function
12939
12940var Parser = function Parser(options, input, startPos) {
12941 this.options = options = getOptions(options);
12942 this.sourceFile = options.sourceFile;
12943 this.keywords = wordsRegexp(keywords[options.ecmaVersion >= 6 ? 6 : options.sourceType === "module" ? "5module" : 5]);
12944 var reserved = "";
12945 if (options.allowReserved !== true) {
12946 reserved = reservedWords$1[options.ecmaVersion >= 6 ? 6 : options.ecmaVersion === 5 ? 5 : 3];
12947 if (options.sourceType === "module") { reserved += " await"; }
12948 }
12949 this.reservedWords = wordsRegexp(reserved);
12950 var reservedStrict = (reserved ? reserved + " " : "") + reservedWords$1.strict;
12951 this.reservedWordsStrict = wordsRegexp(reservedStrict);
12952 this.reservedWordsStrictBind = wordsRegexp(reservedStrict + " " + reservedWords$1.strictBind);
12953 this.input = String(input);
12954
12955 // Used to signal to callers of `readWord1` whether the word
12956 // contained any escape sequences. This is needed because words with
12957 // escape sequences must not be interpreted as keywords.
12958 this.containsEsc = false;
12959
12960 // Set up token state
12961
12962 // The current position of the tokenizer in the input.
12963 if (startPos) {
12964 this.pos = startPos;
12965 this.lineStart = this.input.lastIndexOf("\n", startPos - 1) + 1;
12966 this.curLine = this.input.slice(0, this.lineStart).split(lineBreak).length;
12967 } else {
12968 this.pos = this.lineStart = 0;
12969 this.curLine = 1;
12970 }
12971
12972 // Properties of the current token:
12973 // Its type
12974 this.type = types.eof;
12975 // For tokens that include more information than their type, the value
12976 this.value = null;
12977 // Its start and end offset
12978 this.start = this.end = this.pos;
12979 // And, if locations are used, the {line, column} object
12980 // corresponding to those offsets
12981 this.startLoc = this.endLoc = this.curPosition();
12982
12983 // Position information for the previous token
12984 this.lastTokEndLoc = this.lastTokStartLoc = null;
12985 this.lastTokStart = this.lastTokEnd = this.pos;
12986
12987 // The context stack is used to superficially track syntactic
12988 // context to predict whether a regular expression is allowed in a
12989 // given position.
12990 this.context = this.initialContext();
12991 this.exprAllowed = true;
12992
12993 // Figure out if it's a module code.
12994 this.inModule = options.sourceType === "module";
12995 this.strict = this.inModule || this.strictDirective(this.pos);
12996
12997 // Used to signify the start of a potential arrow function
12998 this.potentialArrowAt = -1;
12999
13000 // Positions to delayed-check that yield/await does not exist in default parameters.
13001 this.yieldPos = this.awaitPos = this.awaitIdentPos = 0;
13002 // Labels in scope.
13003 this.labels = [];
13004 // Thus-far undefined exports.
13005 this.undefinedExports = {};
13006
13007 // If enabled, skip leading hashbang line.
13008 if (this.pos === 0 && options.allowHashBang && this.input.slice(0, 2) === "#!")
13009 { this.skipLineComment(2); }
13010
13011 // Scope tracking for duplicate variable names (see scope.js)
13012 this.scopeStack = [];
13013 this.enterScope(SCOPE_TOP);
13014
13015 // For RegExp validation
13016 this.regexpState = null;
13017};
13018
13019var prototypeAccessors = { inFunction: { configurable: true },inGenerator: { configurable: true },inAsync: { configurable: true },allowSuper: { configurable: true },allowDirectSuper: { configurable: true },treatFunctionsAsVar: { configurable: true },inNonArrowFunction: { configurable: true } };
13020
13021Parser.prototype.parse = function parse () {
13022 var node = this.options.program || this.startNode();
13023 this.nextToken();
13024 return this.parseTopLevel(node)
13025};
13026
13027prototypeAccessors.inFunction.get = function () { return (this.currentVarScope().flags & SCOPE_FUNCTION) > 0 };
13028prototypeAccessors.inGenerator.get = function () { return (this.currentVarScope().flags & SCOPE_GENERATOR) > 0 };
13029prototypeAccessors.inAsync.get = function () { return (this.currentVarScope().flags & SCOPE_ASYNC) > 0 };
13030prototypeAccessors.allowSuper.get = function () { return (this.currentThisScope().flags & SCOPE_SUPER) > 0 };
13031prototypeAccessors.allowDirectSuper.get = function () { return (this.currentThisScope().flags & SCOPE_DIRECT_SUPER) > 0 };
13032prototypeAccessors.treatFunctionsAsVar.get = function () { return this.treatFunctionsAsVarInScope(this.currentScope()) };
13033prototypeAccessors.inNonArrowFunction.get = function () { return (this.currentThisScope().flags & SCOPE_FUNCTION) > 0 };
13034
13035Parser.extend = function extend () {
13036 var plugins = [], len = arguments.length;
13037 while ( len-- ) plugins[ len ] = arguments[ len ];
13038
13039 var cls = this;
13040 for (var i = 0; i < plugins.length; i++) { cls = plugins[i](cls); }
13041 return cls
13042};
13043
13044Parser.parse = function parse (input, options) {
13045 return new this(options, input).parse()
13046};
13047
13048Parser.parseExpressionAt = function parseExpressionAt (input, pos, options) {
13049 var parser = new this(options, input, pos);
13050 parser.nextToken();
13051 return parser.parseExpression()
13052};
13053
13054Parser.tokenizer = function tokenizer (input, options) {
13055 return new this(options, input)
13056};
13057
13058Object.defineProperties( Parser.prototype, prototypeAccessors );
13059
13060var pp = Parser.prototype;
13061
13062// ## Parser utilities
13063
13064var literal = /^(?:'((?:\\.|[^'])*?)'|"((?:\\.|[^"])*?)")/;
13065pp.strictDirective = function(start) {
13066 for (;;) {
13067 // Try to find string literal.
13068 skipWhiteSpace.lastIndex = start;
13069 start += skipWhiteSpace.exec(this.input)[0].length;
13070 var match = literal.exec(this.input.slice(start));
13071 if (!match) { return false }
13072 if ((match[1] || match[2]) === "use strict") {
13073 skipWhiteSpace.lastIndex = start + match[0].length;
13074 var spaceAfter = skipWhiteSpace.exec(this.input), end = spaceAfter.index + spaceAfter[0].length;
13075 var next = this.input.charAt(end);
13076 return next === ";" || next === "}" ||
13077 (lineBreak.test(spaceAfter[0]) &&
13078 !(/[(`.[+\-/*%<>=,?^&]/.test(next) || next === "!" && this.input.charAt(end + 1) === "="))
13079 }
13080 start += match[0].length;
13081
13082 // Skip semicolon, if any.
13083 skipWhiteSpace.lastIndex = start;
13084 start += skipWhiteSpace.exec(this.input)[0].length;
13085 if (this.input[start] === ";")
13086 { start++; }
13087 }
13088};
13089
13090// Predicate that tests whether the next token is of the given
13091// type, and if yes, consumes it as a side effect.
13092
13093pp.eat = function(type) {
13094 if (this.type === type) {
13095 this.next();
13096 return true
13097 } else {
13098 return false
13099 }
13100};
13101
13102// Tests whether parsed token is a contextual keyword.
13103
13104pp.isContextual = function(name) {
13105 return this.type === types.name && this.value === name && !this.containsEsc
13106};
13107
13108// Consumes contextual keyword if possible.
13109
13110pp.eatContextual = function(name) {
13111 if (!this.isContextual(name)) { return false }
13112 this.next();
13113 return true
13114};
13115
13116// Asserts that following token is given contextual keyword.
13117
13118pp.expectContextual = function(name) {
13119 if (!this.eatContextual(name)) { this.unexpected(); }
13120};
13121
13122// Test whether a semicolon can be inserted at the current position.
13123
13124pp.canInsertSemicolon = function() {
13125 return this.type === types.eof ||
13126 this.type === types.braceR ||
13127 lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
13128};
13129
13130pp.insertSemicolon = function() {
13131 if (this.canInsertSemicolon()) {
13132 if (this.options.onInsertedSemicolon)
13133 { this.options.onInsertedSemicolon(this.lastTokEnd, this.lastTokEndLoc); }
13134 return true
13135 }
13136};
13137
13138// Consume a semicolon, or, failing that, see if we are allowed to
13139// pretend that there is a semicolon at this position.
13140
13141pp.semicolon = function() {
13142 if (!this.eat(types.semi) && !this.insertSemicolon()) { this.unexpected(); }
13143};
13144
13145pp.afterTrailingComma = function(tokType, notNext) {
13146 if (this.type === tokType) {
13147 if (this.options.onTrailingComma)
13148 { this.options.onTrailingComma(this.lastTokStart, this.lastTokStartLoc); }
13149 if (!notNext)
13150 { this.next(); }
13151 return true
13152 }
13153};
13154
13155// Expect a token of a given type. If found, consume it, otherwise,
13156// raise an unexpected token error.
13157
13158pp.expect = function(type) {
13159 this.eat(type) || this.unexpected();
13160};
13161
13162// Raise an unexpected token error.
13163
13164pp.unexpected = function(pos) {
13165 this.raise(pos != null ? pos : this.start, "Unexpected token");
13166};
13167
13168function DestructuringErrors() {
13169 this.shorthandAssign =
13170 this.trailingComma =
13171 this.parenthesizedAssign =
13172 this.parenthesizedBind =
13173 this.doubleProto =
13174 -1;
13175}
13176
13177pp.checkPatternErrors = function(refDestructuringErrors, isAssign) {
13178 if (!refDestructuringErrors) { return }
13179 if (refDestructuringErrors.trailingComma > -1)
13180 { this.raiseRecoverable(refDestructuringErrors.trailingComma, "Comma is not permitted after the rest element"); }
13181 var parens = isAssign ? refDestructuringErrors.parenthesizedAssign : refDestructuringErrors.parenthesizedBind;
13182 if (parens > -1) { this.raiseRecoverable(parens, "Parenthesized pattern"); }
13183};
13184
13185pp.checkExpressionErrors = function(refDestructuringErrors, andThrow) {
13186 if (!refDestructuringErrors) { return false }
13187 var shorthandAssign = refDestructuringErrors.shorthandAssign;
13188 var doubleProto = refDestructuringErrors.doubleProto;
13189 if (!andThrow) { return shorthandAssign >= 0 || doubleProto >= 0 }
13190 if (shorthandAssign >= 0)
13191 { this.raise(shorthandAssign, "Shorthand property assignments are valid only in destructuring patterns"); }
13192 if (doubleProto >= 0)
13193 { this.raiseRecoverable(doubleProto, "Redefinition of __proto__ property"); }
13194};
13195
13196pp.checkYieldAwaitInDefaultParams = function() {
13197 if (this.yieldPos && (!this.awaitPos || this.yieldPos < this.awaitPos))
13198 { this.raise(this.yieldPos, "Yield expression cannot be a default value"); }
13199 if (this.awaitPos)
13200 { this.raise(this.awaitPos, "Await expression cannot be a default value"); }
13201};
13202
13203pp.isSimpleAssignTarget = function(expr) {
13204 if (expr.type === "ParenthesizedExpression")
13205 { return this.isSimpleAssignTarget(expr.expression) }
13206 return expr.type === "Identifier" || expr.type === "MemberExpression"
13207};
13208
13209var pp$1 = Parser.prototype;
13210
13211// ### Statement parsing
13212
13213// Parse a program. Initializes the parser, reads any number of
13214// statements, and wraps them in a Program node. Optionally takes a
13215// `program` argument. If present, the statements will be appended
13216// to its body instead of creating a new node.
13217
13218pp$1.parseTopLevel = function(node) {
13219 var exports = {};
13220 if (!node.body) { node.body = []; }
13221 while (this.type !== types.eof) {
13222 var stmt = this.parseStatement(null, true, exports);
13223 node.body.push(stmt);
13224 }
13225 if (this.inModule)
13226 { for (var i = 0, list = Object.keys(this.undefinedExports); i < list.length; i += 1)
13227 {
13228 var name = list[i];
13229
13230 this.raiseRecoverable(this.undefinedExports[name].start, ("Export '" + name + "' is not defined"));
13231 } }
13232 this.adaptDirectivePrologue(node.body);
13233 this.next();
13234 node.sourceType = this.options.sourceType;
13235 return this.finishNode(node, "Program")
13236};
13237
13238var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
13239
13240pp$1.isLet = function(context) {
13241 if (this.options.ecmaVersion < 6 || !this.isContextual("let")) { return false }
13242 skipWhiteSpace.lastIndex = this.pos;
13243 var skip = skipWhiteSpace.exec(this.input);
13244 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
13245 // For ambiguous cases, determine if a LexicalDeclaration (or only a
13246 // Statement) is allowed here. If context is not empty then only a Statement
13247 // is allowed. However, `let [` is an explicit negative lookahead for
13248 // ExpressionStatement, so special-case it first.
13249 if (nextCh === 91) { return true } // '['
13250 if (context) { return false }
13251
13252 if (nextCh === 123) { return true } // '{'
13253 if (isIdentifierStart(nextCh, true)) {
13254 var pos = next + 1;
13255 while (isIdentifierChar(this.input.charCodeAt(pos), true)) { ++pos; }
13256 var ident = this.input.slice(next, pos);
13257 if (!keywordRelationalOperator.test(ident)) { return true }
13258 }
13259 return false
13260};
13261
13262// check 'async [no LineTerminator here] function'
13263// - 'async /*foo*/ function' is OK.
13264// - 'async /*\n*/ function' is invalid.
13265pp$1.isAsyncFunction = function() {
13266 if (this.options.ecmaVersion < 8 || !this.isContextual("async"))
13267 { return false }
13268
13269 skipWhiteSpace.lastIndex = this.pos;
13270 var skip = skipWhiteSpace.exec(this.input);
13271 var next = this.pos + skip[0].length;
13272 return !lineBreak.test(this.input.slice(this.pos, next)) &&
13273 this.input.slice(next, next + 8) === "function" &&
13274 (next + 8 === this.input.length || !isIdentifierChar(this.input.charAt(next + 8)))
13275};
13276
13277// Parse a single statement.
13278//
13279// If expecting a statement and finding a slash operator, parse a
13280// regular expression literal. This is to handle cases like
13281// `if (foo) /blah/.exec(foo)`, where looking at the previous token
13282// does not help.
13283
13284pp$1.parseStatement = function(context, topLevel, exports) {
13285 var starttype = this.type, node = this.startNode(), kind;
13286
13287 if (this.isLet(context)) {
13288 starttype = types._var;
13289 kind = "let";
13290 }
13291
13292 // Most types of statements are recognized by the keyword they
13293 // start with. Many are trivial to parse, some require a bit of
13294 // complexity.
13295
13296 switch (starttype) {
13297 case types._break: case types._continue: return this.parseBreakContinueStatement(node, starttype.keyword)
13298 case types._debugger: return this.parseDebuggerStatement(node)
13299 case types._do: return this.parseDoStatement(node)
13300 case types._for: return this.parseForStatement(node)
13301 case types._function:
13302 // Function as sole body of either an if statement or a labeled statement
13303 // works, but not when it is part of a labeled statement that is the sole
13304 // body of an if statement.
13305 if ((context && (this.strict || context !== "if" && context !== "label")) && this.options.ecmaVersion >= 6) { this.unexpected(); }
13306 return this.parseFunctionStatement(node, false, !context)
13307 case types._class:
13308 if (context) { this.unexpected(); }
13309 return this.parseClass(node, true)
13310 case types._if: return this.parseIfStatement(node)
13311 case types._return: return this.parseReturnStatement(node)
13312 case types._switch: return this.parseSwitchStatement(node)
13313 case types._throw: return this.parseThrowStatement(node)
13314 case types._try: return this.parseTryStatement(node)
13315 case types._const: case types._var:
13316 kind = kind || this.value;
13317 if (context && kind !== "var") { this.unexpected(); }
13318 return this.parseVarStatement(node, kind)
13319 case types._while: return this.parseWhileStatement(node)
13320 case types._with: return this.parseWithStatement(node)
13321 case types.braceL: return this.parseBlock(true, node)
13322 case types.semi: return this.parseEmptyStatement(node)
13323 case types._export:
13324 case types._import:
13325 if (this.options.ecmaVersion > 10 && starttype === types._import) {
13326 skipWhiteSpace.lastIndex = this.pos;
13327 var skip = skipWhiteSpace.exec(this.input);
13328 var next = this.pos + skip[0].length, nextCh = this.input.charCodeAt(next);
13329 if (nextCh === 40 || nextCh === 46) // '(' or '.'
13330 { return this.parseExpressionStatement(node, this.parseExpression()) }
13331 }
13332
13333 if (!this.options.allowImportExportEverywhere) {
13334 if (!topLevel)
13335 { this.raise(this.start, "'import' and 'export' may only appear at the top level"); }
13336 if (!this.inModule)
13337 { this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'"); }
13338 }
13339 return starttype === types._import ? this.parseImport(node) : this.parseExport(node, exports)
13340
13341 // If the statement does not start with a statement keyword or a
13342 // brace, it's an ExpressionStatement or LabeledStatement. We
13343 // simply start parsing an expression, and afterwards, if the
13344 // next token is a colon and the expression was a simple
13345 // Identifier node, we switch to interpreting it as a label.
13346 default:
13347 if (this.isAsyncFunction()) {
13348 if (context) { this.unexpected(); }
13349 this.next();
13350 return this.parseFunctionStatement(node, true, !context)
13351 }
13352
13353 var maybeName = this.value, expr = this.parseExpression();
13354 if (starttype === types.name && expr.type === "Identifier" && this.eat(types.colon))
13355 { return this.parseLabeledStatement(node, maybeName, expr, context) }
13356 else { return this.parseExpressionStatement(node, expr) }
13357 }
13358};
13359
13360pp$1.parseBreakContinueStatement = function(node, keyword) {
13361 var isBreak = keyword === "break";
13362 this.next();
13363 if (this.eat(types.semi) || this.insertSemicolon()) { node.label = null; }
13364 else if (this.type !== types.name) { this.unexpected(); }
13365 else {
13366 node.label = this.parseIdent();
13367 this.semicolon();
13368 }
13369
13370 // Verify that there is an actual destination to break or
13371 // continue to.
13372 var i = 0;
13373 for (; i < this.labels.length; ++i) {
13374 var lab = this.labels[i];
13375 if (node.label == null || lab.name === node.label.name) {
13376 if (lab.kind != null && (isBreak || lab.kind === "loop")) { break }
13377 if (node.label && isBreak) { break }
13378 }
13379 }
13380 if (i === this.labels.length) { this.raise(node.start, "Unsyntactic " + keyword); }
13381 return this.finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement")
13382};
13383
13384pp$1.parseDebuggerStatement = function(node) {
13385 this.next();
13386 this.semicolon();
13387 return this.finishNode(node, "DebuggerStatement")
13388};
13389
13390pp$1.parseDoStatement = function(node) {
13391 this.next();
13392 this.labels.push(loopLabel);
13393 node.body = this.parseStatement("do");
13394 this.labels.pop();
13395 this.expect(types._while);
13396 node.test = this.parseParenExpression();
13397 if (this.options.ecmaVersion >= 6)
13398 { this.eat(types.semi); }
13399 else
13400 { this.semicolon(); }
13401 return this.finishNode(node, "DoWhileStatement")
13402};
13403
13404// Disambiguating between a `for` and a `for`/`in` or `for`/`of`
13405// loop is non-trivial. Basically, we have to parse the init `var`
13406// statement or expression, disallowing the `in` operator (see
13407// the second parameter to `parseExpression`), and then check
13408// whether the next token is `in` or `of`. When there is no init
13409// part (semicolon immediately after the opening parenthesis), it
13410// is a regular `for` loop.
13411
13412pp$1.parseForStatement = function(node) {
13413 this.next();
13414 var awaitAt = (this.options.ecmaVersion >= 9 && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction)) && this.eatContextual("await")) ? this.lastTokStart : -1;
13415 this.labels.push(loopLabel);
13416 this.enterScope(0);
13417 this.expect(types.parenL);
13418 if (this.type === types.semi) {
13419 if (awaitAt > -1) { this.unexpected(awaitAt); }
13420 return this.parseFor(node, null)
13421 }
13422 var isLet = this.isLet();
13423 if (this.type === types._var || this.type === types._const || isLet) {
13424 var init$1 = this.startNode(), kind = isLet ? "let" : this.value;
13425 this.next();
13426 this.parseVar(init$1, true, kind);
13427 this.finishNode(init$1, "VariableDeclaration");
13428 if ((this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) && init$1.declarations.length === 1) {
13429 if (this.options.ecmaVersion >= 9) {
13430 if (this.type === types._in) {
13431 if (awaitAt > -1) { this.unexpected(awaitAt); }
13432 } else { node.await = awaitAt > -1; }
13433 }
13434 return this.parseForIn(node, init$1)
13435 }
13436 if (awaitAt > -1) { this.unexpected(awaitAt); }
13437 return this.parseFor(node, init$1)
13438 }
13439 var refDestructuringErrors = new DestructuringErrors;
13440 var init = this.parseExpression(true, refDestructuringErrors);
13441 if (this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of"))) {
13442 if (this.options.ecmaVersion >= 9) {
13443 if (this.type === types._in) {
13444 if (awaitAt > -1) { this.unexpected(awaitAt); }
13445 } else { node.await = awaitAt > -1; }
13446 }
13447 this.toAssignable(init, false, refDestructuringErrors);
13448 this.checkLValPattern(init);
13449 return this.parseForIn(node, init)
13450 } else {
13451 this.checkExpressionErrors(refDestructuringErrors, true);
13452 }
13453 if (awaitAt > -1) { this.unexpected(awaitAt); }
13454 return this.parseFor(node, init)
13455};
13456
13457pp$1.parseFunctionStatement = function(node, isAsync, declarationPosition) {
13458 this.next();
13459 return this.parseFunction(node, FUNC_STATEMENT | (declarationPosition ? 0 : FUNC_HANGING_STATEMENT), false, isAsync)
13460};
13461
13462pp$1.parseIfStatement = function(node) {
13463 this.next();
13464 node.test = this.parseParenExpression();
13465 // allow function declarations in branches, but only in non-strict mode
13466 node.consequent = this.parseStatement("if");
13467 node.alternate = this.eat(types._else) ? this.parseStatement("if") : null;
13468 return this.finishNode(node, "IfStatement")
13469};
13470
13471pp$1.parseReturnStatement = function(node) {
13472 if (!this.inFunction && !this.options.allowReturnOutsideFunction)
13473 { this.raise(this.start, "'return' outside of function"); }
13474 this.next();
13475
13476 // In `return` (and `break`/`continue`), the keywords with
13477 // optional arguments, we eagerly look for a semicolon or the
13478 // possibility to insert one.
13479
13480 if (this.eat(types.semi) || this.insertSemicolon()) { node.argument = null; }
13481 else { node.argument = this.parseExpression(); this.semicolon(); }
13482 return this.finishNode(node, "ReturnStatement")
13483};
13484
13485pp$1.parseSwitchStatement = function(node) {
13486 this.next();
13487 node.discriminant = this.parseParenExpression();
13488 node.cases = [];
13489 this.expect(types.braceL);
13490 this.labels.push(switchLabel);
13491 this.enterScope(0);
13492
13493 // Statements under must be grouped (by label) in SwitchCase
13494 // nodes. `cur` is used to keep the node that we are currently
13495 // adding statements to.
13496
13497 var cur;
13498 for (var sawDefault = false; this.type !== types.braceR;) {
13499 if (this.type === types._case || this.type === types._default) {
13500 var isCase = this.type === types._case;
13501 if (cur) { this.finishNode(cur, "SwitchCase"); }
13502 node.cases.push(cur = this.startNode());
13503 cur.consequent = [];
13504 this.next();
13505 if (isCase) {
13506 cur.test = this.parseExpression();
13507 } else {
13508 if (sawDefault) { this.raiseRecoverable(this.lastTokStart, "Multiple default clauses"); }
13509 sawDefault = true;
13510 cur.test = null;
13511 }
13512 this.expect(types.colon);
13513 } else {
13514 if (!cur) { this.unexpected(); }
13515 cur.consequent.push(this.parseStatement(null));
13516 }
13517 }
13518 this.exitScope();
13519 if (cur) { this.finishNode(cur, "SwitchCase"); }
13520 this.next(); // Closing brace
13521 this.labels.pop();
13522 return this.finishNode(node, "SwitchStatement")
13523};
13524
13525pp$1.parseThrowStatement = function(node) {
13526 this.next();
13527 if (lineBreak.test(this.input.slice(this.lastTokEnd, this.start)))
13528 { this.raise(this.lastTokEnd, "Illegal newline after throw"); }
13529 node.argument = this.parseExpression();
13530 this.semicolon();
13531 return this.finishNode(node, "ThrowStatement")
13532};
13533
13534// Reused empty array added for node fields that are always empty.
13535
13536var empty = [];
13537
13538pp$1.parseTryStatement = function(node) {
13539 this.next();
13540 node.block = this.parseBlock();
13541 node.handler = null;
13542 if (this.type === types._catch) {
13543 var clause = this.startNode();
13544 this.next();
13545 if (this.eat(types.parenL)) {
13546 clause.param = this.parseBindingAtom();
13547 var simple = clause.param.type === "Identifier";
13548 this.enterScope(simple ? SCOPE_SIMPLE_CATCH : 0);
13549 this.checkLValPattern(clause.param, simple ? BIND_SIMPLE_CATCH : BIND_LEXICAL);
13550 this.expect(types.parenR);
13551 } else {
13552 if (this.options.ecmaVersion < 10) { this.unexpected(); }
13553 clause.param = null;
13554 this.enterScope(0);
13555 }
13556 clause.body = this.parseBlock(false);
13557 this.exitScope();
13558 node.handler = this.finishNode(clause, "CatchClause");
13559 }
13560 node.finalizer = this.eat(types._finally) ? this.parseBlock() : null;
13561 if (!node.handler && !node.finalizer)
13562 { this.raise(node.start, "Missing catch or finally clause"); }
13563 return this.finishNode(node, "TryStatement")
13564};
13565
13566pp$1.parseVarStatement = function(node, kind) {
13567 this.next();
13568 this.parseVar(node, false, kind);
13569 this.semicolon();
13570 return this.finishNode(node, "VariableDeclaration")
13571};
13572
13573pp$1.parseWhileStatement = function(node) {
13574 this.next();
13575 node.test = this.parseParenExpression();
13576 this.labels.push(loopLabel);
13577 node.body = this.parseStatement("while");
13578 this.labels.pop();
13579 return this.finishNode(node, "WhileStatement")
13580};
13581
13582pp$1.parseWithStatement = function(node) {
13583 if (this.strict) { this.raise(this.start, "'with' in strict mode"); }
13584 this.next();
13585 node.object = this.parseParenExpression();
13586 node.body = this.parseStatement("with");
13587 return this.finishNode(node, "WithStatement")
13588};
13589
13590pp$1.parseEmptyStatement = function(node) {
13591 this.next();
13592 return this.finishNode(node, "EmptyStatement")
13593};
13594
13595pp$1.parseLabeledStatement = function(node, maybeName, expr, context) {
13596 for (var i$1 = 0, list = this.labels; i$1 < list.length; i$1 += 1)
13597 {
13598 var label = list[i$1];
13599
13600 if (label.name === maybeName)
13601 { this.raise(expr.start, "Label '" + maybeName + "' is already declared");
13602 } }
13603 var kind = this.type.isLoop ? "loop" : this.type === types._switch ? "switch" : null;
13604 for (var i = this.labels.length - 1; i >= 0; i--) {
13605 var label$1 = this.labels[i];
13606 if (label$1.statementStart === node.start) {
13607 // Update information about previous labels on this node
13608 label$1.statementStart = this.start;
13609 label$1.kind = kind;
13610 } else { break }
13611 }
13612 this.labels.push({name: maybeName, kind: kind, statementStart: this.start});
13613 node.body = this.parseStatement(context ? context.indexOf("label") === -1 ? context + "label" : context : "label");
13614 this.labels.pop();
13615 node.label = expr;
13616 return this.finishNode(node, "LabeledStatement")
13617};
13618
13619pp$1.parseExpressionStatement = function(node, expr) {
13620 node.expression = expr;
13621 this.semicolon();
13622 return this.finishNode(node, "ExpressionStatement")
13623};
13624
13625// Parse a semicolon-enclosed block of statements, handling `"use
13626// strict"` declarations when `allowStrict` is true (used for
13627// function bodies).
13628
13629pp$1.parseBlock = function(createNewLexicalScope, node, exitStrict) {
13630 if ( createNewLexicalScope === void 0 ) createNewLexicalScope = true;
13631 if ( node === void 0 ) node = this.startNode();
13632
13633 node.body = [];
13634 this.expect(types.braceL);
13635 if (createNewLexicalScope) { this.enterScope(0); }
13636 while (this.type !== types.braceR) {
13637 var stmt = this.parseStatement(null);
13638 node.body.push(stmt);
13639 }
13640 if (exitStrict) { this.strict = false; }
13641 this.next();
13642 if (createNewLexicalScope) { this.exitScope(); }
13643 return this.finishNode(node, "BlockStatement")
13644};
13645
13646// Parse a regular `for` loop. The disambiguation code in
13647// `parseStatement` will already have parsed the init statement or
13648// expression.
13649
13650pp$1.parseFor = function(node, init) {
13651 node.init = init;
13652 this.expect(types.semi);
13653 node.test = this.type === types.semi ? null : this.parseExpression();
13654 this.expect(types.semi);
13655 node.update = this.type === types.parenR ? null : this.parseExpression();
13656 this.expect(types.parenR);
13657 node.body = this.parseStatement("for");
13658 this.exitScope();
13659 this.labels.pop();
13660 return this.finishNode(node, "ForStatement")
13661};
13662
13663// Parse a `for`/`in` and `for`/`of` loop, which are almost
13664// same from parser's perspective.
13665
13666pp$1.parseForIn = function(node, init) {
13667 var isForIn = this.type === types._in;
13668 this.next();
13669
13670 if (
13671 init.type === "VariableDeclaration" &&
13672 init.declarations[0].init != null &&
13673 (
13674 !isForIn ||
13675 this.options.ecmaVersion < 8 ||
13676 this.strict ||
13677 init.kind !== "var" ||
13678 init.declarations[0].id.type !== "Identifier"
13679 )
13680 ) {
13681 this.raise(
13682 init.start,
13683 ((isForIn ? "for-in" : "for-of") + " loop variable declaration may not have an initializer")
13684 );
13685 }
13686 node.left = init;
13687 node.right = isForIn ? this.parseExpression() : this.parseMaybeAssign();
13688 this.expect(types.parenR);
13689 node.body = this.parseStatement("for");
13690 this.exitScope();
13691 this.labels.pop();
13692 return this.finishNode(node, isForIn ? "ForInStatement" : "ForOfStatement")
13693};
13694
13695// Parse a list of variable declarations.
13696
13697pp$1.parseVar = function(node, isFor, kind) {
13698 node.declarations = [];
13699 node.kind = kind;
13700 for (;;) {
13701 var decl = this.startNode();
13702 this.parseVarId(decl, kind);
13703 if (this.eat(types.eq)) {
13704 decl.init = this.parseMaybeAssign(isFor);
13705 } else if (kind === "const" && !(this.type === types._in || (this.options.ecmaVersion >= 6 && this.isContextual("of")))) {
13706 this.unexpected();
13707 } else if (decl.id.type !== "Identifier" && !(isFor && (this.type === types._in || this.isContextual("of")))) {
13708 this.raise(this.lastTokEnd, "Complex binding patterns require an initialization value");
13709 } else {
13710 decl.init = null;
13711 }
13712 node.declarations.push(this.finishNode(decl, "VariableDeclarator"));
13713 if (!this.eat(types.comma)) { break }
13714 }
13715 return node
13716};
13717
13718pp$1.parseVarId = function(decl, kind) {
13719 decl.id = this.parseBindingAtom();
13720 this.checkLValPattern(decl.id, kind === "var" ? BIND_VAR : BIND_LEXICAL, false);
13721};
13722
13723var FUNC_STATEMENT = 1, FUNC_HANGING_STATEMENT = 2, FUNC_NULLABLE_ID = 4;
13724
13725// Parse a function declaration or literal (depending on the
13726// `statement & FUNC_STATEMENT`).
13727
13728// Remove `allowExpressionBody` for 7.0.0, as it is only called with false
13729pp$1.parseFunction = function(node, statement, allowExpressionBody, isAsync) {
13730 this.initFunction(node);
13731 if (this.options.ecmaVersion >= 9 || this.options.ecmaVersion >= 6 && !isAsync) {
13732 if (this.type === types.star && (statement & FUNC_HANGING_STATEMENT))
13733 { this.unexpected(); }
13734 node.generator = this.eat(types.star);
13735 }
13736 if (this.options.ecmaVersion >= 8)
13737 { node.async = !!isAsync; }
13738
13739 if (statement & FUNC_STATEMENT) {
13740 node.id = (statement & FUNC_NULLABLE_ID) && this.type !== types.name ? null : this.parseIdent();
13741 if (node.id && !(statement & FUNC_HANGING_STATEMENT))
13742 // If it is a regular function declaration in sloppy mode, then it is
13743 // subject to Annex B semantics (BIND_FUNCTION). Otherwise, the binding
13744 // mode depends on properties of the current scope (see
13745 // treatFunctionsAsVar).
13746 { this.checkLValSimple(node.id, (this.strict || node.generator || node.async) ? this.treatFunctionsAsVar ? BIND_VAR : BIND_LEXICAL : BIND_FUNCTION); }
13747 }
13748
13749 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
13750 this.yieldPos = 0;
13751 this.awaitPos = 0;
13752 this.awaitIdentPos = 0;
13753 this.enterScope(functionFlags(node.async, node.generator));
13754
13755 if (!(statement & FUNC_STATEMENT))
13756 { node.id = this.type === types.name ? this.parseIdent() : null; }
13757
13758 this.parseFunctionParams(node);
13759 this.parseFunctionBody(node, allowExpressionBody, false);
13760
13761 this.yieldPos = oldYieldPos;
13762 this.awaitPos = oldAwaitPos;
13763 this.awaitIdentPos = oldAwaitIdentPos;
13764 return this.finishNode(node, (statement & FUNC_STATEMENT) ? "FunctionDeclaration" : "FunctionExpression")
13765};
13766
13767pp$1.parseFunctionParams = function(node) {
13768 this.expect(types.parenL);
13769 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
13770 this.checkYieldAwaitInDefaultParams();
13771};
13772
13773// Parse a class declaration or literal (depending on the
13774// `isStatement` parameter).
13775
13776pp$1.parseClass = function(node, isStatement) {
13777 this.next();
13778
13779 // ecma-262 14.6 Class Definitions
13780 // A class definition is always strict mode code.
13781 var oldStrict = this.strict;
13782 this.strict = true;
13783
13784 this.parseClassId(node, isStatement);
13785 this.parseClassSuper(node);
13786 var classBody = this.startNode();
13787 var hadConstructor = false;
13788 classBody.body = [];
13789 this.expect(types.braceL);
13790 while (this.type !== types.braceR) {
13791 var element = this.parseClassElement(node.superClass !== null);
13792 if (element) {
13793 classBody.body.push(element);
13794 if (element.type === "MethodDefinition" && element.kind === "constructor") {
13795 if (hadConstructor) { this.raise(element.start, "Duplicate constructor in the same class"); }
13796 hadConstructor = true;
13797 }
13798 }
13799 }
13800 this.strict = oldStrict;
13801 this.next();
13802 node.body = this.finishNode(classBody, "ClassBody");
13803 return this.finishNode(node, isStatement ? "ClassDeclaration" : "ClassExpression")
13804};
13805
13806pp$1.parseClassElement = function(constructorAllowsSuper) {
13807 var this$1 = this;
13808
13809 if (this.eat(types.semi)) { return null }
13810
13811 var method = this.startNode();
13812 var tryContextual = function (k, noLineBreak) {
13813 if ( noLineBreak === void 0 ) noLineBreak = false;
13814
13815 var start = this$1.start, startLoc = this$1.startLoc;
13816 if (!this$1.eatContextual(k)) { return false }
13817 if (this$1.type !== types.parenL && (!noLineBreak || !this$1.canInsertSemicolon())) { return true }
13818 if (method.key) { this$1.unexpected(); }
13819 method.computed = false;
13820 method.key = this$1.startNodeAt(start, startLoc);
13821 method.key.name = k;
13822 this$1.finishNode(method.key, "Identifier");
13823 return false
13824 };
13825
13826 method.kind = "method";
13827 method.static = tryContextual("static");
13828 var isGenerator = this.eat(types.star);
13829 var isAsync = false;
13830 if (!isGenerator) {
13831 if (this.options.ecmaVersion >= 8 && tryContextual("async", true)) {
13832 isAsync = true;
13833 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
13834 } else if (tryContextual("get")) {
13835 method.kind = "get";
13836 } else if (tryContextual("set")) {
13837 method.kind = "set";
13838 }
13839 }
13840 if (!method.key) { this.parsePropertyName(method); }
13841 var key = method.key;
13842 var allowsDirectSuper = false;
13843 if (!method.computed && !method.static && (key.type === "Identifier" && key.name === "constructor" ||
13844 key.type === "Literal" && key.value === "constructor")) {
13845 if (method.kind !== "method") { this.raise(key.start, "Constructor can't have get/set modifier"); }
13846 if (isGenerator) { this.raise(key.start, "Constructor can't be a generator"); }
13847 if (isAsync) { this.raise(key.start, "Constructor can't be an async method"); }
13848 method.kind = "constructor";
13849 allowsDirectSuper = constructorAllowsSuper;
13850 } else if (method.static && key.type === "Identifier" && key.name === "prototype") {
13851 this.raise(key.start, "Classes may not have a static property named prototype");
13852 }
13853 this.parseClassMethod(method, isGenerator, isAsync, allowsDirectSuper);
13854 if (method.kind === "get" && method.value.params.length !== 0)
13855 { this.raiseRecoverable(method.value.start, "getter should have no params"); }
13856 if (method.kind === "set" && method.value.params.length !== 1)
13857 { this.raiseRecoverable(method.value.start, "setter should have exactly one param"); }
13858 if (method.kind === "set" && method.value.params[0].type === "RestElement")
13859 { this.raiseRecoverable(method.value.params[0].start, "Setter cannot use rest params"); }
13860 return method
13861};
13862
13863pp$1.parseClassMethod = function(method, isGenerator, isAsync, allowsDirectSuper) {
13864 method.value = this.parseMethod(isGenerator, isAsync, allowsDirectSuper);
13865 return this.finishNode(method, "MethodDefinition")
13866};
13867
13868pp$1.parseClassId = function(node, isStatement) {
13869 if (this.type === types.name) {
13870 node.id = this.parseIdent();
13871 if (isStatement)
13872 { this.checkLValSimple(node.id, BIND_LEXICAL, false); }
13873 } else {
13874 if (isStatement === true)
13875 { this.unexpected(); }
13876 node.id = null;
13877 }
13878};
13879
13880pp$1.parseClassSuper = function(node) {
13881 node.superClass = this.eat(types._extends) ? this.parseExprSubscripts() : null;
13882};
13883
13884// Parses module export declaration.
13885
13886pp$1.parseExport = function(node, exports) {
13887 this.next();
13888 // export * from '...'
13889 if (this.eat(types.star)) {
13890 if (this.options.ecmaVersion >= 11) {
13891 if (this.eatContextual("as")) {
13892 node.exported = this.parseIdent(true);
13893 this.checkExport(exports, node.exported.name, this.lastTokStart);
13894 } else {
13895 node.exported = null;
13896 }
13897 }
13898 this.expectContextual("from");
13899 if (this.type !== types.string) { this.unexpected(); }
13900 node.source = this.parseExprAtom();
13901 this.semicolon();
13902 return this.finishNode(node, "ExportAllDeclaration")
13903 }
13904 if (this.eat(types._default)) { // export default ...
13905 this.checkExport(exports, "default", this.lastTokStart);
13906 var isAsync;
13907 if (this.type === types._function || (isAsync = this.isAsyncFunction())) {
13908 var fNode = this.startNode();
13909 this.next();
13910 if (isAsync) { this.next(); }
13911 node.declaration = this.parseFunction(fNode, FUNC_STATEMENT | FUNC_NULLABLE_ID, false, isAsync);
13912 } else if (this.type === types._class) {
13913 var cNode = this.startNode();
13914 node.declaration = this.parseClass(cNode, "nullableID");
13915 } else {
13916 node.declaration = this.parseMaybeAssign();
13917 this.semicolon();
13918 }
13919 return this.finishNode(node, "ExportDefaultDeclaration")
13920 }
13921 // export var|const|let|function|class ...
13922 if (this.shouldParseExportStatement()) {
13923 node.declaration = this.parseStatement(null);
13924 if (node.declaration.type === "VariableDeclaration")
13925 { this.checkVariableExport(exports, node.declaration.declarations); }
13926 else
13927 { this.checkExport(exports, node.declaration.id.name, node.declaration.id.start); }
13928 node.specifiers = [];
13929 node.source = null;
13930 } else { // export { x, y as z } [from '...']
13931 node.declaration = null;
13932 node.specifiers = this.parseExportSpecifiers(exports);
13933 if (this.eatContextual("from")) {
13934 if (this.type !== types.string) { this.unexpected(); }
13935 node.source = this.parseExprAtom();
13936 } else {
13937 for (var i = 0, list = node.specifiers; i < list.length; i += 1) {
13938 // check for keywords used as local names
13939 var spec = list[i];
13940
13941 this.checkUnreserved(spec.local);
13942 // check if export is defined
13943 this.checkLocalExport(spec.local);
13944 }
13945
13946 node.source = null;
13947 }
13948 this.semicolon();
13949 }
13950 return this.finishNode(node, "ExportNamedDeclaration")
13951};
13952
13953pp$1.checkExport = function(exports, name, pos) {
13954 if (!exports) { return }
13955 if (has(exports, name))
13956 { this.raiseRecoverable(pos, "Duplicate export '" + name + "'"); }
13957 exports[name] = true;
13958};
13959
13960pp$1.checkPatternExport = function(exports, pat) {
13961 var type = pat.type;
13962 if (type === "Identifier")
13963 { this.checkExport(exports, pat.name, pat.start); }
13964 else if (type === "ObjectPattern")
13965 { for (var i = 0, list = pat.properties; i < list.length; i += 1)
13966 {
13967 var prop = list[i];
13968
13969 this.checkPatternExport(exports, prop);
13970 } }
13971 else if (type === "ArrayPattern")
13972 { for (var i$1 = 0, list$1 = pat.elements; i$1 < list$1.length; i$1 += 1) {
13973 var elt = list$1[i$1];
13974
13975 if (elt) { this.checkPatternExport(exports, elt); }
13976 } }
13977 else if (type === "Property")
13978 { this.checkPatternExport(exports, pat.value); }
13979 else if (type === "AssignmentPattern")
13980 { this.checkPatternExport(exports, pat.left); }
13981 else if (type === "RestElement")
13982 { this.checkPatternExport(exports, pat.argument); }
13983 else if (type === "ParenthesizedExpression")
13984 { this.checkPatternExport(exports, pat.expression); }
13985};
13986
13987pp$1.checkVariableExport = function(exports, decls) {
13988 if (!exports) { return }
13989 for (var i = 0, list = decls; i < list.length; i += 1)
13990 {
13991 var decl = list[i];
13992
13993 this.checkPatternExport(exports, decl.id);
13994 }
13995};
13996
13997pp$1.shouldParseExportStatement = function() {
13998 return this.type.keyword === "var" ||
13999 this.type.keyword === "const" ||
14000 this.type.keyword === "class" ||
14001 this.type.keyword === "function" ||
14002 this.isLet() ||
14003 this.isAsyncFunction()
14004};
14005
14006// Parses a comma-separated list of module exports.
14007
14008pp$1.parseExportSpecifiers = function(exports) {
14009 var nodes = [], first = true;
14010 // export { x, y as z } [from '...']
14011 this.expect(types.braceL);
14012 while (!this.eat(types.braceR)) {
14013 if (!first) {
14014 this.expect(types.comma);
14015 if (this.afterTrailingComma(types.braceR)) { break }
14016 } else { first = false; }
14017
14018 var node = this.startNode();
14019 node.local = this.parseIdent(true);
14020 node.exported = this.eatContextual("as") ? this.parseIdent(true) : node.local;
14021 this.checkExport(exports, node.exported.name, node.exported.start);
14022 nodes.push(this.finishNode(node, "ExportSpecifier"));
14023 }
14024 return nodes
14025};
14026
14027// Parses import declaration.
14028
14029pp$1.parseImport = function(node) {
14030 this.next();
14031 // import '...'
14032 if (this.type === types.string) {
14033 node.specifiers = empty;
14034 node.source = this.parseExprAtom();
14035 } else {
14036 node.specifiers = this.parseImportSpecifiers();
14037 this.expectContextual("from");
14038 node.source = this.type === types.string ? this.parseExprAtom() : this.unexpected();
14039 }
14040 this.semicolon();
14041 return this.finishNode(node, "ImportDeclaration")
14042};
14043
14044// Parses a comma-separated list of module imports.
14045
14046pp$1.parseImportSpecifiers = function() {
14047 var nodes = [], first = true;
14048 if (this.type === types.name) {
14049 // import defaultObj, { x, y as z } from '...'
14050 var node = this.startNode();
14051 node.local = this.parseIdent();
14052 this.checkLValSimple(node.local, BIND_LEXICAL);
14053 nodes.push(this.finishNode(node, "ImportDefaultSpecifier"));
14054 if (!this.eat(types.comma)) { return nodes }
14055 }
14056 if (this.type === types.star) {
14057 var node$1 = this.startNode();
14058 this.next();
14059 this.expectContextual("as");
14060 node$1.local = this.parseIdent();
14061 this.checkLValSimple(node$1.local, BIND_LEXICAL);
14062 nodes.push(this.finishNode(node$1, "ImportNamespaceSpecifier"));
14063 return nodes
14064 }
14065 this.expect(types.braceL);
14066 while (!this.eat(types.braceR)) {
14067 if (!first) {
14068 this.expect(types.comma);
14069 if (this.afterTrailingComma(types.braceR)) { break }
14070 } else { first = false; }
14071
14072 var node$2 = this.startNode();
14073 node$2.imported = this.parseIdent(true);
14074 if (this.eatContextual("as")) {
14075 node$2.local = this.parseIdent();
14076 } else {
14077 this.checkUnreserved(node$2.imported);
14078 node$2.local = node$2.imported;
14079 }
14080 this.checkLValSimple(node$2.local, BIND_LEXICAL);
14081 nodes.push(this.finishNode(node$2, "ImportSpecifier"));
14082 }
14083 return nodes
14084};
14085
14086// Set `ExpressionStatement#directive` property for directive prologues.
14087pp$1.adaptDirectivePrologue = function(statements) {
14088 for (var i = 0; i < statements.length && this.isDirectiveCandidate(statements[i]); ++i) {
14089 statements[i].directive = statements[i].expression.raw.slice(1, -1);
14090 }
14091};
14092pp$1.isDirectiveCandidate = function(statement) {
14093 return (
14094 statement.type === "ExpressionStatement" &&
14095 statement.expression.type === "Literal" &&
14096 typeof statement.expression.value === "string" &&
14097 // Reject parenthesized strings.
14098 (this.input[statement.start] === "\"" || this.input[statement.start] === "'")
14099 )
14100};
14101
14102var pp$2 = Parser.prototype;
14103
14104// Convert existing expression atom to assignable pattern
14105// if possible.
14106
14107pp$2.toAssignable = function(node, isBinding, refDestructuringErrors) {
14108 if (this.options.ecmaVersion >= 6 && node) {
14109 switch (node.type) {
14110 case "Identifier":
14111 if (this.inAsync && node.name === "await")
14112 { this.raise(node.start, "Cannot use 'await' as identifier inside an async function"); }
14113 break
14114
14115 case "ObjectPattern":
14116 case "ArrayPattern":
14117 case "AssignmentPattern":
14118 case "RestElement":
14119 break
14120
14121 case "ObjectExpression":
14122 node.type = "ObjectPattern";
14123 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
14124 for (var i = 0, list = node.properties; i < list.length; i += 1) {
14125 var prop = list[i];
14126
14127 this.toAssignable(prop, isBinding);
14128 // Early error:
14129 // AssignmentRestProperty[Yield, Await] :
14130 // `...` DestructuringAssignmentTarget[Yield, Await]
14131 //
14132 // It is a Syntax Error if |DestructuringAssignmentTarget| is an |ArrayLiteral| or an |ObjectLiteral|.
14133 if (
14134 prop.type === "RestElement" &&
14135 (prop.argument.type === "ArrayPattern" || prop.argument.type === "ObjectPattern")
14136 ) {
14137 this.raise(prop.argument.start, "Unexpected token");
14138 }
14139 }
14140 break
14141
14142 case "Property":
14143 // AssignmentProperty has type === "Property"
14144 if (node.kind !== "init") { this.raise(node.key.start, "Object pattern can't contain getter or setter"); }
14145 this.toAssignable(node.value, isBinding);
14146 break
14147
14148 case "ArrayExpression":
14149 node.type = "ArrayPattern";
14150 if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
14151 this.toAssignableList(node.elements, isBinding);
14152 break
14153
14154 case "SpreadElement":
14155 node.type = "RestElement";
14156 this.toAssignable(node.argument, isBinding);
14157 if (node.argument.type === "AssignmentPattern")
14158 { this.raise(node.argument.start, "Rest elements cannot have a default value"); }
14159 break
14160
14161 case "AssignmentExpression":
14162 if (node.operator !== "=") { this.raise(node.left.end, "Only '=' operator can be used for specifying default value."); }
14163 node.type = "AssignmentPattern";
14164 delete node.operator;
14165 this.toAssignable(node.left, isBinding);
14166 break
14167
14168 case "ParenthesizedExpression":
14169 this.toAssignable(node.expression, isBinding, refDestructuringErrors);
14170 break
14171
14172 case "ChainExpression":
14173 this.raiseRecoverable(node.start, "Optional chaining cannot appear in left-hand side");
14174 break
14175
14176 case "MemberExpression":
14177 if (!isBinding) { break }
14178
14179 default:
14180 this.raise(node.start, "Assigning to rvalue");
14181 }
14182 } else if (refDestructuringErrors) { this.checkPatternErrors(refDestructuringErrors, true); }
14183 return node
14184};
14185
14186// Convert list of expression atoms to binding list.
14187
14188pp$2.toAssignableList = function(exprList, isBinding) {
14189 var end = exprList.length;
14190 for (var i = 0; i < end; i++) {
14191 var elt = exprList[i];
14192 if (elt) { this.toAssignable(elt, isBinding); }
14193 }
14194 if (end) {
14195 var last = exprList[end - 1];
14196 if (this.options.ecmaVersion === 6 && isBinding && last && last.type === "RestElement" && last.argument.type !== "Identifier")
14197 { this.unexpected(last.argument.start); }
14198 }
14199 return exprList
14200};
14201
14202// Parses spread element.
14203
14204pp$2.parseSpread = function(refDestructuringErrors) {
14205 var node = this.startNode();
14206 this.next();
14207 node.argument = this.parseMaybeAssign(false, refDestructuringErrors);
14208 return this.finishNode(node, "SpreadElement")
14209};
14210
14211pp$2.parseRestBinding = function() {
14212 var node = this.startNode();
14213 this.next();
14214
14215 // RestElement inside of a function parameter must be an identifier
14216 if (this.options.ecmaVersion === 6 && this.type !== types.name)
14217 { this.unexpected(); }
14218
14219 node.argument = this.parseBindingAtom();
14220
14221 return this.finishNode(node, "RestElement")
14222};
14223
14224// Parses lvalue (assignable) atom.
14225
14226pp$2.parseBindingAtom = function() {
14227 if (this.options.ecmaVersion >= 6) {
14228 switch (this.type) {
14229 case types.bracketL:
14230 var node = this.startNode();
14231 this.next();
14232 node.elements = this.parseBindingList(types.bracketR, true, true);
14233 return this.finishNode(node, "ArrayPattern")
14234
14235 case types.braceL:
14236 return this.parseObj(true)
14237 }
14238 }
14239 return this.parseIdent()
14240};
14241
14242pp$2.parseBindingList = function(close, allowEmpty, allowTrailingComma) {
14243 var elts = [], first = true;
14244 while (!this.eat(close)) {
14245 if (first) { first = false; }
14246 else { this.expect(types.comma); }
14247 if (allowEmpty && this.type === types.comma) {
14248 elts.push(null);
14249 } else if (allowTrailingComma && this.afterTrailingComma(close)) {
14250 break
14251 } else if (this.type === types.ellipsis) {
14252 var rest = this.parseRestBinding();
14253 this.parseBindingListItem(rest);
14254 elts.push(rest);
14255 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
14256 this.expect(close);
14257 break
14258 } else {
14259 var elem = this.parseMaybeDefault(this.start, this.startLoc);
14260 this.parseBindingListItem(elem);
14261 elts.push(elem);
14262 }
14263 }
14264 return elts
14265};
14266
14267pp$2.parseBindingListItem = function(param) {
14268 return param
14269};
14270
14271// Parses assignment pattern around given atom if possible.
14272
14273pp$2.parseMaybeDefault = function(startPos, startLoc, left) {
14274 left = left || this.parseBindingAtom();
14275 if (this.options.ecmaVersion < 6 || !this.eat(types.eq)) { return left }
14276 var node = this.startNodeAt(startPos, startLoc);
14277 node.left = left;
14278 node.right = this.parseMaybeAssign();
14279 return this.finishNode(node, "AssignmentPattern")
14280};
14281
14282// The following three functions all verify that a node is an lvalue —
14283// something that can be bound, or assigned to. In order to do so, they perform
14284// a variety of checks:
14285//
14286// - Check that none of the bound/assigned-to identifiers are reserved words.
14287// - Record name declarations for bindings in the appropriate scope.
14288// - Check duplicate argument names, if checkClashes is set.
14289//
14290// If a complex binding pattern is encountered (e.g., object and array
14291// destructuring), the entire pattern is recursively checked.
14292//
14293// There are three versions of checkLVal*() appropriate for different
14294// circumstances:
14295//
14296// - checkLValSimple() shall be used if the syntactic construct supports
14297// nothing other than identifiers and member expressions. Parenthesized
14298// expressions are also correctly handled. This is generally appropriate for
14299// constructs for which the spec says
14300//
14301// > It is a Syntax Error if AssignmentTargetType of [the production] is not
14302// > simple.
14303//
14304// It is also appropriate for checking if an identifier is valid and not
14305// defined elsewhere, like import declarations or function/class identifiers.
14306//
14307// Examples where this is used include:
14308// a += …;
14309// import a from '…';
14310// where a is the node to be checked.
14311//
14312// - checkLValPattern() shall be used if the syntactic construct supports
14313// anything checkLValSimple() supports, as well as object and array
14314// destructuring patterns. This is generally appropriate for constructs for
14315// which the spec says
14316//
14317// > It is a Syntax Error if [the production] is neither an ObjectLiteral nor
14318// > an ArrayLiteral and AssignmentTargetType of [the production] is not
14319// > simple.
14320//
14321// Examples where this is used include:
14322// (a = …);
14323// const a = …;
14324// try { … } catch (a) { … }
14325// where a is the node to be checked.
14326//
14327// - checkLValInnerPattern() shall be used if the syntactic construct supports
14328// anything checkLValPattern() supports, as well as default assignment
14329// patterns, rest elements, and other constructs that may appear within an
14330// object or array destructuring pattern.
14331//
14332// As a special case, function parameters also use checkLValInnerPattern(),
14333// as they also support defaults and rest constructs.
14334//
14335// These functions deliberately support both assignment and binding constructs,
14336// as the logic for both is exceedingly similar. If the node is the target of
14337// an assignment, then bindingType should be set to BIND_NONE. Otherwise, it
14338// should be set to the appropriate BIND_* constant, like BIND_VAR or
14339// BIND_LEXICAL.
14340//
14341// If the function is called with a non-BIND_NONE bindingType, then
14342// additionally a checkClashes object may be specified to allow checking for
14343// duplicate argument names. checkClashes is ignored if the provided construct
14344// is an assignment (i.e., bindingType is BIND_NONE).
14345
14346pp$2.checkLValSimple = function(expr, bindingType, checkClashes) {
14347 if ( bindingType === void 0 ) bindingType = BIND_NONE;
14348
14349 var isBind = bindingType !== BIND_NONE;
14350
14351 switch (expr.type) {
14352 case "Identifier":
14353 if (this.strict && this.reservedWordsStrictBind.test(expr.name))
14354 { this.raiseRecoverable(expr.start, (isBind ? "Binding " : "Assigning to ") + expr.name + " in strict mode"); }
14355 if (isBind) {
14356 if (bindingType === BIND_LEXICAL && expr.name === "let")
14357 { this.raiseRecoverable(expr.start, "let is disallowed as a lexically bound name"); }
14358 if (checkClashes) {
14359 if (has(checkClashes, expr.name))
14360 { this.raiseRecoverable(expr.start, "Argument name clash"); }
14361 checkClashes[expr.name] = true;
14362 }
14363 if (bindingType !== BIND_OUTSIDE) { this.declareName(expr.name, bindingType, expr.start); }
14364 }
14365 break
14366
14367 case "ChainExpression":
14368 this.raiseRecoverable(expr.start, "Optional chaining cannot appear in left-hand side");
14369 break
14370
14371 case "MemberExpression":
14372 if (isBind) { this.raiseRecoverable(expr.start, "Binding member expression"); }
14373 break
14374
14375 case "ParenthesizedExpression":
14376 if (isBind) { this.raiseRecoverable(expr.start, "Binding parenthesized expression"); }
14377 return this.checkLValSimple(expr.expression, bindingType, checkClashes)
14378
14379 default:
14380 this.raise(expr.start, (isBind ? "Binding" : "Assigning to") + " rvalue");
14381 }
14382};
14383
14384pp$2.checkLValPattern = function(expr, bindingType, checkClashes) {
14385 if ( bindingType === void 0 ) bindingType = BIND_NONE;
14386
14387 switch (expr.type) {
14388 case "ObjectPattern":
14389 for (var i = 0, list = expr.properties; i < list.length; i += 1) {
14390 var prop = list[i];
14391
14392 this.checkLValInnerPattern(prop, bindingType, checkClashes);
14393 }
14394 break
14395
14396 case "ArrayPattern":
14397 for (var i$1 = 0, list$1 = expr.elements; i$1 < list$1.length; i$1 += 1) {
14398 var elem = list$1[i$1];
14399
14400 if (elem) { this.checkLValInnerPattern(elem, bindingType, checkClashes); }
14401 }
14402 break
14403
14404 default:
14405 this.checkLValSimple(expr, bindingType, checkClashes);
14406 }
14407};
14408
14409pp$2.checkLValInnerPattern = function(expr, bindingType, checkClashes) {
14410 if ( bindingType === void 0 ) bindingType = BIND_NONE;
14411
14412 switch (expr.type) {
14413 case "Property":
14414 // AssignmentProperty has type === "Property"
14415 this.checkLValInnerPattern(expr.value, bindingType, checkClashes);
14416 break
14417
14418 case "AssignmentPattern":
14419 this.checkLValPattern(expr.left, bindingType, checkClashes);
14420 break
14421
14422 case "RestElement":
14423 this.checkLValPattern(expr.argument, bindingType, checkClashes);
14424 break
14425
14426 default:
14427 this.checkLValPattern(expr, bindingType, checkClashes);
14428 }
14429};
14430
14431// A recursive descent parser operates by defining functions for all
14432
14433var pp$3 = Parser.prototype;
14434
14435// Check if property name clashes with already added.
14436// Object/class getters and setters are not allowed to clash —
14437// either with each other or with an init property — and in
14438// strict mode, init properties are also not allowed to be repeated.
14439
14440pp$3.checkPropClash = function(prop, propHash, refDestructuringErrors) {
14441 if (this.options.ecmaVersion >= 9 && prop.type === "SpreadElement")
14442 { return }
14443 if (this.options.ecmaVersion >= 6 && (prop.computed || prop.method || prop.shorthand))
14444 { return }
14445 var key = prop.key;
14446 var name;
14447 switch (key.type) {
14448 case "Identifier": name = key.name; break
14449 case "Literal": name = String(key.value); break
14450 default: return
14451 }
14452 var kind = prop.kind;
14453 if (this.options.ecmaVersion >= 6) {
14454 if (name === "__proto__" && kind === "init") {
14455 if (propHash.proto) {
14456 if (refDestructuringErrors) {
14457 if (refDestructuringErrors.doubleProto < 0)
14458 { refDestructuringErrors.doubleProto = key.start; }
14459 // Backwards-compat kludge. Can be removed in version 6.0
14460 } else { this.raiseRecoverable(key.start, "Redefinition of __proto__ property"); }
14461 }
14462 propHash.proto = true;
14463 }
14464 return
14465 }
14466 name = "$" + name;
14467 var other = propHash[name];
14468 if (other) {
14469 var redefinition;
14470 if (kind === "init") {
14471 redefinition = this.strict && other.init || other.get || other.set;
14472 } else {
14473 redefinition = other.init || other[kind];
14474 }
14475 if (redefinition)
14476 { this.raiseRecoverable(key.start, "Redefinition of property"); }
14477 } else {
14478 other = propHash[name] = {
14479 init: false,
14480 get: false,
14481 set: false
14482 };
14483 }
14484 other[kind] = true;
14485};
14486
14487// ### Expression parsing
14488
14489// These nest, from the most general expression type at the top to
14490// 'atomic', nondivisible expression types at the bottom. Most of
14491// the functions will simply let the function(s) below them parse,
14492// and, *if* the syntactic construct they handle is present, wrap
14493// the AST node that the inner parser gave them in another node.
14494
14495// Parse a full expression. The optional arguments are used to
14496// forbid the `in` operator (in for loops initalization expressions)
14497// and provide reference for storing '=' operator inside shorthand
14498// property assignment in contexts where both object expression
14499// and object pattern might appear (so it's possible to raise
14500// delayed syntax error at correct position).
14501
14502pp$3.parseExpression = function(noIn, refDestructuringErrors) {
14503 var startPos = this.start, startLoc = this.startLoc;
14504 var expr = this.parseMaybeAssign(noIn, refDestructuringErrors);
14505 if (this.type === types.comma) {
14506 var node = this.startNodeAt(startPos, startLoc);
14507 node.expressions = [expr];
14508 while (this.eat(types.comma)) { node.expressions.push(this.parseMaybeAssign(noIn, refDestructuringErrors)); }
14509 return this.finishNode(node, "SequenceExpression")
14510 }
14511 return expr
14512};
14513
14514// Parse an assignment expression. This includes applications of
14515// operators like `+=`.
14516
14517pp$3.parseMaybeAssign = function(noIn, refDestructuringErrors, afterLeftParse) {
14518 if (this.isContextual("yield")) {
14519 if (this.inGenerator) { return this.parseYield(noIn) }
14520 // The tokenizer will assume an expression is allowed after
14521 // `yield`, but this isn't that kind of yield
14522 else { this.exprAllowed = false; }
14523 }
14524
14525 var ownDestructuringErrors = false, oldParenAssign = -1, oldTrailingComma = -1;
14526 if (refDestructuringErrors) {
14527 oldParenAssign = refDestructuringErrors.parenthesizedAssign;
14528 oldTrailingComma = refDestructuringErrors.trailingComma;
14529 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = -1;
14530 } else {
14531 refDestructuringErrors = new DestructuringErrors;
14532 ownDestructuringErrors = true;
14533 }
14534
14535 var startPos = this.start, startLoc = this.startLoc;
14536 if (this.type === types.parenL || this.type === types.name)
14537 { this.potentialArrowAt = this.start; }
14538 var left = this.parseMaybeConditional(noIn, refDestructuringErrors);
14539 if (afterLeftParse) { left = afterLeftParse.call(this, left, startPos, startLoc); }
14540 if (this.type.isAssign) {
14541 var node = this.startNodeAt(startPos, startLoc);
14542 node.operator = this.value;
14543 if (this.type === types.eq)
14544 { left = this.toAssignable(left, false, refDestructuringErrors); }
14545 if (!ownDestructuringErrors) {
14546 refDestructuringErrors.parenthesizedAssign = refDestructuringErrors.trailingComma = refDestructuringErrors.doubleProto = -1;
14547 }
14548 if (refDestructuringErrors.shorthandAssign >= left.start)
14549 { refDestructuringErrors.shorthandAssign = -1; } // reset because shorthand default was used correctly
14550 if (this.type === types.eq)
14551 { this.checkLValPattern(left); }
14552 else
14553 { this.checkLValSimple(left); }
14554 node.left = left;
14555 this.next();
14556 node.right = this.parseMaybeAssign(noIn);
14557 return this.finishNode(node, "AssignmentExpression")
14558 } else {
14559 if (ownDestructuringErrors) { this.checkExpressionErrors(refDestructuringErrors, true); }
14560 }
14561 if (oldParenAssign > -1) { refDestructuringErrors.parenthesizedAssign = oldParenAssign; }
14562 if (oldTrailingComma > -1) { refDestructuringErrors.trailingComma = oldTrailingComma; }
14563 return left
14564};
14565
14566// Parse a ternary conditional (`?:`) operator.
14567
14568pp$3.parseMaybeConditional = function(noIn, refDestructuringErrors) {
14569 var startPos = this.start, startLoc = this.startLoc;
14570 var expr = this.parseExprOps(noIn, refDestructuringErrors);
14571 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
14572 if (this.eat(types.question)) {
14573 var node = this.startNodeAt(startPos, startLoc);
14574 node.test = expr;
14575 node.consequent = this.parseMaybeAssign();
14576 this.expect(types.colon);
14577 node.alternate = this.parseMaybeAssign(noIn);
14578 return this.finishNode(node, "ConditionalExpression")
14579 }
14580 return expr
14581};
14582
14583// Start the precedence parser.
14584
14585pp$3.parseExprOps = function(noIn, refDestructuringErrors) {
14586 var startPos = this.start, startLoc = this.startLoc;
14587 var expr = this.parseMaybeUnary(refDestructuringErrors, false);
14588 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
14589 return expr.start === startPos && expr.type === "ArrowFunctionExpression" ? expr : this.parseExprOp(expr, startPos, startLoc, -1, noIn)
14590};
14591
14592// Parse binary operators with the operator precedence parsing
14593// algorithm. `left` is the left-hand side of the operator.
14594// `minPrec` provides context that allows the function to stop and
14595// defer further parser to one of its callers when it encounters an
14596// operator that has a lower precedence than the set it is parsing.
14597
14598pp$3.parseExprOp = function(left, leftStartPos, leftStartLoc, minPrec, noIn) {
14599 var prec = this.type.binop;
14600 if (prec != null && (!noIn || this.type !== types._in)) {
14601 if (prec > minPrec) {
14602 var logical = this.type === types.logicalOR || this.type === types.logicalAND;
14603 var coalesce = this.type === types.coalesce;
14604 if (coalesce) {
14605 // Handle the precedence of `tt.coalesce` as equal to the range of logical expressions.
14606 // In other words, `node.right` shouldn't contain logical expressions in order to check the mixed error.
14607 prec = types.logicalAND.binop;
14608 }
14609 var op = this.value;
14610 this.next();
14611 var startPos = this.start, startLoc = this.startLoc;
14612 var right = this.parseExprOp(this.parseMaybeUnary(null, false), startPos, startLoc, prec, noIn);
14613 var node = this.buildBinary(leftStartPos, leftStartLoc, left, right, op, logical || coalesce);
14614 if ((logical && this.type === types.coalesce) || (coalesce && (this.type === types.logicalOR || this.type === types.logicalAND))) {
14615 this.raiseRecoverable(this.start, "Logical expressions and coalesce expressions cannot be mixed. Wrap either by parentheses");
14616 }
14617 return this.parseExprOp(node, leftStartPos, leftStartLoc, minPrec, noIn)
14618 }
14619 }
14620 return left
14621};
14622
14623pp$3.buildBinary = function(startPos, startLoc, left, right, op, logical) {
14624 var node = this.startNodeAt(startPos, startLoc);
14625 node.left = left;
14626 node.operator = op;
14627 node.right = right;
14628 return this.finishNode(node, logical ? "LogicalExpression" : "BinaryExpression")
14629};
14630
14631// Parse unary operators, both prefix and postfix.
14632
14633pp$3.parseMaybeUnary = function(refDestructuringErrors, sawUnary) {
14634 var startPos = this.start, startLoc = this.startLoc, expr;
14635 if (this.isContextual("await") && (this.inAsync || (!this.inFunction && this.options.allowAwaitOutsideFunction))) {
14636 expr = this.parseAwait();
14637 sawUnary = true;
14638 } else if (this.type.prefix) {
14639 var node = this.startNode(), update = this.type === types.incDec;
14640 node.operator = this.value;
14641 node.prefix = true;
14642 this.next();
14643 node.argument = this.parseMaybeUnary(null, true);
14644 this.checkExpressionErrors(refDestructuringErrors, true);
14645 if (update) { this.checkLValSimple(node.argument); }
14646 else if (this.strict && node.operator === "delete" &&
14647 node.argument.type === "Identifier")
14648 { this.raiseRecoverable(node.start, "Deleting local variable in strict mode"); }
14649 else { sawUnary = true; }
14650 expr = this.finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
14651 } else {
14652 expr = this.parseExprSubscripts(refDestructuringErrors);
14653 if (this.checkExpressionErrors(refDestructuringErrors)) { return expr }
14654 while (this.type.postfix && !this.canInsertSemicolon()) {
14655 var node$1 = this.startNodeAt(startPos, startLoc);
14656 node$1.operator = this.value;
14657 node$1.prefix = false;
14658 node$1.argument = expr;
14659 this.checkLValSimple(expr);
14660 this.next();
14661 expr = this.finishNode(node$1, "UpdateExpression");
14662 }
14663 }
14664
14665 if (!sawUnary && this.eat(types.starstar))
14666 { return this.buildBinary(startPos, startLoc, expr, this.parseMaybeUnary(null, false), "**", false) }
14667 else
14668 { return expr }
14669};
14670
14671// Parse call, dot, and `[]`-subscript expressions.
14672
14673pp$3.parseExprSubscripts = function(refDestructuringErrors) {
14674 var startPos = this.start, startLoc = this.startLoc;
14675 var expr = this.parseExprAtom(refDestructuringErrors);
14676 if (expr.type === "ArrowFunctionExpression" && this.input.slice(this.lastTokStart, this.lastTokEnd) !== ")")
14677 { return expr }
14678 var result = this.parseSubscripts(expr, startPos, startLoc);
14679 if (refDestructuringErrors && result.type === "MemberExpression") {
14680 if (refDestructuringErrors.parenthesizedAssign >= result.start) { refDestructuringErrors.parenthesizedAssign = -1; }
14681 if (refDestructuringErrors.parenthesizedBind >= result.start) { refDestructuringErrors.parenthesizedBind = -1; }
14682 }
14683 return result
14684};
14685
14686pp$3.parseSubscripts = function(base, startPos, startLoc, noCalls) {
14687 var maybeAsyncArrow = this.options.ecmaVersion >= 8 && base.type === "Identifier" && base.name === "async" &&
14688 this.lastTokEnd === base.end && !this.canInsertSemicolon() && base.end - base.start === 5 &&
14689 this.potentialArrowAt === base.start;
14690 var optionalChained = false;
14691
14692 while (true) {
14693 var element = this.parseSubscript(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained);
14694
14695 if (element.optional) { optionalChained = true; }
14696 if (element === base || element.type === "ArrowFunctionExpression") {
14697 if (optionalChained) {
14698 var chainNode = this.startNodeAt(startPos, startLoc);
14699 chainNode.expression = element;
14700 element = this.finishNode(chainNode, "ChainExpression");
14701 }
14702 return element
14703 }
14704
14705 base = element;
14706 }
14707};
14708
14709pp$3.parseSubscript = function(base, startPos, startLoc, noCalls, maybeAsyncArrow, optionalChained) {
14710 var optionalSupported = this.options.ecmaVersion >= 11;
14711 var optional = optionalSupported && this.eat(types.questionDot);
14712 if (noCalls && optional) { this.raise(this.lastTokStart, "Optional chaining cannot appear in the callee of new expressions"); }
14713
14714 var computed = this.eat(types.bracketL);
14715 if (computed || (optional && this.type !== types.parenL && this.type !== types.backQuote) || this.eat(types.dot)) {
14716 var node = this.startNodeAt(startPos, startLoc);
14717 node.object = base;
14718 node.property = computed ? this.parseExpression() : this.parseIdent(this.options.allowReserved !== "never");
14719 node.computed = !!computed;
14720 if (computed) { this.expect(types.bracketR); }
14721 if (optionalSupported) {
14722 node.optional = optional;
14723 }
14724 base = this.finishNode(node, "MemberExpression");
14725 } else if (!noCalls && this.eat(types.parenL)) {
14726 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
14727 this.yieldPos = 0;
14728 this.awaitPos = 0;
14729 this.awaitIdentPos = 0;
14730 var exprList = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false, refDestructuringErrors);
14731 if (maybeAsyncArrow && !optional && !this.canInsertSemicolon() && this.eat(types.arrow)) {
14732 this.checkPatternErrors(refDestructuringErrors, false);
14733 this.checkYieldAwaitInDefaultParams();
14734 if (this.awaitIdentPos > 0)
14735 { this.raise(this.awaitIdentPos, "Cannot use 'await' as identifier inside an async function"); }
14736 this.yieldPos = oldYieldPos;
14737 this.awaitPos = oldAwaitPos;
14738 this.awaitIdentPos = oldAwaitIdentPos;
14739 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList, true)
14740 }
14741 this.checkExpressionErrors(refDestructuringErrors, true);
14742 this.yieldPos = oldYieldPos || this.yieldPos;
14743 this.awaitPos = oldAwaitPos || this.awaitPos;
14744 this.awaitIdentPos = oldAwaitIdentPos || this.awaitIdentPos;
14745 var node$1 = this.startNodeAt(startPos, startLoc);
14746 node$1.callee = base;
14747 node$1.arguments = exprList;
14748 if (optionalSupported) {
14749 node$1.optional = optional;
14750 }
14751 base = this.finishNode(node$1, "CallExpression");
14752 } else if (this.type === types.backQuote) {
14753 if (optional || optionalChained) {
14754 this.raise(this.start, "Optional chaining cannot appear in the tag of tagged template expressions");
14755 }
14756 var node$2 = this.startNodeAt(startPos, startLoc);
14757 node$2.tag = base;
14758 node$2.quasi = this.parseTemplate({isTagged: true});
14759 base = this.finishNode(node$2, "TaggedTemplateExpression");
14760 }
14761 return base
14762};
14763
14764// Parse an atomic expression — either a single token that is an
14765// expression, an expression started by a keyword like `function` or
14766// `new`, or an expression wrapped in punctuation like `()`, `[]`,
14767// or `{}`.
14768
14769pp$3.parseExprAtom = function(refDestructuringErrors) {
14770 // If a division operator appears in an expression position, the
14771 // tokenizer got confused, and we force it to read a regexp instead.
14772 if (this.type === types.slash) { this.readRegexp(); }
14773
14774 var node, canBeArrow = this.potentialArrowAt === this.start;
14775 switch (this.type) {
14776 case types._super:
14777 if (!this.allowSuper)
14778 { this.raise(this.start, "'super' keyword outside a method"); }
14779 node = this.startNode();
14780 this.next();
14781 if (this.type === types.parenL && !this.allowDirectSuper)
14782 { this.raise(node.start, "super() call outside constructor of a subclass"); }
14783 // The `super` keyword can appear at below:
14784 // SuperProperty:
14785 // super [ Expression ]
14786 // super . IdentifierName
14787 // SuperCall:
14788 // super ( Arguments )
14789 if (this.type !== types.dot && this.type !== types.bracketL && this.type !== types.parenL)
14790 { this.unexpected(); }
14791 return this.finishNode(node, "Super")
14792
14793 case types._this:
14794 node = this.startNode();
14795 this.next();
14796 return this.finishNode(node, "ThisExpression")
14797
14798 case types.name:
14799 var startPos = this.start, startLoc = this.startLoc, containsEsc = this.containsEsc;
14800 var id = this.parseIdent(false);
14801 if (this.options.ecmaVersion >= 8 && !containsEsc && id.name === "async" && !this.canInsertSemicolon() && this.eat(types._function))
14802 { return this.parseFunction(this.startNodeAt(startPos, startLoc), 0, false, true) }
14803 if (canBeArrow && !this.canInsertSemicolon()) {
14804 if (this.eat(types.arrow))
14805 { return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], false) }
14806 if (this.options.ecmaVersion >= 8 && id.name === "async" && this.type === types.name && !containsEsc) {
14807 id = this.parseIdent(false);
14808 if (this.canInsertSemicolon() || !this.eat(types.arrow))
14809 { this.unexpected(); }
14810 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), [id], true)
14811 }
14812 }
14813 return id
14814
14815 case types.regexp:
14816 var value = this.value;
14817 node = this.parseLiteral(value.value);
14818 node.regex = {pattern: value.pattern, flags: value.flags};
14819 return node
14820
14821 case types.num: case types.string:
14822 return this.parseLiteral(this.value)
14823
14824 case types._null: case types._true: case types._false:
14825 node = this.startNode();
14826 node.value = this.type === types._null ? null : this.type === types._true;
14827 node.raw = this.type.keyword;
14828 this.next();
14829 return this.finishNode(node, "Literal")
14830
14831 case types.parenL:
14832 var start = this.start, expr = this.parseParenAndDistinguishExpression(canBeArrow);
14833 if (refDestructuringErrors) {
14834 if (refDestructuringErrors.parenthesizedAssign < 0 && !this.isSimpleAssignTarget(expr))
14835 { refDestructuringErrors.parenthesizedAssign = start; }
14836 if (refDestructuringErrors.parenthesizedBind < 0)
14837 { refDestructuringErrors.parenthesizedBind = start; }
14838 }
14839 return expr
14840
14841 case types.bracketL:
14842 node = this.startNode();
14843 this.next();
14844 node.elements = this.parseExprList(types.bracketR, true, true, refDestructuringErrors);
14845 return this.finishNode(node, "ArrayExpression")
14846
14847 case types.braceL:
14848 return this.parseObj(false, refDestructuringErrors)
14849
14850 case types._function:
14851 node = this.startNode();
14852 this.next();
14853 return this.parseFunction(node, 0)
14854
14855 case types._class:
14856 return this.parseClass(this.startNode(), false)
14857
14858 case types._new:
14859 return this.parseNew()
14860
14861 case types.backQuote:
14862 return this.parseTemplate()
14863
14864 case types._import:
14865 if (this.options.ecmaVersion >= 11) {
14866 return this.parseExprImport()
14867 } else {
14868 return this.unexpected()
14869 }
14870
14871 default:
14872 this.unexpected();
14873 }
14874};
14875
14876pp$3.parseExprImport = function() {
14877 var node = this.startNode();
14878
14879 // Consume `import` as an identifier for `import.meta`.
14880 // Because `this.parseIdent(true)` doesn't check escape sequences, it needs the check of `this.containsEsc`.
14881 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword import"); }
14882 var meta = this.parseIdent(true);
14883
14884 switch (this.type) {
14885 case types.parenL:
14886 return this.parseDynamicImport(node)
14887 case types.dot:
14888 node.meta = meta;
14889 return this.parseImportMeta(node)
14890 default:
14891 this.unexpected();
14892 }
14893};
14894
14895pp$3.parseDynamicImport = function(node) {
14896 this.next(); // skip `(`
14897
14898 // Parse node.source.
14899 node.source = this.parseMaybeAssign();
14900
14901 // Verify ending.
14902 if (!this.eat(types.parenR)) {
14903 var errorPos = this.start;
14904 if (this.eat(types.comma) && this.eat(types.parenR)) {
14905 this.raiseRecoverable(errorPos, "Trailing comma is not allowed in import()");
14906 } else {
14907 this.unexpected(errorPos);
14908 }
14909 }
14910
14911 return this.finishNode(node, "ImportExpression")
14912};
14913
14914pp$3.parseImportMeta = function(node) {
14915 this.next(); // skip `.`
14916
14917 var containsEsc = this.containsEsc;
14918 node.property = this.parseIdent(true);
14919
14920 if (node.property.name !== "meta")
14921 { this.raiseRecoverable(node.property.start, "The only valid meta property for import is 'import.meta'"); }
14922 if (containsEsc)
14923 { this.raiseRecoverable(node.start, "'import.meta' must not contain escaped characters"); }
14924 if (this.options.sourceType !== "module")
14925 { this.raiseRecoverable(node.start, "Cannot use 'import.meta' outside a module"); }
14926
14927 return this.finishNode(node, "MetaProperty")
14928};
14929
14930pp$3.parseLiteral = function(value) {
14931 var node = this.startNode();
14932 node.value = value;
14933 node.raw = this.input.slice(this.start, this.end);
14934 if (node.raw.charCodeAt(node.raw.length - 1) === 110) { node.bigint = node.raw.slice(0, -1).replace(/_/g, ""); }
14935 this.next();
14936 return this.finishNode(node, "Literal")
14937};
14938
14939pp$3.parseParenExpression = function() {
14940 this.expect(types.parenL);
14941 var val = this.parseExpression();
14942 this.expect(types.parenR);
14943 return val
14944};
14945
14946pp$3.parseParenAndDistinguishExpression = function(canBeArrow) {
14947 var startPos = this.start, startLoc = this.startLoc, val, allowTrailingComma = this.options.ecmaVersion >= 8;
14948 if (this.options.ecmaVersion >= 6) {
14949 this.next();
14950
14951 var innerStartPos = this.start, innerStartLoc = this.startLoc;
14952 var exprList = [], first = true, lastIsComma = false;
14953 var refDestructuringErrors = new DestructuringErrors, oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, spreadStart;
14954 this.yieldPos = 0;
14955 this.awaitPos = 0;
14956 // Do not save awaitIdentPos to allow checking awaits nested in parameters
14957 while (this.type !== types.parenR) {
14958 first ? first = false : this.expect(types.comma);
14959 if (allowTrailingComma && this.afterTrailingComma(types.parenR, true)) {
14960 lastIsComma = true;
14961 break
14962 } else if (this.type === types.ellipsis) {
14963 spreadStart = this.start;
14964 exprList.push(this.parseParenItem(this.parseRestBinding()));
14965 if (this.type === types.comma) { this.raise(this.start, "Comma is not permitted after the rest element"); }
14966 break
14967 } else {
14968 exprList.push(this.parseMaybeAssign(false, refDestructuringErrors, this.parseParenItem));
14969 }
14970 }
14971 var innerEndPos = this.start, innerEndLoc = this.startLoc;
14972 this.expect(types.parenR);
14973
14974 if (canBeArrow && !this.canInsertSemicolon() && this.eat(types.arrow)) {
14975 this.checkPatternErrors(refDestructuringErrors, false);
14976 this.checkYieldAwaitInDefaultParams();
14977 this.yieldPos = oldYieldPos;
14978 this.awaitPos = oldAwaitPos;
14979 return this.parseParenArrowList(startPos, startLoc, exprList)
14980 }
14981
14982 if (!exprList.length || lastIsComma) { this.unexpected(this.lastTokStart); }
14983 if (spreadStart) { this.unexpected(spreadStart); }
14984 this.checkExpressionErrors(refDestructuringErrors, true);
14985 this.yieldPos = oldYieldPos || this.yieldPos;
14986 this.awaitPos = oldAwaitPos || this.awaitPos;
14987
14988 if (exprList.length > 1) {
14989 val = this.startNodeAt(innerStartPos, innerStartLoc);
14990 val.expressions = exprList;
14991 this.finishNodeAt(val, "SequenceExpression", innerEndPos, innerEndLoc);
14992 } else {
14993 val = exprList[0];
14994 }
14995 } else {
14996 val = this.parseParenExpression();
14997 }
14998
14999 if (this.options.preserveParens) {
15000 var par = this.startNodeAt(startPos, startLoc);
15001 par.expression = val;
15002 return this.finishNode(par, "ParenthesizedExpression")
15003 } else {
15004 return val
15005 }
15006};
15007
15008pp$3.parseParenItem = function(item) {
15009 return item
15010};
15011
15012pp$3.parseParenArrowList = function(startPos, startLoc, exprList) {
15013 return this.parseArrowExpression(this.startNodeAt(startPos, startLoc), exprList)
15014};
15015
15016// New's precedence is slightly tricky. It must allow its argument to
15017// be a `[]` or dot subscript expression, but not a call — at least,
15018// not without wrapping it in parentheses. Thus, it uses the noCalls
15019// argument to parseSubscripts to prevent it from consuming the
15020// argument list.
15021
15022var empty$1 = [];
15023
15024pp$3.parseNew = function() {
15025 if (this.containsEsc) { this.raiseRecoverable(this.start, "Escape sequence in keyword new"); }
15026 var node = this.startNode();
15027 var meta = this.parseIdent(true);
15028 if (this.options.ecmaVersion >= 6 && this.eat(types.dot)) {
15029 node.meta = meta;
15030 var containsEsc = this.containsEsc;
15031 node.property = this.parseIdent(true);
15032 if (node.property.name !== "target")
15033 { this.raiseRecoverable(node.property.start, "The only valid meta property for new is 'new.target'"); }
15034 if (containsEsc)
15035 { this.raiseRecoverable(node.start, "'new.target' must not contain escaped characters"); }
15036 if (!this.inNonArrowFunction)
15037 { this.raiseRecoverable(node.start, "'new.target' can only be used in functions"); }
15038 return this.finishNode(node, "MetaProperty")
15039 }
15040 var startPos = this.start, startLoc = this.startLoc, isImport = this.type === types._import;
15041 node.callee = this.parseSubscripts(this.parseExprAtom(), startPos, startLoc, true);
15042 if (isImport && node.callee.type === "ImportExpression") {
15043 this.raise(startPos, "Cannot use new with import()");
15044 }
15045 if (this.eat(types.parenL)) { node.arguments = this.parseExprList(types.parenR, this.options.ecmaVersion >= 8, false); }
15046 else { node.arguments = empty$1; }
15047 return this.finishNode(node, "NewExpression")
15048};
15049
15050// Parse template expression.
15051
15052pp$3.parseTemplateElement = function(ref) {
15053 var isTagged = ref.isTagged;
15054
15055 var elem = this.startNode();
15056 if (this.type === types.invalidTemplate) {
15057 if (!isTagged) {
15058 this.raiseRecoverable(this.start, "Bad escape sequence in untagged template literal");
15059 }
15060 elem.value = {
15061 raw: this.value,
15062 cooked: null
15063 };
15064 } else {
15065 elem.value = {
15066 raw: this.input.slice(this.start, this.end).replace(/\r\n?/g, "\n"),
15067 cooked: this.value
15068 };
15069 }
15070 this.next();
15071 elem.tail = this.type === types.backQuote;
15072 return this.finishNode(elem, "TemplateElement")
15073};
15074
15075pp$3.parseTemplate = function(ref) {
15076 if ( ref === void 0 ) ref = {};
15077 var isTagged = ref.isTagged; if ( isTagged === void 0 ) isTagged = false;
15078
15079 var node = this.startNode();
15080 this.next();
15081 node.expressions = [];
15082 var curElt = this.parseTemplateElement({isTagged: isTagged});
15083 node.quasis = [curElt];
15084 while (!curElt.tail) {
15085 if (this.type === types.eof) { this.raise(this.pos, "Unterminated template literal"); }
15086 this.expect(types.dollarBraceL);
15087 node.expressions.push(this.parseExpression());
15088 this.expect(types.braceR);
15089 node.quasis.push(curElt = this.parseTemplateElement({isTagged: isTagged}));
15090 }
15091 this.next();
15092 return this.finishNode(node, "TemplateLiteral")
15093};
15094
15095pp$3.isAsyncProp = function(prop) {
15096 return !prop.computed && prop.key.type === "Identifier" && prop.key.name === "async" &&
15097 (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)) &&
15098 !lineBreak.test(this.input.slice(this.lastTokEnd, this.start))
15099};
15100
15101// Parse an object literal or binding pattern.
15102
15103pp$3.parseObj = function(isPattern, refDestructuringErrors) {
15104 var node = this.startNode(), first = true, propHash = {};
15105 node.properties = [];
15106 this.next();
15107 while (!this.eat(types.braceR)) {
15108 if (!first) {
15109 this.expect(types.comma);
15110 if (this.options.ecmaVersion >= 5 && this.afterTrailingComma(types.braceR)) { break }
15111 } else { first = false; }
15112
15113 var prop = this.parseProperty(isPattern, refDestructuringErrors);
15114 if (!isPattern) { this.checkPropClash(prop, propHash, refDestructuringErrors); }
15115 node.properties.push(prop);
15116 }
15117 return this.finishNode(node, isPattern ? "ObjectPattern" : "ObjectExpression")
15118};
15119
15120pp$3.parseProperty = function(isPattern, refDestructuringErrors) {
15121 var prop = this.startNode(), isGenerator, isAsync, startPos, startLoc;
15122 if (this.options.ecmaVersion >= 9 && this.eat(types.ellipsis)) {
15123 if (isPattern) {
15124 prop.argument = this.parseIdent(false);
15125 if (this.type === types.comma) {
15126 this.raise(this.start, "Comma is not permitted after the rest element");
15127 }
15128 return this.finishNode(prop, "RestElement")
15129 }
15130 // To disallow parenthesized identifier via `this.toAssignable()`.
15131 if (this.type === types.parenL && refDestructuringErrors) {
15132 if (refDestructuringErrors.parenthesizedAssign < 0) {
15133 refDestructuringErrors.parenthesizedAssign = this.start;
15134 }
15135 if (refDestructuringErrors.parenthesizedBind < 0) {
15136 refDestructuringErrors.parenthesizedBind = this.start;
15137 }
15138 }
15139 // Parse argument.
15140 prop.argument = this.parseMaybeAssign(false, refDestructuringErrors);
15141 // To disallow trailing comma via `this.toAssignable()`.
15142 if (this.type === types.comma && refDestructuringErrors && refDestructuringErrors.trailingComma < 0) {
15143 refDestructuringErrors.trailingComma = this.start;
15144 }
15145 // Finish
15146 return this.finishNode(prop, "SpreadElement")
15147 }
15148 if (this.options.ecmaVersion >= 6) {
15149 prop.method = false;
15150 prop.shorthand = false;
15151 if (isPattern || refDestructuringErrors) {
15152 startPos = this.start;
15153 startLoc = this.startLoc;
15154 }
15155 if (!isPattern)
15156 { isGenerator = this.eat(types.star); }
15157 }
15158 var containsEsc = this.containsEsc;
15159 this.parsePropertyName(prop);
15160 if (!isPattern && !containsEsc && this.options.ecmaVersion >= 8 && !isGenerator && this.isAsyncProp(prop)) {
15161 isAsync = true;
15162 isGenerator = this.options.ecmaVersion >= 9 && this.eat(types.star);
15163 this.parsePropertyName(prop, refDestructuringErrors);
15164 } else {
15165 isAsync = false;
15166 }
15167 this.parsePropertyValue(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc);
15168 return this.finishNode(prop, "Property")
15169};
15170
15171pp$3.parsePropertyValue = function(prop, isPattern, isGenerator, isAsync, startPos, startLoc, refDestructuringErrors, containsEsc) {
15172 if ((isGenerator || isAsync) && this.type === types.colon)
15173 { this.unexpected(); }
15174
15175 if (this.eat(types.colon)) {
15176 prop.value = isPattern ? this.parseMaybeDefault(this.start, this.startLoc) : this.parseMaybeAssign(false, refDestructuringErrors);
15177 prop.kind = "init";
15178 } else if (this.options.ecmaVersion >= 6 && this.type === types.parenL) {
15179 if (isPattern) { this.unexpected(); }
15180 prop.kind = "init";
15181 prop.method = true;
15182 prop.value = this.parseMethod(isGenerator, isAsync);
15183 } else if (!isPattern && !containsEsc &&
15184 this.options.ecmaVersion >= 5 && !prop.computed && prop.key.type === "Identifier" &&
15185 (prop.key.name === "get" || prop.key.name === "set") &&
15186 (this.type !== types.comma && this.type !== types.braceR && this.type !== types.eq)) {
15187 if (isGenerator || isAsync) { this.unexpected(); }
15188 prop.kind = prop.key.name;
15189 this.parsePropertyName(prop);
15190 prop.value = this.parseMethod(false);
15191 var paramCount = prop.kind === "get" ? 0 : 1;
15192 if (prop.value.params.length !== paramCount) {
15193 var start = prop.value.start;
15194 if (prop.kind === "get")
15195 { this.raiseRecoverable(start, "getter should have no params"); }
15196 else
15197 { this.raiseRecoverable(start, "setter should have exactly one param"); }
15198 } else {
15199 if (prop.kind === "set" && prop.value.params[0].type === "RestElement")
15200 { this.raiseRecoverable(prop.value.params[0].start, "Setter cannot use rest params"); }
15201 }
15202 } else if (this.options.ecmaVersion >= 6 && !prop.computed && prop.key.type === "Identifier") {
15203 if (isGenerator || isAsync) { this.unexpected(); }
15204 this.checkUnreserved(prop.key);
15205 if (prop.key.name === "await" && !this.awaitIdentPos)
15206 { this.awaitIdentPos = startPos; }
15207 prop.kind = "init";
15208 if (isPattern) {
15209 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
15210 } else if (this.type === types.eq && refDestructuringErrors) {
15211 if (refDestructuringErrors.shorthandAssign < 0)
15212 { refDestructuringErrors.shorthandAssign = this.start; }
15213 prop.value = this.parseMaybeDefault(startPos, startLoc, this.copyNode(prop.key));
15214 } else {
15215 prop.value = this.copyNode(prop.key);
15216 }
15217 prop.shorthand = true;
15218 } else { this.unexpected(); }
15219};
15220
15221pp$3.parsePropertyName = function(prop) {
15222 if (this.options.ecmaVersion >= 6) {
15223 if (this.eat(types.bracketL)) {
15224 prop.computed = true;
15225 prop.key = this.parseMaybeAssign();
15226 this.expect(types.bracketR);
15227 return prop.key
15228 } else {
15229 prop.computed = false;
15230 }
15231 }
15232 return prop.key = this.type === types.num || this.type === types.string ? this.parseExprAtom() : this.parseIdent(this.options.allowReserved !== "never")
15233};
15234
15235// Initialize empty function node.
15236
15237pp$3.initFunction = function(node) {
15238 node.id = null;
15239 if (this.options.ecmaVersion >= 6) { node.generator = node.expression = false; }
15240 if (this.options.ecmaVersion >= 8) { node.async = false; }
15241};
15242
15243// Parse object or class method.
15244
15245pp$3.parseMethod = function(isGenerator, isAsync, allowDirectSuper) {
15246 var node = this.startNode(), oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
15247
15248 this.initFunction(node);
15249 if (this.options.ecmaVersion >= 6)
15250 { node.generator = isGenerator; }
15251 if (this.options.ecmaVersion >= 8)
15252 { node.async = !!isAsync; }
15253
15254 this.yieldPos = 0;
15255 this.awaitPos = 0;
15256 this.awaitIdentPos = 0;
15257 this.enterScope(functionFlags(isAsync, node.generator) | SCOPE_SUPER | (allowDirectSuper ? SCOPE_DIRECT_SUPER : 0));
15258
15259 this.expect(types.parenL);
15260 node.params = this.parseBindingList(types.parenR, false, this.options.ecmaVersion >= 8);
15261 this.checkYieldAwaitInDefaultParams();
15262 this.parseFunctionBody(node, false, true);
15263
15264 this.yieldPos = oldYieldPos;
15265 this.awaitPos = oldAwaitPos;
15266 this.awaitIdentPos = oldAwaitIdentPos;
15267 return this.finishNode(node, "FunctionExpression")
15268};
15269
15270// Parse arrow function expression with given parameters.
15271
15272pp$3.parseArrowExpression = function(node, params, isAsync) {
15273 var oldYieldPos = this.yieldPos, oldAwaitPos = this.awaitPos, oldAwaitIdentPos = this.awaitIdentPos;
15274
15275 this.enterScope(functionFlags(isAsync, false) | SCOPE_ARROW);
15276 this.initFunction(node);
15277 if (this.options.ecmaVersion >= 8) { node.async = !!isAsync; }
15278
15279 this.yieldPos = 0;
15280 this.awaitPos = 0;
15281 this.awaitIdentPos = 0;
15282
15283 node.params = this.toAssignableList(params, true);
15284 this.parseFunctionBody(node, true, false);
15285
15286 this.yieldPos = oldYieldPos;
15287 this.awaitPos = oldAwaitPos;
15288 this.awaitIdentPos = oldAwaitIdentPos;
15289 return this.finishNode(node, "ArrowFunctionExpression")
15290};
15291
15292// Parse function body and check parameters.
15293
15294pp$3.parseFunctionBody = function(node, isArrowFunction, isMethod) {
15295 var isExpression = isArrowFunction && this.type !== types.braceL;
15296 var oldStrict = this.strict, useStrict = false;
15297
15298 if (isExpression) {
15299 node.body = this.parseMaybeAssign();
15300 node.expression = true;
15301 this.checkParams(node, false);
15302 } else {
15303 var nonSimple = this.options.ecmaVersion >= 7 && !this.isSimpleParamList(node.params);
15304 if (!oldStrict || nonSimple) {
15305 useStrict = this.strictDirective(this.end);
15306 // If this is a strict mode function, verify that argument names
15307 // are not repeated, and it does not try to bind the words `eval`
15308 // or `arguments`.
15309 if (useStrict && nonSimple)
15310 { this.raiseRecoverable(node.start, "Illegal 'use strict' directive in function with non-simple parameter list"); }
15311 }
15312 // Start a new scope with regard to labels and the `inFunction`
15313 // flag (restore them to their old value afterwards).
15314 var oldLabels = this.labels;
15315 this.labels = [];
15316 if (useStrict) { this.strict = true; }
15317
15318 // Add the params to varDeclaredNames to ensure that an error is thrown
15319 // if a let/const declaration in the function clashes with one of the params.
15320 this.checkParams(node, !oldStrict && !useStrict && !isArrowFunction && !isMethod && this.isSimpleParamList(node.params));
15321 // Ensure the function name isn't a forbidden identifier in strict mode, e.g. 'eval'
15322 if (this.strict && node.id) { this.checkLValSimple(node.id, BIND_OUTSIDE); }
15323 node.body = this.parseBlock(false, undefined, useStrict && !oldStrict);
15324 node.expression = false;
15325 this.adaptDirectivePrologue(node.body.body);
15326 this.labels = oldLabels;
15327 }
15328 this.exitScope();
15329};
15330
15331pp$3.isSimpleParamList = function(params) {
15332 for (var i = 0, list = params; i < list.length; i += 1)
15333 {
15334 var param = list[i];
15335
15336 if (param.type !== "Identifier") { return false
15337 } }
15338 return true
15339};
15340
15341// Checks function params for various disallowed patterns such as using "eval"
15342// or "arguments" and duplicate parameters.
15343
15344pp$3.checkParams = function(node, allowDuplicates) {
15345 var nameHash = {};
15346 for (var i = 0, list = node.params; i < list.length; i += 1)
15347 {
15348 var param = list[i];
15349
15350 this.checkLValInnerPattern(param, BIND_VAR, allowDuplicates ? null : nameHash);
15351 }
15352};
15353
15354// Parses a comma-separated list of expressions, and returns them as
15355// an array. `close` is the token type that ends the list, and
15356// `allowEmpty` can be turned on to allow subsequent commas with
15357// nothing in between them to be parsed as `null` (which is needed
15358// for array literals).
15359
15360pp$3.parseExprList = function(close, allowTrailingComma, allowEmpty, refDestructuringErrors) {
15361 var elts = [], first = true;
15362 while (!this.eat(close)) {
15363 if (!first) {
15364 this.expect(types.comma);
15365 if (allowTrailingComma && this.afterTrailingComma(close)) { break }
15366 } else { first = false; }
15367
15368 var elt = (void 0);
15369 if (allowEmpty && this.type === types.comma)
15370 { elt = null; }
15371 else if (this.type === types.ellipsis) {
15372 elt = this.parseSpread(refDestructuringErrors);
15373 if (refDestructuringErrors && this.type === types.comma && refDestructuringErrors.trailingComma < 0)
15374 { refDestructuringErrors.trailingComma = this.start; }
15375 } else {
15376 elt = this.parseMaybeAssign(false, refDestructuringErrors);
15377 }
15378 elts.push(elt);
15379 }
15380 return elts
15381};
15382
15383pp$3.checkUnreserved = function(ref) {
15384 var start = ref.start;
15385 var end = ref.end;
15386 var name = ref.name;
15387
15388 if (this.inGenerator && name === "yield")
15389 { this.raiseRecoverable(start, "Cannot use 'yield' as identifier inside a generator"); }
15390 if (this.inAsync && name === "await")
15391 { this.raiseRecoverable(start, "Cannot use 'await' as identifier inside an async function"); }
15392 if (this.keywords.test(name))
15393 { this.raise(start, ("Unexpected keyword '" + name + "'")); }
15394 if (this.options.ecmaVersion < 6 &&
15395 this.input.slice(start, end).indexOf("\\") !== -1) { return }
15396 var re = this.strict ? this.reservedWordsStrict : this.reservedWords;
15397 if (re.test(name)) {
15398 if (!this.inAsync && name === "await")
15399 { this.raiseRecoverable(start, "Cannot use keyword 'await' outside an async function"); }
15400 this.raiseRecoverable(start, ("The keyword '" + name + "' is reserved"));
15401 }
15402};
15403
15404// Parse the next token as an identifier. If `liberal` is true (used
15405// when parsing properties), it will also convert keywords into
15406// identifiers.
15407
15408pp$3.parseIdent = function(liberal, isBinding) {
15409 var node = this.startNode();
15410 if (this.type === types.name) {
15411 node.name = this.value;
15412 } else if (this.type.keyword) {
15413 node.name = this.type.keyword;
15414
15415 // To fix https://github.com/acornjs/acorn/issues/575
15416 // `class` and `function` keywords push new context into this.context.
15417 // But there is no chance to pop the context if the keyword is consumed as an identifier such as a property name.
15418 // If the previous token is a dot, this does not apply because the context-managing code already ignored the keyword
15419 if ((node.name === "class" || node.name === "function") &&
15420 (this.lastTokEnd !== this.lastTokStart + 1 || this.input.charCodeAt(this.lastTokStart) !== 46)) {
15421 this.context.pop();
15422 }
15423 } else {
15424 this.unexpected();
15425 }
15426 this.next(!!liberal);
15427 this.finishNode(node, "Identifier");
15428 if (!liberal) {
15429 this.checkUnreserved(node);
15430 if (node.name === "await" && !this.awaitIdentPos)
15431 { this.awaitIdentPos = node.start; }
15432 }
15433 return node
15434};
15435
15436// Parses yield expression inside generator.
15437
15438pp$3.parseYield = function(noIn) {
15439 if (!this.yieldPos) { this.yieldPos = this.start; }
15440
15441 var node = this.startNode();
15442 this.next();
15443 if (this.type === types.semi || this.canInsertSemicolon() || (this.type !== types.star && !this.type.startsExpr)) {
15444 node.delegate = false;
15445 node.argument = null;
15446 } else {
15447 node.delegate = this.eat(types.star);
15448 node.argument = this.parseMaybeAssign(noIn);
15449 }
15450 return this.finishNode(node, "YieldExpression")
15451};
15452
15453pp$3.parseAwait = function() {
15454 if (!this.awaitPos) { this.awaitPos = this.start; }
15455
15456 var node = this.startNode();
15457 this.next();
15458 node.argument = this.parseMaybeUnary(null, false);
15459 return this.finishNode(node, "AwaitExpression")
15460};
15461
15462var pp$4 = Parser.prototype;
15463
15464// This function is used to raise exceptions on parse errors. It
15465// takes an offset integer (into the current `input`) to indicate
15466// the location of the error, attaches the position to the end
15467// of the error message, and then raises a `SyntaxError` with that
15468// message.
15469
15470pp$4.raise = function(pos, message) {
15471 var loc = getLineInfo(this.input, pos);
15472 message += " (" + loc.line + ":" + loc.column + ")";
15473 var err = new SyntaxError(message);
15474 err.pos = pos; err.loc = loc; err.raisedAt = this.pos;
15475 throw err
15476};
15477
15478pp$4.raiseRecoverable = pp$4.raise;
15479
15480pp$4.curPosition = function() {
15481 if (this.options.locations) {
15482 return new Position(this.curLine, this.pos - this.lineStart)
15483 }
15484};
15485
15486var pp$5 = Parser.prototype;
15487
15488var Scope$1 = function Scope(flags) {
15489 this.flags = flags;
15490 // A list of var-declared names in the current lexical scope
15491 this.var = [];
15492 // A list of lexically-declared names in the current lexical scope
15493 this.lexical = [];
15494 // A list of lexically-declared FunctionDeclaration names in the current lexical scope
15495 this.functions = [];
15496};
15497
15498// The functions in this module keep track of declared variables in the current scope in order to detect duplicate variable names.
15499
15500pp$5.enterScope = function(flags) {
15501 this.scopeStack.push(new Scope$1(flags));
15502};
15503
15504pp$5.exitScope = function() {
15505 this.scopeStack.pop();
15506};
15507
15508// The spec says:
15509// > At the top level of a function, or script, function declarations are
15510// > treated like var declarations rather than like lexical declarations.
15511pp$5.treatFunctionsAsVarInScope = function(scope) {
15512 return (scope.flags & SCOPE_FUNCTION) || !this.inModule && (scope.flags & SCOPE_TOP)
15513};
15514
15515pp$5.declareName = function(name, bindingType, pos) {
15516 var redeclared = false;
15517 if (bindingType === BIND_LEXICAL) {
15518 var scope = this.currentScope();
15519 redeclared = scope.lexical.indexOf(name) > -1 || scope.functions.indexOf(name) > -1 || scope.var.indexOf(name) > -1;
15520 scope.lexical.push(name);
15521 if (this.inModule && (scope.flags & SCOPE_TOP))
15522 { delete this.undefinedExports[name]; }
15523 } else if (bindingType === BIND_SIMPLE_CATCH) {
15524 var scope$1 = this.currentScope();
15525 scope$1.lexical.push(name);
15526 } else if (bindingType === BIND_FUNCTION) {
15527 var scope$2 = this.currentScope();
15528 if (this.treatFunctionsAsVar)
15529 { redeclared = scope$2.lexical.indexOf(name) > -1; }
15530 else
15531 { redeclared = scope$2.lexical.indexOf(name) > -1 || scope$2.var.indexOf(name) > -1; }
15532 scope$2.functions.push(name);
15533 } else {
15534 for (var i = this.scopeStack.length - 1; i >= 0; --i) {
15535 var scope$3 = this.scopeStack[i];
15536 if (scope$3.lexical.indexOf(name) > -1 && !((scope$3.flags & SCOPE_SIMPLE_CATCH) && scope$3.lexical[0] === name) ||
15537 !this.treatFunctionsAsVarInScope(scope$3) && scope$3.functions.indexOf(name) > -1) {
15538 redeclared = true;
15539 break
15540 }
15541 scope$3.var.push(name);
15542 if (this.inModule && (scope$3.flags & SCOPE_TOP))
15543 { delete this.undefinedExports[name]; }
15544 if (scope$3.flags & SCOPE_VAR) { break }
15545 }
15546 }
15547 if (redeclared) { this.raiseRecoverable(pos, ("Identifier '" + name + "' has already been declared")); }
15548};
15549
15550pp$5.checkLocalExport = function(id) {
15551 // scope.functions must be empty as Module code is always strict.
15552 if (this.scopeStack[0].lexical.indexOf(id.name) === -1 &&
15553 this.scopeStack[0].var.indexOf(id.name) === -1) {
15554 this.undefinedExports[id.name] = id;
15555 }
15556};
15557
15558pp$5.currentScope = function() {
15559 return this.scopeStack[this.scopeStack.length - 1]
15560};
15561
15562pp$5.currentVarScope = function() {
15563 for (var i = this.scopeStack.length - 1;; i--) {
15564 var scope = this.scopeStack[i];
15565 if (scope.flags & SCOPE_VAR) { return scope }
15566 }
15567};
15568
15569// Could be useful for `this`, `new.target`, `super()`, `super.property`, and `super[property]`.
15570pp$5.currentThisScope = function() {
15571 for (var i = this.scopeStack.length - 1;; i--) {
15572 var scope = this.scopeStack[i];
15573 if (scope.flags & SCOPE_VAR && !(scope.flags & SCOPE_ARROW)) { return scope }
15574 }
15575};
15576
15577var Node = function Node(parser, pos, loc) {
15578 this.type = "";
15579 this.start = pos;
15580 this.end = 0;
15581 if (parser.options.locations)
15582 { this.loc = new SourceLocation(parser, loc); }
15583 if (parser.options.directSourceFile)
15584 { this.sourceFile = parser.options.directSourceFile; }
15585 if (parser.options.ranges)
15586 { this.range = [pos, 0]; }
15587};
15588
15589// Start an AST node, attaching a start offset.
15590
15591var pp$6 = Parser.prototype;
15592
15593pp$6.startNode = function() {
15594 return new Node(this, this.start, this.startLoc)
15595};
15596
15597pp$6.startNodeAt = function(pos, loc) {
15598 return new Node(this, pos, loc)
15599};
15600
15601// Finish an AST node, adding `type` and `end` properties.
15602
15603function finishNodeAt(node, type, pos, loc) {
15604 node.type = type;
15605 node.end = pos;
15606 if (this.options.locations)
15607 { node.loc.end = loc; }
15608 if (this.options.ranges)
15609 { node.range[1] = pos; }
15610 return node
15611}
15612
15613pp$6.finishNode = function(node, type) {
15614 return finishNodeAt.call(this, node, type, this.lastTokEnd, this.lastTokEndLoc)
15615};
15616
15617// Finish node at given position
15618
15619pp$6.finishNodeAt = function(node, type, pos, loc) {
15620 return finishNodeAt.call(this, node, type, pos, loc)
15621};
15622
15623pp$6.copyNode = function(node) {
15624 var newNode = new Node(this, node.start, this.startLoc);
15625 for (var prop in node) { newNode[prop] = node[prop]; }
15626 return newNode
15627};
15628
15629// The algorithm used to determine whether a regexp can appear at a
15630
15631var TokContext = function TokContext(token, isExpr, preserveSpace, override, generator) {
15632 this.token = token;
15633 this.isExpr = !!isExpr;
15634 this.preserveSpace = !!preserveSpace;
15635 this.override = override;
15636 this.generator = !!generator;
15637};
15638
15639var types$1 = {
15640 b_stat: new TokContext("{", false),
15641 b_expr: new TokContext("{", true),
15642 b_tmpl: new TokContext("${", false),
15643 p_stat: new TokContext("(", false),
15644 p_expr: new TokContext("(", true),
15645 q_tmpl: new TokContext("`", true, true, function (p) { return p.tryReadTemplateToken(); }),
15646 f_stat: new TokContext("function", false),
15647 f_expr: new TokContext("function", true),
15648 f_expr_gen: new TokContext("function", true, false, null, true),
15649 f_gen: new TokContext("function", false, false, null, true)
15650};
15651
15652var pp$7 = Parser.prototype;
15653
15654pp$7.initialContext = function() {
15655 return [types$1.b_stat]
15656};
15657
15658pp$7.braceIsBlock = function(prevType) {
15659 var parent = this.curContext();
15660 if (parent === types$1.f_expr || parent === types$1.f_stat)
15661 { return true }
15662 if (prevType === types.colon && (parent === types$1.b_stat || parent === types$1.b_expr))
15663 { return !parent.isExpr }
15664
15665 // The check for `tt.name && exprAllowed` detects whether we are
15666 // after a `yield` or `of` construct. See the `updateContext` for
15667 // `tt.name`.
15668 if (prevType === types._return || prevType === types.name && this.exprAllowed)
15669 { return lineBreak.test(this.input.slice(this.lastTokEnd, this.start)) }
15670 if (prevType === types._else || prevType === types.semi || prevType === types.eof || prevType === types.parenR || prevType === types.arrow)
15671 { return true }
15672 if (prevType === types.braceL)
15673 { return parent === types$1.b_stat }
15674 if (prevType === types._var || prevType === types._const || prevType === types.name)
15675 { return false }
15676 return !this.exprAllowed
15677};
15678
15679pp$7.inGeneratorContext = function() {
15680 for (var i = this.context.length - 1; i >= 1; i--) {
15681 var context = this.context[i];
15682 if (context.token === "function")
15683 { return context.generator }
15684 }
15685 return false
15686};
15687
15688pp$7.updateContext = function(prevType) {
15689 var update, type = this.type;
15690 if (type.keyword && prevType === types.dot)
15691 { this.exprAllowed = false; }
15692 else if (update = type.updateContext)
15693 { update.call(this, prevType); }
15694 else
15695 { this.exprAllowed = type.beforeExpr; }
15696};
15697
15698// Token-specific context update code
15699
15700types.parenR.updateContext = types.braceR.updateContext = function() {
15701 if (this.context.length === 1) {
15702 this.exprAllowed = true;
15703 return
15704 }
15705 var out = this.context.pop();
15706 if (out === types$1.b_stat && this.curContext().token === "function") {
15707 out = this.context.pop();
15708 }
15709 this.exprAllowed = !out.isExpr;
15710};
15711
15712types.braceL.updateContext = function(prevType) {
15713 this.context.push(this.braceIsBlock(prevType) ? types$1.b_stat : types$1.b_expr);
15714 this.exprAllowed = true;
15715};
15716
15717types.dollarBraceL.updateContext = function() {
15718 this.context.push(types$1.b_tmpl);
15719 this.exprAllowed = true;
15720};
15721
15722types.parenL.updateContext = function(prevType) {
15723 var statementParens = prevType === types._if || prevType === types._for || prevType === types._with || prevType === types._while;
15724 this.context.push(statementParens ? types$1.p_stat : types$1.p_expr);
15725 this.exprAllowed = true;
15726};
15727
15728types.incDec.updateContext = function() {
15729 // tokExprAllowed stays unchanged
15730};
15731
15732types._function.updateContext = types._class.updateContext = function(prevType) {
15733 if (prevType.beforeExpr && prevType !== types._else &&
15734 !(prevType === types.semi && this.curContext() !== types$1.p_stat) &&
15735 !(prevType === types._return && lineBreak.test(this.input.slice(this.lastTokEnd, this.start))) &&
15736 !((prevType === types.colon || prevType === types.braceL) && this.curContext() === types$1.b_stat))
15737 { this.context.push(types$1.f_expr); }
15738 else
15739 { this.context.push(types$1.f_stat); }
15740 this.exprAllowed = false;
15741};
15742
15743types.backQuote.updateContext = function() {
15744 if (this.curContext() === types$1.q_tmpl)
15745 { this.context.pop(); }
15746 else
15747 { this.context.push(types$1.q_tmpl); }
15748 this.exprAllowed = false;
15749};
15750
15751types.star.updateContext = function(prevType) {
15752 if (prevType === types._function) {
15753 var index = this.context.length - 1;
15754 if (this.context[index] === types$1.f_expr)
15755 { this.context[index] = types$1.f_expr_gen; }
15756 else
15757 { this.context[index] = types$1.f_gen; }
15758 }
15759 this.exprAllowed = true;
15760};
15761
15762types.name.updateContext = function(prevType) {
15763 var allowed = false;
15764 if (this.options.ecmaVersion >= 6 && prevType !== types.dot) {
15765 if (this.value === "of" && !this.exprAllowed ||
15766 this.value === "yield" && this.inGeneratorContext())
15767 { allowed = true; }
15768 }
15769 this.exprAllowed = allowed;
15770};
15771
15772// This file contains Unicode properties extracted from the ECMAScript
15773// specification. The lists are extracted like so:
15774// $$('#table-binary-unicode-properties > figure > table > tbody > tr > td:nth-child(1) code').map(el => el.innerText)
15775
15776// #table-binary-unicode-properties
15777var 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";
15778var ecma10BinaryProperties = ecma9BinaryProperties + " Extended_Pictographic";
15779var ecma11BinaryProperties = ecma10BinaryProperties;
15780var ecma12BinaryProperties = ecma11BinaryProperties + " EBase EComp EMod EPres ExtPict";
15781var unicodeBinaryProperties = {
15782 9: ecma9BinaryProperties,
15783 10: ecma10BinaryProperties,
15784 11: ecma11BinaryProperties,
15785 12: ecma12BinaryProperties
15786};
15787
15788// #table-unicode-general-category-values
15789var 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";
15790
15791// #table-unicode-script-values
15792var 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";
15793var ecma10ScriptValues = ecma9ScriptValues + " Dogra Dogr Gunjala_Gondi Gong Hanifi_Rohingya Rohg Makasar Maka Medefaidrin Medf Old_Sogdian Sogo Sogdian Sogd";
15794var ecma11ScriptValues = ecma10ScriptValues + " Elymaic Elym Nandinagari Nand Nyiakeng_Puachue_Hmong Hmnp Wancho Wcho";
15795var ecma12ScriptValues = ecma11ScriptValues + " Chorasmian Chrs Diak Dives_Akuru Khitan_Small_Script Kits Yezi Yezidi";
15796var unicodeScriptValues = {
15797 9: ecma9ScriptValues,
15798 10: ecma10ScriptValues,
15799 11: ecma11ScriptValues,
15800 12: ecma12ScriptValues
15801};
15802
15803var data = {};
15804function buildUnicodeData(ecmaVersion) {
15805 var d = data[ecmaVersion] = {
15806 binary: wordsRegexp(unicodeBinaryProperties[ecmaVersion] + " " + unicodeGeneralCategoryValues),
15807 nonBinary: {
15808 General_Category: wordsRegexp(unicodeGeneralCategoryValues),
15809 Script: wordsRegexp(unicodeScriptValues[ecmaVersion])
15810 }
15811 };
15812 d.nonBinary.Script_Extensions = d.nonBinary.Script;
15813
15814 d.nonBinary.gc = d.nonBinary.General_Category;
15815 d.nonBinary.sc = d.nonBinary.Script;
15816 d.nonBinary.scx = d.nonBinary.Script_Extensions;
15817}
15818buildUnicodeData(9);
15819buildUnicodeData(10);
15820buildUnicodeData(11);
15821buildUnicodeData(12);
15822
15823var pp$8 = Parser.prototype;
15824
15825var RegExpValidationState = function RegExpValidationState(parser) {
15826 this.parser = parser;
15827 this.validFlags = "gim" + (parser.options.ecmaVersion >= 6 ? "uy" : "") + (parser.options.ecmaVersion >= 9 ? "s" : "");
15828 this.unicodeProperties = data[parser.options.ecmaVersion >= 12 ? 12 : parser.options.ecmaVersion];
15829 this.source = "";
15830 this.flags = "";
15831 this.start = 0;
15832 this.switchU = false;
15833 this.switchN = false;
15834 this.pos = 0;
15835 this.lastIntValue = 0;
15836 this.lastStringValue = "";
15837 this.lastAssertionIsQuantifiable = false;
15838 this.numCapturingParens = 0;
15839 this.maxBackReference = 0;
15840 this.groupNames = [];
15841 this.backReferenceNames = [];
15842};
15843
15844RegExpValidationState.prototype.reset = function reset (start, pattern, flags) {
15845 var unicode = flags.indexOf("u") !== -1;
15846 this.start = start | 0;
15847 this.source = pattern + "";
15848 this.flags = flags;
15849 this.switchU = unicode && this.parser.options.ecmaVersion >= 6;
15850 this.switchN = unicode && this.parser.options.ecmaVersion >= 9;
15851};
15852
15853RegExpValidationState.prototype.raise = function raise (message) {
15854 this.parser.raiseRecoverable(this.start, ("Invalid regular expression: /" + (this.source) + "/: " + message));
15855};
15856
15857// If u flag is given, this returns the code point at the index (it combines a surrogate pair).
15858// Otherwise, this returns the code unit of the index (can be a part of a surrogate pair).
15859RegExpValidationState.prototype.at = function at (i, forceU) {
15860 if ( forceU === void 0 ) forceU = false;
15861
15862 var s = this.source;
15863 var l = s.length;
15864 if (i >= l) {
15865 return -1
15866 }
15867 var c = s.charCodeAt(i);
15868 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l) {
15869 return c
15870 }
15871 var next = s.charCodeAt(i + 1);
15872 return next >= 0xDC00 && next <= 0xDFFF ? (c << 10) + next - 0x35FDC00 : c
15873};
15874
15875RegExpValidationState.prototype.nextIndex = function nextIndex (i, forceU) {
15876 if ( forceU === void 0 ) forceU = false;
15877
15878 var s = this.source;
15879 var l = s.length;
15880 if (i >= l) {
15881 return l
15882 }
15883 var c = s.charCodeAt(i), next;
15884 if (!(forceU || this.switchU) || c <= 0xD7FF || c >= 0xE000 || i + 1 >= l ||
15885 (next = s.charCodeAt(i + 1)) < 0xDC00 || next > 0xDFFF) {
15886 return i + 1
15887 }
15888 return i + 2
15889};
15890
15891RegExpValidationState.prototype.current = function current (forceU) {
15892 if ( forceU === void 0 ) forceU = false;
15893
15894 return this.at(this.pos, forceU)
15895};
15896
15897RegExpValidationState.prototype.lookahead = function lookahead (forceU) {
15898 if ( forceU === void 0 ) forceU = false;
15899
15900 return this.at(this.nextIndex(this.pos, forceU), forceU)
15901};
15902
15903RegExpValidationState.prototype.advance = function advance (forceU) {
15904 if ( forceU === void 0 ) forceU = false;
15905
15906 this.pos = this.nextIndex(this.pos, forceU);
15907};
15908
15909RegExpValidationState.prototype.eat = function eat (ch, forceU) {
15910 if ( forceU === void 0 ) forceU = false;
15911
15912 if (this.current(forceU) === ch) {
15913 this.advance(forceU);
15914 return true
15915 }
15916 return false
15917};
15918
15919function codePointToString(ch) {
15920 if (ch <= 0xFFFF) { return String.fromCharCode(ch) }
15921 ch -= 0x10000;
15922 return String.fromCharCode((ch >> 10) + 0xD800, (ch & 0x03FF) + 0xDC00)
15923}
15924
15925/**
15926 * Validate the flags part of a given RegExpLiteral.
15927 *
15928 * @param {RegExpValidationState} state The state to validate RegExp.
15929 * @returns {void}
15930 */
15931pp$8.validateRegExpFlags = function(state) {
15932 var validFlags = state.validFlags;
15933 var flags = state.flags;
15934
15935 for (var i = 0; i < flags.length; i++) {
15936 var flag = flags.charAt(i);
15937 if (validFlags.indexOf(flag) === -1) {
15938 this.raise(state.start, "Invalid regular expression flag");
15939 }
15940 if (flags.indexOf(flag, i + 1) > -1) {
15941 this.raise(state.start, "Duplicate regular expression flag");
15942 }
15943 }
15944};
15945
15946/**
15947 * Validate the pattern part of a given RegExpLiteral.
15948 *
15949 * @param {RegExpValidationState} state The state to validate RegExp.
15950 * @returns {void}
15951 */
15952pp$8.validateRegExpPattern = function(state) {
15953 this.regexp_pattern(state);
15954
15955 // The goal symbol for the parse is |Pattern[~U, ~N]|. If the result of
15956 // parsing contains a |GroupName|, reparse with the goal symbol
15957 // |Pattern[~U, +N]| and use this result instead. Throw a *SyntaxError*
15958 // exception if _P_ did not conform to the grammar, if any elements of _P_
15959 // were not matched by the parse, or if any Early Error conditions exist.
15960 if (!state.switchN && this.options.ecmaVersion >= 9 && state.groupNames.length > 0) {
15961 state.switchN = true;
15962 this.regexp_pattern(state);
15963 }
15964};
15965
15966// https://www.ecma-international.org/ecma-262/8.0/#prod-Pattern
15967pp$8.regexp_pattern = function(state) {
15968 state.pos = 0;
15969 state.lastIntValue = 0;
15970 state.lastStringValue = "";
15971 state.lastAssertionIsQuantifiable = false;
15972 state.numCapturingParens = 0;
15973 state.maxBackReference = 0;
15974 state.groupNames.length = 0;
15975 state.backReferenceNames.length = 0;
15976
15977 this.regexp_disjunction(state);
15978
15979 if (state.pos !== state.source.length) {
15980 // Make the same messages as V8.
15981 if (state.eat(0x29 /* ) */)) {
15982 state.raise("Unmatched ')'");
15983 }
15984 if (state.eat(0x5D /* ] */) || state.eat(0x7D /* } */)) {
15985 state.raise("Lone quantifier brackets");
15986 }
15987 }
15988 if (state.maxBackReference > state.numCapturingParens) {
15989 state.raise("Invalid escape");
15990 }
15991 for (var i = 0, list = state.backReferenceNames; i < list.length; i += 1) {
15992 var name = list[i];
15993
15994 if (state.groupNames.indexOf(name) === -1) {
15995 state.raise("Invalid named capture referenced");
15996 }
15997 }
15998};
15999
16000// https://www.ecma-international.org/ecma-262/8.0/#prod-Disjunction
16001pp$8.regexp_disjunction = function(state) {
16002 this.regexp_alternative(state);
16003 while (state.eat(0x7C /* | */)) {
16004 this.regexp_alternative(state);
16005 }
16006
16007 // Make the same message as V8.
16008 if (this.regexp_eatQuantifier(state, true)) {
16009 state.raise("Nothing to repeat");
16010 }
16011 if (state.eat(0x7B /* { */)) {
16012 state.raise("Lone quantifier brackets");
16013 }
16014};
16015
16016// https://www.ecma-international.org/ecma-262/8.0/#prod-Alternative
16017pp$8.regexp_alternative = function(state) {
16018 while (state.pos < state.source.length && this.regexp_eatTerm(state))
16019 { }
16020};
16021
16022// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Term
16023pp$8.regexp_eatTerm = function(state) {
16024 if (this.regexp_eatAssertion(state)) {
16025 // Handle `QuantifiableAssertion Quantifier` alternative.
16026 // `state.lastAssertionIsQuantifiable` is true if the last eaten Assertion
16027 // is a QuantifiableAssertion.
16028 if (state.lastAssertionIsQuantifiable && this.regexp_eatQuantifier(state)) {
16029 // Make the same message as V8.
16030 if (state.switchU) {
16031 state.raise("Invalid quantifier");
16032 }
16033 }
16034 return true
16035 }
16036
16037 if (state.switchU ? this.regexp_eatAtom(state) : this.regexp_eatExtendedAtom(state)) {
16038 this.regexp_eatQuantifier(state);
16039 return true
16040 }
16041
16042 return false
16043};
16044
16045// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-Assertion
16046pp$8.regexp_eatAssertion = function(state) {
16047 var start = state.pos;
16048 state.lastAssertionIsQuantifiable = false;
16049
16050 // ^, $
16051 if (state.eat(0x5E /* ^ */) || state.eat(0x24 /* $ */)) {
16052 return true
16053 }
16054
16055 // \b \B
16056 if (state.eat(0x5C /* \ */)) {
16057 if (state.eat(0x42 /* B */) || state.eat(0x62 /* b */)) {
16058 return true
16059 }
16060 state.pos = start;
16061 }
16062
16063 // Lookahead / Lookbehind
16064 if (state.eat(0x28 /* ( */) && state.eat(0x3F /* ? */)) {
16065 var lookbehind = false;
16066 if (this.options.ecmaVersion >= 9) {
16067 lookbehind = state.eat(0x3C /* < */);
16068 }
16069 if (state.eat(0x3D /* = */) || state.eat(0x21 /* ! */)) {
16070 this.regexp_disjunction(state);
16071 if (!state.eat(0x29 /* ) */)) {
16072 state.raise("Unterminated group");
16073 }
16074 state.lastAssertionIsQuantifiable = !lookbehind;
16075 return true
16076 }
16077 }
16078
16079 state.pos = start;
16080 return false
16081};
16082
16083// https://www.ecma-international.org/ecma-262/8.0/#prod-Quantifier
16084pp$8.regexp_eatQuantifier = function(state, noError) {
16085 if ( noError === void 0 ) noError = false;
16086
16087 if (this.regexp_eatQuantifierPrefix(state, noError)) {
16088 state.eat(0x3F /* ? */);
16089 return true
16090 }
16091 return false
16092};
16093
16094// https://www.ecma-international.org/ecma-262/8.0/#prod-QuantifierPrefix
16095pp$8.regexp_eatQuantifierPrefix = function(state, noError) {
16096 return (
16097 state.eat(0x2A /* * */) ||
16098 state.eat(0x2B /* + */) ||
16099 state.eat(0x3F /* ? */) ||
16100 this.regexp_eatBracedQuantifier(state, noError)
16101 )
16102};
16103pp$8.regexp_eatBracedQuantifier = function(state, noError) {
16104 var start = state.pos;
16105 if (state.eat(0x7B /* { */)) {
16106 var min = 0, max = -1;
16107 if (this.regexp_eatDecimalDigits(state)) {
16108 min = state.lastIntValue;
16109 if (state.eat(0x2C /* , */) && this.regexp_eatDecimalDigits(state)) {
16110 max = state.lastIntValue;
16111 }
16112 if (state.eat(0x7D /* } */)) {
16113 // SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-term
16114 if (max !== -1 && max < min && !noError) {
16115 state.raise("numbers out of order in {} quantifier");
16116 }
16117 return true
16118 }
16119 }
16120 if (state.switchU && !noError) {
16121 state.raise("Incomplete quantifier");
16122 }
16123 state.pos = start;
16124 }
16125 return false
16126};
16127
16128// https://www.ecma-international.org/ecma-262/8.0/#prod-Atom
16129pp$8.regexp_eatAtom = function(state) {
16130 return (
16131 this.regexp_eatPatternCharacters(state) ||
16132 state.eat(0x2E /* . */) ||
16133 this.regexp_eatReverseSolidusAtomEscape(state) ||
16134 this.regexp_eatCharacterClass(state) ||
16135 this.regexp_eatUncapturingGroup(state) ||
16136 this.regexp_eatCapturingGroup(state)
16137 )
16138};
16139pp$8.regexp_eatReverseSolidusAtomEscape = function(state) {
16140 var start = state.pos;
16141 if (state.eat(0x5C /* \ */)) {
16142 if (this.regexp_eatAtomEscape(state)) {
16143 return true
16144 }
16145 state.pos = start;
16146 }
16147 return false
16148};
16149pp$8.regexp_eatUncapturingGroup = function(state) {
16150 var start = state.pos;
16151 if (state.eat(0x28 /* ( */)) {
16152 if (state.eat(0x3F /* ? */) && state.eat(0x3A /* : */)) {
16153 this.regexp_disjunction(state);
16154 if (state.eat(0x29 /* ) */)) {
16155 return true
16156 }
16157 state.raise("Unterminated group");
16158 }
16159 state.pos = start;
16160 }
16161 return false
16162};
16163pp$8.regexp_eatCapturingGroup = function(state) {
16164 if (state.eat(0x28 /* ( */)) {
16165 if (this.options.ecmaVersion >= 9) {
16166 this.regexp_groupSpecifier(state);
16167 } else if (state.current() === 0x3F /* ? */) {
16168 state.raise("Invalid group");
16169 }
16170 this.regexp_disjunction(state);
16171 if (state.eat(0x29 /* ) */)) {
16172 state.numCapturingParens += 1;
16173 return true
16174 }
16175 state.raise("Unterminated group");
16176 }
16177 return false
16178};
16179
16180// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedAtom
16181pp$8.regexp_eatExtendedAtom = function(state) {
16182 return (
16183 state.eat(0x2E /* . */) ||
16184 this.regexp_eatReverseSolidusAtomEscape(state) ||
16185 this.regexp_eatCharacterClass(state) ||
16186 this.regexp_eatUncapturingGroup(state) ||
16187 this.regexp_eatCapturingGroup(state) ||
16188 this.regexp_eatInvalidBracedQuantifier(state) ||
16189 this.regexp_eatExtendedPatternCharacter(state)
16190 )
16191};
16192
16193// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-InvalidBracedQuantifier
16194pp$8.regexp_eatInvalidBracedQuantifier = function(state) {
16195 if (this.regexp_eatBracedQuantifier(state, true)) {
16196 state.raise("Nothing to repeat");
16197 }
16198 return false
16199};
16200
16201// https://www.ecma-international.org/ecma-262/8.0/#prod-SyntaxCharacter
16202pp$8.regexp_eatSyntaxCharacter = function(state) {
16203 var ch = state.current();
16204 if (isSyntaxCharacter(ch)) {
16205 state.lastIntValue = ch;
16206 state.advance();
16207 return true
16208 }
16209 return false
16210};
16211function isSyntaxCharacter(ch) {
16212 return (
16213 ch === 0x24 /* $ */ ||
16214 ch >= 0x28 /* ( */ && ch <= 0x2B /* + */ ||
16215 ch === 0x2E /* . */ ||
16216 ch === 0x3F /* ? */ ||
16217 ch >= 0x5B /* [ */ && ch <= 0x5E /* ^ */ ||
16218 ch >= 0x7B /* { */ && ch <= 0x7D /* } */
16219 )
16220}
16221
16222// https://www.ecma-international.org/ecma-262/8.0/#prod-PatternCharacter
16223// But eat eager.
16224pp$8.regexp_eatPatternCharacters = function(state) {
16225 var start = state.pos;
16226 var ch = 0;
16227 while ((ch = state.current()) !== -1 && !isSyntaxCharacter(ch)) {
16228 state.advance();
16229 }
16230 return state.pos !== start
16231};
16232
16233// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ExtendedPatternCharacter
16234pp$8.regexp_eatExtendedPatternCharacter = function(state) {
16235 var ch = state.current();
16236 if (
16237 ch !== -1 &&
16238 ch !== 0x24 /* $ */ &&
16239 !(ch >= 0x28 /* ( */ && ch <= 0x2B /* + */) &&
16240 ch !== 0x2E /* . */ &&
16241 ch !== 0x3F /* ? */ &&
16242 ch !== 0x5B /* [ */ &&
16243 ch !== 0x5E /* ^ */ &&
16244 ch !== 0x7C /* | */
16245 ) {
16246 state.advance();
16247 return true
16248 }
16249 return false
16250};
16251
16252// GroupSpecifier ::
16253// [empty]
16254// `?` GroupName
16255pp$8.regexp_groupSpecifier = function(state) {
16256 if (state.eat(0x3F /* ? */)) {
16257 if (this.regexp_eatGroupName(state)) {
16258 if (state.groupNames.indexOf(state.lastStringValue) !== -1) {
16259 state.raise("Duplicate capture group name");
16260 }
16261 state.groupNames.push(state.lastStringValue);
16262 return
16263 }
16264 state.raise("Invalid group");
16265 }
16266};
16267
16268// GroupName ::
16269// `<` RegExpIdentifierName `>`
16270// Note: this updates `state.lastStringValue` property with the eaten name.
16271pp$8.regexp_eatGroupName = function(state) {
16272 state.lastStringValue = "";
16273 if (state.eat(0x3C /* < */)) {
16274 if (this.regexp_eatRegExpIdentifierName(state) && state.eat(0x3E /* > */)) {
16275 return true
16276 }
16277 state.raise("Invalid capture group name");
16278 }
16279 return false
16280};
16281
16282// RegExpIdentifierName ::
16283// RegExpIdentifierStart
16284// RegExpIdentifierName RegExpIdentifierPart
16285// Note: this updates `state.lastStringValue` property with the eaten name.
16286pp$8.regexp_eatRegExpIdentifierName = function(state) {
16287 state.lastStringValue = "";
16288 if (this.regexp_eatRegExpIdentifierStart(state)) {
16289 state.lastStringValue += codePointToString(state.lastIntValue);
16290 while (this.regexp_eatRegExpIdentifierPart(state)) {
16291 state.lastStringValue += codePointToString(state.lastIntValue);
16292 }
16293 return true
16294 }
16295 return false
16296};
16297
16298// RegExpIdentifierStart ::
16299// UnicodeIDStart
16300// `$`
16301// `_`
16302// `\` RegExpUnicodeEscapeSequence[+U]
16303pp$8.regexp_eatRegExpIdentifierStart = function(state) {
16304 var start = state.pos;
16305 var forceU = this.options.ecmaVersion >= 11;
16306 var ch = state.current(forceU);
16307 state.advance(forceU);
16308
16309 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
16310 ch = state.lastIntValue;
16311 }
16312 if (isRegExpIdentifierStart(ch)) {
16313 state.lastIntValue = ch;
16314 return true
16315 }
16316
16317 state.pos = start;
16318 return false
16319};
16320function isRegExpIdentifierStart(ch) {
16321 return isIdentifierStart(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */
16322}
16323
16324// RegExpIdentifierPart ::
16325// UnicodeIDContinue
16326// `$`
16327// `_`
16328// `\` RegExpUnicodeEscapeSequence[+U]
16329// <ZWNJ>
16330// <ZWJ>
16331pp$8.regexp_eatRegExpIdentifierPart = function(state) {
16332 var start = state.pos;
16333 var forceU = this.options.ecmaVersion >= 11;
16334 var ch = state.current(forceU);
16335 state.advance(forceU);
16336
16337 if (ch === 0x5C /* \ */ && this.regexp_eatRegExpUnicodeEscapeSequence(state, forceU)) {
16338 ch = state.lastIntValue;
16339 }
16340 if (isRegExpIdentifierPart(ch)) {
16341 state.lastIntValue = ch;
16342 return true
16343 }
16344
16345 state.pos = start;
16346 return false
16347};
16348function isRegExpIdentifierPart(ch) {
16349 return isIdentifierChar(ch, true) || ch === 0x24 /* $ */ || ch === 0x5F /* _ */ || ch === 0x200C /* <ZWNJ> */ || ch === 0x200D /* <ZWJ> */
16350}
16351
16352// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-AtomEscape
16353pp$8.regexp_eatAtomEscape = function(state) {
16354 if (
16355 this.regexp_eatBackReference(state) ||
16356 this.regexp_eatCharacterClassEscape(state) ||
16357 this.regexp_eatCharacterEscape(state) ||
16358 (state.switchN && this.regexp_eatKGroupName(state))
16359 ) {
16360 return true
16361 }
16362 if (state.switchU) {
16363 // Make the same message as V8.
16364 if (state.current() === 0x63 /* c */) {
16365 state.raise("Invalid unicode escape");
16366 }
16367 state.raise("Invalid escape");
16368 }
16369 return false
16370};
16371pp$8.regexp_eatBackReference = function(state) {
16372 var start = state.pos;
16373 if (this.regexp_eatDecimalEscape(state)) {
16374 var n = state.lastIntValue;
16375 if (state.switchU) {
16376 // For SyntaxError in https://www.ecma-international.org/ecma-262/8.0/#sec-atomescape
16377 if (n > state.maxBackReference) {
16378 state.maxBackReference = n;
16379 }
16380 return true
16381 }
16382 if (n <= state.numCapturingParens) {
16383 return true
16384 }
16385 state.pos = start;
16386 }
16387 return false
16388};
16389pp$8.regexp_eatKGroupName = function(state) {
16390 if (state.eat(0x6B /* k */)) {
16391 if (this.regexp_eatGroupName(state)) {
16392 state.backReferenceNames.push(state.lastStringValue);
16393 return true
16394 }
16395 state.raise("Invalid named reference");
16396 }
16397 return false
16398};
16399
16400// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-CharacterEscape
16401pp$8.regexp_eatCharacterEscape = function(state) {
16402 return (
16403 this.regexp_eatControlEscape(state) ||
16404 this.regexp_eatCControlLetter(state) ||
16405 this.regexp_eatZero(state) ||
16406 this.regexp_eatHexEscapeSequence(state) ||
16407 this.regexp_eatRegExpUnicodeEscapeSequence(state, false) ||
16408 (!state.switchU && this.regexp_eatLegacyOctalEscapeSequence(state)) ||
16409 this.regexp_eatIdentityEscape(state)
16410 )
16411};
16412pp$8.regexp_eatCControlLetter = function(state) {
16413 var start = state.pos;
16414 if (state.eat(0x63 /* c */)) {
16415 if (this.regexp_eatControlLetter(state)) {
16416 return true
16417 }
16418 state.pos = start;
16419 }
16420 return false
16421};
16422pp$8.regexp_eatZero = function(state) {
16423 if (state.current() === 0x30 /* 0 */ && !isDecimalDigit(state.lookahead())) {
16424 state.lastIntValue = 0;
16425 state.advance();
16426 return true
16427 }
16428 return false
16429};
16430
16431// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlEscape
16432pp$8.regexp_eatControlEscape = function(state) {
16433 var ch = state.current();
16434 if (ch === 0x74 /* t */) {
16435 state.lastIntValue = 0x09; /* \t */
16436 state.advance();
16437 return true
16438 }
16439 if (ch === 0x6E /* n */) {
16440 state.lastIntValue = 0x0A; /* \n */
16441 state.advance();
16442 return true
16443 }
16444 if (ch === 0x76 /* v */) {
16445 state.lastIntValue = 0x0B; /* \v */
16446 state.advance();
16447 return true
16448 }
16449 if (ch === 0x66 /* f */) {
16450 state.lastIntValue = 0x0C; /* \f */
16451 state.advance();
16452 return true
16453 }
16454 if (ch === 0x72 /* r */) {
16455 state.lastIntValue = 0x0D; /* \r */
16456 state.advance();
16457 return true
16458 }
16459 return false
16460};
16461
16462// https://www.ecma-international.org/ecma-262/8.0/#prod-ControlLetter
16463pp$8.regexp_eatControlLetter = function(state) {
16464 var ch = state.current();
16465 if (isControlLetter(ch)) {
16466 state.lastIntValue = ch % 0x20;
16467 state.advance();
16468 return true
16469 }
16470 return false
16471};
16472function isControlLetter(ch) {
16473 return (
16474 (ch >= 0x41 /* A */ && ch <= 0x5A /* Z */) ||
16475 (ch >= 0x61 /* a */ && ch <= 0x7A /* z */)
16476 )
16477}
16478
16479// https://www.ecma-international.org/ecma-262/8.0/#prod-RegExpUnicodeEscapeSequence
16480pp$8.regexp_eatRegExpUnicodeEscapeSequence = function(state, forceU) {
16481 if ( forceU === void 0 ) forceU = false;
16482
16483 var start = state.pos;
16484 var switchU = forceU || state.switchU;
16485
16486 if (state.eat(0x75 /* u */)) {
16487 if (this.regexp_eatFixedHexDigits(state, 4)) {
16488 var lead = state.lastIntValue;
16489 if (switchU && lead >= 0xD800 && lead <= 0xDBFF) {
16490 var leadSurrogateEnd = state.pos;
16491 if (state.eat(0x5C /* \ */) && state.eat(0x75 /* u */) && this.regexp_eatFixedHexDigits(state, 4)) {
16492 var trail = state.lastIntValue;
16493 if (trail >= 0xDC00 && trail <= 0xDFFF) {
16494 state.lastIntValue = (lead - 0xD800) * 0x400 + (trail - 0xDC00) + 0x10000;
16495 return true
16496 }
16497 }
16498 state.pos = leadSurrogateEnd;
16499 state.lastIntValue = lead;
16500 }
16501 return true
16502 }
16503 if (
16504 switchU &&
16505 state.eat(0x7B /* { */) &&
16506 this.regexp_eatHexDigits(state) &&
16507 state.eat(0x7D /* } */) &&
16508 isValidUnicode(state.lastIntValue)
16509 ) {
16510 return true
16511 }
16512 if (switchU) {
16513 state.raise("Invalid unicode escape");
16514 }
16515 state.pos = start;
16516 }
16517
16518 return false
16519};
16520function isValidUnicode(ch) {
16521 return ch >= 0 && ch <= 0x10FFFF
16522}
16523
16524// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-IdentityEscape
16525pp$8.regexp_eatIdentityEscape = function(state) {
16526 if (state.switchU) {
16527 if (this.regexp_eatSyntaxCharacter(state)) {
16528 return true
16529 }
16530 if (state.eat(0x2F /* / */)) {
16531 state.lastIntValue = 0x2F; /* / */
16532 return true
16533 }
16534 return false
16535 }
16536
16537 var ch = state.current();
16538 if (ch !== 0x63 /* c */ && (!state.switchN || ch !== 0x6B /* k */)) {
16539 state.lastIntValue = ch;
16540 state.advance();
16541 return true
16542 }
16543
16544 return false
16545};
16546
16547// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalEscape
16548pp$8.regexp_eatDecimalEscape = function(state) {
16549 state.lastIntValue = 0;
16550 var ch = state.current();
16551 if (ch >= 0x31 /* 1 */ && ch <= 0x39 /* 9 */) {
16552 do {
16553 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
16554 state.advance();
16555 } while ((ch = state.current()) >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */)
16556 return true
16557 }
16558 return false
16559};
16560
16561// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClassEscape
16562pp$8.regexp_eatCharacterClassEscape = function(state) {
16563 var ch = state.current();
16564
16565 if (isCharacterClassEscape(ch)) {
16566 state.lastIntValue = -1;
16567 state.advance();
16568 return true
16569 }
16570
16571 if (
16572 state.switchU &&
16573 this.options.ecmaVersion >= 9 &&
16574 (ch === 0x50 /* P */ || ch === 0x70 /* p */)
16575 ) {
16576 state.lastIntValue = -1;
16577 state.advance();
16578 if (
16579 state.eat(0x7B /* { */) &&
16580 this.regexp_eatUnicodePropertyValueExpression(state) &&
16581 state.eat(0x7D /* } */)
16582 ) {
16583 return true
16584 }
16585 state.raise("Invalid property name");
16586 }
16587
16588 return false
16589};
16590function isCharacterClassEscape(ch) {
16591 return (
16592 ch === 0x64 /* d */ ||
16593 ch === 0x44 /* D */ ||
16594 ch === 0x73 /* s */ ||
16595 ch === 0x53 /* S */ ||
16596 ch === 0x77 /* w */ ||
16597 ch === 0x57 /* W */
16598 )
16599}
16600
16601// UnicodePropertyValueExpression ::
16602// UnicodePropertyName `=` UnicodePropertyValue
16603// LoneUnicodePropertyNameOrValue
16604pp$8.regexp_eatUnicodePropertyValueExpression = function(state) {
16605 var start = state.pos;
16606
16607 // UnicodePropertyName `=` UnicodePropertyValue
16608 if (this.regexp_eatUnicodePropertyName(state) && state.eat(0x3D /* = */)) {
16609 var name = state.lastStringValue;
16610 if (this.regexp_eatUnicodePropertyValue(state)) {
16611 var value = state.lastStringValue;
16612 this.regexp_validateUnicodePropertyNameAndValue(state, name, value);
16613 return true
16614 }
16615 }
16616 state.pos = start;
16617
16618 // LoneUnicodePropertyNameOrValue
16619 if (this.regexp_eatLoneUnicodePropertyNameOrValue(state)) {
16620 var nameOrValue = state.lastStringValue;
16621 this.regexp_validateUnicodePropertyNameOrValue(state, nameOrValue);
16622 return true
16623 }
16624 return false
16625};
16626pp$8.regexp_validateUnicodePropertyNameAndValue = function(state, name, value) {
16627 if (!has(state.unicodeProperties.nonBinary, name))
16628 { state.raise("Invalid property name"); }
16629 if (!state.unicodeProperties.nonBinary[name].test(value))
16630 { state.raise("Invalid property value"); }
16631};
16632pp$8.regexp_validateUnicodePropertyNameOrValue = function(state, nameOrValue) {
16633 if (!state.unicodeProperties.binary.test(nameOrValue))
16634 { state.raise("Invalid property name"); }
16635};
16636
16637// UnicodePropertyName ::
16638// UnicodePropertyNameCharacters
16639pp$8.regexp_eatUnicodePropertyName = function(state) {
16640 var ch = 0;
16641 state.lastStringValue = "";
16642 while (isUnicodePropertyNameCharacter(ch = state.current())) {
16643 state.lastStringValue += codePointToString(ch);
16644 state.advance();
16645 }
16646 return state.lastStringValue !== ""
16647};
16648function isUnicodePropertyNameCharacter(ch) {
16649 return isControlLetter(ch) || ch === 0x5F /* _ */
16650}
16651
16652// UnicodePropertyValue ::
16653// UnicodePropertyValueCharacters
16654pp$8.regexp_eatUnicodePropertyValue = function(state) {
16655 var ch = 0;
16656 state.lastStringValue = "";
16657 while (isUnicodePropertyValueCharacter(ch = state.current())) {
16658 state.lastStringValue += codePointToString(ch);
16659 state.advance();
16660 }
16661 return state.lastStringValue !== ""
16662};
16663function isUnicodePropertyValueCharacter(ch) {
16664 return isUnicodePropertyNameCharacter(ch) || isDecimalDigit(ch)
16665}
16666
16667// LoneUnicodePropertyNameOrValue ::
16668// UnicodePropertyValueCharacters
16669pp$8.regexp_eatLoneUnicodePropertyNameOrValue = function(state) {
16670 return this.regexp_eatUnicodePropertyValue(state)
16671};
16672
16673// https://www.ecma-international.org/ecma-262/8.0/#prod-CharacterClass
16674pp$8.regexp_eatCharacterClass = function(state) {
16675 if (state.eat(0x5B /* [ */)) {
16676 state.eat(0x5E /* ^ */);
16677 this.regexp_classRanges(state);
16678 if (state.eat(0x5D /* ] */)) {
16679 return true
16680 }
16681 // Unreachable since it threw "unterminated regular expression" error before.
16682 state.raise("Unterminated character class");
16683 }
16684 return false
16685};
16686
16687// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassRanges
16688// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRanges
16689// https://www.ecma-international.org/ecma-262/8.0/#prod-NonemptyClassRangesNoDash
16690pp$8.regexp_classRanges = function(state) {
16691 while (this.regexp_eatClassAtom(state)) {
16692 var left = state.lastIntValue;
16693 if (state.eat(0x2D /* - */) && this.regexp_eatClassAtom(state)) {
16694 var right = state.lastIntValue;
16695 if (state.switchU && (left === -1 || right === -1)) {
16696 state.raise("Invalid character class");
16697 }
16698 if (left !== -1 && right !== -1 && left > right) {
16699 state.raise("Range out of order in character class");
16700 }
16701 }
16702 }
16703};
16704
16705// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtom
16706// https://www.ecma-international.org/ecma-262/8.0/#prod-ClassAtomNoDash
16707pp$8.regexp_eatClassAtom = function(state) {
16708 var start = state.pos;
16709
16710 if (state.eat(0x5C /* \ */)) {
16711 if (this.regexp_eatClassEscape(state)) {
16712 return true
16713 }
16714 if (state.switchU) {
16715 // Make the same message as V8.
16716 var ch$1 = state.current();
16717 if (ch$1 === 0x63 /* c */ || isOctalDigit(ch$1)) {
16718 state.raise("Invalid class escape");
16719 }
16720 state.raise("Invalid escape");
16721 }
16722 state.pos = start;
16723 }
16724
16725 var ch = state.current();
16726 if (ch !== 0x5D /* ] */) {
16727 state.lastIntValue = ch;
16728 state.advance();
16729 return true
16730 }
16731
16732 return false
16733};
16734
16735// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassEscape
16736pp$8.regexp_eatClassEscape = function(state) {
16737 var start = state.pos;
16738
16739 if (state.eat(0x62 /* b */)) {
16740 state.lastIntValue = 0x08; /* <BS> */
16741 return true
16742 }
16743
16744 if (state.switchU && state.eat(0x2D /* - */)) {
16745 state.lastIntValue = 0x2D; /* - */
16746 return true
16747 }
16748
16749 if (!state.switchU && state.eat(0x63 /* c */)) {
16750 if (this.regexp_eatClassControlLetter(state)) {
16751 return true
16752 }
16753 state.pos = start;
16754 }
16755
16756 return (
16757 this.regexp_eatCharacterClassEscape(state) ||
16758 this.regexp_eatCharacterEscape(state)
16759 )
16760};
16761
16762// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-ClassControlLetter
16763pp$8.regexp_eatClassControlLetter = function(state) {
16764 var ch = state.current();
16765 if (isDecimalDigit(ch) || ch === 0x5F /* _ */) {
16766 state.lastIntValue = ch % 0x20;
16767 state.advance();
16768 return true
16769 }
16770 return false
16771};
16772
16773// https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
16774pp$8.regexp_eatHexEscapeSequence = function(state) {
16775 var start = state.pos;
16776 if (state.eat(0x78 /* x */)) {
16777 if (this.regexp_eatFixedHexDigits(state, 2)) {
16778 return true
16779 }
16780 if (state.switchU) {
16781 state.raise("Invalid escape");
16782 }
16783 state.pos = start;
16784 }
16785 return false
16786};
16787
16788// https://www.ecma-international.org/ecma-262/8.0/#prod-DecimalDigits
16789pp$8.regexp_eatDecimalDigits = function(state) {
16790 var start = state.pos;
16791 var ch = 0;
16792 state.lastIntValue = 0;
16793 while (isDecimalDigit(ch = state.current())) {
16794 state.lastIntValue = 10 * state.lastIntValue + (ch - 0x30 /* 0 */);
16795 state.advance();
16796 }
16797 return state.pos !== start
16798};
16799function isDecimalDigit(ch) {
16800 return ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */
16801}
16802
16803// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigits
16804pp$8.regexp_eatHexDigits = function(state) {
16805 var start = state.pos;
16806 var ch = 0;
16807 state.lastIntValue = 0;
16808 while (isHexDigit(ch = state.current())) {
16809 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
16810 state.advance();
16811 }
16812 return state.pos !== start
16813};
16814function isHexDigit(ch) {
16815 return (
16816 (ch >= 0x30 /* 0 */ && ch <= 0x39 /* 9 */) ||
16817 (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) ||
16818 (ch >= 0x61 /* a */ && ch <= 0x66 /* f */)
16819 )
16820}
16821function hexToInt(ch) {
16822 if (ch >= 0x41 /* A */ && ch <= 0x46 /* F */) {
16823 return 10 + (ch - 0x41 /* A */)
16824 }
16825 if (ch >= 0x61 /* a */ && ch <= 0x66 /* f */) {
16826 return 10 + (ch - 0x61 /* a */)
16827 }
16828 return ch - 0x30 /* 0 */
16829}
16830
16831// https://www.ecma-international.org/ecma-262/8.0/#prod-annexB-LegacyOctalEscapeSequence
16832// Allows only 0-377(octal) i.e. 0-255(decimal).
16833pp$8.regexp_eatLegacyOctalEscapeSequence = function(state) {
16834 if (this.regexp_eatOctalDigit(state)) {
16835 var n1 = state.lastIntValue;
16836 if (this.regexp_eatOctalDigit(state)) {
16837 var n2 = state.lastIntValue;
16838 if (n1 <= 3 && this.regexp_eatOctalDigit(state)) {
16839 state.lastIntValue = n1 * 64 + n2 * 8 + state.lastIntValue;
16840 } else {
16841 state.lastIntValue = n1 * 8 + n2;
16842 }
16843 } else {
16844 state.lastIntValue = n1;
16845 }
16846 return true
16847 }
16848 return false
16849};
16850
16851// https://www.ecma-international.org/ecma-262/8.0/#prod-OctalDigit
16852pp$8.regexp_eatOctalDigit = function(state) {
16853 var ch = state.current();
16854 if (isOctalDigit(ch)) {
16855 state.lastIntValue = ch - 0x30; /* 0 */
16856 state.advance();
16857 return true
16858 }
16859 state.lastIntValue = 0;
16860 return false
16861};
16862function isOctalDigit(ch) {
16863 return ch >= 0x30 /* 0 */ && ch <= 0x37 /* 7 */
16864}
16865
16866// https://www.ecma-international.org/ecma-262/8.0/#prod-Hex4Digits
16867// https://www.ecma-international.org/ecma-262/8.0/#prod-HexDigit
16868// And HexDigit HexDigit in https://www.ecma-international.org/ecma-262/8.0/#prod-HexEscapeSequence
16869pp$8.regexp_eatFixedHexDigits = function(state, length) {
16870 var start = state.pos;
16871 state.lastIntValue = 0;
16872 for (var i = 0; i < length; ++i) {
16873 var ch = state.current();
16874 if (!isHexDigit(ch)) {
16875 state.pos = start;
16876 return false
16877 }
16878 state.lastIntValue = 16 * state.lastIntValue + hexToInt(ch);
16879 state.advance();
16880 }
16881 return true
16882};
16883
16884// Object type used to represent tokens. Note that normally, tokens
16885// simply exist as properties on the parser object. This is only
16886// used for the onToken callback and the external tokenizer.
16887
16888var Token = function Token(p) {
16889 this.type = p.type;
16890 this.value = p.value;
16891 this.start = p.start;
16892 this.end = p.end;
16893 if (p.options.locations)
16894 { this.loc = new SourceLocation(p, p.startLoc, p.endLoc); }
16895 if (p.options.ranges)
16896 { this.range = [p.start, p.end]; }
16897};
16898
16899// ## Tokenizer
16900
16901var pp$9 = Parser.prototype;
16902
16903// Move to the next token
16904
16905pp$9.next = function(ignoreEscapeSequenceInKeyword) {
16906 if (!ignoreEscapeSequenceInKeyword && this.type.keyword && this.containsEsc)
16907 { this.raiseRecoverable(this.start, "Escape sequence in keyword " + this.type.keyword); }
16908 if (this.options.onToken)
16909 { this.options.onToken(new Token(this)); }
16910
16911 this.lastTokEnd = this.end;
16912 this.lastTokStart = this.start;
16913 this.lastTokEndLoc = this.endLoc;
16914 this.lastTokStartLoc = this.startLoc;
16915 this.nextToken();
16916};
16917
16918pp$9.getToken = function() {
16919 this.next();
16920 return new Token(this)
16921};
16922
16923// If we're in an ES6 environment, make parsers iterable
16924if (typeof Symbol !== "undefined")
16925 { pp$9[Symbol.iterator] = function() {
16926 var this$1 = this;
16927
16928 return {
16929 next: function () {
16930 var token = this$1.getToken();
16931 return {
16932 done: token.type === types.eof,
16933 value: token
16934 }
16935 }
16936 }
16937 }; }
16938
16939// Toggle strict mode. Re-reads the next number or string to please
16940// pedantic tests (`"use strict"; 010;` should fail).
16941
16942pp$9.curContext = function() {
16943 return this.context[this.context.length - 1]
16944};
16945
16946// Read a single token, updating the parser object's token-related
16947// properties.
16948
16949pp$9.nextToken = function() {
16950 var curContext = this.curContext();
16951 if (!curContext || !curContext.preserveSpace) { this.skipSpace(); }
16952
16953 this.start = this.pos;
16954 if (this.options.locations) { this.startLoc = this.curPosition(); }
16955 if (this.pos >= this.input.length) { return this.finishToken(types.eof) }
16956
16957 if (curContext.override) { return curContext.override(this) }
16958 else { this.readToken(this.fullCharCodeAtPos()); }
16959};
16960
16961pp$9.readToken = function(code) {
16962 // Identifier or keyword. '\uXXXX' sequences are allowed in
16963 // identifiers, so '\' also dispatches to that.
16964 if (isIdentifierStart(code, this.options.ecmaVersion >= 6) || code === 92 /* '\' */)
16965 { return this.readWord() }
16966
16967 return this.getTokenFromCode(code)
16968};
16969
16970pp$9.fullCharCodeAtPos = function() {
16971 var code = this.input.charCodeAt(this.pos);
16972 if (code <= 0xd7ff || code >= 0xe000) { return code }
16973 var next = this.input.charCodeAt(this.pos + 1);
16974 return (code << 10) + next - 0x35fdc00
16975};
16976
16977pp$9.skipBlockComment = function() {
16978 var startLoc = this.options.onComment && this.curPosition();
16979 var start = this.pos, end = this.input.indexOf("*/", this.pos += 2);
16980 if (end === -1) { this.raise(this.pos - 2, "Unterminated comment"); }
16981 this.pos = end + 2;
16982 if (this.options.locations) {
16983 lineBreakG.lastIndex = start;
16984 var match;
16985 while ((match = lineBreakG.exec(this.input)) && match.index < this.pos) {
16986 ++this.curLine;
16987 this.lineStart = match.index + match[0].length;
16988 }
16989 }
16990 if (this.options.onComment)
16991 { this.options.onComment(true, this.input.slice(start + 2, end), start, this.pos,
16992 startLoc, this.curPosition()); }
16993};
16994
16995pp$9.skipLineComment = function(startSkip) {
16996 var start = this.pos;
16997 var startLoc = this.options.onComment && this.curPosition();
16998 var ch = this.input.charCodeAt(this.pos += startSkip);
16999 while (this.pos < this.input.length && !isNewLine(ch)) {
17000 ch = this.input.charCodeAt(++this.pos);
17001 }
17002 if (this.options.onComment)
17003 { this.options.onComment(false, this.input.slice(start + startSkip, this.pos), start, this.pos,
17004 startLoc, this.curPosition()); }
17005};
17006
17007// Called at the start of the parse and after every token. Skips
17008// whitespace and comments, and.
17009
17010pp$9.skipSpace = function() {
17011 loop: while (this.pos < this.input.length) {
17012 var ch = this.input.charCodeAt(this.pos);
17013 switch (ch) {
17014 case 32: case 160: // ' '
17015 ++this.pos;
17016 break
17017 case 13:
17018 if (this.input.charCodeAt(this.pos + 1) === 10) {
17019 ++this.pos;
17020 }
17021 case 10: case 8232: case 8233:
17022 ++this.pos;
17023 if (this.options.locations) {
17024 ++this.curLine;
17025 this.lineStart = this.pos;
17026 }
17027 break
17028 case 47: // '/'
17029 switch (this.input.charCodeAt(this.pos + 1)) {
17030 case 42: // '*'
17031 this.skipBlockComment();
17032 break
17033 case 47:
17034 this.skipLineComment(2);
17035 break
17036 default:
17037 break loop
17038 }
17039 break
17040 default:
17041 if (ch > 8 && ch < 14 || ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
17042 ++this.pos;
17043 } else {
17044 break loop
17045 }
17046 }
17047 }
17048};
17049
17050// Called at the end of every token. Sets `end`, `val`, and
17051// maintains `context` and `exprAllowed`, and skips the space after
17052// the token, so that the next one's `start` will point at the
17053// right position.
17054
17055pp$9.finishToken = function(type, val) {
17056 this.end = this.pos;
17057 if (this.options.locations) { this.endLoc = this.curPosition(); }
17058 var prevType = this.type;
17059 this.type = type;
17060 this.value = val;
17061
17062 this.updateContext(prevType);
17063};
17064
17065// ### Token reading
17066
17067// This is the function that is called to fetch the next token. It
17068// is somewhat obscure, because it works in character codes rather
17069// than characters, and because operator parsing has been inlined
17070// into it.
17071//
17072// All in the name of speed.
17073//
17074pp$9.readToken_dot = function() {
17075 var next = this.input.charCodeAt(this.pos + 1);
17076 if (next >= 48 && next <= 57) { return this.readNumber(true) }
17077 var next2 = this.input.charCodeAt(this.pos + 2);
17078 if (this.options.ecmaVersion >= 6 && next === 46 && next2 === 46) { // 46 = dot '.'
17079 this.pos += 3;
17080 return this.finishToken(types.ellipsis)
17081 } else {
17082 ++this.pos;
17083 return this.finishToken(types.dot)
17084 }
17085};
17086
17087pp$9.readToken_slash = function() { // '/'
17088 var next = this.input.charCodeAt(this.pos + 1);
17089 if (this.exprAllowed) { ++this.pos; return this.readRegexp() }
17090 if (next === 61) { return this.finishOp(types.assign, 2) }
17091 return this.finishOp(types.slash, 1)
17092};
17093
17094pp$9.readToken_mult_modulo_exp = function(code) { // '%*'
17095 var next = this.input.charCodeAt(this.pos + 1);
17096 var size = 1;
17097 var tokentype = code === 42 ? types.star : types.modulo;
17098
17099 // exponentiation operator ** and **=
17100 if (this.options.ecmaVersion >= 7 && code === 42 && next === 42) {
17101 ++size;
17102 tokentype = types.starstar;
17103 next = this.input.charCodeAt(this.pos + 2);
17104 }
17105
17106 if (next === 61) { return this.finishOp(types.assign, size + 1) }
17107 return this.finishOp(tokentype, size)
17108};
17109
17110pp$9.readToken_pipe_amp = function(code) { // '|&'
17111 var next = this.input.charCodeAt(this.pos + 1);
17112 if (next === code) {
17113 if (this.options.ecmaVersion >= 12) {
17114 var next2 = this.input.charCodeAt(this.pos + 2);
17115 if (next2 === 61) { return this.finishOp(types.assign, 3) }
17116 }
17117 return this.finishOp(code === 124 ? types.logicalOR : types.logicalAND, 2)
17118 }
17119 if (next === 61) { return this.finishOp(types.assign, 2) }
17120 return this.finishOp(code === 124 ? types.bitwiseOR : types.bitwiseAND, 1)
17121};
17122
17123pp$9.readToken_caret = function() { // '^'
17124 var next = this.input.charCodeAt(this.pos + 1);
17125 if (next === 61) { return this.finishOp(types.assign, 2) }
17126 return this.finishOp(types.bitwiseXOR, 1)
17127};
17128
17129pp$9.readToken_plus_min = function(code) { // '+-'
17130 var next = this.input.charCodeAt(this.pos + 1);
17131 if (next === code) {
17132 if (next === 45 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 62 &&
17133 (this.lastTokEnd === 0 || lineBreak.test(this.input.slice(this.lastTokEnd, this.pos)))) {
17134 // A `-->` line comment
17135 this.skipLineComment(3);
17136 this.skipSpace();
17137 return this.nextToken()
17138 }
17139 return this.finishOp(types.incDec, 2)
17140 }
17141 if (next === 61) { return this.finishOp(types.assign, 2) }
17142 return this.finishOp(types.plusMin, 1)
17143};
17144
17145pp$9.readToken_lt_gt = function(code) { // '<>'
17146 var next = this.input.charCodeAt(this.pos + 1);
17147 var size = 1;
17148 if (next === code) {
17149 size = code === 62 && this.input.charCodeAt(this.pos + 2) === 62 ? 3 : 2;
17150 if (this.input.charCodeAt(this.pos + size) === 61) { return this.finishOp(types.assign, size + 1) }
17151 return this.finishOp(types.bitShift, size)
17152 }
17153 if (next === 33 && code === 60 && !this.inModule && this.input.charCodeAt(this.pos + 2) === 45 &&
17154 this.input.charCodeAt(this.pos + 3) === 45) {
17155 // `<!--`, an XML-style comment that should be interpreted as a line comment
17156 this.skipLineComment(4);
17157 this.skipSpace();
17158 return this.nextToken()
17159 }
17160 if (next === 61) { size = 2; }
17161 return this.finishOp(types.relational, size)
17162};
17163
17164pp$9.readToken_eq_excl = function(code) { // '=!'
17165 var next = this.input.charCodeAt(this.pos + 1);
17166 if (next === 61) { return this.finishOp(types.equality, this.input.charCodeAt(this.pos + 2) === 61 ? 3 : 2) }
17167 if (code === 61 && next === 62 && this.options.ecmaVersion >= 6) { // '=>'
17168 this.pos += 2;
17169 return this.finishToken(types.arrow)
17170 }
17171 return this.finishOp(code === 61 ? types.eq : types.prefix, 1)
17172};
17173
17174pp$9.readToken_question = function() { // '?'
17175 var ecmaVersion = this.options.ecmaVersion;
17176 if (ecmaVersion >= 11) {
17177 var next = this.input.charCodeAt(this.pos + 1);
17178 if (next === 46) {
17179 var next2 = this.input.charCodeAt(this.pos + 2);
17180 if (next2 < 48 || next2 > 57) { return this.finishOp(types.questionDot, 2) }
17181 }
17182 if (next === 63) {
17183 if (ecmaVersion >= 12) {
17184 var next2$1 = this.input.charCodeAt(this.pos + 2);
17185 if (next2$1 === 61) { return this.finishOp(types.assign, 3) }
17186 }
17187 return this.finishOp(types.coalesce, 2)
17188 }
17189 }
17190 return this.finishOp(types.question, 1)
17191};
17192
17193pp$9.getTokenFromCode = function(code) {
17194 switch (code) {
17195 // The interpretation of a dot depends on whether it is followed
17196 // by a digit or another two dots.
17197 case 46: // '.'
17198 return this.readToken_dot()
17199
17200 // Punctuation tokens.
17201 case 40: ++this.pos; return this.finishToken(types.parenL)
17202 case 41: ++this.pos; return this.finishToken(types.parenR)
17203 case 59: ++this.pos; return this.finishToken(types.semi)
17204 case 44: ++this.pos; return this.finishToken(types.comma)
17205 case 91: ++this.pos; return this.finishToken(types.bracketL)
17206 case 93: ++this.pos; return this.finishToken(types.bracketR)
17207 case 123: ++this.pos; return this.finishToken(types.braceL)
17208 case 125: ++this.pos; return this.finishToken(types.braceR)
17209 case 58: ++this.pos; return this.finishToken(types.colon)
17210
17211 case 96: // '`'
17212 if (this.options.ecmaVersion < 6) { break }
17213 ++this.pos;
17214 return this.finishToken(types.backQuote)
17215
17216 case 48: // '0'
17217 var next = this.input.charCodeAt(this.pos + 1);
17218 if (next === 120 || next === 88) { return this.readRadixNumber(16) } // '0x', '0X' - hex number
17219 if (this.options.ecmaVersion >= 6) {
17220 if (next === 111 || next === 79) { return this.readRadixNumber(8) } // '0o', '0O' - octal number
17221 if (next === 98 || next === 66) { return this.readRadixNumber(2) } // '0b', '0B' - binary number
17222 }
17223
17224 // Anything else beginning with a digit is an integer, octal
17225 // number, or float.
17226 case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: // 1-9
17227 return this.readNumber(false)
17228
17229 // Quotes produce strings.
17230 case 34: case 39: // '"', "'"
17231 return this.readString(code)
17232
17233 // Operators are parsed inline in tiny state machines. '=' (61) is
17234 // often referred to. `finishOp` simply skips the amount of
17235 // characters it is given as second argument, and returns a token
17236 // of the type given by its first argument.
17237
17238 case 47: // '/'
17239 return this.readToken_slash()
17240
17241 case 37: case 42: // '%*'
17242 return this.readToken_mult_modulo_exp(code)
17243
17244 case 124: case 38: // '|&'
17245 return this.readToken_pipe_amp(code)
17246
17247 case 94: // '^'
17248 return this.readToken_caret()
17249
17250 case 43: case 45: // '+-'
17251 return this.readToken_plus_min(code)
17252
17253 case 60: case 62: // '<>'
17254 return this.readToken_lt_gt(code)
17255
17256 case 61: case 33: // '=!'
17257 return this.readToken_eq_excl(code)
17258
17259 case 63: // '?'
17260 return this.readToken_question()
17261
17262 case 126: // '~'
17263 return this.finishOp(types.prefix, 1)
17264 }
17265
17266 this.raise(this.pos, "Unexpected character '" + codePointToString$1(code) + "'");
17267};
17268
17269pp$9.finishOp = function(type, size) {
17270 var str = this.input.slice(this.pos, this.pos + size);
17271 this.pos += size;
17272 return this.finishToken(type, str)
17273};
17274
17275pp$9.readRegexp = function() {
17276 var escaped, inClass, start = this.pos;
17277 for (;;) {
17278 if (this.pos >= this.input.length) { this.raise(start, "Unterminated regular expression"); }
17279 var ch = this.input.charAt(this.pos);
17280 if (lineBreak.test(ch)) { this.raise(start, "Unterminated regular expression"); }
17281 if (!escaped) {
17282 if (ch === "[") { inClass = true; }
17283 else if (ch === "]" && inClass) { inClass = false; }
17284 else if (ch === "/" && !inClass) { break }
17285 escaped = ch === "\\";
17286 } else { escaped = false; }
17287 ++this.pos;
17288 }
17289 var pattern = this.input.slice(start, this.pos);
17290 ++this.pos;
17291 var flagsStart = this.pos;
17292 var flags = this.readWord1();
17293 if (this.containsEsc) { this.unexpected(flagsStart); }
17294
17295 // Validate pattern
17296 var state = this.regexpState || (this.regexpState = new RegExpValidationState(this));
17297 state.reset(start, pattern, flags);
17298 this.validateRegExpFlags(state);
17299 this.validateRegExpPattern(state);
17300
17301 // Create Literal#value property value.
17302 var value = null;
17303 try {
17304 value = new RegExp(pattern, flags);
17305 } catch (e) {
17306 // ESTree requires null if it failed to instantiate RegExp object.
17307 // https://github.com/estree/estree/blob/a27003adf4fd7bfad44de9cef372a2eacd527b1c/es5.md#regexpliteral
17308 }
17309
17310 return this.finishToken(types.regexp, {pattern: pattern, flags: flags, value: value})
17311};
17312
17313// Read an integer in the given radix. Return null if zero digits
17314// were read, the integer value otherwise. When `len` is given, this
17315// will return `null` unless the integer has exactly `len` digits.
17316
17317pp$9.readInt = function(radix, len, maybeLegacyOctalNumericLiteral) {
17318 // `len` is used for character escape sequences. In that case, disallow separators.
17319 var allowSeparators = this.options.ecmaVersion >= 12 && len === undefined;
17320
17321 // `maybeLegacyOctalNumericLiteral` is true if it doesn't have prefix (0x,0o,0b)
17322 // and isn't fraction part nor exponent part. In that case, if the first digit
17323 // is zero then disallow separators.
17324 var isLegacyOctalNumericLiteral = maybeLegacyOctalNumericLiteral && this.input.charCodeAt(this.pos) === 48;
17325
17326 var start = this.pos, total = 0, lastCode = 0;
17327 for (var i = 0, e = len == null ? Infinity : len; i < e; ++i, ++this.pos) {
17328 var code = this.input.charCodeAt(this.pos), val = (void 0);
17329
17330 if (allowSeparators && code === 95) {
17331 if (isLegacyOctalNumericLiteral) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed in legacy octal numeric literals"); }
17332 if (lastCode === 95) { this.raiseRecoverable(this.pos, "Numeric separator must be exactly one underscore"); }
17333 if (i === 0) { this.raiseRecoverable(this.pos, "Numeric separator is not allowed at the first of digits"); }
17334 lastCode = code;
17335 continue
17336 }
17337
17338 if (code >= 97) { val = code - 97 + 10; } // a
17339 else if (code >= 65) { val = code - 65 + 10; } // A
17340 else if (code >= 48 && code <= 57) { val = code - 48; } // 0-9
17341 else { val = Infinity; }
17342 if (val >= radix) { break }
17343 lastCode = code;
17344 total = total * radix + val;
17345 }
17346
17347 if (allowSeparators && lastCode === 95) { this.raiseRecoverable(this.pos - 1, "Numeric separator is not allowed at the last of digits"); }
17348 if (this.pos === start || len != null && this.pos - start !== len) { return null }
17349
17350 return total
17351};
17352
17353function stringToNumber(str, isLegacyOctalNumericLiteral) {
17354 if (isLegacyOctalNumericLiteral) {
17355 return parseInt(str, 8)
17356 }
17357
17358 // `parseFloat(value)` stops parsing at the first numeric separator then returns a wrong value.
17359 return parseFloat(str.replace(/_/g, ""))
17360}
17361
17362function stringToBigInt(str) {
17363 if (typeof BigInt !== "function") {
17364 return null
17365 }
17366
17367 // `BigInt(value)` throws syntax error if the string contains numeric separators.
17368 return BigInt(str.replace(/_/g, ""))
17369}
17370
17371pp$9.readRadixNumber = function(radix) {
17372 var start = this.pos;
17373 this.pos += 2; // 0x
17374 var val = this.readInt(radix);
17375 if (val == null) { this.raise(this.start + 2, "Expected number in radix " + radix); }
17376 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
17377 val = stringToBigInt(this.input.slice(start, this.pos));
17378 ++this.pos;
17379 } else if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
17380 return this.finishToken(types.num, val)
17381};
17382
17383// Read an integer, octal integer, or floating-point number.
17384
17385pp$9.readNumber = function(startsWithDot) {
17386 var start = this.pos;
17387 if (!startsWithDot && this.readInt(10, undefined, true) === null) { this.raise(start, "Invalid number"); }
17388 var octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
17389 if (octal && this.strict) { this.raise(start, "Invalid number"); }
17390 var next = this.input.charCodeAt(this.pos);
17391 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
17392 var val$1 = stringToBigInt(this.input.slice(start, this.pos));
17393 ++this.pos;
17394 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
17395 return this.finishToken(types.num, val$1)
17396 }
17397 if (octal && /[89]/.test(this.input.slice(start, this.pos))) { octal = false; }
17398 if (next === 46 && !octal) { // '.'
17399 ++this.pos;
17400 this.readInt(10);
17401 next = this.input.charCodeAt(this.pos);
17402 }
17403 if ((next === 69 || next === 101) && !octal) { // 'eE'
17404 next = this.input.charCodeAt(++this.pos);
17405 if (next === 43 || next === 45) { ++this.pos; } // '+-'
17406 if (this.readInt(10) === null) { this.raise(start, "Invalid number"); }
17407 }
17408 if (isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
17409
17410 var val = stringToNumber(this.input.slice(start, this.pos), octal);
17411 return this.finishToken(types.num, val)
17412};
17413
17414// Read a string value, interpreting backslash-escapes.
17415
17416pp$9.readCodePoint = function() {
17417 var ch = this.input.charCodeAt(this.pos), code;
17418
17419 if (ch === 123) { // '{'
17420 if (this.options.ecmaVersion < 6) { this.unexpected(); }
17421 var codePos = ++this.pos;
17422 code = this.readHexChar(this.input.indexOf("}", this.pos) - this.pos);
17423 ++this.pos;
17424 if (code > 0x10FFFF) { this.invalidStringToken(codePos, "Code point out of bounds"); }
17425 } else {
17426 code = this.readHexChar(4);
17427 }
17428 return code
17429};
17430
17431function codePointToString$1(code) {
17432 // UTF-16 Decoding
17433 if (code <= 0xFFFF) { return String.fromCharCode(code) }
17434 code -= 0x10000;
17435 return String.fromCharCode((code >> 10) + 0xD800, (code & 1023) + 0xDC00)
17436}
17437
17438pp$9.readString = function(quote) {
17439 var out = "", chunkStart = ++this.pos;
17440 for (;;) {
17441 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated string constant"); }
17442 var ch = this.input.charCodeAt(this.pos);
17443 if (ch === quote) { break }
17444 if (ch === 92) { // '\'
17445 out += this.input.slice(chunkStart, this.pos);
17446 out += this.readEscapedChar(false);
17447 chunkStart = this.pos;
17448 } else {
17449 if (isNewLine(ch, this.options.ecmaVersion >= 10)) { this.raise(this.start, "Unterminated string constant"); }
17450 ++this.pos;
17451 }
17452 }
17453 out += this.input.slice(chunkStart, this.pos++);
17454 return this.finishToken(types.string, out)
17455};
17456
17457// Reads template string tokens.
17458
17459var INVALID_TEMPLATE_ESCAPE_ERROR = {};
17460
17461pp$9.tryReadTemplateToken = function() {
17462 this.inTemplateElement = true;
17463 try {
17464 this.readTmplToken();
17465 } catch (err) {
17466 if (err === INVALID_TEMPLATE_ESCAPE_ERROR) {
17467 this.readInvalidTemplateToken();
17468 } else {
17469 throw err
17470 }
17471 }
17472
17473 this.inTemplateElement = false;
17474};
17475
17476pp$9.invalidStringToken = function(position, message) {
17477 if (this.inTemplateElement && this.options.ecmaVersion >= 9) {
17478 throw INVALID_TEMPLATE_ESCAPE_ERROR
17479 } else {
17480 this.raise(position, message);
17481 }
17482};
17483
17484pp$9.readTmplToken = function() {
17485 var out = "", chunkStart = this.pos;
17486 for (;;) {
17487 if (this.pos >= this.input.length) { this.raise(this.start, "Unterminated template"); }
17488 var ch = this.input.charCodeAt(this.pos);
17489 if (ch === 96 || ch === 36 && this.input.charCodeAt(this.pos + 1) === 123) { // '`', '${'
17490 if (this.pos === this.start && (this.type === types.template || this.type === types.invalidTemplate)) {
17491 if (ch === 36) {
17492 this.pos += 2;
17493 return this.finishToken(types.dollarBraceL)
17494 } else {
17495 ++this.pos;
17496 return this.finishToken(types.backQuote)
17497 }
17498 }
17499 out += this.input.slice(chunkStart, this.pos);
17500 return this.finishToken(types.template, out)
17501 }
17502 if (ch === 92) { // '\'
17503 out += this.input.slice(chunkStart, this.pos);
17504 out += this.readEscapedChar(true);
17505 chunkStart = this.pos;
17506 } else if (isNewLine(ch)) {
17507 out += this.input.slice(chunkStart, this.pos);
17508 ++this.pos;
17509 switch (ch) {
17510 case 13:
17511 if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; }
17512 case 10:
17513 out += "\n";
17514 break
17515 default:
17516 out += String.fromCharCode(ch);
17517 break
17518 }
17519 if (this.options.locations) {
17520 ++this.curLine;
17521 this.lineStart = this.pos;
17522 }
17523 chunkStart = this.pos;
17524 } else {
17525 ++this.pos;
17526 }
17527 }
17528};
17529
17530// Reads a template token to search for the end, without validating any escape sequences
17531pp$9.readInvalidTemplateToken = function() {
17532 for (; this.pos < this.input.length; this.pos++) {
17533 switch (this.input[this.pos]) {
17534 case "\\":
17535 ++this.pos;
17536 break
17537
17538 case "$":
17539 if (this.input[this.pos + 1] !== "{") {
17540 break
17541 }
17542 // falls through
17543
17544 case "`":
17545 return this.finishToken(types.invalidTemplate, this.input.slice(this.start, this.pos))
17546
17547 // no default
17548 }
17549 }
17550 this.raise(this.start, "Unterminated template");
17551};
17552
17553// Used to read escaped characters
17554
17555pp$9.readEscapedChar = function(inTemplate) {
17556 var ch = this.input.charCodeAt(++this.pos);
17557 ++this.pos;
17558 switch (ch) {
17559 case 110: return "\n" // 'n' -> '\n'
17560 case 114: return "\r" // 'r' -> '\r'
17561 case 120: return String.fromCharCode(this.readHexChar(2)) // 'x'
17562 case 117: return codePointToString$1(this.readCodePoint()) // 'u'
17563 case 116: return "\t" // 't' -> '\t'
17564 case 98: return "\b" // 'b' -> '\b'
17565 case 118: return "\u000b" // 'v' -> '\u000b'
17566 case 102: return "\f" // 'f' -> '\f'
17567 case 13: if (this.input.charCodeAt(this.pos) === 10) { ++this.pos; } // '\r\n'
17568 case 10: // ' \n'
17569 if (this.options.locations) { this.lineStart = this.pos; ++this.curLine; }
17570 return ""
17571 case 56:
17572 case 57:
17573 if (this.strict) {
17574 this.invalidStringToken(
17575 this.pos - 1,
17576 "Invalid escape sequence"
17577 );
17578 }
17579 if (inTemplate) {
17580 var codePos = this.pos - 1;
17581
17582 this.invalidStringToken(
17583 codePos,
17584 "Invalid escape sequence in template string"
17585 );
17586
17587 return null
17588 }
17589 default:
17590 if (ch >= 48 && ch <= 55) {
17591 var octalStr = this.input.substr(this.pos - 1, 3).match(/^[0-7]+/)[0];
17592 var octal = parseInt(octalStr, 8);
17593 if (octal > 255) {
17594 octalStr = octalStr.slice(0, -1);
17595 octal = parseInt(octalStr, 8);
17596 }
17597 this.pos += octalStr.length - 1;
17598 ch = this.input.charCodeAt(this.pos);
17599 if ((octalStr !== "0" || ch === 56 || ch === 57) && (this.strict || inTemplate)) {
17600 this.invalidStringToken(
17601 this.pos - 1 - octalStr.length,
17602 inTemplate
17603 ? "Octal literal in template string"
17604 : "Octal literal in strict mode"
17605 );
17606 }
17607 return String.fromCharCode(octal)
17608 }
17609 if (isNewLine(ch)) {
17610 // Unicode new line characters after \ get removed from output in both
17611 // template literals and strings
17612 return ""
17613 }
17614 return String.fromCharCode(ch)
17615 }
17616};
17617
17618// Used to read character escape sequences ('\x', '\u', '\U').
17619
17620pp$9.readHexChar = function(len) {
17621 var codePos = this.pos;
17622 var n = this.readInt(16, len);
17623 if (n === null) { this.invalidStringToken(codePos, "Bad character escape sequence"); }
17624 return n
17625};
17626
17627// Read an identifier, and return it as a string. Sets `this.containsEsc`
17628// to whether the word contained a '\u' escape.
17629//
17630// Incrementally adds only escaped chars, adding other chunks as-is
17631// as a micro-optimization.
17632
17633pp$9.readWord1 = function() {
17634 this.containsEsc = false;
17635 var word = "", first = true, chunkStart = this.pos;
17636 var astral = this.options.ecmaVersion >= 6;
17637 while (this.pos < this.input.length) {
17638 var ch = this.fullCharCodeAtPos();
17639 if (isIdentifierChar(ch, astral)) {
17640 this.pos += ch <= 0xffff ? 1 : 2;
17641 } else if (ch === 92) { // "\"
17642 this.containsEsc = true;
17643 word += this.input.slice(chunkStart, this.pos);
17644 var escStart = this.pos;
17645 if (this.input.charCodeAt(++this.pos) !== 117) // "u"
17646 { this.invalidStringToken(this.pos, "Expecting Unicode escape sequence \\uXXXX"); }
17647 ++this.pos;
17648 var esc = this.readCodePoint();
17649 if (!(first ? isIdentifierStart : isIdentifierChar)(esc, astral))
17650 { this.invalidStringToken(escStart, "Invalid Unicode escape"); }
17651 word += codePointToString$1(esc);
17652 chunkStart = this.pos;
17653 } else {
17654 break
17655 }
17656 first = false;
17657 }
17658 return word + this.input.slice(chunkStart, this.pos)
17659};
17660
17661// Read an identifier or keyword token. Will check for reserved
17662// words when necessary.
17663
17664pp$9.readWord = function() {
17665 var word = this.readWord1();
17666 var type = types.name;
17667 if (this.keywords.test(word)) {
17668 type = keywords$1[word];
17669 }
17670 return this.finishToken(type, word)
17671};
17672
17673// Acorn is a tiny, fast JavaScript parser written in JavaScript.
17674
17675var version$1 = "8.0.3";
17676
17677Parser.acorn = {
17678 Parser: Parser,
17679 version: version$1,
17680 defaultOptions: defaultOptions,
17681 Position: Position,
17682 SourceLocation: SourceLocation,
17683 getLineInfo: getLineInfo,
17684 Node: Node,
17685 TokenType: TokenType,
17686 tokTypes: types,
17687 keywordTypes: keywords$1,
17688 TokContext: TokContext,
17689 tokContexts: types$1,
17690 isIdentifierChar: isIdentifierChar,
17691 isIdentifierStart: isIdentifierStart,
17692 Token: Token,
17693 isNewLine: isNewLine,
17694 lineBreak: lineBreak,
17695 lineBreakG: lineBreakG,
17696 nonASCIIwhitespace: nonASCIIwhitespace
17697};
17698
17699// The main exported interface (under `self.acorn` when in the
17700// browser) is a `parse` function that takes a code string and
17701// returns an abstract syntax tree as specified by [Mozilla parser
17702// API][api].
17703//
17704// [api]: https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
17705
17706function parse(input, options) {
17707 return Parser.parse(input, options)
17708}
17709
17710// This function tries to parse a single expression at a given
17711// offset in a string. Useful for parsing mixed-language formats
17712// that embed JavaScript expressions.
17713
17714function parseExpressionAt(input, pos, options) {
17715 return Parser.parseExpressionAt(input, pos, options)
17716}
17717
17718// Acorn is organized as a tokenizer and a recursive-descent parser.
17719// The `tokenizer` export provides an interface to the tokenizer.
17720
17721function tokenizer(input, options) {
17722 return Parser.tokenizer(input, options)
17723}
17724
17725var acorn = {
17726 __proto__: null,
17727 Node: Node,
17728 Parser: Parser,
17729 Position: Position,
17730 SourceLocation: SourceLocation,
17731 TokContext: TokContext,
17732 Token: Token,
17733 TokenType: TokenType,
17734 defaultOptions: defaultOptions,
17735 getLineInfo: getLineInfo,
17736 isIdentifierChar: isIdentifierChar,
17737 isIdentifierStart: isIdentifierStart,
17738 isNewLine: isNewLine,
17739 keywordTypes: keywords$1,
17740 lineBreak: lineBreak,
17741 lineBreakG: lineBreakG,
17742 nonASCIIwhitespace: nonASCIIwhitespace,
17743 parse: parse,
17744 parseExpressionAt: parseExpressionAt,
17745 tokContexts: types$1,
17746 tokTypes: types,
17747 tokenizer: tokenizer,
17748 version: version$1
17749};
17750
17751class GlobalScope extends Scope {
17752 constructor() {
17753 super();
17754 this.variables.set('undefined', new UndefinedVariable());
17755 }
17756 findVariable(name) {
17757 let variable = this.variables.get(name);
17758 if (!variable) {
17759 variable = new GlobalVariable(name);
17760 this.variables.set(name, variable);
17761 }
17762 return variable;
17763 }
17764}
17765
17766const readFile = (file) => new Promise((fulfil, reject) => readFile$1(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
17767function mkdirpath(path) {
17768 const dir = dirname(path);
17769 try {
17770 readdirSync(dir);
17771 }
17772 catch (err) {
17773 mkdirpath(dir);
17774 try {
17775 mkdirSync(dir);
17776 }
17777 catch (err2) {
17778 if (err2.code !== 'EEXIST') {
17779 throw err2;
17780 }
17781 }
17782 }
17783}
17784function writeFile(dest, data) {
17785 return new Promise((fulfil, reject) => {
17786 mkdirpath(dest);
17787 writeFile$1(dest, data, err => {
17788 if (err) {
17789 reject(err);
17790 }
17791 else {
17792 fulfil();
17793 }
17794 });
17795 });
17796}
17797
17798async function resolveId(source, importer, preserveSymlinks, pluginDriver, skip, customOptions) {
17799 const pluginResult = await pluginDriver.hookFirst('resolveId', [source, importer, { custom: customOptions }], null, skip);
17800 if (pluginResult != null)
17801 return pluginResult;
17802 // external modules (non-entry modules that start with neither '.' or '/')
17803 // are skipped at this stage.
17804 if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
17805 return null;
17806 // `resolve` processes paths from right to left, prepending them until an
17807 // absolute path is created. Absolute importees therefore shortcircuit the
17808 // resolve call and require no special handing on our part.
17809 // See https://nodejs.org/api/path.html#path_path_resolve_paths
17810 return addJsExtensionIfNecessary(resolve(importer ? dirname(importer) : resolve(), source), preserveSymlinks);
17811}
17812function addJsExtensionIfNecessary(file, preserveSymlinks) {
17813 let found = findFile(file, preserveSymlinks);
17814 if (found)
17815 return found;
17816 found = findFile(file + '.mjs', preserveSymlinks);
17817 if (found)
17818 return found;
17819 found = findFile(file + '.js', preserveSymlinks);
17820 return found;
17821}
17822function findFile(file, preserveSymlinks) {
17823 try {
17824 const stats = lstatSync(file);
17825 if (!preserveSymlinks && stats.isSymbolicLink())
17826 return findFile(realpathSync(file), preserveSymlinks);
17827 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
17828 // check case
17829 const name = basename(file);
17830 const files = readdirSync(dirname(file));
17831 if (files.indexOf(name) !== -1)
17832 return file;
17833 }
17834 }
17835 catch (_a) {
17836 // suppress
17837 }
17838}
17839
17840const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
17841const ANONYMOUS_OUTPUT_PLUGIN_PREFIX = 'at output position ';
17842function throwPluginError(err, plugin, { hook, id } = {}) {
17843 if (typeof err === 'string')
17844 err = { message: err };
17845 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
17846 err.pluginCode = err.code;
17847 }
17848 err.code = Errors.PLUGIN_ERROR;
17849 err.plugin = plugin;
17850 if (hook) {
17851 err.hook = hook;
17852 }
17853 if (id) {
17854 err.id = id;
17855 }
17856 return error(err);
17857}
17858const deprecatedHooks = [
17859 { active: true, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
17860];
17861function warnDeprecatedHooks(plugins, options) {
17862 for (const { active, deprecated, replacement } of deprecatedHooks) {
17863 for (const plugin of plugins) {
17864 if (deprecated in plugin) {
17865 warnDeprecation({
17866 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
17867 plugin: plugin.name
17868 }, active, options);
17869 }
17870 }
17871 }
17872}
17873
17874function createPluginCache(cache) {
17875 return {
17876 has(id) {
17877 const item = cache[id];
17878 if (!item)
17879 return false;
17880 item[0] = 0;
17881 return true;
17882 },
17883 get(id) {
17884 const item = cache[id];
17885 if (!item)
17886 return undefined;
17887 item[0] = 0;
17888 return item[1];
17889 },
17890 set(id, value) {
17891 cache[id] = [0, value];
17892 },
17893 delete(id) {
17894 return delete cache[id];
17895 }
17896 };
17897}
17898function getTrackedPluginCache(pluginCache, onUse) {
17899 return {
17900 has(id) {
17901 onUse();
17902 return pluginCache.has(id);
17903 },
17904 get(id) {
17905 onUse();
17906 return pluginCache.get(id);
17907 },
17908 set(id, value) {
17909 onUse();
17910 return pluginCache.set(id, value);
17911 },
17912 delete(id) {
17913 onUse();
17914 return pluginCache.delete(id);
17915 }
17916 };
17917}
17918const NO_CACHE = {
17919 has() {
17920 return false;
17921 },
17922 get() {
17923 return undefined;
17924 },
17925 set() { },
17926 delete() {
17927 return false;
17928 }
17929};
17930function uncacheablePluginError(pluginName) {
17931 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
17932 pluginName.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX)) {
17933 return error({
17934 code: 'ANONYMOUS_PLUGIN_CACHE',
17935 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
17936 });
17937 }
17938 return error({
17939 code: 'DUPLICATE_PLUGIN_NAME',
17940 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).`
17941 });
17942}
17943function getCacheForUncacheablePlugin(pluginName) {
17944 return {
17945 has() {
17946 return uncacheablePluginError(pluginName);
17947 },
17948 get() {
17949 return uncacheablePluginError(pluginName);
17950 },
17951 set() {
17952 return uncacheablePluginError(pluginName);
17953 },
17954 delete() {
17955 return uncacheablePluginError(pluginName);
17956 }
17957 };
17958}
17959
17960function transform(source, module, pluginDriver, warn) {
17961 const id = module.id;
17962 const sourcemapChain = [];
17963 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
17964 const originalCode = source.code;
17965 let ast = source.ast;
17966 const transformDependencies = [];
17967 const emittedFiles = [];
17968 let customTransformCache = false;
17969 const useCustomTransformCache = () => (customTransformCache = true);
17970 let curPlugin;
17971 const curSource = source.code;
17972 function transformReducer(previousCode, result, plugin) {
17973 let code;
17974 let map;
17975 if (typeof result === 'string') {
17976 code = result;
17977 }
17978 else if (result && typeof result === 'object') {
17979 module.updateOptions(result);
17980 if (result.code == null) {
17981 if (result.map || result.ast) {
17982 warn(errNoTransformMapOrAstWithoutCode(plugin.name));
17983 }
17984 return previousCode;
17985 }
17986 ({ code, map, ast } = result);
17987 }
17988 else {
17989 return previousCode;
17990 }
17991 // strict null check allows 'null' maps to not be pushed to the chain,
17992 // while 'undefined' gets the missing map warning
17993 if (map !== null) {
17994 sourcemapChain.push(decodedSourcemap(typeof map === 'string' ? JSON.parse(map) : map) || {
17995 missing: true,
17996 plugin: plugin.name
17997 });
17998 }
17999 return code;
18000 }
18001 return pluginDriver
18002 .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
18003 curPlugin = plugin;
18004 return {
18005 ...pluginContext,
18006 cache: customTransformCache
18007 ? pluginContext.cache
18008 : getTrackedPluginCache(pluginContext.cache, useCustomTransformCache),
18009 warn(warning, pos) {
18010 if (typeof warning === 'string')
18011 warning = { message: warning };
18012 if (pos)
18013 augmentCodeLocation(warning, pos, curSource, id);
18014 warning.id = id;
18015 warning.hook = 'transform';
18016 pluginContext.warn(warning);
18017 },
18018 error(err, pos) {
18019 if (typeof err === 'string')
18020 err = { message: err };
18021 if (pos)
18022 augmentCodeLocation(err, pos, curSource, id);
18023 err.id = id;
18024 err.hook = 'transform';
18025 return pluginContext.error(err);
18026 },
18027 emitAsset(name, source) {
18028 emittedFiles.push({ type: 'asset', name, source });
18029 return pluginContext.emitAsset(name, source);
18030 },
18031 emitChunk(id, options) {
18032 emittedFiles.push({ type: 'chunk', id, name: options && options.name });
18033 return pluginContext.emitChunk(id, options);
18034 },
18035 emitFile(emittedFile) {
18036 emittedFiles.push(emittedFile);
18037 return pluginDriver.emitFile(emittedFile);
18038 },
18039 addWatchFile(id) {
18040 transformDependencies.push(id);
18041 pluginContext.addWatchFile(id);
18042 },
18043 setAssetSource() {
18044 return this.error({
18045 code: 'INVALID_SETASSETSOURCE',
18046 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
18047 });
18048 },
18049 getCombinedSourcemap() {
18050 const combinedMap = collapseSourcemap(id, originalCode, originalSourcemap, sourcemapChain, warn);
18051 if (!combinedMap) {
18052 const magicString = new MagicString(originalCode);
18053 return magicString.generateMap({ includeContent: true, hires: true, source: id });
18054 }
18055 if (originalSourcemap !== combinedMap) {
18056 originalSourcemap = combinedMap;
18057 sourcemapChain.length = 0;
18058 }
18059 return new SourceMap({
18060 ...combinedMap,
18061 file: null,
18062 sourcesContent: combinedMap.sourcesContent
18063 });
18064 }
18065 };
18066 })
18067 .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
18068 .then(code => {
18069 if (!customTransformCache) {
18070 // files emitted by a transform hook need to be emitted again if the hook is skipped
18071 if (emittedFiles.length)
18072 module.transformFiles = emittedFiles;
18073 }
18074 return {
18075 ast,
18076 code,
18077 customTransformCache,
18078 meta: module.info.meta,
18079 originalCode,
18080 originalSourcemap,
18081 sourcemapChain,
18082 transformDependencies
18083 };
18084 });
18085}
18086
18087class ModuleLoader {
18088 constructor(graph, modulesById, options, pluginDriver) {
18089 this.graph = graph;
18090 this.modulesById = modulesById;
18091 this.options = options;
18092 this.pluginDriver = pluginDriver;
18093 this.implicitEntryModules = new Set();
18094 this.indexedEntryModules = [];
18095 this.latestLoadModulesPromise = Promise.resolve();
18096 this.nextEntryModuleIndex = 0;
18097 this.hasModuleSideEffects = options.treeshake
18098 ? options.treeshake.moduleSideEffects
18099 : () => true;
18100 }
18101 async addAdditionalModules(unresolvedModules) {
18102 const result = this.extendLoadModulesPromise(Promise.all(unresolvedModules.map(id => this.loadEntryModule(id, false, undefined, null))));
18103 await this.awaitLoadModulesPromise();
18104 return result;
18105 }
18106 async addEntryModules(unresolvedEntryModules, isUserDefined) {
18107 const firstEntryModuleIndex = this.nextEntryModuleIndex;
18108 this.nextEntryModuleIndex += unresolvedEntryModules.length;
18109 const newEntryModules = await this.extendLoadModulesPromise(Promise.all(unresolvedEntryModules.map(({ id, importer }) => this.loadEntryModule(id, true, importer, null))).then(entryModules => {
18110 let moduleIndex = firstEntryModuleIndex;
18111 for (let index = 0; index < entryModules.length; index++) {
18112 const entryModule = entryModules[index];
18113 entryModule.isUserDefinedEntryPoint =
18114 entryModule.isUserDefinedEntryPoint || isUserDefined;
18115 addChunkNamesToModule(entryModule, unresolvedEntryModules[index], isUserDefined);
18116 const existingIndexedModule = this.indexedEntryModules.find(indexedModule => indexedModule.module === entryModule);
18117 if (!existingIndexedModule) {
18118 this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
18119 }
18120 else {
18121 existingIndexedModule.index = Math.min(existingIndexedModule.index, moduleIndex);
18122 }
18123 moduleIndex++;
18124 }
18125 this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
18126 return entryModules;
18127 }));
18128 await this.awaitLoadModulesPromise();
18129 return {
18130 entryModules: this.indexedEntryModules.map(({ module }) => module),
18131 implicitEntryModules: [...this.implicitEntryModules],
18132 newEntryModules
18133 };
18134 }
18135 async emitChunk({ fileName, id, importer, name, implicitlyLoadedAfterOneOf, preserveSignature }) {
18136 const unresolvedModule = {
18137 fileName: fileName || null,
18138 id,
18139 importer,
18140 name: name || null
18141 };
18142 const module = implicitlyLoadedAfterOneOf
18143 ? await this.addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfterOneOf)
18144 : (await this.addEntryModules([unresolvedModule], false)).newEntryModules[0];
18145 if (preserveSignature != null) {
18146 module.preserveSignature = preserveSignature;
18147 }
18148 return module;
18149 }
18150 async resolveId(source, importer, customOptions, skip = null) {
18151 return this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(this.options.external(source, importer, false)
18152 ? false
18153 : await resolveId(source, importer, this.options.preserveSymlinks, this.pluginDriver, skip, customOptions), importer, source));
18154 }
18155 addDefaultsToResolvedId(resolvedId) {
18156 var _a, _b;
18157 if (!resolvedId) {
18158 return null;
18159 }
18160 const external = resolvedId.external || false;
18161 return {
18162 external,
18163 id: resolvedId.id,
18164 meta: resolvedId.meta || EMPTY_OBJECT,
18165 moduleSideEffects: (_a = resolvedId.moduleSideEffects) !== null && _a !== void 0 ? _a : this.hasModuleSideEffects(resolvedId.id, external),
18166 syntheticNamedExports: (_b = resolvedId.syntheticNamedExports) !== null && _b !== void 0 ? _b : false
18167 };
18168 }
18169 addEntryWithImplicitDependants(unresolvedModule, implicitlyLoadedAfter) {
18170 return this.extendLoadModulesPromise(this.loadEntryModule(unresolvedModule.id, false, unresolvedModule.importer, null).then(async (entryModule) => {
18171 addChunkNamesToModule(entryModule, unresolvedModule, false);
18172 if (!entryModule.info.isEntry) {
18173 this.implicitEntryModules.add(entryModule);
18174 const implicitlyLoadedAfterModules = await Promise.all(implicitlyLoadedAfter.map(id => this.loadEntryModule(id, false, unresolvedModule.importer, entryModule.id)));
18175 for (const module of implicitlyLoadedAfterModules) {
18176 entryModule.implicitlyLoadedAfter.add(module);
18177 }
18178 for (const dependant of entryModule.implicitlyLoadedAfter) {
18179 dependant.implicitlyLoadedBefore.add(entryModule);
18180 }
18181 }
18182 return entryModule;
18183 }));
18184 }
18185 async addModuleSource(id, importer, module) {
18186 var _a;
18187 timeStart('load modules', 3);
18188 let source;
18189 try {
18190 source = (_a = (await this.pluginDriver.hookFirst('load', [id]))) !== null && _a !== void 0 ? _a : (await readFile(id));
18191 }
18192 catch (err) {
18193 timeEnd('load modules', 3);
18194 let msg = `Could not load ${id}`;
18195 if (importer)
18196 msg += ` (imported by ${relativeId(importer)})`;
18197 msg += `: ${err.message}`;
18198 err.message = msg;
18199 throw err;
18200 }
18201 timeEnd('load modules', 3);
18202 const sourceDescription = typeof source === 'string'
18203 ? { code: source }
18204 : typeof source === 'object' && typeof source.code === 'string'
18205 ? source
18206 : error(errBadLoader(id));
18207 const cachedModule = this.graph.cachedModules.get(id);
18208 if (cachedModule &&
18209 !cachedModule.customTransformCache &&
18210 cachedModule.originalCode === sourceDescription.code) {
18211 if (cachedModule.transformFiles) {
18212 for (const emittedFile of cachedModule.transformFiles)
18213 this.pluginDriver.emitFile(emittedFile);
18214 }
18215 module.setSource(cachedModule);
18216 }
18217 else {
18218 module.updateOptions(sourceDescription);
18219 module.setSource(await transform(sourceDescription, module, this.pluginDriver, this.options.onwarn));
18220 }
18221 }
18222 async awaitLoadModulesPromise() {
18223 let startingPromise;
18224 do {
18225 startingPromise = this.latestLoadModulesPromise;
18226 await startingPromise;
18227 } while (startingPromise !== this.latestLoadModulesPromise);
18228 }
18229 extendLoadModulesPromise(loadNewModulesPromise) {
18230 this.latestLoadModulesPromise = Promise.all([
18231 loadNewModulesPromise,
18232 this.latestLoadModulesPromise
18233 ]);
18234 this.latestLoadModulesPromise.catch(() => {
18235 /* Avoid unhandled Promise rejections */
18236 });
18237 return loadNewModulesPromise;
18238 }
18239 async fetchDynamicDependencies(module) {
18240 const dependencies = await Promise.all(module.dynamicImports.map(async (dynamicImport) => {
18241 const resolvedId = await this.resolveDynamicImport(module, typeof dynamicImport.argument === 'string'
18242 ? dynamicImport.argument
18243 : dynamicImport.argument.esTreeNode, module.id);
18244 if (resolvedId === null)
18245 return null;
18246 if (typeof resolvedId === 'string') {
18247 dynamicImport.resolution = resolvedId;
18248 return null;
18249 }
18250 return (dynamicImport.resolution = await this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId));
18251 }));
18252 for (const dependency of dependencies) {
18253 if (dependency) {
18254 module.dynamicDependencies.add(dependency);
18255 dependency.dynamicImporters.push(module.id);
18256 }
18257 }
18258 }
18259 async fetchModule({ id, meta, moduleSideEffects, syntheticNamedExports }, importer, isEntry) {
18260 const existingModule = this.modulesById.get(id);
18261 if (existingModule instanceof Module) {
18262 if (isEntry) {
18263 existingModule.info.isEntry = true;
18264 this.implicitEntryModules.delete(existingModule);
18265 for (const dependant of existingModule.implicitlyLoadedAfter) {
18266 dependant.implicitlyLoadedBefore.delete(existingModule);
18267 }
18268 existingModule.implicitlyLoadedAfter.clear();
18269 }
18270 return existingModule;
18271 }
18272 const module = new Module(this.graph, id, this.options, isEntry, moduleSideEffects, syntheticNamedExports, meta);
18273 this.modulesById.set(id, module);
18274 this.graph.watchFiles[id] = true;
18275 await this.addModuleSource(id, importer, module);
18276 await this.pluginDriver.hookParallel('moduleParsed', [module.info]);
18277 await Promise.all([
18278 this.fetchStaticDependencies(module),
18279 this.fetchDynamicDependencies(module)
18280 ]);
18281 module.linkImports();
18282 return module;
18283 }
18284 fetchResolvedDependency(source, importer, resolvedId) {
18285 if (resolvedId.external) {
18286 if (!this.modulesById.has(resolvedId.id)) {
18287 this.modulesById.set(resolvedId.id, new ExternalModule(this.options, resolvedId.id, resolvedId.moduleSideEffects, resolvedId.meta));
18288 }
18289 const externalModule = this.modulesById.get(resolvedId.id);
18290 if (!(externalModule instanceof ExternalModule)) {
18291 return error(errInternalIdCannotBeExternal(source, importer));
18292 }
18293 return Promise.resolve(externalModule);
18294 }
18295 else {
18296 return this.fetchModule(resolvedId, importer, false);
18297 }
18298 }
18299 async fetchStaticDependencies(module) {
18300 for (const dependency of await Promise.all(Array.from(module.sources, async (source) => this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
18301 module.resolvedIds[source] ||
18302 this.handleResolveId(await this.resolveId(source, module.id, EMPTY_OBJECT), source, module.id)))))) {
18303 module.dependencies.add(dependency);
18304 dependency.importers.push(module.id);
18305 }
18306 }
18307 getNormalizedResolvedIdWithoutDefaults(resolveIdResult, importer, source) {
18308 if (resolveIdResult) {
18309 if (typeof resolveIdResult === 'object') {
18310 return {
18311 ...resolveIdResult,
18312 external: resolveIdResult.external || this.options.external(resolveIdResult.id, importer, true)
18313 };
18314 }
18315 const external = this.options.external(resolveIdResult, importer, true);
18316 return {
18317 external,
18318 id: external ? normalizeRelativeExternalId(resolveIdResult, importer) : resolveIdResult
18319 };
18320 }
18321 const id = normalizeRelativeExternalId(source, importer);
18322 if (resolveIdResult !== false && !this.options.external(id, importer, true)) {
18323 return null;
18324 }
18325 return {
18326 external: true,
18327 id
18328 };
18329 }
18330 handleResolveId(resolvedId, source, importer) {
18331 if (resolvedId === null) {
18332 if (isRelative(source)) {
18333 return error(errUnresolvedImport(source, importer));
18334 }
18335 this.options.onwarn(errUnresolvedImportTreatedAsExternal(source, importer));
18336 return {
18337 external: true,
18338 id: source,
18339 meta: EMPTY_OBJECT,
18340 moduleSideEffects: this.hasModuleSideEffects(source, true),
18341 syntheticNamedExports: false
18342 };
18343 }
18344 else {
18345 if (resolvedId.external && resolvedId.syntheticNamedExports) {
18346 this.options.onwarn(errExternalSyntheticExports(source, importer));
18347 }
18348 }
18349 return resolvedId;
18350 }
18351 async loadEntryModule(unresolvedId, isEntry, importer, implicitlyLoadedBefore) {
18352 const resolveIdResult = await resolveId(unresolvedId, importer, this.options.preserveSymlinks, this.pluginDriver, null, EMPTY_OBJECT);
18353 if (resolveIdResult == null) {
18354 return error(implicitlyLoadedBefore === null
18355 ? errUnresolvedEntry(unresolvedId)
18356 : errUnresolvedImplicitDependant(unresolvedId, implicitlyLoadedBefore));
18357 }
18358 if (resolveIdResult === false ||
18359 (typeof resolveIdResult === 'object' && resolveIdResult.external)) {
18360 return error(implicitlyLoadedBefore === null
18361 ? errEntryCannotBeExternal(unresolvedId)
18362 : errImplicitDependantCannotBeExternal(unresolvedId, implicitlyLoadedBefore));
18363 }
18364 return this.fetchModule(this.addDefaultsToResolvedId(typeof resolveIdResult === 'object' ? resolveIdResult : { id: resolveIdResult }), undefined, isEntry);
18365 }
18366 async resolveDynamicImport(module, specifier, importer) {
18367 const resolution = await this.pluginDriver.hookFirst('resolveDynamicImport', [
18368 specifier,
18369 importer
18370 ]);
18371 if (typeof specifier !== 'string') {
18372 if (typeof resolution === 'string') {
18373 return resolution;
18374 }
18375 if (!resolution) {
18376 return null;
18377 }
18378 return {
18379 external: false,
18380 moduleSideEffects: true,
18381 ...resolution
18382 };
18383 }
18384 if (resolution == null) {
18385 return (module.resolvedIds[specifier] =
18386 module.resolvedIds[specifier] ||
18387 this.handleResolveId(await this.resolveId(specifier, module.id, EMPTY_OBJECT), specifier, module.id));
18388 }
18389 return this.handleResolveId(this.addDefaultsToResolvedId(this.getNormalizedResolvedIdWithoutDefaults(resolution, importer, specifier)), specifier, importer);
18390 }
18391}
18392function normalizeRelativeExternalId(source, importer) {
18393 return isRelative(source)
18394 ? importer
18395 ? resolve(importer, '..', source)
18396 : resolve(source)
18397 : source;
18398}
18399function addChunkNamesToModule(module, { fileName, name }, isUserDefined) {
18400 if (fileName !== null) {
18401 module.chunkFileNames.add(fileName);
18402 }
18403 else if (name !== null) {
18404 if (module.chunkName === null) {
18405 module.chunkName = name;
18406 }
18407 if (isUserDefined) {
18408 module.userChunkNames.add(name);
18409 }
18410 }
18411}
18412
18413function getDeprecatedContextHandler(handler, handlerName, newHandlerName, pluginName, activeDeprecation, options) {
18414 let deprecationWarningShown = false;
18415 return ((...args) => {
18416 if (!deprecationWarningShown) {
18417 deprecationWarningShown = true;
18418 warnDeprecation({
18419 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
18420 plugin: pluginName
18421 }, activeDeprecation, options);
18422 }
18423 return handler(...args);
18424 });
18425}
18426function getPluginContexts(pluginCache, graph, options, fileEmitter) {
18427 const existingPluginNames = new Set();
18428 return (plugin, pidx) => {
18429 let cacheable = true;
18430 if (typeof plugin.cacheKey !== 'string') {
18431 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) ||
18432 plugin.name.startsWith(ANONYMOUS_OUTPUT_PLUGIN_PREFIX) ||
18433 existingPluginNames.has(plugin.name)) {
18434 cacheable = false;
18435 }
18436 else {
18437 existingPluginNames.add(plugin.name);
18438 }
18439 }
18440 let cacheInstance;
18441 if (!pluginCache) {
18442 cacheInstance = NO_CACHE;
18443 }
18444 else if (cacheable) {
18445 const cacheKey = plugin.cacheKey || plugin.name;
18446 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
18447 }
18448 else {
18449 cacheInstance = getCacheForUncacheablePlugin(plugin.name);
18450 }
18451 const context = {
18452 addWatchFile(id) {
18453 if (graph.phase >= BuildPhase.GENERATE) {
18454 return this.error(errInvalidRollupPhaseForAddWatchFile());
18455 }
18456 graph.watchFiles[id] = true;
18457 },
18458 cache: cacheInstance,
18459 emitAsset: getDeprecatedContextHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, true, options),
18460 emitChunk: getDeprecatedContextHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, true, options),
18461 emitFile: fileEmitter.emitFile,
18462 error(err) {
18463 return throwPluginError(err, plugin.name);
18464 },
18465 getAssetFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, true, options),
18466 getChunkFileName: getDeprecatedContextHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, true, options),
18467 getFileName: fileEmitter.getFileName,
18468 getModuleIds: () => graph.modulesById.keys(),
18469 getModuleInfo: graph.getModuleInfo,
18470 getWatchFiles: () => Object.keys(graph.watchFiles),
18471 isExternal: getDeprecatedContextHandler((id, parentId, isResolved = false) => options.external(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, true, options),
18472 meta: {
18473 rollupVersion: version,
18474 watchMode: graph.watchMode
18475 },
18476 get moduleIds() {
18477 function* wrappedModuleIds() {
18478 warnDeprecation({
18479 message: `Accessing "this.moduleIds" on the plugin context by plugin ${plugin.name} is deprecated. The "this.getModuleIds" plugin context function should be used instead.`,
18480 plugin: plugin.name
18481 }, false, options);
18482 yield* moduleIds;
18483 }
18484 const moduleIds = graph.modulesById.keys();
18485 return wrappedModuleIds();
18486 },
18487 parse: graph.contextParse,
18488 resolve(source, importer, { custom, skipSelf } = BLANK) {
18489 return graph.moduleLoader.resolveId(source, importer, custom, skipSelf ? pidx : null);
18490 },
18491 resolveId: getDeprecatedContextHandler((source, importer) => graph.moduleLoader
18492 .resolveId(source, importer, BLANK)
18493 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, true, options),
18494 setAssetSource: fileEmitter.setAssetSource,
18495 warn(warning) {
18496 if (typeof warning === 'string')
18497 warning = { message: warning };
18498 if (warning.code)
18499 warning.pluginCode = warning.code;
18500 warning.code = 'PLUGIN_WARNING';
18501 warning.plugin = plugin.name;
18502 options.onwarn(warning);
18503 }
18504 };
18505 return context;
18506 };
18507}
18508
18509const inputHookNames = {
18510 buildEnd: 1,
18511 buildStart: 1,
18512 closeWatcher: 1,
18513 load: 1,
18514 moduleParsed: 1,
18515 options: 1,
18516 resolveDynamicImport: 1,
18517 resolveId: 1,
18518 transform: 1,
18519 watchChange: 1
18520};
18521const inputHooks = Object.keys(inputHookNames);
18522function throwInvalidHookError(hookName, pluginName) {
18523 return error({
18524 code: 'INVALID_PLUGIN_HOOK',
18525 message: `Error running plugin hook ${hookName} for ${pluginName}, expected a function hook.`
18526 });
18527}
18528class PluginDriver {
18529 constructor(graph, options, userPlugins, pluginCache, basePluginDriver) {
18530 this.graph = graph;
18531 this.options = options;
18532 warnDeprecatedHooks(userPlugins, options);
18533 this.pluginCache = pluginCache;
18534 this.fileEmitter = new FileEmitter(graph, options, basePluginDriver && basePluginDriver.fileEmitter);
18535 this.emitFile = this.fileEmitter.emitFile;
18536 this.getFileName = this.fileEmitter.getFileName;
18537 this.finaliseAssets = this.fileEmitter.assertAssetsFinalized;
18538 this.setOutputBundle = this.fileEmitter.setOutputBundle;
18539 this.plugins = userPlugins.concat(basePluginDriver ? basePluginDriver.plugins : []);
18540 this.pluginContexts = this.plugins.map(getPluginContexts(pluginCache, graph, options, this.fileEmitter));
18541 if (basePluginDriver) {
18542 for (const plugin of userPlugins) {
18543 for (const hook of inputHooks) {
18544 if (hook in plugin) {
18545 options.onwarn(errInputHookInOutputPlugin(plugin.name, hook));
18546 }
18547 }
18548 }
18549 }
18550 }
18551 createOutputPluginDriver(plugins) {
18552 return new PluginDriver(this.graph, this.options, plugins, this.pluginCache, this);
18553 }
18554 // chains, first non-null result stops and returns
18555 hookFirst(hookName, args, replaceContext, skip) {
18556 let promise = Promise.resolve(undefined);
18557 for (let i = 0; i < this.plugins.length; i++) {
18558 if (skip === i)
18559 continue;
18560 promise = promise.then(result => {
18561 if (result != null)
18562 return result;
18563 return this.runHook(hookName, args, i, false, replaceContext);
18564 });
18565 }
18566 return promise;
18567 }
18568 // chains synchronously, first non-null result stops and returns
18569 hookFirstSync(hookName, args, replaceContext) {
18570 for (let i = 0; i < this.plugins.length; i++) {
18571 const result = this.runHookSync(hookName, args, i, replaceContext);
18572 if (result != null)
18573 return result;
18574 }
18575 return null;
18576 }
18577 // parallel, ignores returns
18578 hookParallel(hookName, args, replaceContext) {
18579 const promises = [];
18580 for (let i = 0; i < this.plugins.length; i++) {
18581 const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
18582 if (!hookPromise)
18583 continue;
18584 promises.push(hookPromise);
18585 }
18586 return Promise.all(promises).then(() => { });
18587 }
18588 // chains, reduces returned value, handling the reduced value as the first hook argument
18589 hookReduceArg0(hookName, [arg0, ...rest], reduce, replaceContext) {
18590 let promise = Promise.resolve(arg0);
18591 for (let i = 0; i < this.plugins.length; i++) {
18592 promise = promise.then(arg0 => {
18593 const args = [arg0, ...rest];
18594 const hookPromise = this.runHook(hookName, args, i, false, replaceContext);
18595 if (!hookPromise)
18596 return arg0;
18597 return hookPromise.then(result => reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]));
18598 });
18599 }
18600 return promise;
18601 }
18602 // chains synchronously, reduces returned value, handling the reduced value as the first hook argument
18603 hookReduceArg0Sync(hookName, [arg0, ...rest], reduce, replaceContext) {
18604 for (let i = 0; i < this.plugins.length; i++) {
18605 const args = [arg0, ...rest];
18606 const result = this.runHookSync(hookName, args, i, replaceContext);
18607 arg0 = reduce.call(this.pluginContexts[i], arg0, result, this.plugins[i]);
18608 }
18609 return arg0;
18610 }
18611 // chains, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
18612 hookReduceValue(hookName, initialValue, args, reduce, replaceContext) {
18613 let promise = Promise.resolve(initialValue);
18614 for (let i = 0; i < this.plugins.length; i++) {
18615 promise = promise.then(value => {
18616 const hookPromise = this.runHook(hookName, args, i, true, replaceContext);
18617 if (!hookPromise)
18618 return value;
18619 return hookPromise.then(result => reduce.call(this.pluginContexts[i], value, result, this.plugins[i]));
18620 });
18621 }
18622 return promise;
18623 }
18624 // chains synchronously, reduces returned value to type T, handling the reduced value separately. permits hooks as values.
18625 hookReduceValueSync(hookName, initialValue, args, reduce, replaceContext) {
18626 let acc = initialValue;
18627 for (let i = 0; i < this.plugins.length; i++) {
18628 const result = this.runHookSync(hookName, args, i, replaceContext);
18629 acc = reduce.call(this.pluginContexts[i], acc, result, this.plugins[i]);
18630 }
18631 return acc;
18632 }
18633 // chains, ignores returns
18634 hookSeq(hookName, args, replaceContext) {
18635 let promise = Promise.resolve();
18636 for (let i = 0; i < this.plugins.length; i++) {
18637 promise = promise.then(() => this.runHook(hookName, args, i, false, replaceContext));
18638 }
18639 return promise;
18640 }
18641 // chains synchronously, ignores returns
18642 hookSeqSync(hookName, args, replaceContext) {
18643 for (let i = 0; i < this.plugins.length; i++) {
18644 this.runHookSync(hookName, args, i, replaceContext);
18645 }
18646 }
18647 runHook(hookName, args, pluginIndex, permitValues, hookContext) {
18648 const plugin = this.plugins[pluginIndex];
18649 const hook = plugin[hookName];
18650 if (!hook)
18651 return undefined;
18652 let context = this.pluginContexts[pluginIndex];
18653 if (hookContext) {
18654 context = hookContext(context, plugin);
18655 }
18656 return Promise.resolve()
18657 .then(() => {
18658 // permit values allows values to be returned instead of a functional hook
18659 if (typeof hook !== 'function') {
18660 if (permitValues)
18661 return hook;
18662 return throwInvalidHookError(hookName, plugin.name);
18663 }
18664 return hook.apply(context, args);
18665 })
18666 .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
18667 }
18668 /**
18669 * Run a sync plugin hook and return the result.
18670 * @param hookName Name of the plugin hook. Must be in `PluginHooks`.
18671 * @param args Arguments passed to the plugin hook.
18672 * @param pluginIndex Index of the plugin inside `this.plugins[]`.
18673 * @param hookContext When passed, the plugin context can be overridden.
18674 */
18675 runHookSync(hookName, args, pluginIndex, hookContext) {
18676 const plugin = this.plugins[pluginIndex];
18677 const hook = plugin[hookName];
18678 if (!hook)
18679 return undefined;
18680 let context = this.pluginContexts[pluginIndex];
18681 if (hookContext) {
18682 context = hookContext(context, plugin);
18683 }
18684 try {
18685 // permit values allows values to be returned instead of a functional hook
18686 if (typeof hook !== 'function') {
18687 return throwInvalidHookError(hookName, plugin.name);
18688 }
18689 return hook.apply(context, args);
18690 }
18691 catch (err) {
18692 return throwPluginError(err, plugin.name, { hook: hookName });
18693 }
18694 }
18695}
18696
18697function normalizeEntryModules(entryModules) {
18698 if (Array.isArray(entryModules)) {
18699 return entryModules.map(id => ({
18700 fileName: null,
18701 id,
18702 implicitlyLoadedAfter: [],
18703 importer: undefined,
18704 name: null
18705 }));
18706 }
18707 return Object.keys(entryModules).map(name => ({
18708 fileName: null,
18709 id: entryModules[name],
18710 implicitlyLoadedAfter: [],
18711 importer: undefined,
18712 name
18713 }));
18714}
18715class Graph {
18716 constructor(options, watcher) {
18717 var _a, _b;
18718 this.options = options;
18719 this.entryModules = [];
18720 this.modulesById = new Map();
18721 this.needsTreeshakingPass = false;
18722 this.phase = BuildPhase.LOAD_AND_PARSE;
18723 this.watchFiles = Object.create(null);
18724 this.watchMode = false;
18725 this.externalModules = [];
18726 this.implicitEntryModules = [];
18727 this.modules = [];
18728 this.getModuleInfo = (moduleId) => {
18729 const foundModule = this.modulesById.get(moduleId);
18730 if (!foundModule)
18731 return null;
18732 return foundModule.info;
18733 };
18734 this.deoptimizationTracker = new PathTracker();
18735 this.cachedModules = new Map();
18736 if (options.cache !== false) {
18737 if ((_a = options.cache) === null || _a === void 0 ? void 0 : _a.modules) {
18738 for (const module of options.cache.modules)
18739 this.cachedModules.set(module.id, module);
18740 }
18741 this.pluginCache = ((_b = options.cache) === null || _b === void 0 ? void 0 : _b.plugins) || Object.create(null);
18742 // increment access counter
18743 for (const name in this.pluginCache) {
18744 const cache = this.pluginCache[name];
18745 for (const key of Object.keys(cache))
18746 cache[key][0]++;
18747 }
18748 }
18749 this.contextParse = (code, options = {}) => this.acornParser.parse(code, {
18750 ...this.options.acorn,
18751 ...options
18752 });
18753 if (watcher) {
18754 this.watchMode = true;
18755 const handleChange = (...args) => this.pluginDriver.hookSeqSync('watchChange', args);
18756 const handleClose = () => this.pluginDriver.hookSeqSync('closeWatcher', []);
18757 watcher.on('change', handleChange);
18758 watcher.on('close', handleClose);
18759 watcher.once('restart', () => {
18760 watcher.removeListener('change', handleChange);
18761 watcher.removeListener('close', handleClose);
18762 });
18763 }
18764 this.pluginDriver = new PluginDriver(this, options, options.plugins, this.pluginCache);
18765 this.scope = new GlobalScope();
18766 this.acornParser = Parser.extend(...options.acornInjectPlugins);
18767 this.moduleLoader = new ModuleLoader(this, this.modulesById, this.options, this.pluginDriver);
18768 }
18769 async build() {
18770 timeStart('generate module graph', 2);
18771 await this.generateModuleGraph();
18772 timeEnd('generate module graph', 2);
18773 timeStart('sort modules', 2);
18774 this.phase = BuildPhase.ANALYSE;
18775 this.sortModules();
18776 timeEnd('sort modules', 2);
18777 timeStart('mark included statements', 2);
18778 this.includeStatements();
18779 timeEnd('mark included statements', 2);
18780 this.phase = BuildPhase.GENERATE;
18781 }
18782 getCache() {
18783 // handle plugin cache eviction
18784 for (const name in this.pluginCache) {
18785 const cache = this.pluginCache[name];
18786 let allDeleted = true;
18787 for (const key of Object.keys(cache)) {
18788 if (cache[key][0] >= this.options.experimentalCacheExpiry)
18789 delete cache[key];
18790 else
18791 allDeleted = false;
18792 }
18793 if (allDeleted)
18794 delete this.pluginCache[name];
18795 }
18796 return {
18797 modules: this.modules.map(module => module.toJSON()),
18798 plugins: this.pluginCache
18799 };
18800 }
18801 async generateModuleGraph() {
18802 ({
18803 entryModules: this.entryModules,
18804 implicitEntryModules: this.implicitEntryModules
18805 } = await this.moduleLoader.addEntryModules(normalizeEntryModules(this.options.input), true));
18806 if (this.entryModules.length === 0) {
18807 throw new Error('You must supply options.input to rollup');
18808 }
18809 for (const module of this.modulesById.values()) {
18810 if (module instanceof Module) {
18811 this.modules.push(module);
18812 }
18813 else {
18814 this.externalModules.push(module);
18815 }
18816 }
18817 }
18818 includeStatements() {
18819 for (const module of [...this.entryModules, ...this.implicitEntryModules]) {
18820 if (module.preserveSignature !== false) {
18821 module.includeAllExports(false);
18822 }
18823 else {
18824 markModuleAndImpureDependenciesAsExecuted(module);
18825 }
18826 }
18827 if (this.options.treeshake) {
18828 let treeshakingPass = 1;
18829 do {
18830 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
18831 this.needsTreeshakingPass = false;
18832 for (const module of this.modules) {
18833 if (module.isExecuted) {
18834 if (module.info.hasModuleSideEffects === 'no-treeshake') {
18835 module.includeAllInBundle();
18836 }
18837 else {
18838 module.include();
18839 }
18840 }
18841 }
18842 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
18843 } while (this.needsTreeshakingPass);
18844 }
18845 else {
18846 for (const module of this.modules)
18847 module.includeAllInBundle();
18848 }
18849 for (const externalModule of this.externalModules)
18850 externalModule.warnUnusedImports();
18851 for (const module of this.implicitEntryModules) {
18852 for (const dependant of module.implicitlyLoadedAfter) {
18853 if (!(dependant.info.isEntry || dependant.isIncluded())) {
18854 error(errImplicitDependantIsNotIncluded(dependant));
18855 }
18856 }
18857 }
18858 }
18859 sortModules() {
18860 const { orderedModules, cyclePaths } = analyseModuleExecution(this.entryModules);
18861 for (const cyclePath of cyclePaths) {
18862 this.options.onwarn({
18863 code: 'CIRCULAR_DEPENDENCY',
18864 cycle: cyclePath,
18865 importer: cyclePath[0],
18866 message: `Circular dependency: ${cyclePath.join(' -> ')}`
18867 });
18868 }
18869 this.modules = orderedModules;
18870 for (const module of this.modules) {
18871 module.bindReferences();
18872 }
18873 this.warnForMissingExports();
18874 }
18875 warnForMissingExports() {
18876 for (const module of this.modules) {
18877 for (const importName of Object.keys(module.importDescriptions)) {
18878 const importDescription = module.importDescriptions[importName];
18879 if (importDescription.name !== '*' &&
18880 !importDescription.module.getVariableForExportName(importDescription.name)) {
18881 module.warn({
18882 code: 'NON_EXISTENT_EXPORT',
18883 message: `Non-existent export '${importDescription.name}' is imported from ${relativeId(importDescription.module.id)}`,
18884 name: importDescription.name,
18885 source: importDescription.module.id
18886 }, importDescription.start);
18887 }
18888 }
18889 }
18890 }
18891}
18892
18893function ensureArray(items) {
18894 if (Array.isArray(items)) {
18895 return items.filter(Boolean);
18896 }
18897 if (items) {
18898 return [items];
18899 }
18900 return [];
18901}
18902
18903function createCommonjsModule(fn, basedir, module) {
18904 return module = {
18905 path: basedir,
18906 exports: {},
18907 require: function (path, base) {
18908 return commonjsRequire();
18909 }
18910 }, fn(module, module.exports), module.exports;
18911}
18912
18913function getAugmentedNamespace(n) {
18914 if (n.__esModule) return n;
18915 var a = Object.defineProperty({}, '__esModule', {value: true});
18916 Object.keys(n).forEach(function (k) {
18917 var d = Object.getOwnPropertyDescriptor(n, k);
18918 Object.defineProperty(a, k, d.get ? d : {
18919 enumerable: true,
18920 get: function () {
18921 return n[k];
18922 }
18923 });
18924 });
18925 return a;
18926}
18927
18928function commonjsRequire () {
18929 throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
18930}
18931
18932var require$$0 = /*@__PURE__*/getAugmentedNamespace(acorn);
18933
18934const getPrototype = Object.getPrototypeOf || (o => o.__proto__);
18935
18936const getAcorn = Parser => {
18937 if (Parser.acorn) return Parser.acorn
18938
18939 const acorn = require$$0;
18940
18941 if (acorn.version.indexOf("6.") != 0 && acorn.version.indexOf("6.0.") == 0 && acorn.version.indexOf("7.") != 0) {
18942 throw new Error(`acorn-private-class-elements requires acorn@^6.1.0 or acorn@7.0.0, not ${acorn.version}`)
18943 }
18944
18945 // Make sure `Parser` comes from the same acorn as we `require`d,
18946 // otherwise the comparisons fail.
18947 for (let cur = Parser; cur && cur !== acorn.Parser; cur = getPrototype(cur)) {
18948 if (cur !== acorn.Parser) {
18949 throw new Error("acorn-private-class-elements does not support mixing different acorn copies")
18950 }
18951 }
18952 return acorn
18953};
18954
18955var acornPrivateClassElements = function(Parser) {
18956 // Only load this plugin once.
18957 if (Parser.prototype.parsePrivateName) {
18958 return Parser
18959 }
18960
18961 const acorn = getAcorn(Parser);
18962
18963 Parser = class extends Parser {
18964 _branch() {
18965 this.__branch = this.__branch || new Parser({ecmaVersion: this.options.ecmaVersion}, this.input);
18966 this.__branch.end = this.end;
18967 this.__branch.pos = this.pos;
18968 this.__branch.type = this.type;
18969 this.__branch.value = this.value;
18970 this.__branch.containsEsc = this.containsEsc;
18971 return this.__branch
18972 }
18973
18974 parsePrivateClassElementName(element) {
18975 element.computed = false;
18976 element.key = this.parsePrivateName();
18977 if (element.key.name == "constructor") this.raise(element.key.start, "Classes may not have a private element named constructor");
18978 const accept = {get: "set", set: "get"}[element.kind];
18979 const privateBoundNames = this._privateBoundNames;
18980 if (Object.prototype.hasOwnProperty.call(privateBoundNames, element.key.name) && privateBoundNames[element.key.name] !== accept) {
18981 this.raise(element.start, "Duplicate private element");
18982 }
18983 privateBoundNames[element.key.name] = element.kind || true;
18984 delete this._unresolvedPrivateNames[element.key.name];
18985 return element.key
18986 }
18987
18988 parsePrivateName() {
18989 const node = this.startNode();
18990 node.name = this.value;
18991 this.next();
18992 this.finishNode(node, "PrivateName");
18993 if (this.options.allowReserved == "never") this.checkUnreserved(node);
18994 return node
18995 }
18996
18997 // Parse # token
18998 getTokenFromCode(code) {
18999 if (code === 35) {
19000 ++this.pos;
19001 const word = this.readWord1();
19002 return this.finishToken(this.privateNameToken, word)
19003 }
19004 return super.getTokenFromCode(code)
19005 }
19006
19007 // Manage stacks and check for undeclared private names
19008 parseClass(node, isStatement) {
19009 const oldOuterPrivateBoundNames = this._outerPrivateBoundNames;
19010 this._outerPrivateBoundNames = this._privateBoundNames;
19011 this._privateBoundNames = Object.create(this._privateBoundNames || null);
19012 const oldOuterUnresolvedPrivateNames = this._outerUnresolvedPrivateNames;
19013 this._outerUnresolvedPrivateNames = this._unresolvedPrivateNames;
19014 this._unresolvedPrivateNames = Object.create(null);
19015
19016 const _return = super.parseClass(node, isStatement);
19017
19018 const unresolvedPrivateNames = this._unresolvedPrivateNames;
19019 this._privateBoundNames = this._outerPrivateBoundNames;
19020 this._outerPrivateBoundNames = oldOuterPrivateBoundNames;
19021 this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
19022 this._outerUnresolvedPrivateNames = oldOuterUnresolvedPrivateNames;
19023 if (!this._unresolvedPrivateNames) {
19024 const names = Object.keys(unresolvedPrivateNames);
19025 if (names.length) {
19026 names.sort((n1, n2) => unresolvedPrivateNames[n1] - unresolvedPrivateNames[n2]);
19027 this.raise(unresolvedPrivateNames[names[0]], "Usage of undeclared private name");
19028 }
19029 } else Object.assign(this._unresolvedPrivateNames, unresolvedPrivateNames);
19030 return _return
19031 }
19032
19033 // Class heritage is evaluated with outer private environment
19034 parseClassSuper(node) {
19035 const privateBoundNames = this._privateBoundNames;
19036 this._privateBoundNames = this._outerPrivateBoundNames;
19037 const unresolvedPrivateNames = this._unresolvedPrivateNames;
19038 this._unresolvedPrivateNames = this._outerUnresolvedPrivateNames;
19039 const _return = super.parseClassSuper(node);
19040 this._privateBoundNames = privateBoundNames;
19041 this._unresolvedPrivateNames = unresolvedPrivateNames;
19042 return _return
19043 }
19044
19045 // Parse private element access
19046 parseSubscript(base, startPos, startLoc, _noCalls, _maybeAsyncArrow, _optionalChained) {
19047 const optionalSupported = this.options.ecmaVersion >= 11 && acorn.tokTypes.questionDot;
19048 const branch = this._branch();
19049 if (!(
19050 (branch.eat(acorn.tokTypes.dot) || (optionalSupported && branch.eat(acorn.tokTypes.questionDot))) &&
19051 branch.type == this.privateNameToken
19052 )) {
19053 return super.parseSubscript.apply(this, arguments)
19054 }
19055 let optional = false;
19056 if (!this.eat(acorn.tokTypes.dot)) {
19057 this.expect(acorn.tokTypes.questionDot);
19058 optional = true;
19059 }
19060 let node = this.startNodeAt(startPos, startLoc);
19061 node.object = base;
19062 node.computed = false;
19063 if (optionalSupported) {
19064 node.optional = optional;
19065 }
19066 if (this.type == this.privateNameToken) {
19067 if (base.type == "Super") {
19068 this.raise(this.start, "Cannot access private element on super");
19069 }
19070 node.property = this.parsePrivateName();
19071 if (!this._privateBoundNames || !this._privateBoundNames[node.property.name]) {
19072 if (!this._unresolvedPrivateNames) {
19073 this.raise(node.property.start, "Usage of undeclared private name");
19074 }
19075 this._unresolvedPrivateNames[node.property.name] = node.property.start;
19076 }
19077 } else {
19078 node.property = this.parseIdent(true);
19079 }
19080 return this.finishNode(node, "MemberExpression")
19081 }
19082
19083 // Prohibit delete of private class elements
19084 parseMaybeUnary(refDestructuringErrors, sawUnary) {
19085 const _return = super.parseMaybeUnary(refDestructuringErrors, sawUnary);
19086 if (_return.operator == "delete") {
19087 if (_return.argument.type == "MemberExpression" && _return.argument.property.type == "PrivateName") {
19088 this.raise(_return.start, "Private elements may not be deleted");
19089 }
19090 }
19091 return _return
19092 }
19093 };
19094 Parser.prototype.privateNameToken = new acorn.TokenType("privateName");
19095 return Parser
19096};
19097
19098var acornClassFields = function(Parser) {
19099 const acorn = Parser.acorn || require$$0;
19100 const tt = acorn.tokTypes;
19101
19102 Parser = acornPrivateClassElements(Parser);
19103 return class extends Parser {
19104 _maybeParseFieldValue(field) {
19105 if (this.eat(tt.eq)) {
19106 const oldInFieldValue = this._inFieldValue;
19107 this._inFieldValue = true;
19108 if (this.type === tt.name && this.value === "await" && (this.inAsync || this.options.allowAwaitOutsideFunction)) {
19109 field.value = this.parseAwait();
19110 } else field.value = this.parseExpression();
19111 this._inFieldValue = oldInFieldValue;
19112 } else field.value = null;
19113 }
19114
19115 // Parse fields
19116 parseClassElement(_constructorAllowsSuper) {
19117 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)) {
19118 const branch = this._branch();
19119 if (branch.type == tt.bracketL) {
19120 let count = 0;
19121 do {
19122 if (branch.eat(tt.bracketL)) ++count;
19123 else if (branch.eat(tt.bracketR)) --count;
19124 else branch.next();
19125 } while (count > 0)
19126 } else branch.next(true);
19127 let isField = branch.type == tt.eq || branch.type == tt.semi;
19128 if (!isField && branch.canInsertSemicolon()) {
19129 isField = branch.type != tt.parenL;
19130 }
19131 if (isField) {
19132 const node = this.startNode();
19133 if (this.type == this.privateNameToken) {
19134 this.parsePrivateClassElementName(node);
19135 } else {
19136 this.parsePropertyName(node);
19137 }
19138 if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
19139 (node.key.type === "Literal" && node.key.value === "constructor")) {
19140 this.raise(node.key.start, "Classes may not have a field called constructor");
19141 }
19142 this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
19143 this._maybeParseFieldValue(node);
19144 this.exitScope();
19145 this.finishNode(node, "FieldDefinition");
19146 this.semicolon();
19147 return node
19148 }
19149 }
19150
19151 return super.parseClassElement.apply(this, arguments)
19152 }
19153
19154 // Prohibit arguments in class field initializers
19155 parseIdent(liberal, isBinding) {
19156 const ident = super.parseIdent(liberal, isBinding);
19157 if (this._inFieldValue && ident.name == "arguments") this.raise(ident.start, "A class field initializer may not contain arguments");
19158 return ident
19159 }
19160 }
19161};
19162
19163function withoutAcornBigInt(acorn, Parser) {
19164 return class extends Parser {
19165 readInt(radix, len) {
19166 // Hack: len is only != null for unicode escape sequences,
19167 // where numeric separators are not allowed
19168 if (len != null) return super.readInt(radix, len)
19169
19170 let start = this.pos, total = 0, acceptUnderscore = false;
19171 for (;;) {
19172 let code = this.input.charCodeAt(this.pos), val;
19173 if (code >= 97) val = code - 97 + 10; // a
19174 else if (code == 95) {
19175 if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
19176 ++this.pos;
19177 acceptUnderscore = false;
19178 continue
19179 } else if (code >= 65) val = code - 65 + 10; // A
19180 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
19181 else val = Infinity;
19182 if (val >= radix) break
19183 ++this.pos;
19184 total = total * radix + val;
19185 acceptUnderscore = true;
19186 }
19187 if (this.pos === start) return null
19188 if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
19189
19190 return total
19191 }
19192
19193 readNumber(startsWithDot) {
19194 const token = super.readNumber(startsWithDot);
19195 let octal = this.end - this.start >= 2 && this.input.charCodeAt(this.start) === 48;
19196 const stripped = this.getNumberInput(this.start, this.end);
19197 if (stripped.length < this.end - this.start) {
19198 if (octal) this.raise(this.start, "Invalid number");
19199 this.value = parseFloat(stripped);
19200 }
19201 return token
19202 }
19203
19204 // This is used by acorn-bigint
19205 getNumberInput(start, end) {
19206 return this.input.slice(start, end).replace(/_/g, "")
19207 }
19208 }
19209}
19210
19211function withAcornBigInt(acorn, Parser) {
19212 return class extends Parser {
19213 readInt(radix, len) {
19214 // Hack: len is only != null for unicode escape sequences,
19215 // where numeric separators are not allowed
19216 if (len != null) return super.readInt(radix, len)
19217
19218 let start = this.pos, total = 0, acceptUnderscore = false;
19219 for (;;) {
19220 let code = this.input.charCodeAt(this.pos), val;
19221 if (code >= 97) val = code - 97 + 10; // a
19222 else if (code == 95) {
19223 if (!acceptUnderscore) this.raise(this.pos, "Invalid numeric separator");
19224 ++this.pos;
19225 acceptUnderscore = false;
19226 continue
19227 } else if (code >= 65) val = code - 65 + 10; // A
19228 else if (code >= 48 && code <= 57) val = code - 48; // 0-9
19229 else val = Infinity;
19230 if (val >= radix) break
19231 ++this.pos;
19232 total = total * radix + val;
19233 acceptUnderscore = true;
19234 }
19235 if (this.pos === start) return null
19236 if (!acceptUnderscore) this.raise(this.pos - 1, "Invalid numeric separator");
19237
19238 return total
19239 }
19240
19241 readNumber(startsWithDot) {
19242 let start = this.pos;
19243 if (!startsWithDot && this.readInt(10) === null) this.raise(start, "Invalid number");
19244 let octal = this.pos - start >= 2 && this.input.charCodeAt(start) === 48;
19245 let octalLike = false;
19246 if (octal && this.strict) this.raise(start, "Invalid number");
19247 let next = this.input.charCodeAt(this.pos);
19248 if (!octal && !startsWithDot && this.options.ecmaVersion >= 11 && next === 110) {
19249 let str = this.getNumberInput(start, this.pos);
19250 // eslint-disable-next-line node/no-unsupported-features/es-builtins
19251 let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
19252 ++this.pos;
19253 if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
19254 return this.finishToken(acorn.tokTypes.num, val)
19255 }
19256 if (octal && /[89]/.test(this.input.slice(start, this.pos))) {
19257 octal = false;
19258 octalLike = true;
19259 }
19260 if (next === 46 && !octal) { // '.'
19261 ++this.pos;
19262 this.readInt(10);
19263 next = this.input.charCodeAt(this.pos);
19264 }
19265 if ((next === 69 || next === 101) && !octal) { // 'eE'
19266 next = this.input.charCodeAt(++this.pos);
19267 if (next === 43 || next === 45) ++this.pos; // '+-'
19268 if (this.readInt(10) === null) this.raise(start, "Invalid number");
19269 }
19270 if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
19271 let str = this.getNumberInput(start, this.pos);
19272 if ((octal || octalLike) && str.length < this.pos - start) {
19273 this.raise(start, "Invalid number");
19274 }
19275
19276 let val = octal ? parseInt(str, 8) : parseFloat(str);
19277 return this.finishToken(acorn.tokTypes.num, val)
19278 }
19279
19280 parseLiteral(value) {
19281 const ret = super.parseLiteral(value);
19282 if (ret.bigint) ret.bigint = ret.bigint.replace(/_/g, "");
19283 return ret
19284 }
19285
19286 readRadixNumber(radix) {
19287 let start = this.pos;
19288 this.pos += 2; // 0x
19289 let val = this.readInt(radix);
19290 if (val == null) { this.raise(this.start + 2, `Expected number in radix ${radix}`); }
19291 if (this.options.ecmaVersion >= 11 && this.input.charCodeAt(this.pos) === 110) {
19292 let str = this.getNumberInput(start, this.pos);
19293 // eslint-disable-next-line node/no-unsupported-features/es-builtins
19294 val = typeof BigInt !== "undefined" ? BigInt(str) : null;
19295 ++this.pos;
19296 } else if (acorn.isIdentifierStart(this.fullCharCodeAtPos())) { this.raise(this.pos, "Identifier directly after number"); }
19297 return this.finishToken(acorn.tokTypes.num, val)
19298 }
19299
19300 // This is used by acorn-bigint, which theoretically could be used with acorn@6.2 || acorn@7
19301 getNumberInput(start, end) {
19302 return this.input.slice(start, end).replace(/_/g, "")
19303 }
19304 }
19305}
19306
19307// eslint-disable-next-line node/no-unsupported-features/es-syntax
19308function numericSeparator(Parser) {
19309 const acorn = Parser.acorn || require$$0;
19310 const withAcornBigIntSupport = (acorn.version.startsWith("6.") && !(acorn.version.startsWith("6.0.") || acorn.version.startsWith("6.1."))) || acorn.version.startsWith("7.");
19311
19312 return withAcornBigIntSupport ? withAcornBigInt(acorn, Parser) : withoutAcornBigInt(acorn, Parser)
19313}
19314
19315var acornNumericSeparator = numericSeparator;
19316
19317var acornStaticClassFeatures = function(Parser) {
19318 const ExtendedParser = acornPrivateClassElements(Parser);
19319
19320 const acorn = Parser.acorn || require$$0;
19321 const tt = acorn.tokTypes;
19322
19323 return class extends ExtendedParser {
19324 _maybeParseFieldValue(field) {
19325 if (this.eat(tt.eq)) {
19326 const oldInFieldValue = this._inStaticFieldScope;
19327 this._inStaticFieldScope = this.currentThisScope();
19328 field.value = this.parseExpression();
19329 this._inStaticFieldScope = oldInFieldValue;
19330 } else field.value = null;
19331 }
19332
19333 // Parse fields
19334 parseClassElement(_constructorAllowsSuper) {
19335 if (this.options.ecmaVersion < 8 || !this.isContextual("static")) {
19336 return super.parseClassElement.apply(this, arguments)
19337 }
19338
19339 const branch = this._branch();
19340 branch.next();
19341 if ([tt.name, tt.bracketL, tt.string, tt.num, this.privateNameToken].indexOf(branch.type) == -1 && !branch.type.keyword) {
19342 return super.parseClassElement.apply(this, arguments)
19343 }
19344 if (branch.type == tt.bracketL) {
19345 let count = 0;
19346 do {
19347 if (branch.eat(tt.bracketL)) ++count;
19348 else if (branch.eat(tt.bracketR)) --count;
19349 else branch.next();
19350 } while (count > 0)
19351 } else branch.next();
19352 if (branch.type != tt.eq && !branch.canInsertSemicolon() && branch.type != tt.semi) {
19353 return super.parseClassElement.apply(this, arguments)
19354 }
19355
19356 const node = this.startNode();
19357 node.static = this.eatContextual("static");
19358 if (this.type == this.privateNameToken) {
19359 this.parsePrivateClassElementName(node);
19360 } else {
19361 this.parsePropertyName(node);
19362 }
19363 if ((node.key.type === "Identifier" && node.key.name === "constructor") ||
19364 (node.key.type === "Literal" && !node.computed && node.key.value === "constructor")) {
19365 this.raise(node.key.start, "Classes may not have a field called constructor");
19366 }
19367 if ((node.key.name || node.key.value) === "prototype" && !node.computed) {
19368 this.raise(node.key.start, "Classes may not have a static property named prototype");
19369 }
19370
19371 this.enterScope(64 | 2 | 1); // See acorn's scopeflags.js
19372 this._maybeParseFieldValue(node);
19373 this.exitScope();
19374 this.finishNode(node, "FieldDefinition");
19375 this.semicolon();
19376 return node
19377 }
19378
19379 // Parse private static methods
19380 parsePropertyName(prop) {
19381 if (prop.static && this.type == this.privateNameToken) {
19382 this.parsePrivateClassElementName(prop);
19383 } else {
19384 super.parsePropertyName(prop);
19385 }
19386 }
19387
19388 // Prohibit arguments in class field initializers
19389 parseIdent(liberal, isBinding) {
19390 const ident = super.parseIdent(liberal, isBinding);
19391 if (this._inStaticFieldScope && this.currentThisScope() === this._inStaticFieldScope && ident.name == "arguments") {
19392 this.raise(ident.start, "A static class field initializer may not contain arguments");
19393 }
19394 return ident
19395 }
19396 }
19397};
19398
19399const defaultOnWarn = warning => console.warn(warning.message || warning);
19400function warnUnknownOptions(passedOptions, validOptions, optionType, warn, ignoredKeys = /$./) {
19401 const validOptionSet = new Set(validOptions);
19402 const unknownOptions = Object.keys(passedOptions).filter(key => !(validOptionSet.has(key) || ignoredKeys.test(key)));
19403 if (unknownOptions.length > 0) {
19404 warn({
19405 code: 'UNKNOWN_OPTION',
19406 message: `Unknown ${optionType}: ${unknownOptions.join(', ')}. Allowed options: ${[
19407 ...validOptionSet
19408 ]
19409 .sort()
19410 .join(', ')}`
19411 });
19412 }
19413}
19414
19415function normalizeInputOptions(config) {
19416 var _a, _b;
19417 // These are options that may trigger special warnings or behaviour later
19418 // if the user did not select an explicit value
19419 const unsetOptions = new Set();
19420 const context = (_a = config.context) !== null && _a !== void 0 ? _a : 'undefined';
19421 const onwarn = getOnwarn(config);
19422 const strictDeprecations = config.strictDeprecations || false;
19423 const options = {
19424 acorn: getAcorn$1(config),
19425 acornInjectPlugins: getAcornInjectPlugins(config),
19426 cache: getCache(config),
19427 context,
19428 experimentalCacheExpiry: (_b = config.experimentalCacheExpiry) !== null && _b !== void 0 ? _b : 10,
19429 external: getIdMatcher(config.external),
19430 inlineDynamicImports: getInlineDynamicImports(config, onwarn, strictDeprecations),
19431 input: getInput(config),
19432 manualChunks: getManualChunks(config, onwarn, strictDeprecations),
19433 moduleContext: getModuleContext(config, context),
19434 onwarn,
19435 perf: config.perf || false,
19436 plugins: ensureArray(config.plugins),
19437 preserveEntrySignatures: getPreserveEntrySignatures(config, unsetOptions),
19438 preserveModules: getPreserveModules(config, onwarn, strictDeprecations),
19439 preserveSymlinks: config.preserveSymlinks || false,
19440 shimMissingExports: config.shimMissingExports || false,
19441 strictDeprecations,
19442 treeshake: getTreeshake(config, onwarn, strictDeprecations)
19443 };
19444 warnUnknownOptions(config, [...Object.keys(options), 'watch'], 'input options', options.onwarn, /^(output)$/);
19445 return { options, unsetOptions };
19446}
19447const getOnwarn = (config) => {
19448 return config.onwarn
19449 ? warning => {
19450 warning.toString = () => {
19451 let str = '';
19452 if (warning.plugin)
19453 str += `(${warning.plugin} plugin) `;
19454 if (warning.loc)
19455 str += `${relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
19456 str += warning.message;
19457 return str;
19458 };
19459 config.onwarn(warning, defaultOnWarn);
19460 }
19461 : defaultOnWarn;
19462};
19463const getAcorn$1 = (config) => ({
19464 allowAwaitOutsideFunction: true,
19465 ecmaVersion: 'latest',
19466 preserveParens: false,
19467 sourceType: 'module',
19468 ...config.acorn
19469});
19470const getAcornInjectPlugins = (config) => [
19471 acornClassFields,
19472 acornStaticClassFeatures,
19473 acornNumericSeparator,
19474 ...ensureArray(config.acornInjectPlugins)
19475];
19476const getCache = (config) => {
19477 var _a;
19478 return ((_a = config.cache) === null || _a === void 0 ? void 0 : _a.cache) || config.cache;
19479};
19480const getIdMatcher = (option) => {
19481 if (option === true) {
19482 return () => true;
19483 }
19484 if (typeof option === 'function') {
19485 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
19486 }
19487 if (option) {
19488 const ids = new Set();
19489 const matchers = [];
19490 for (const value of ensureArray(option)) {
19491 if (value instanceof RegExp) {
19492 matchers.push(value);
19493 }
19494 else {
19495 ids.add(value);
19496 }
19497 }
19498 return (id, ..._args) => ids.has(id) || matchers.some(matcher => matcher.test(id));
19499 }
19500 return () => false;
19501};
19502const getInlineDynamicImports = (config, warn, strictDeprecations) => {
19503 const configInlineDynamicImports = config.inlineDynamicImports;
19504 if (configInlineDynamicImports) {
19505 warnDeprecationWithOptions('The "inlineDynamicImports" option is deprecated. Use the "output.inlineDynamicImports" option instead.', false, warn, strictDeprecations);
19506 }
19507 return configInlineDynamicImports;
19508};
19509const getInput = (config) => {
19510 const configInput = config.input;
19511 return configInput == null ? [] : typeof configInput === 'string' ? [configInput] : configInput;
19512};
19513const getManualChunks = (config, warn, strictDeprecations) => {
19514 const configManualChunks = config.manualChunks;
19515 if (configManualChunks) {
19516 warnDeprecationWithOptions('The "manualChunks" option is deprecated. Use the "output.manualChunks" option instead.', false, warn, strictDeprecations);
19517 }
19518 return configManualChunks;
19519};
19520const getModuleContext = (config, context) => {
19521 const configModuleContext = config.moduleContext;
19522 if (typeof configModuleContext === 'function') {
19523 return id => { var _a; return (_a = configModuleContext(id)) !== null && _a !== void 0 ? _a : context; };
19524 }
19525 if (configModuleContext) {
19526 const contextByModuleId = Object.create(null);
19527 for (const key of Object.keys(configModuleContext)) {
19528 contextByModuleId[resolve(key)] = configModuleContext[key];
19529 }
19530 return id => contextByModuleId[id] || context;
19531 }
19532 return () => context;
19533};
19534const getPreserveEntrySignatures = (config, unsetOptions) => {
19535 const configPreserveEntrySignatures = config.preserveEntrySignatures;
19536 if (configPreserveEntrySignatures == null) {
19537 unsetOptions.add('preserveEntrySignatures');
19538 }
19539 return configPreserveEntrySignatures !== null && configPreserveEntrySignatures !== void 0 ? configPreserveEntrySignatures : 'strict';
19540};
19541const getPreserveModules = (config, warn, strictDeprecations) => {
19542 const configPreserveModules = config.preserveModules;
19543 if (configPreserveModules) {
19544 warnDeprecationWithOptions('The "preserveModules" option is deprecated. Use the "output.preserveModules" option instead.', false, warn, strictDeprecations);
19545 }
19546 return configPreserveModules;
19547};
19548const getTreeshake = (config, warn, strictDeprecations) => {
19549 const configTreeshake = config.treeshake;
19550 if (configTreeshake === false) {
19551 return false;
19552 }
19553 if (configTreeshake && configTreeshake !== true) {
19554 if (typeof configTreeshake.pureExternalModules !== 'undefined') {
19555 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);
19556 }
19557 return {
19558 annotations: configTreeshake.annotations !== false,
19559 moduleSideEffects: getHasModuleSideEffects(configTreeshake.moduleSideEffects, configTreeshake.pureExternalModules, warn),
19560 propertyReadSideEffects: configTreeshake.propertyReadSideEffects !== false,
19561 tryCatchDeoptimization: configTreeshake.tryCatchDeoptimization !== false,
19562 unknownGlobalSideEffects: configTreeshake.unknownGlobalSideEffects !== false
19563 };
19564 }
19565 return {
19566 annotations: true,
19567 moduleSideEffects: () => true,
19568 propertyReadSideEffects: true,
19569 tryCatchDeoptimization: true,
19570 unknownGlobalSideEffects: true
19571 };
19572};
19573const getHasModuleSideEffects = (moduleSideEffectsOption, pureExternalModules, warn) => {
19574 if (typeof moduleSideEffectsOption === 'boolean') {
19575 return () => moduleSideEffectsOption;
19576 }
19577 if (moduleSideEffectsOption === 'no-external') {
19578 return (_id, external) => !external;
19579 }
19580 if (typeof moduleSideEffectsOption === 'function') {
19581 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
19582 }
19583 if (Array.isArray(moduleSideEffectsOption)) {
19584 const ids = new Set(moduleSideEffectsOption);
19585 return id => ids.has(id);
19586 }
19587 if (moduleSideEffectsOption) {
19588 warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
19589 }
19590 const isPureExternalModule = getIdMatcher(pureExternalModules);
19591 return (id, external) => !(external && isPureExternalModule(id));
19592};
19593
19594function normalizeOutputOptions(config, inputOptions, unsetInputOptions) {
19595 var _a, _b, _c, _d, _e, _f, _g;
19596 // These are options that may trigger special warnings or behaviour later
19597 // if the user did not select an explicit value
19598 const unsetOptions = new Set(unsetInputOptions);
19599 const compact = config.compact || false;
19600 const format = getFormat(config);
19601 const inlineDynamicImports = getInlineDynamicImports$1(config, inputOptions);
19602 const preserveModules = getPreserveModules$1(config, inlineDynamicImports, inputOptions);
19603 const file = getFile(config, preserveModules, inputOptions);
19604 const outputOptions = {
19605 amd: getAmd(config),
19606 assetFileNames: (_a = config.assetFileNames) !== null && _a !== void 0 ? _a : 'assets/[name]-[hash][extname]',
19607 banner: getAddon(config, 'banner'),
19608 chunkFileNames: (_b = config.chunkFileNames) !== null && _b !== void 0 ? _b : '[name]-[hash].js',
19609 compact,
19610 dir: getDir(config, file),
19611 dynamicImportFunction: getDynamicImportFunction(config, inputOptions),
19612 entryFileNames: getEntryFileNames(config, unsetOptions),
19613 esModule: (_c = config.esModule) !== null && _c !== void 0 ? _c : true,
19614 exports: getExports(config, unsetOptions),
19615 extend: config.extend || false,
19616 externalLiveBindings: (_d = config.externalLiveBindings) !== null && _d !== void 0 ? _d : true,
19617 file,
19618 footer: getAddon(config, 'footer'),
19619 format,
19620 freeze: (_e = config.freeze) !== null && _e !== void 0 ? _e : true,
19621 globals: config.globals || {},
19622 hoistTransitiveImports: (_f = config.hoistTransitiveImports) !== null && _f !== void 0 ? _f : true,
19623 indent: getIndent(config, compact),
19624 inlineDynamicImports,
19625 interop: getInterop(config, inputOptions),
19626 intro: getAddon(config, 'intro'),
19627 manualChunks: getManualChunks$1(config, inlineDynamicImports, preserveModules, inputOptions),
19628 minifyInternalExports: getMinifyInternalExports(config, format, compact),
19629 name: config.name,
19630 namespaceToStringTag: config.namespaceToStringTag || false,
19631 noConflict: config.noConflict || false,
19632 outro: getAddon(config, 'outro'),
19633 paths: config.paths || {},
19634 plugins: ensureArray(config.plugins),
19635 preferConst: config.preferConst || false,
19636 preserveModules,
19637 preserveModulesRoot: getPreserveModulesRoot(config),
19638 sourcemap: config.sourcemap || false,
19639 sourcemapExcludeSources: config.sourcemapExcludeSources || false,
19640 sourcemapFile: config.sourcemapFile,
19641 sourcemapPathTransform: config.sourcemapPathTransform,
19642 strict: (_g = config.strict) !== null && _g !== void 0 ? _g : true,
19643 systemNullSetters: config.systemNullSetters || false
19644 };
19645 warnUnknownOptions(config, Object.keys(outputOptions), 'output options', inputOptions.onwarn);
19646 return { options: outputOptions, unsetOptions };
19647}
19648const getFile = (config, preserveModules, inputOptions) => {
19649 const file = config.file;
19650 if (typeof file === 'string') {
19651 if (preserveModules) {
19652 return error({
19653 code: 'INVALID_OPTION',
19654 message: 'You must set "output.dir" instead of "output.file" when using the "output.preserveModules" option.'
19655 });
19656 }
19657 if (!Array.isArray(inputOptions.input))
19658 return error({
19659 code: 'INVALID_OPTION',
19660 message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
19661 });
19662 }
19663 return file;
19664};
19665const getFormat = (config) => {
19666 const configFormat = config.format;
19667 switch (configFormat) {
19668 case undefined:
19669 case 'es':
19670 case 'esm':
19671 case 'module':
19672 return 'es';
19673 case 'cjs':
19674 case 'commonjs':
19675 return 'cjs';
19676 case 'system':
19677 case 'systemjs':
19678 return 'system';
19679 case 'amd':
19680 case 'iife':
19681 case 'umd':
19682 return configFormat;
19683 default:
19684 return error({
19685 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "es", "iife" or "umd".`,
19686 url: `https://rollupjs.org/guide/en/#outputformat`
19687 });
19688 }
19689};
19690const getInlineDynamicImports$1 = (config, inputOptions) => {
19691 var _a;
19692 const inlineDynamicImports = ((_a = config.inlineDynamicImports) !== null && _a !== void 0 ? _a : inputOptions.inlineDynamicImports) ||
19693 false;
19694 const { input } = inputOptions;
19695 if (inlineDynamicImports && (Array.isArray(input) ? input : Object.keys(input)).length > 1) {
19696 return error({
19697 code: 'INVALID_OPTION',
19698 message: 'Multiple inputs are not supported for "output.inlineDynamicImports".'
19699 });
19700 }
19701 return inlineDynamicImports;
19702};
19703const getPreserveModules$1 = (config, inlineDynamicImports, inputOptions) => {
19704 var _a;
19705 const preserveModules = ((_a = config.preserveModules) !== null && _a !== void 0 ? _a : inputOptions.preserveModules) || false;
19706 if (preserveModules) {
19707 if (inlineDynamicImports) {
19708 return error({
19709 code: 'INVALID_OPTION',
19710 message: `The "output.inlineDynamicImports" option is not supported for "output.preserveModules".`
19711 });
19712 }
19713 if (inputOptions.preserveEntrySignatures === false) {
19714 return error({
19715 code: 'INVALID_OPTION',
19716 message: 'Setting "preserveEntrySignatures" to "false" is not supported for "output.preserveModules".'
19717 });
19718 }
19719 }
19720 return preserveModules;
19721};
19722const getPreserveModulesRoot = (config) => {
19723 const preserveModulesRoot = config.preserveModulesRoot;
19724 if (preserveModulesRoot === null || preserveModulesRoot === undefined) {
19725 return undefined;
19726 }
19727 return resolve(preserveModulesRoot);
19728};
19729const getAmd = (config) => ({
19730 define: 'define',
19731 ...config.amd
19732});
19733const getAddon = (config, name) => {
19734 const configAddon = config[name];
19735 if (typeof configAddon === 'function') {
19736 return configAddon;
19737 }
19738 return () => configAddon || '';
19739};
19740const getDir = (config, file) => {
19741 const dir = config.dir;
19742 if (typeof dir === 'string' && typeof file === 'string') {
19743 return error({
19744 code: 'INVALID_OPTION',
19745 message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
19746 });
19747 }
19748 return dir;
19749};
19750const getDynamicImportFunction = (config, inputOptions) => {
19751 const configDynamicImportFunction = config.dynamicImportFunction;
19752 if (configDynamicImportFunction) {
19753 warnDeprecation(`The "output.dynamicImportFunction" option is deprecated. Use the "renderDynamicImport" plugin hook instead.`, false, inputOptions);
19754 }
19755 return configDynamicImportFunction;
19756};
19757const getEntryFileNames = (config, unsetOptions) => {
19758 const configEntryFileNames = config.entryFileNames;
19759 if (configEntryFileNames == null) {
19760 unsetOptions.add('entryFileNames');
19761 }
19762 return configEntryFileNames !== null && configEntryFileNames !== void 0 ? configEntryFileNames : '[name].js';
19763};
19764function getExports(config, unsetOptions) {
19765 const configExports = config.exports;
19766 if (configExports == null) {
19767 unsetOptions.add('exports');
19768 }
19769 else if (!['default', 'named', 'none', 'auto'].includes(configExports)) {
19770 return error(errInvalidExportOptionValue(configExports));
19771 }
19772 return configExports || 'auto';
19773}
19774const getIndent = (config, compact) => {
19775 if (compact) {
19776 return '';
19777 }
19778 const configIndent = config.indent;
19779 return configIndent === false ? '' : configIndent !== null && configIndent !== void 0 ? configIndent : true;
19780};
19781const ALLOWED_INTEROP_TYPES = new Set(['auto', 'esModule', 'default', 'defaultOnly', true, false]);
19782const getInterop = (config, inputOptions) => {
19783 const configInterop = config.interop;
19784 const validatedInteropTypes = new Set();
19785 const validateInterop = (interop) => {
19786 if (!validatedInteropTypes.has(interop)) {
19787 validatedInteropTypes.add(interop);
19788 if (!ALLOWED_INTEROP_TYPES.has(interop)) {
19789 return error({
19790 code: 'INVALID_OPTION',
19791 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.`,
19792 url: 'https://rollupjs.org/guide/en/#outputinterop'
19793 });
19794 }
19795 if (typeof interop === 'boolean') {
19796 warnDeprecation({
19797 message: `The boolean value "${interop}" for the "output.interop" option is deprecated. Use ${interop ? '"auto"' : '"esModule", "default" or "defaultOnly"'} instead.`,
19798 url: 'https://rollupjs.org/guide/en/#outputinterop'
19799 }, false, inputOptions);
19800 }
19801 }
19802 return interop;
19803 };
19804 if (typeof configInterop === 'function') {
19805 const interopPerId = Object.create(null);
19806 let defaultInterop = null;
19807 return id => id === null
19808 ? defaultInterop || validateInterop((defaultInterop = configInterop(id)))
19809 : id in interopPerId
19810 ? interopPerId[id]
19811 : validateInterop((interopPerId[id] = configInterop(id)));
19812 }
19813 return configInterop === undefined ? () => true : () => validateInterop(configInterop);
19814};
19815const getManualChunks$1 = (config, inlineDynamicImports, preserveModules, inputOptions) => {
19816 const configManualChunks = config.manualChunks || inputOptions.manualChunks;
19817 if (configManualChunks) {
19818 if (inlineDynamicImports) {
19819 return error({
19820 code: 'INVALID_OPTION',
19821 message: 'The "output.manualChunks" option is not supported for "output.inlineDynamicImports".'
19822 });
19823 }
19824 if (preserveModules) {
19825 return error({
19826 code: 'INVALID_OPTION',
19827 message: 'The "output.manualChunks" option is not supported for "output.preserveModules".'
19828 });
19829 }
19830 }
19831 return configManualChunks || {};
19832};
19833const getMinifyInternalExports = (config, format, compact) => { var _a; return (_a = config.minifyInternalExports) !== null && _a !== void 0 ? _a : (compact || format === 'es' || format === 'system'); };
19834
19835function rollup(rawInputOptions) {
19836 return rollupInternal(rawInputOptions, null);
19837}
19838async function rollupInternal(rawInputOptions, watcher) {
19839 const { options: inputOptions, unsetOptions: unsetInputOptions } = await getInputOptions(rawInputOptions, watcher !== null);
19840 initialiseTimers(inputOptions);
19841 const graph = new Graph(inputOptions, watcher);
19842 // remove the cache option from the memory after graph creation (cache is not used anymore)
19843 const useCache = rawInputOptions.cache !== false;
19844 delete inputOptions.cache;
19845 delete rawInputOptions.cache;
19846 timeStart('BUILD', 1);
19847 try {
19848 await graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
19849 await graph.build();
19850 }
19851 catch (err) {
19852 const watchFiles = Object.keys(graph.watchFiles);
19853 if (watchFiles.length > 0) {
19854 err.watchFiles = watchFiles;
19855 }
19856 await graph.pluginDriver.hookParallel('buildEnd', [err]);
19857 throw err;
19858 }
19859 await graph.pluginDriver.hookParallel('buildEnd', []);
19860 timeEnd('BUILD', 1);
19861 const result = {
19862 cache: useCache ? graph.getCache() : undefined,
19863 async generate(rawOutputOptions) {
19864 return handleGenerateWrite(false, inputOptions, unsetInputOptions, rawOutputOptions, graph);
19865 },
19866 watchFiles: Object.keys(graph.watchFiles),
19867 async write(rawOutputOptions) {
19868 return handleGenerateWrite(true, inputOptions, unsetInputOptions, rawOutputOptions, graph);
19869 }
19870 };
19871 if (inputOptions.perf)
19872 result.getTimings = getTimings;
19873 return result;
19874}
19875async function getInputOptions(rawInputOptions, watchMode) {
19876 if (!rawInputOptions) {
19877 throw new Error('You must supply an options object to rollup');
19878 }
19879 const rawPlugins = ensureArray(rawInputOptions.plugins);
19880 const { options, unsetOptions } = normalizeInputOptions(await rawPlugins.reduce(applyOptionHook(watchMode), Promise.resolve(rawInputOptions)));
19881 normalizePlugins(options.plugins, ANONYMOUS_PLUGIN_PREFIX);
19882 return { options, unsetOptions };
19883}
19884function applyOptionHook(watchMode) {
19885 return async (inputOptions, plugin) => {
19886 if (plugin.options)
19887 return (plugin.options.call({ meta: { rollupVersion: version, watchMode } }, await inputOptions) || inputOptions);
19888 return inputOptions;
19889 };
19890}
19891function normalizePlugins(plugins, anonymousPrefix) {
19892 for (let pluginIndex = 0; pluginIndex < plugins.length; pluginIndex++) {
19893 const plugin = plugins[pluginIndex];
19894 if (!plugin.name) {
19895 plugin.name = `${anonymousPrefix}${pluginIndex + 1}`;
19896 }
19897 }
19898}
19899async function handleGenerateWrite(isWrite, inputOptions, unsetInputOptions, rawOutputOptions, graph) {
19900 const { options: outputOptions, outputPluginDriver, unsetOptions } = getOutputOptionsAndPluginDriver(rawOutputOptions, graph.pluginDriver, inputOptions, unsetInputOptions);
19901 const bundle = new Bundle$1(outputOptions, unsetOptions, inputOptions, outputPluginDriver, graph);
19902 const generated = await bundle.generate(isWrite);
19903 if (isWrite) {
19904 if (!outputOptions.dir && !outputOptions.file) {
19905 return error({
19906 code: 'MISSING_OPTION',
19907 message: 'You must specify "output.file" or "output.dir" for the build.'
19908 });
19909 }
19910 await Promise.all(Object.keys(generated).map(chunkId => writeOutputFile(generated[chunkId], outputOptions)));
19911 await outputPluginDriver.hookParallel('writeBundle', [outputOptions, generated]);
19912 }
19913 return createOutput(generated);
19914}
19915function getOutputOptionsAndPluginDriver(rawOutputOptions, inputPluginDriver, inputOptions, unsetInputOptions) {
19916 if (!rawOutputOptions) {
19917 throw new Error('You must supply an options object');
19918 }
19919 const rawPlugins = ensureArray(rawOutputOptions.plugins);
19920 normalizePlugins(rawPlugins, ANONYMOUS_OUTPUT_PLUGIN_PREFIX);
19921 const outputPluginDriver = inputPluginDriver.createOutputPluginDriver(rawPlugins);
19922 return {
19923 ...getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver),
19924 outputPluginDriver
19925 };
19926}
19927function getOutputOptions(inputOptions, unsetInputOptions, rawOutputOptions, outputPluginDriver) {
19928 return normalizeOutputOptions(outputPluginDriver.hookReduceArg0Sync('outputOptions', [rawOutputOptions.output || rawOutputOptions], (outputOptions, result) => result || outputOptions, pluginContext => {
19929 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
19930 return {
19931 ...pluginContext,
19932 emitFile: emitError,
19933 setAssetSource: emitError
19934 };
19935 }), inputOptions, unsetInputOptions);
19936}
19937function createOutput(outputBundle) {
19938 return {
19939 output: Object.keys(outputBundle)
19940 .map(fileName => outputBundle[fileName])
19941 .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
19942 const fileTypeA = getSortingFileType(outputFileA);
19943 const fileTypeB = getSortingFileType(outputFileB);
19944 if (fileTypeA === fileTypeB)
19945 return 0;
19946 return fileTypeA < fileTypeB ? -1 : 1;
19947 })
19948 };
19949}
19950var SortingFileType;
19951(function (SortingFileType) {
19952 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
19953 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
19954 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
19955})(SortingFileType || (SortingFileType = {}));
19956function getSortingFileType(file) {
19957 if (file.type === 'asset') {
19958 return SortingFileType.ASSET;
19959 }
19960 if (file.isEntry) {
19961 return SortingFileType.ENTRY_CHUNK;
19962 }
19963 return SortingFileType.SECONDARY_CHUNK;
19964}
19965function writeOutputFile(outputFile, outputOptions) {
19966 const fileName = resolve(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
19967 let writeSourceMapPromise;
19968 let source;
19969 if (outputFile.type === 'asset') {
19970 source = outputFile.source;
19971 }
19972 else {
19973 source = outputFile.code;
19974 if (outputOptions.sourcemap && outputFile.map) {
19975 let url;
19976 if (outputOptions.sourcemap === 'inline') {
19977 url = outputFile.map.toUrl();
19978 }
19979 else {
19980 url = `${basename(outputFile.fileName)}.map`;
19981 writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
19982 }
19983 if (outputOptions.sourcemap !== 'hidden') {
19984 source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
19985 }
19986 }
19987 }
19988 return Promise.all([writeFile(fileName, source), writeSourceMapPromise]);
19989}
19990
19991let fsEvents;
19992let fsEventsImportError;
19993function loadFsEvents() {
19994 return import('fsevents')
19995 .then(namespace => {
19996 fsEvents = namespace.default;
19997 })
19998 .catch(err => {
19999 fsEventsImportError = err;
20000 });
20001}
20002// A call to this function will be injected into the chokidar code
20003function getFsEvents() {
20004 if (fsEventsImportError)
20005 throw fsEventsImportError;
20006 return fsEvents;
20007}
20008
20009var fseventsImporter = {
20010 __proto__: null,
20011 loadFsEvents: loadFsEvents,
20012 getFsEvents: getFsEvents
20013};
20014
20015class WatchEmitter extends EventEmitter {
20016 constructor() {
20017 super();
20018 // Allows more than 10 bundles to be watched without
20019 // showing the `MaxListenersExceededWarning` to the user.
20020 this.setMaxListeners(Infinity);
20021 }
20022 close() { }
20023}
20024function watch(configs) {
20025 const emitter = new WatchEmitter();
20026 const configArray = ensureArray(configs);
20027 const watchConfigs = configArray.filter(config => config.watch !== false);
20028 if (watchConfigs.length === 0) {
20029 throw error(errInvalidOption('watch', 'there must be at least one config where "watch" is not set to "false"'));
20030 }
20031 loadFsEvents()
20032 .then(() => import('./watch.js'))
20033 .then(({ Watcher }) => new Watcher(watchConfigs, emitter));
20034 return emitter;
20035}
20036
20037export { createCommonjsModule, defaultOnWarn, ensureArray, fseventsImporter, getAugmentedNamespace, rollup, rollupInternal, version, warnUnknownOptions, watch };