UNPKG

619 kBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v1.25.2
4 Wed, 23 Oct 2019 05:48:50 GMT - commit b123169865e670d3b961d5afaef090aa4e019fef
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11'use strict';
12
13Object.defineProperty(exports, '__esModule', { value: true });
14
15var index = require('./shared/index.js');
16var util = require('util');
17var path = require('path');
18var fs = require('fs');
19var acorn = require('acorn');
20var events = require('events');
21require('module');
22
23/*! *****************************************************************************
24Copyright (c) Microsoft Corporation. All rights reserved.
25Licensed under the Apache License, Version 2.0 (the "License"); you may not use
26this file except in compliance with the License. You may obtain a copy of the
27License at http://www.apache.org/licenses/LICENSE-2.0
28
29THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
30KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
31WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
32MERCHANTABLITY OR NON-INFRINGEMENT.
33
34See the Apache Version 2.0 License for specific language governing permissions
35and limitations under the License.
36***************************************************************************** */
37function __awaiter(thisArg, _arguments, P, generator) {
38 return new (P || (P = Promise))(function (resolve, reject) {
39 function fulfilled(value) { try {
40 step(generator.next(value));
41 }
42 catch (e) {
43 reject(e);
44 } }
45 function rejected(value) { try {
46 step(generator["throw"](value));
47 }
48 catch (e) {
49 reject(e);
50 } }
51 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
52 step((generator = generator.apply(thisArg, _arguments || [])).next());
53 });
54}
55
56var minimalisticAssert = assert;
57function assert(val, msg) {
58 if (!val)
59 throw new Error(msg || 'Assertion failed');
60}
61assert.equal = function assertEqual(l, r, msg) {
62 if (l != r)
63 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
64};
65
66var inherits_browser = index.createCommonjsModule(function (module) {
67 if (typeof Object.create === 'function') {
68 // implementation from standard node.js 'util' module
69 module.exports = function inherits(ctor, superCtor) {
70 ctor.super_ = superCtor;
71 ctor.prototype = Object.create(superCtor.prototype, {
72 constructor: {
73 value: ctor,
74 enumerable: false,
75 writable: true,
76 configurable: true
77 }
78 });
79 };
80 }
81 else {
82 // old school shim for old browsers
83 module.exports = function inherits(ctor, superCtor) {
84 ctor.super_ = superCtor;
85 var TempCtor = function () { };
86 TempCtor.prototype = superCtor.prototype;
87 ctor.prototype = new TempCtor();
88 ctor.prototype.constructor = ctor;
89 };
90 }
91});
92
93var inherits = index.createCommonjsModule(function (module) {
94 try {
95 var util$1 = util;
96 if (typeof util$1.inherits !== 'function')
97 throw '';
98 module.exports = util$1.inherits;
99 }
100 catch (e) {
101 module.exports = inherits_browser;
102 }
103});
104
105var inherits_1 = inherits;
106function isSurrogatePair(msg, i) {
107 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
108 return false;
109 }
110 if (i < 0 || i + 1 >= msg.length) {
111 return false;
112 }
113 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
114}
115function toArray(msg, enc) {
116 if (Array.isArray(msg))
117 return msg.slice();
118 if (!msg)
119 return [];
120 var res = [];
121 if (typeof msg === 'string') {
122 if (!enc) {
123 // Inspired by stringToUtf8ByteArray() in closure-library by Google
124 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
125 // Apache License 2.0
126 // https://github.com/google/closure-library/blob/master/LICENSE
127 var p = 0;
128 for (var i = 0; i < msg.length; i++) {
129 var c = msg.charCodeAt(i);
130 if (c < 128) {
131 res[p++] = c;
132 }
133 else if (c < 2048) {
134 res[p++] = (c >> 6) | 192;
135 res[p++] = (c & 63) | 128;
136 }
137 else if (isSurrogatePair(msg, i)) {
138 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
139 res[p++] = (c >> 18) | 240;
140 res[p++] = ((c >> 12) & 63) | 128;
141 res[p++] = ((c >> 6) & 63) | 128;
142 res[p++] = (c & 63) | 128;
143 }
144 else {
145 res[p++] = (c >> 12) | 224;
146 res[p++] = ((c >> 6) & 63) | 128;
147 res[p++] = (c & 63) | 128;
148 }
149 }
150 }
151 else if (enc === 'hex') {
152 msg = msg.replace(/[^a-z0-9]+/ig, '');
153 if (msg.length % 2 !== 0)
154 msg = '0' + msg;
155 for (i = 0; i < msg.length; i += 2)
156 res.push(parseInt(msg[i] + msg[i + 1], 16));
157 }
158 }
159 else {
160 for (i = 0; i < msg.length; i++)
161 res[i] = msg[i] | 0;
162 }
163 return res;
164}
165var toArray_1 = toArray;
166function toHex(msg) {
167 var res = '';
168 for (var i = 0; i < msg.length; i++)
169 res += zero2(msg[i].toString(16));
170 return res;
171}
172var toHex_1 = toHex;
173function htonl(w) {
174 var res = (w >>> 24) |
175 ((w >>> 8) & 0xff00) |
176 ((w << 8) & 0xff0000) |
177 ((w & 0xff) << 24);
178 return res >>> 0;
179}
180var htonl_1 = htonl;
181function toHex32(msg, endian) {
182 var res = '';
183 for (var i = 0; i < msg.length; i++) {
184 var w = msg[i];
185 if (endian === 'little')
186 w = htonl(w);
187 res += zero8(w.toString(16));
188 }
189 return res;
190}
191var toHex32_1 = toHex32;
192function zero2(word) {
193 if (word.length === 1)
194 return '0' + word;
195 else
196 return word;
197}
198var zero2_1 = zero2;
199function zero8(word) {
200 if (word.length === 7)
201 return '0' + word;
202 else if (word.length === 6)
203 return '00' + word;
204 else if (word.length === 5)
205 return '000' + word;
206 else if (word.length === 4)
207 return '0000' + word;
208 else if (word.length === 3)
209 return '00000' + word;
210 else if (word.length === 2)
211 return '000000' + word;
212 else if (word.length === 1)
213 return '0000000' + word;
214 else
215 return word;
216}
217var zero8_1 = zero8;
218function join32(msg, start, end, endian) {
219 var len = end - start;
220 minimalisticAssert(len % 4 === 0);
221 var res = new Array(len / 4);
222 for (var i = 0, k = start; i < res.length; i++, k += 4) {
223 var w;
224 if (endian === 'big')
225 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
226 else
227 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
228 res[i] = w >>> 0;
229 }
230 return res;
231}
232var join32_1 = join32;
233function split32(msg, endian) {
234 var res = new Array(msg.length * 4);
235 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
236 var m = msg[i];
237 if (endian === 'big') {
238 res[k] = m >>> 24;
239 res[k + 1] = (m >>> 16) & 0xff;
240 res[k + 2] = (m >>> 8) & 0xff;
241 res[k + 3] = m & 0xff;
242 }
243 else {
244 res[k + 3] = m >>> 24;
245 res[k + 2] = (m >>> 16) & 0xff;
246 res[k + 1] = (m >>> 8) & 0xff;
247 res[k] = m & 0xff;
248 }
249 }
250 return res;
251}
252var split32_1 = split32;
253function rotr32(w, b) {
254 return (w >>> b) | (w << (32 - b));
255}
256var rotr32_1 = rotr32;
257function rotl32(w, b) {
258 return (w << b) | (w >>> (32 - b));
259}
260var rotl32_1 = rotl32;
261function sum32(a, b) {
262 return (a + b) >>> 0;
263}
264var sum32_1 = sum32;
265function sum32_3(a, b, c) {
266 return (a + b + c) >>> 0;
267}
268var sum32_3_1 = sum32_3;
269function sum32_4(a, b, c, d) {
270 return (a + b + c + d) >>> 0;
271}
272var sum32_4_1 = sum32_4;
273function sum32_5(a, b, c, d, e) {
274 return (a + b + c + d + e) >>> 0;
275}
276var sum32_5_1 = sum32_5;
277function sum64(buf, pos, ah, al) {
278 var bh = buf[pos];
279 var bl = buf[pos + 1];
280 var lo = (al + bl) >>> 0;
281 var hi = (lo < al ? 1 : 0) + ah + bh;
282 buf[pos] = hi >>> 0;
283 buf[pos + 1] = lo;
284}
285var sum64_1 = sum64;
286function sum64_hi(ah, al, bh, bl) {
287 var lo = (al + bl) >>> 0;
288 var hi = (lo < al ? 1 : 0) + ah + bh;
289 return hi >>> 0;
290}
291var sum64_hi_1 = sum64_hi;
292function sum64_lo(ah, al, bh, bl) {
293 var lo = al + bl;
294 return lo >>> 0;
295}
296var sum64_lo_1 = sum64_lo;
297function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
298 var carry = 0;
299 var lo = al;
300 lo = (lo + bl) >>> 0;
301 carry += lo < al ? 1 : 0;
302 lo = (lo + cl) >>> 0;
303 carry += lo < cl ? 1 : 0;
304 lo = (lo + dl) >>> 0;
305 carry += lo < dl ? 1 : 0;
306 var hi = ah + bh + ch + dh + carry;
307 return hi >>> 0;
308}
309var sum64_4_hi_1 = sum64_4_hi;
310function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
311 var lo = al + bl + cl + dl;
312 return lo >>> 0;
313}
314var sum64_4_lo_1 = sum64_4_lo;
315function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
316 var carry = 0;
317 var lo = al;
318 lo = (lo + bl) >>> 0;
319 carry += lo < al ? 1 : 0;
320 lo = (lo + cl) >>> 0;
321 carry += lo < cl ? 1 : 0;
322 lo = (lo + dl) >>> 0;
323 carry += lo < dl ? 1 : 0;
324 lo = (lo + el) >>> 0;
325 carry += lo < el ? 1 : 0;
326 var hi = ah + bh + ch + dh + eh + carry;
327 return hi >>> 0;
328}
329var sum64_5_hi_1 = sum64_5_hi;
330function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
331 var lo = al + bl + cl + dl + el;
332 return lo >>> 0;
333}
334var sum64_5_lo_1 = sum64_5_lo;
335function rotr64_hi(ah, al, num) {
336 var r = (al << (32 - num)) | (ah >>> num);
337 return r >>> 0;
338}
339var rotr64_hi_1 = rotr64_hi;
340function rotr64_lo(ah, al, num) {
341 var r = (ah << (32 - num)) | (al >>> num);
342 return r >>> 0;
343}
344var rotr64_lo_1 = rotr64_lo;
345function shr64_hi(ah, al, num) {
346 return ah >>> num;
347}
348var shr64_hi_1 = shr64_hi;
349function shr64_lo(ah, al, num) {
350 var r = (ah << (32 - num)) | (al >>> num);
351 return r >>> 0;
352}
353var shr64_lo_1 = shr64_lo;
354var utils = {
355 inherits: inherits_1,
356 toArray: toArray_1,
357 toHex: toHex_1,
358 htonl: htonl_1,
359 toHex32: toHex32_1,
360 zero2: zero2_1,
361 zero8: zero8_1,
362 join32: join32_1,
363 split32: split32_1,
364 rotr32: rotr32_1,
365 rotl32: rotl32_1,
366 sum32: sum32_1,
367 sum32_3: sum32_3_1,
368 sum32_4: sum32_4_1,
369 sum32_5: sum32_5_1,
370 sum64: sum64_1,
371 sum64_hi: sum64_hi_1,
372 sum64_lo: sum64_lo_1,
373 sum64_4_hi: sum64_4_hi_1,
374 sum64_4_lo: sum64_4_lo_1,
375 sum64_5_hi: sum64_5_hi_1,
376 sum64_5_lo: sum64_5_lo_1,
377 rotr64_hi: rotr64_hi_1,
378 rotr64_lo: rotr64_lo_1,
379 shr64_hi: shr64_hi_1,
380 shr64_lo: shr64_lo_1
381};
382
383function BlockHash() {
384 this.pending = null;
385 this.pendingTotal = 0;
386 this.blockSize = this.constructor.blockSize;
387 this.outSize = this.constructor.outSize;
388 this.hmacStrength = this.constructor.hmacStrength;
389 this.padLength = this.constructor.padLength / 8;
390 this.endian = 'big';
391 this._delta8 = this.blockSize / 8;
392 this._delta32 = this.blockSize / 32;
393}
394var BlockHash_1 = BlockHash;
395BlockHash.prototype.update = function update(msg, enc) {
396 // Convert message to array, pad it, and join into 32bit blocks
397 msg = utils.toArray(msg, enc);
398 if (!this.pending)
399 this.pending = msg;
400 else
401 this.pending = this.pending.concat(msg);
402 this.pendingTotal += msg.length;
403 // Enough data, try updating
404 if (this.pending.length >= this._delta8) {
405 msg = this.pending;
406 // Process pending data in blocks
407 var r = msg.length % this._delta8;
408 this.pending = msg.slice(msg.length - r, msg.length);
409 if (this.pending.length === 0)
410 this.pending = null;
411 msg = utils.join32(msg, 0, msg.length - r, this.endian);
412 for (var i = 0; i < msg.length; i += this._delta32)
413 this._update(msg, i, i + this._delta32);
414 }
415 return this;
416};
417BlockHash.prototype.digest = function digest(enc) {
418 this.update(this._pad());
419 minimalisticAssert(this.pending === null);
420 return this._digest(enc);
421};
422BlockHash.prototype._pad = function pad() {
423 var len = this.pendingTotal;
424 var bytes = this._delta8;
425 var k = bytes - ((len + this.padLength) % bytes);
426 var res = new Array(k + this.padLength);
427 res[0] = 0x80;
428 for (var i = 1; i < k; i++)
429 res[i] = 0;
430 // Append length
431 len <<= 3;
432 if (this.endian === 'big') {
433 for (var t = 8; t < this.padLength; t++)
434 res[i++] = 0;
435 res[i++] = 0;
436 res[i++] = 0;
437 res[i++] = 0;
438 res[i++] = 0;
439 res[i++] = (len >>> 24) & 0xff;
440 res[i++] = (len >>> 16) & 0xff;
441 res[i++] = (len >>> 8) & 0xff;
442 res[i++] = len & 0xff;
443 }
444 else {
445 res[i++] = len & 0xff;
446 res[i++] = (len >>> 8) & 0xff;
447 res[i++] = (len >>> 16) & 0xff;
448 res[i++] = (len >>> 24) & 0xff;
449 res[i++] = 0;
450 res[i++] = 0;
451 res[i++] = 0;
452 res[i++] = 0;
453 for (t = 8; t < this.padLength; t++)
454 res[i++] = 0;
455 }
456 return res;
457};
458var common = {
459 BlockHash: BlockHash_1
460};
461
462var rotr32$1 = utils.rotr32;
463function ft_1(s, x, y, z) {
464 if (s === 0)
465 return ch32(x, y, z);
466 if (s === 1 || s === 3)
467 return p32(x, y, z);
468 if (s === 2)
469 return maj32(x, y, z);
470}
471var ft_1_1 = ft_1;
472function ch32(x, y, z) {
473 return (x & y) ^ ((~x) & z);
474}
475var ch32_1 = ch32;
476function maj32(x, y, z) {
477 return (x & y) ^ (x & z) ^ (y & z);
478}
479var maj32_1 = maj32;
480function p32(x, y, z) {
481 return x ^ y ^ z;
482}
483var p32_1 = p32;
484function s0_256(x) {
485 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
486}
487var s0_256_1 = s0_256;
488function s1_256(x) {
489 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
490}
491var s1_256_1 = s1_256;
492function g0_256(x) {
493 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
494}
495var g0_256_1 = g0_256;
496function g1_256(x) {
497 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
498}
499var g1_256_1 = g1_256;
500var common$1 = {
501 ft_1: ft_1_1,
502 ch32: ch32_1,
503 maj32: maj32_1,
504 p32: p32_1,
505 s0_256: s0_256_1,
506 s1_256: s1_256_1,
507 g0_256: g0_256_1,
508 g1_256: g1_256_1
509};
510
511var sum32$1 = utils.sum32;
512var sum32_4$1 = utils.sum32_4;
513var sum32_5$1 = utils.sum32_5;
514var ch32$1 = common$1.ch32;
515var maj32$1 = common$1.maj32;
516var s0_256$1 = common$1.s0_256;
517var s1_256$1 = common$1.s1_256;
518var g0_256$1 = common$1.g0_256;
519var g1_256$1 = common$1.g1_256;
520var BlockHash$1 = common.BlockHash;
521var sha256_K = [
522 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
523 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
524 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
525 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
526 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
527 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
528 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
529 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
530 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
531 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
532 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
533 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
534 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
535 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
536 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
537 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
538];
539function SHA256() {
540 if (!(this instanceof SHA256))
541 return new SHA256();
542 BlockHash$1.call(this);
543 this.h = [
544 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
545 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
546 ];
547 this.k = sha256_K;
548 this.W = new Array(64);
549}
550utils.inherits(SHA256, BlockHash$1);
551var _256 = SHA256;
552SHA256.blockSize = 512;
553SHA256.outSize = 256;
554SHA256.hmacStrength = 192;
555SHA256.padLength = 64;
556SHA256.prototype._update = function _update(msg, start) {
557 var W = this.W;
558 for (var i = 0; i < 16; i++)
559 W[i] = msg[start + i];
560 for (; i < W.length; i++)
561 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
562 var a = this.h[0];
563 var b = this.h[1];
564 var c = this.h[2];
565 var d = this.h[3];
566 var e = this.h[4];
567 var f = this.h[5];
568 var g = this.h[6];
569 var h = this.h[7];
570 minimalisticAssert(this.k.length === W.length);
571 for (i = 0; i < W.length; i++) {
572 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
573 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
574 h = g;
575 g = f;
576 f = e;
577 e = sum32$1(d, T1);
578 d = c;
579 c = b;
580 b = a;
581 a = sum32$1(T1, T2);
582 }
583 this.h[0] = sum32$1(this.h[0], a);
584 this.h[1] = sum32$1(this.h[1], b);
585 this.h[2] = sum32$1(this.h[2], c);
586 this.h[3] = sum32$1(this.h[3], d);
587 this.h[4] = sum32$1(this.h[4], e);
588 this.h[5] = sum32$1(this.h[5], f);
589 this.h[6] = sum32$1(this.h[6], g);
590 this.h[7] = sum32$1(this.h[7], h);
591};
592SHA256.prototype._digest = function digest(enc) {
593 if (enc === 'hex')
594 return utils.toHex32(this.h, 'big');
595 else
596 return utils.split32(this.h, 'big');
597};
598
599var charToInteger = {};
600var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
601for (var i = 0; i < chars.length; i++) {
602 charToInteger[chars.charCodeAt(i)] = i;
603}
604function decode(mappings) {
605 var generatedCodeColumn = 0; // first field
606 var sourceFileIndex = 0; // second field
607 var sourceCodeLine = 0; // third field
608 var sourceCodeColumn = 0; // fourth field
609 var nameIndex = 0; // fifth field
610 var decoded = [];
611 var line = [];
612 var segment = [];
613 for (var i = 0, j = 0, shift = 0, value = 0, len = mappings.length; i < len; i++) {
614 var c = mappings.charCodeAt(i);
615 if (c === 44) { // ","
616 if (segment.length)
617 line.push(segment);
618 segment = [];
619 j = 0;
620 }
621 else if (c === 59) { // ";"
622 if (segment.length)
623 line.push(segment);
624 segment = [];
625 j = 0;
626 decoded.push(line);
627 line = [];
628 generatedCodeColumn = 0;
629 }
630 else {
631 var integer = charToInteger[c];
632 if (integer === undefined) {
633 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
634 }
635 var hasContinuationBit = integer & 32;
636 integer &= 31;
637 value += integer << shift;
638 if (hasContinuationBit) {
639 shift += 5;
640 }
641 else {
642 var shouldNegate = value & 1;
643 value >>>= 1;
644 if (shouldNegate) {
645 value = -value;
646 if (value === 0)
647 value = -0x80000000;
648 }
649 if (j == 0) {
650 generatedCodeColumn += value;
651 segment.push(generatedCodeColumn);
652 }
653 else if (j === 1) {
654 sourceFileIndex += value;
655 segment.push(sourceFileIndex);
656 }
657 else if (j === 2) {
658 sourceCodeLine += value;
659 segment.push(sourceCodeLine);
660 }
661 else if (j === 3) {
662 sourceCodeColumn += value;
663 segment.push(sourceCodeColumn);
664 }
665 else if (j === 4) {
666 nameIndex += value;
667 segment.push(nameIndex);
668 }
669 j++;
670 value = shift = 0; // reset
671 }
672 }
673 }
674 if (segment.length)
675 line.push(segment);
676 decoded.push(line);
677 return decoded;
678}
679function encode(decoded) {
680 var sourceFileIndex = 0; // second field
681 var sourceCodeLine = 0; // third field
682 var sourceCodeColumn = 0; // fourth field
683 var nameIndex = 0; // fifth field
684 var mappings = '';
685 for (var i = 0; i < decoded.length; i++) {
686 var line = decoded[i];
687 if (i > 0)
688 mappings += ';';
689 if (line.length === 0)
690 continue;
691 var generatedCodeColumn = 0; // first field
692 var lineMappings = [];
693 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
694 var segment = line_1[_i];
695 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
696 generatedCodeColumn = segment[0];
697 if (segment.length > 1) {
698 segmentMappings +=
699 encodeInteger(segment[1] - sourceFileIndex) +
700 encodeInteger(segment[2] - sourceCodeLine) +
701 encodeInteger(segment[3] - sourceCodeColumn);
702 sourceFileIndex = segment[1];
703 sourceCodeLine = segment[2];
704 sourceCodeColumn = segment[3];
705 }
706 if (segment.length === 5) {
707 segmentMappings += encodeInteger(segment[4] - nameIndex);
708 nameIndex = segment[4];
709 }
710 lineMappings.push(segmentMappings);
711 }
712 mappings += lineMappings.join(',');
713 }
714 return mappings;
715}
716function encodeInteger(num) {
717 var result = '';
718 num = num < 0 ? (-num << 1) | 1 : num << 1;
719 do {
720 var clamped = num & 31;
721 num >>>= 5;
722 if (num > 0) {
723 clamped |= 32;
724 }
725 result += chars[clamped];
726 } while (num > 0);
727 return result;
728}
729
730var Chunk = function Chunk(start, end, content) {
731 this.start = start;
732 this.end = end;
733 this.original = content;
734 this.intro = '';
735 this.outro = '';
736 this.content = content;
737 this.storeName = false;
738 this.edited = false;
739 // we make these non-enumerable, for sanity while debugging
740 Object.defineProperties(this, {
741 previous: { writable: true, value: null },
742 next: { writable: true, value: null }
743 });
744};
745Chunk.prototype.appendLeft = function appendLeft(content) {
746 this.outro += content;
747};
748Chunk.prototype.appendRight = function appendRight(content) {
749 this.intro = this.intro + content;
750};
751Chunk.prototype.clone = function clone() {
752 var chunk = new Chunk(this.start, this.end, this.original);
753 chunk.intro = this.intro;
754 chunk.outro = this.outro;
755 chunk.content = this.content;
756 chunk.storeName = this.storeName;
757 chunk.edited = this.edited;
758 return chunk;
759};
760Chunk.prototype.contains = function contains(index) {
761 return this.start < index && index < this.end;
762};
763Chunk.prototype.eachNext = function eachNext(fn) {
764 var chunk = this;
765 while (chunk) {
766 fn(chunk);
767 chunk = chunk.next;
768 }
769};
770Chunk.prototype.eachPrevious = function eachPrevious(fn) {
771 var chunk = this;
772 while (chunk) {
773 fn(chunk);
774 chunk = chunk.previous;
775 }
776};
777Chunk.prototype.edit = function edit(content, storeName, contentOnly) {
778 this.content = content;
779 if (!contentOnly) {
780 this.intro = '';
781 this.outro = '';
782 }
783 this.storeName = storeName;
784 this.edited = true;
785 return this;
786};
787Chunk.prototype.prependLeft = function prependLeft(content) {
788 this.outro = content + this.outro;
789};
790Chunk.prototype.prependRight = function prependRight(content) {
791 this.intro = content + this.intro;
792};
793Chunk.prototype.split = function split(index) {
794 var sliceIndex = index - this.start;
795 var originalBefore = this.original.slice(0, sliceIndex);
796 var originalAfter = this.original.slice(sliceIndex);
797 this.original = originalBefore;
798 var newChunk = new Chunk(index, this.end, originalAfter);
799 newChunk.outro = this.outro;
800 this.outro = '';
801 this.end = index;
802 if (this.edited) {
803 // TODO is this block necessary?...
804 newChunk.edit('', false);
805 this.content = '';
806 }
807 else {
808 this.content = originalBefore;
809 }
810 newChunk.next = this.next;
811 if (newChunk.next) {
812 newChunk.next.previous = newChunk;
813 }
814 newChunk.previous = this;
815 this.next = newChunk;
816 return newChunk;
817};
818Chunk.prototype.toString = function toString() {
819 return this.intro + this.content + this.outro;
820};
821Chunk.prototype.trimEnd = function trimEnd(rx) {
822 this.outro = this.outro.replace(rx, '');
823 if (this.outro.length) {
824 return true;
825 }
826 var trimmed = this.content.replace(rx, '');
827 if (trimmed.length) {
828 if (trimmed !== this.content) {
829 this.split(this.start + trimmed.length).edit('', undefined, true);
830 }
831 return true;
832 }
833 else {
834 this.edit('', undefined, true);
835 this.intro = this.intro.replace(rx, '');
836 if (this.intro.length) {
837 return true;
838 }
839 }
840};
841Chunk.prototype.trimStart = function trimStart(rx) {
842 this.intro = this.intro.replace(rx, '');
843 if (this.intro.length) {
844 return true;
845 }
846 var trimmed = this.content.replace(rx, '');
847 if (trimmed.length) {
848 if (trimmed !== this.content) {
849 this.split(this.end - trimmed.length);
850 this.edit('', undefined, true);
851 }
852 return true;
853 }
854 else {
855 this.edit('', undefined, true);
856 this.outro = this.outro.replace(rx, '');
857 if (this.outro.length) {
858 return true;
859 }
860 }
861};
862var btoa = function () {
863 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
864};
865if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
866 btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
867}
868else if (typeof Buffer === 'function') {
869 btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
870}
871var SourceMap = function SourceMap(properties) {
872 this.version = 3;
873 this.file = properties.file;
874 this.sources = properties.sources;
875 this.sourcesContent = properties.sourcesContent;
876 this.names = properties.names;
877 this.mappings = encode(properties.mappings);
878};
879SourceMap.prototype.toString = function toString() {
880 return JSON.stringify(this);
881};
882SourceMap.prototype.toUrl = function toUrl() {
883 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
884};
885function guessIndent(code) {
886 var lines = code.split('\n');
887 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
888 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
889 if (tabbed.length === 0 && spaced.length === 0) {
890 return null;
891 }
892 // More lines tabbed than spaced? Assume tabs, and
893 // default to tabs in the case of a tie (or nothing
894 // to go on)
895 if (tabbed.length >= spaced.length) {
896 return '\t';
897 }
898 // Otherwise, we need to guess the multiple
899 var min = spaced.reduce(function (previous, current) {
900 var numSpaces = /^ +/.exec(current)[0].length;
901 return Math.min(numSpaces, previous);
902 }, Infinity);
903 return new Array(min + 1).join(' ');
904}
905function getRelativePath(from, to) {
906 var fromParts = from.split(/[/\\]/);
907 var toParts = to.split(/[/\\]/);
908 fromParts.pop(); // get dirname
909 while (fromParts[0] === toParts[0]) {
910 fromParts.shift();
911 toParts.shift();
912 }
913 if (fromParts.length) {
914 var i = fromParts.length;
915 while (i--) {
916 fromParts[i] = '..';
917 }
918 }
919 return fromParts.concat(toParts).join('/');
920}
921var toString = Object.prototype.toString;
922function isObject(thing) {
923 return toString.call(thing) === '[object Object]';
924}
925function getLocator(source) {
926 var originalLines = source.split('\n');
927 var lineOffsets = [];
928 for (var i = 0, pos = 0; i < originalLines.length; i++) {
929 lineOffsets.push(pos);
930 pos += originalLines[i].length + 1;
931 }
932 return function locate(index) {
933 var i = 0;
934 var j = lineOffsets.length;
935 while (i < j) {
936 var m = (i + j) >> 1;
937 if (index < lineOffsets[m]) {
938 j = m;
939 }
940 else {
941 i = m + 1;
942 }
943 }
944 var line = i - 1;
945 var column = index - lineOffsets[line];
946 return { line: line, column: column };
947 };
948}
949var Mappings = function Mappings(hires) {
950 this.hires = hires;
951 this.generatedCodeLine = 0;
952 this.generatedCodeColumn = 0;
953 this.raw = [];
954 this.rawSegments = this.raw[this.generatedCodeLine] = [];
955 this.pending = null;
956};
957Mappings.prototype.addEdit = function addEdit(sourceIndex, content, loc, nameIndex) {
958 if (content.length) {
959 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
960 if (nameIndex >= 0) {
961 segment.push(nameIndex);
962 }
963 this.rawSegments.push(segment);
964 }
965 else if (this.pending) {
966 this.rawSegments.push(this.pending);
967 }
968 this.advance(content);
969 this.pending = null;
970};
971Mappings.prototype.addUneditedChunk = function addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
972 var this$1 = this;
973 var originalCharIndex = chunk.start;
974 var first = true;
975 while (originalCharIndex < chunk.end) {
976 if (this$1.hires || first || sourcemapLocations[originalCharIndex]) {
977 this$1.rawSegments.push([this$1.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
978 }
979 if (original[originalCharIndex] === '\n') {
980 loc.line += 1;
981 loc.column = 0;
982 this$1.generatedCodeLine += 1;
983 this$1.raw[this$1.generatedCodeLine] = this$1.rawSegments = [];
984 this$1.generatedCodeColumn = 0;
985 }
986 else {
987 loc.column += 1;
988 this$1.generatedCodeColumn += 1;
989 }
990 originalCharIndex += 1;
991 first = false;
992 }
993 this.pending = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
994};
995Mappings.prototype.advance = function advance(str) {
996 var this$1 = this;
997 if (!str) {
998 return;
999 }
1000 var lines = str.split('\n');
1001 if (lines.length > 1) {
1002 for (var i = 0; i < lines.length - 1; i++) {
1003 this$1.generatedCodeLine++;
1004 this$1.raw[this$1.generatedCodeLine] = this$1.rawSegments = [];
1005 }
1006 this.generatedCodeColumn = 0;
1007 }
1008 this.generatedCodeColumn += lines[lines.length - 1].length;
1009};
1010var n = '\n';
1011var warned = {
1012 insertLeft: false,
1013 insertRight: false,
1014 storeName: false
1015};
1016var MagicString = function MagicString(string, options) {
1017 if (options === void 0)
1018 options = {};
1019 var chunk = new Chunk(0, string.length, string);
1020 Object.defineProperties(this, {
1021 original: { writable: true, value: string },
1022 outro: { writable: true, value: '' },
1023 intro: { writable: true, value: '' },
1024 firstChunk: { writable: true, value: chunk },
1025 lastChunk: { writable: true, value: chunk },
1026 lastSearchedChunk: { writable: true, value: chunk },
1027 byStart: { writable: true, value: {} },
1028 byEnd: { writable: true, value: {} },
1029 filename: { writable: true, value: options.filename },
1030 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
1031 sourcemapLocations: { writable: true, value: {} },
1032 storedNames: { writable: true, value: {} },
1033 indentStr: { writable: true, value: guessIndent(string) }
1034 });
1035 this.byStart[0] = chunk;
1036 this.byEnd[string.length] = chunk;
1037};
1038MagicString.prototype.addSourcemapLocation = function addSourcemapLocation(char) {
1039 this.sourcemapLocations[char] = true;
1040};
1041MagicString.prototype.append = function append(content) {
1042 if (typeof content !== 'string') {
1043 throw new TypeError('outro content must be a string');
1044 }
1045 this.outro += content;
1046 return this;
1047};
1048MagicString.prototype.appendLeft = function appendLeft(index, content) {
1049 if (typeof content !== 'string') {
1050 throw new TypeError('inserted content must be a string');
1051 }
1052 this._split(index);
1053 var chunk = this.byEnd[index];
1054 if (chunk) {
1055 chunk.appendLeft(content);
1056 }
1057 else {
1058 this.intro += content;
1059 }
1060 return this;
1061};
1062MagicString.prototype.appendRight = function appendRight(index, content) {
1063 if (typeof content !== 'string') {
1064 throw new TypeError('inserted content must be a string');
1065 }
1066 this._split(index);
1067 var chunk = this.byStart[index];
1068 if (chunk) {
1069 chunk.appendRight(content);
1070 }
1071 else {
1072 this.outro += content;
1073 }
1074 return this;
1075};
1076MagicString.prototype.clone = function clone() {
1077 var cloned = new MagicString(this.original, { filename: this.filename });
1078 var originalChunk = this.firstChunk;
1079 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1080 while (originalChunk) {
1081 cloned.byStart[clonedChunk.start] = clonedChunk;
1082 cloned.byEnd[clonedChunk.end] = clonedChunk;
1083 var nextOriginalChunk = originalChunk.next;
1084 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1085 if (nextClonedChunk) {
1086 clonedChunk.next = nextClonedChunk;
1087 nextClonedChunk.previous = clonedChunk;
1088 clonedChunk = nextClonedChunk;
1089 }
1090 originalChunk = nextOriginalChunk;
1091 }
1092 cloned.lastChunk = clonedChunk;
1093 if (this.indentExclusionRanges) {
1094 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1095 }
1096 Object.keys(this.sourcemapLocations).forEach(function (loc) {
1097 cloned.sourcemapLocations[loc] = true;
1098 });
1099 cloned.intro = this.intro;
1100 cloned.outro = this.outro;
1101 return cloned;
1102};
1103MagicString.prototype.generateDecodedMap = function generateDecodedMap(options) {
1104 var this$1 = this;
1105 options = options || {};
1106 var sourceIndex = 0;
1107 var names = Object.keys(this.storedNames);
1108 var mappings = new Mappings(options.hires);
1109 var locate = getLocator(this.original);
1110 if (this.intro) {
1111 mappings.advance(this.intro);
1112 }
1113 this.firstChunk.eachNext(function (chunk) {
1114 var loc = locate(chunk.start);
1115 if (chunk.intro.length) {
1116 mappings.advance(chunk.intro);
1117 }
1118 if (chunk.edited) {
1119 mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
1120 }
1121 else {
1122 mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
1123 }
1124 if (chunk.outro.length) {
1125 mappings.advance(chunk.outro);
1126 }
1127 });
1128 return {
1129 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1130 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
1131 sourcesContent: options.includeContent ? [this.original] : [null],
1132 names: names,
1133 mappings: mappings.raw
1134 };
1135};
1136MagicString.prototype.generateMap = function generateMap(options) {
1137 return new SourceMap(this.generateDecodedMap(options));
1138};
1139MagicString.prototype.getIndentString = function getIndentString() {
1140 return this.indentStr === null ? '\t' : this.indentStr;
1141};
1142MagicString.prototype.indent = function indent(indentStr, options) {
1143 var this$1 = this;
1144 var pattern = /^[^\r\n]/gm;
1145 if (isObject(indentStr)) {
1146 options = indentStr;
1147 indentStr = undefined;
1148 }
1149 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
1150 if (indentStr === '') {
1151 return this;
1152 } // noop
1153 options = options || {};
1154 // Process exclusion ranges
1155 var isExcluded = {};
1156 if (options.exclude) {
1157 var exclusions = typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1158 exclusions.forEach(function (exclusion) {
1159 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
1160 isExcluded[i] = true;
1161 }
1162 });
1163 }
1164 var shouldIndentNextCharacter = options.indentStart !== false;
1165 var replacer = function (match) {
1166 if (shouldIndentNextCharacter) {
1167 return ("" + indentStr + match);
1168 }
1169 shouldIndentNextCharacter = true;
1170 return match;
1171 };
1172 this.intro = this.intro.replace(pattern, replacer);
1173 var charIndex = 0;
1174 var chunk = this.firstChunk;
1175 while (chunk) {
1176 var end = chunk.end;
1177 if (chunk.edited) {
1178 if (!isExcluded[charIndex]) {
1179 chunk.content = chunk.content.replace(pattern, replacer);
1180 if (chunk.content.length) {
1181 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1182 }
1183 }
1184 }
1185 else {
1186 charIndex = chunk.start;
1187 while (charIndex < end) {
1188 if (!isExcluded[charIndex]) {
1189 var char = this$1.original[charIndex];
1190 if (char === '\n') {
1191 shouldIndentNextCharacter = true;
1192 }
1193 else if (char !== '\r' && shouldIndentNextCharacter) {
1194 shouldIndentNextCharacter = false;
1195 if (charIndex === chunk.start) {
1196 chunk.prependRight(indentStr);
1197 }
1198 else {
1199 this$1._splitChunk(chunk, charIndex);
1200 chunk = chunk.next;
1201 chunk.prependRight(indentStr);
1202 }
1203 }
1204 }
1205 charIndex += 1;
1206 }
1207 }
1208 charIndex = chunk.end;
1209 chunk = chunk.next;
1210 }
1211 this.outro = this.outro.replace(pattern, replacer);
1212 return this;
1213};
1214MagicString.prototype.insert = function insert() {
1215 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
1216};
1217MagicString.prototype.insertLeft = function insertLeft(index, content) {
1218 if (!warned.insertLeft) {
1219 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
1220 warned.insertLeft = true;
1221 }
1222 return this.appendLeft(index, content);
1223};
1224MagicString.prototype.insertRight = function insertRight(index, content) {
1225 if (!warned.insertRight) {
1226 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
1227 warned.insertRight = true;
1228 }
1229 return this.prependRight(index, content);
1230};
1231MagicString.prototype.move = function move(start, end, index) {
1232 if (index >= start && index <= end) {
1233 throw new Error('Cannot move a selection inside itself');
1234 }
1235 this._split(start);
1236 this._split(end);
1237 this._split(index);
1238 var first = this.byStart[start];
1239 var last = this.byEnd[end];
1240 var oldLeft = first.previous;
1241 var oldRight = last.next;
1242 var newRight = this.byStart[index];
1243 if (!newRight && last === this.lastChunk) {
1244 return this;
1245 }
1246 var newLeft = newRight ? newRight.previous : this.lastChunk;
1247 if (oldLeft) {
1248 oldLeft.next = oldRight;
1249 }
1250 if (oldRight) {
1251 oldRight.previous = oldLeft;
1252 }
1253 if (newLeft) {
1254 newLeft.next = first;
1255 }
1256 if (newRight) {
1257 newRight.previous = last;
1258 }
1259 if (!first.previous) {
1260 this.firstChunk = last.next;
1261 }
1262 if (!last.next) {
1263 this.lastChunk = first.previous;
1264 this.lastChunk.next = null;
1265 }
1266 first.previous = newLeft;
1267 last.next = newRight || null;
1268 if (!newLeft) {
1269 this.firstChunk = first;
1270 }
1271 if (!newRight) {
1272 this.lastChunk = last;
1273 }
1274 return this;
1275};
1276MagicString.prototype.overwrite = function overwrite(start, end, content, options) {
1277 var this$1 = this;
1278 if (typeof content !== 'string') {
1279 throw new TypeError('replacement content must be a string');
1280 }
1281 while (start < 0) {
1282 start += this$1.original.length;
1283 }
1284 while (end < 0) {
1285 end += this$1.original.length;
1286 }
1287 if (end > this.original.length) {
1288 throw new Error('end is out of bounds');
1289 }
1290 if (start === end) {
1291 throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead');
1292 }
1293 this._split(start);
1294 this._split(end);
1295 if (options === true) {
1296 if (!warned.storeName) {
1297 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
1298 warned.storeName = true;
1299 }
1300 options = { storeName: true };
1301 }
1302 var storeName = options !== undefined ? options.storeName : false;
1303 var contentOnly = options !== undefined ? options.contentOnly : false;
1304 if (storeName) {
1305 var original = this.original.slice(start, end);
1306 this.storedNames[original] = true;
1307 }
1308 var first = this.byStart[start];
1309 var last = this.byEnd[end];
1310 if (first) {
1311 if (end > first.end && first.next !== this.byStart[first.end]) {
1312 throw new Error('Cannot overwrite across a split point');
1313 }
1314 first.edit(content, storeName, contentOnly);
1315 if (first !== last) {
1316 var chunk = first.next;
1317 while (chunk !== last) {
1318 chunk.edit('', false);
1319 chunk = chunk.next;
1320 }
1321 chunk.edit('', false);
1322 }
1323 }
1324 else {
1325 // must be inserting at the end
1326 var newChunk = new Chunk(start, end, '').edit(content, storeName);
1327 // TODO last chunk in the array may not be the last chunk, if it's moved...
1328 last.next = newChunk;
1329 newChunk.previous = last;
1330 }
1331 return this;
1332};
1333MagicString.prototype.prepend = function prepend(content) {
1334 if (typeof content !== 'string') {
1335 throw new TypeError('outro content must be a string');
1336 }
1337 this.intro = content + this.intro;
1338 return this;
1339};
1340MagicString.prototype.prependLeft = function prependLeft(index, content) {
1341 if (typeof content !== 'string') {
1342 throw new TypeError('inserted content must be a string');
1343 }
1344 this._split(index);
1345 var chunk = this.byEnd[index];
1346 if (chunk) {
1347 chunk.prependLeft(content);
1348 }
1349 else {
1350 this.intro = content + this.intro;
1351 }
1352 return this;
1353};
1354MagicString.prototype.prependRight = function prependRight(index, content) {
1355 if (typeof content !== 'string') {
1356 throw new TypeError('inserted content must be a string');
1357 }
1358 this._split(index);
1359 var chunk = this.byStart[index];
1360 if (chunk) {
1361 chunk.prependRight(content);
1362 }
1363 else {
1364 this.outro = content + this.outro;
1365 }
1366 return this;
1367};
1368MagicString.prototype.remove = function remove(start, end) {
1369 var this$1 = this;
1370 while (start < 0) {
1371 start += this$1.original.length;
1372 }
1373 while (end < 0) {
1374 end += this$1.original.length;
1375 }
1376 if (start === end) {
1377 return this;
1378 }
1379 if (start < 0 || end > this.original.length) {
1380 throw new Error('Character is out of bounds');
1381 }
1382 if (start > end) {
1383 throw new Error('end must be greater than start');
1384 }
1385 this._split(start);
1386 this._split(end);
1387 var chunk = this.byStart[start];
1388 while (chunk) {
1389 chunk.intro = '';
1390 chunk.outro = '';
1391 chunk.edit('');
1392 chunk = end > chunk.end ? this$1.byStart[chunk.end] : null;
1393 }
1394 return this;
1395};
1396MagicString.prototype.lastChar = function lastChar() {
1397 if (this.outro.length) {
1398 return this.outro[this.outro.length - 1];
1399 }
1400 var chunk = this.lastChunk;
1401 do {
1402 if (chunk.outro.length) {
1403 return chunk.outro[chunk.outro.length - 1];
1404 }
1405 if (chunk.content.length) {
1406 return chunk.content[chunk.content.length - 1];
1407 }
1408 if (chunk.intro.length) {
1409 return chunk.intro[chunk.intro.length - 1];
1410 }
1411 } while (chunk = chunk.previous);
1412 if (this.intro.length) {
1413 return this.intro[this.intro.length - 1];
1414 }
1415 return '';
1416};
1417MagicString.prototype.lastLine = function lastLine() {
1418 var lineIndex = this.outro.lastIndexOf(n);
1419 if (lineIndex !== -1) {
1420 return this.outro.substr(lineIndex + 1);
1421 }
1422 var lineStr = this.outro;
1423 var chunk = this.lastChunk;
1424 do {
1425 if (chunk.outro.length > 0) {
1426 lineIndex = chunk.outro.lastIndexOf(n);
1427 if (lineIndex !== -1) {
1428 return chunk.outro.substr(lineIndex + 1) + lineStr;
1429 }
1430 lineStr = chunk.outro + lineStr;
1431 }
1432 if (chunk.content.length > 0) {
1433 lineIndex = chunk.content.lastIndexOf(n);
1434 if (lineIndex !== -1) {
1435 return chunk.content.substr(lineIndex + 1) + lineStr;
1436 }
1437 lineStr = chunk.content + lineStr;
1438 }
1439 if (chunk.intro.length > 0) {
1440 lineIndex = chunk.intro.lastIndexOf(n);
1441 if (lineIndex !== -1) {
1442 return chunk.intro.substr(lineIndex + 1) + lineStr;
1443 }
1444 lineStr = chunk.intro + lineStr;
1445 }
1446 } while (chunk = chunk.previous);
1447 lineIndex = this.intro.lastIndexOf(n);
1448 if (lineIndex !== -1) {
1449 return this.intro.substr(lineIndex + 1) + lineStr;
1450 }
1451 return this.intro + lineStr;
1452};
1453MagicString.prototype.slice = function slice(start, end) {
1454 var this$1 = this;
1455 if (start === void 0)
1456 start = 0;
1457 if (end === void 0)
1458 end = this.original.length;
1459 while (start < 0) {
1460 start += this$1.original.length;
1461 }
1462 while (end < 0) {
1463 end += this$1.original.length;
1464 }
1465 var result = '';
1466 // find start chunk
1467 var chunk = this.firstChunk;
1468 while (chunk && (chunk.start > start || chunk.end <= start)) {
1469 // found end chunk before start
1470 if (chunk.start < end && chunk.end >= end) {
1471 return result;
1472 }
1473 chunk = chunk.next;
1474 }
1475 if (chunk && chunk.edited && chunk.start !== start) {
1476 throw new Error(("Cannot use replaced character " + start + " as slice start anchor."));
1477 }
1478 var startChunk = chunk;
1479 while (chunk) {
1480 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1481 result += chunk.intro;
1482 }
1483 var containsEnd = chunk.start < end && chunk.end >= end;
1484 if (containsEnd && chunk.edited && chunk.end !== end) {
1485 throw new Error(("Cannot use replaced character " + end + " as slice end anchor."));
1486 }
1487 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1488 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1489 result += chunk.content.slice(sliceStart, sliceEnd);
1490 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1491 result += chunk.outro;
1492 }
1493 if (containsEnd) {
1494 break;
1495 }
1496 chunk = chunk.next;
1497 }
1498 return result;
1499};
1500// TODO deprecate this? not really very useful
1501MagicString.prototype.snip = function snip(start, end) {
1502 var clone = this.clone();
1503 clone.remove(0, start);
1504 clone.remove(end, clone.original.length);
1505 return clone;
1506};
1507MagicString.prototype._split = function _split(index) {
1508 var this$1 = this;
1509 if (this.byStart[index] || this.byEnd[index]) {
1510 return;
1511 }
1512 var chunk = this.lastSearchedChunk;
1513 var searchForward = index > chunk.end;
1514 while (chunk) {
1515 if (chunk.contains(index)) {
1516 return this$1._splitChunk(chunk, index);
1517 }
1518 chunk = searchForward ? this$1.byStart[chunk.end] : this$1.byEnd[chunk.start];
1519 }
1520};
1521MagicString.prototype._splitChunk = function _splitChunk(chunk, index) {
1522 if (chunk.edited && chunk.content.length) {
1523 // zero-length edited chunks are a special case (overlapping replacements)
1524 var loc = getLocator(this.original)(index);
1525 throw new Error(("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")"));
1526 }
1527 var newChunk = chunk.split(index);
1528 this.byEnd[index] = chunk;
1529 this.byStart[index] = newChunk;
1530 this.byEnd[newChunk.end] = newChunk;
1531 if (chunk === this.lastChunk) {
1532 this.lastChunk = newChunk;
1533 }
1534 this.lastSearchedChunk = chunk;
1535 return true;
1536};
1537MagicString.prototype.toString = function toString() {
1538 var str = this.intro;
1539 var chunk = this.firstChunk;
1540 while (chunk) {
1541 str += chunk.toString();
1542 chunk = chunk.next;
1543 }
1544 return str + this.outro;
1545};
1546MagicString.prototype.isEmpty = function isEmpty() {
1547 var chunk = this.firstChunk;
1548 do {
1549 if (chunk.intro.length && chunk.intro.trim() ||
1550 chunk.content.length && chunk.content.trim() ||
1551 chunk.outro.length && chunk.outro.trim()) {
1552 return false;
1553 }
1554 } while (chunk = chunk.next);
1555 return true;
1556};
1557MagicString.prototype.length = function length() {
1558 var chunk = this.firstChunk;
1559 var length = 0;
1560 do {
1561 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1562 } while (chunk = chunk.next);
1563 return length;
1564};
1565MagicString.prototype.trimLines = function trimLines() {
1566 return this.trim('[\\r\\n]');
1567};
1568MagicString.prototype.trim = function trim(charType) {
1569 return this.trimStart(charType).trimEnd(charType);
1570};
1571MagicString.prototype.trimEndAborted = function trimEndAborted(charType) {
1572 var this$1 = this;
1573 var rx = new RegExp((charType || '\\s') + '+$');
1574 this.outro = this.outro.replace(rx, '');
1575 if (this.outro.length) {
1576 return true;
1577 }
1578 var chunk = this.lastChunk;
1579 do {
1580 var end = chunk.end;
1581 var aborted = chunk.trimEnd(rx);
1582 // if chunk was trimmed, we have a new lastChunk
1583 if (chunk.end !== end) {
1584 if (this$1.lastChunk === chunk) {
1585 this$1.lastChunk = chunk.next;
1586 }
1587 this$1.byEnd[chunk.end] = chunk;
1588 this$1.byStart[chunk.next.start] = chunk.next;
1589 this$1.byEnd[chunk.next.end] = chunk.next;
1590 }
1591 if (aborted) {
1592 return true;
1593 }
1594 chunk = chunk.previous;
1595 } while (chunk);
1596 return false;
1597};
1598MagicString.prototype.trimEnd = function trimEnd(charType) {
1599 this.trimEndAborted(charType);
1600 return this;
1601};
1602MagicString.prototype.trimStartAborted = function trimStartAborted(charType) {
1603 var this$1 = this;
1604 var rx = new RegExp('^' + (charType || '\\s') + '+');
1605 this.intro = this.intro.replace(rx, '');
1606 if (this.intro.length) {
1607 return true;
1608 }
1609 var chunk = this.firstChunk;
1610 do {
1611 var end = chunk.end;
1612 var aborted = chunk.trimStart(rx);
1613 if (chunk.end !== end) {
1614 // special case...
1615 if (chunk === this$1.lastChunk) {
1616 this$1.lastChunk = chunk.next;
1617 }
1618 this$1.byEnd[chunk.end] = chunk;
1619 this$1.byStart[chunk.next.start] = chunk.next;
1620 this$1.byEnd[chunk.next.end] = chunk.next;
1621 }
1622 if (aborted) {
1623 return true;
1624 }
1625 chunk = chunk.next;
1626 } while (chunk);
1627 return false;
1628};
1629MagicString.prototype.trimStart = function trimStart(charType) {
1630 this.trimStartAborted(charType);
1631 return this;
1632};
1633var hasOwnProp = Object.prototype.hasOwnProperty;
1634var Bundle = function Bundle(options) {
1635 if (options === void 0)
1636 options = {};
1637 this.intro = options.intro || '';
1638 this.separator = options.separator !== undefined ? options.separator : '\n';
1639 this.sources = [];
1640 this.uniqueSources = [];
1641 this.uniqueSourceIndexByFilename = {};
1642};
1643Bundle.prototype.addSource = function addSource(source) {
1644 if (source instanceof MagicString) {
1645 return this.addSource({
1646 content: source,
1647 filename: source.filename,
1648 separator: this.separator
1649 });
1650 }
1651 if (!isObject(source) || !source.content) {
1652 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
1653 }
1654 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
1655 if (!hasOwnProp.call(source, option)) {
1656 source[option] = source.content[option];
1657 }
1658 });
1659 if (source.separator === undefined) {
1660 // TODO there's a bunch of this sort of thing, needs cleaning up
1661 source.separator = this.separator;
1662 }
1663 if (source.filename) {
1664 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
1665 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
1666 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
1667 }
1668 else {
1669 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
1670 if (source.content.original !== uniqueSource.content) {
1671 throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
1672 }
1673 }
1674 }
1675 this.sources.push(source);
1676 return this;
1677};
1678Bundle.prototype.append = function append(str, options) {
1679 this.addSource({
1680 content: new MagicString(str),
1681 separator: (options && options.separator) || ''
1682 });
1683 return this;
1684};
1685Bundle.prototype.clone = function clone() {
1686 var bundle = new Bundle({
1687 intro: this.intro,
1688 separator: this.separator
1689 });
1690 this.sources.forEach(function (source) {
1691 bundle.addSource({
1692 filename: source.filename,
1693 content: source.content.clone(),
1694 separator: source.separator
1695 });
1696 });
1697 return bundle;
1698};
1699Bundle.prototype.generateDecodedMap = function generateDecodedMap(options) {
1700 var this$1 = this;
1701 if (options === void 0)
1702 options = {};
1703 var names = [];
1704 this.sources.forEach(function (source) {
1705 Object.keys(source.content.storedNames).forEach(function (name) {
1706 if (!~names.indexOf(name)) {
1707 names.push(name);
1708 }
1709 });
1710 });
1711 var mappings = new Mappings(options.hires);
1712 if (this.intro) {
1713 mappings.advance(this.intro);
1714 }
1715 this.sources.forEach(function (source, i) {
1716 if (i > 0) {
1717 mappings.advance(this$1.separator);
1718 }
1719 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
1720 var magicString = source.content;
1721 var locate = getLocator(magicString.original);
1722 if (magicString.intro) {
1723 mappings.advance(magicString.intro);
1724 }
1725 magicString.firstChunk.eachNext(function (chunk) {
1726 var loc = locate(chunk.start);
1727 if (chunk.intro.length) {
1728 mappings.advance(chunk.intro);
1729 }
1730 if (source.filename) {
1731 if (chunk.edited) {
1732 mappings.addEdit(sourceIndex, chunk.content, loc, chunk.storeName ? names.indexOf(chunk.original) : -1);
1733 }
1734 else {
1735 mappings.addUneditedChunk(sourceIndex, chunk, magicString.original, loc, magicString.sourcemapLocations);
1736 }
1737 }
1738 else {
1739 mappings.advance(chunk.content);
1740 }
1741 if (chunk.outro.length) {
1742 mappings.advance(chunk.outro);
1743 }
1744 });
1745 if (magicString.outro) {
1746 mappings.advance(magicString.outro);
1747 }
1748 });
1749 return {
1750 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1751 sources: this.uniqueSources.map(function (source) {
1752 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
1753 }),
1754 sourcesContent: this.uniqueSources.map(function (source) {
1755 return options.includeContent ? source.content : null;
1756 }),
1757 names: names,
1758 mappings: mappings.raw
1759 };
1760};
1761Bundle.prototype.generateMap = function generateMap(options) {
1762 return new SourceMap(this.generateDecodedMap(options));
1763};
1764Bundle.prototype.getIndentString = function getIndentString() {
1765 var indentStringCounts = {};
1766 this.sources.forEach(function (source) {
1767 var indentStr = source.content.indentStr;
1768 if (indentStr === null) {
1769 return;
1770 }
1771 if (!indentStringCounts[indentStr]) {
1772 indentStringCounts[indentStr] = 0;
1773 }
1774 indentStringCounts[indentStr] += 1;
1775 });
1776 return (Object.keys(indentStringCounts).sort(function (a, b) {
1777 return indentStringCounts[a] - indentStringCounts[b];
1778 })[0] || '\t');
1779};
1780Bundle.prototype.indent = function indent(indentStr) {
1781 var this$1 = this;
1782 if (!arguments.length) {
1783 indentStr = this.getIndentString();
1784 }
1785 if (indentStr === '') {
1786 return this;
1787 } // noop
1788 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
1789 this.sources.forEach(function (source, i) {
1790 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1791 var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
1792 source.content.indent(indentStr, {
1793 exclude: source.indentExclusionRanges,
1794 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
1795 });
1796 trailingNewline = source.content.lastChar() === '\n';
1797 });
1798 if (this.intro) {
1799 this.intro =
1800 indentStr +
1801 this.intro.replace(/^[^\n]/gm, function (match, index) {
1802 return index > 0 ? indentStr + match : match;
1803 });
1804 }
1805 return this;
1806};
1807Bundle.prototype.prepend = function prepend(str) {
1808 this.intro = str + this.intro;
1809 return this;
1810};
1811Bundle.prototype.toString = function toString() {
1812 var this$1 = this;
1813 var body = this.sources
1814 .map(function (source, i) {
1815 var separator = source.separator !== undefined ? source.separator : this$1.separator;
1816 var str = (i > 0 ? separator : '') + source.content.toString();
1817 return str;
1818 })
1819 .join('');
1820 return this.intro + body;
1821};
1822Bundle.prototype.isEmpty = function isEmpty() {
1823 if (this.intro.length && this.intro.trim()) {
1824 return false;
1825 }
1826 if (this.sources.some(function (source) { return !source.content.isEmpty(); })) {
1827 return false;
1828 }
1829 return true;
1830};
1831Bundle.prototype.length = function length() {
1832 return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
1833};
1834Bundle.prototype.trimLines = function trimLines() {
1835 return this.trim('[\\r\\n]');
1836};
1837Bundle.prototype.trim = function trim(charType) {
1838 return this.trimStart(charType).trimEnd(charType);
1839};
1840Bundle.prototype.trimStart = function trimStart(charType) {
1841 var this$1 = this;
1842 var rx = new RegExp('^' + (charType || '\\s') + '+');
1843 this.intro = this.intro.replace(rx, '');
1844 if (!this.intro) {
1845 var source;
1846 var i = 0;
1847 do {
1848 source = this$1.sources[i++];
1849 if (!source) {
1850 break;
1851 }
1852 } while (!source.content.trimStartAborted(charType));
1853 }
1854 return this;
1855};
1856Bundle.prototype.trimEnd = function trimEnd(charType) {
1857 var this$1 = this;
1858 var rx = new RegExp((charType || '\\s') + '+$');
1859 var source;
1860 var i = this.sources.length - 1;
1861 do {
1862 source = this$1.sources[i--];
1863 if (!source) {
1864 this$1.intro = this$1.intro.replace(rx, '');
1865 break;
1866 }
1867 } while (!source.content.trimEndAborted(charType));
1868 return this;
1869};
1870
1871function relative(from, to) {
1872 const fromParts = from.split(/[/\\]/).filter(Boolean);
1873 const toParts = to.split(/[/\\]/).filter(Boolean);
1874 if (fromParts[0] === '.')
1875 fromParts.shift();
1876 if (toParts[0] === '.')
1877 toParts.shift();
1878 while (fromParts[0] && toParts[0] && fromParts[0] === toParts[0]) {
1879 fromParts.shift();
1880 toParts.shift();
1881 }
1882 while (toParts[0] === '..' && fromParts.length > 0) {
1883 toParts.shift();
1884 fromParts.pop();
1885 }
1886 while (fromParts.pop()) {
1887 toParts.unshift('..');
1888 }
1889 return toParts.join('/');
1890}
1891
1892const UnknownKey = Symbol('Unknown Key');
1893const EMPTY_PATH = [];
1894const UNKNOWN_PATH = [UnknownKey];
1895const EntitiesKey = Symbol('Entities');
1896class PathTracker {
1897 constructor() {
1898 this.entityPaths = Object.create(null, { [EntitiesKey]: { value: new Set() } });
1899 }
1900 getEntities(path) {
1901 let currentPaths = this.entityPaths;
1902 for (const pathSegment of path) {
1903 currentPaths = currentPaths[pathSegment] =
1904 currentPaths[pathSegment] ||
1905 Object.create(null, { [EntitiesKey]: { value: new Set() } });
1906 }
1907 return currentPaths[EntitiesKey];
1908 }
1909}
1910const EMPTY_IMMUTABLE_TRACKER = new PathTracker();
1911
1912const BROKEN_FLOW_NONE = 0;
1913const BROKEN_FLOW_BREAK_CONTINUE = 1;
1914const BROKEN_FLOW_ERROR_RETURN_LABEL = 2;
1915function createInclusionContext() {
1916 return {
1917 brokenFlow: BROKEN_FLOW_NONE,
1918 includedLabels: new Set()
1919 };
1920}
1921function createHasEffectsContext() {
1922 return {
1923 accessed: new PathTracker(),
1924 assigned: new PathTracker(),
1925 brokenFlow: BROKEN_FLOW_NONE,
1926 called: new PathTracker(),
1927 ignore: {
1928 breaks: false,
1929 continues: false,
1930 labels: new Set(),
1931 returnAwaitYield: false
1932 },
1933 includedLabels: new Set(),
1934 instantiated: new PathTracker(),
1935 replacedVariableInits: new Map()
1936 };
1937}
1938
1939const BLANK = Object.create(null);
1940
1941const BlockStatement = 'BlockStatement';
1942const CallExpression = 'CallExpression';
1943const ExportAllDeclaration = 'ExportAllDeclaration';
1944const ExpressionStatement = 'ExpressionStatement';
1945const FunctionExpression = 'FunctionExpression';
1946const Identifier = 'Identifier';
1947const ImportDefaultSpecifier = 'ImportDefaultSpecifier';
1948const ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
1949const Program = 'Program';
1950const Property = 'Property';
1951const ReturnStatement = 'ReturnStatement';
1952const VariableDeclaration = 'VariableDeclaration';
1953
1954function treeshakeNode(node, code, start, end) {
1955 code.remove(start, end);
1956 if (node.annotations) {
1957 for (const annotation of node.annotations) {
1958 if (annotation.start < start) {
1959 code.remove(annotation.start, annotation.end);
1960 }
1961 else {
1962 return;
1963 }
1964 }
1965 }
1966}
1967function removeAnnotations(node, code) {
1968 if (!node.annotations && node.parent.type === ExpressionStatement) {
1969 node = node.parent;
1970 }
1971 if (node.annotations) {
1972 for (const annotation of node.annotations) {
1973 code.remove(annotation.start, annotation.end);
1974 }
1975 }
1976}
1977
1978const NO_SEMICOLON = { isNoStatement: true };
1979// This assumes there are only white-space and comments between start and the string we are looking for
1980function findFirstOccurrenceOutsideComment(code, searchString, start = 0) {
1981 let searchPos, charCodeAfterSlash;
1982 searchPos = code.indexOf(searchString, start);
1983 while (true) {
1984 start = code.indexOf('/', start);
1985 if (start === -1 || start > searchPos)
1986 return searchPos;
1987 charCodeAfterSlash = code.charCodeAt(++start);
1988 ++start;
1989 // With our assumption, '/' always starts a comment. Determine comment type:
1990 start =
1991 charCodeAfterSlash === 47 /*"/"*/
1992 ? code.indexOf('\n', start) + 1
1993 : code.indexOf('*/', start) + 2;
1994 if (start > searchPos) {
1995 searchPos = code.indexOf(searchString, start);
1996 }
1997 }
1998}
1999// This assumes "code" only contains white-space and comments
2000function findFirstLineBreakOutsideComment(code) {
2001 let lineBreakPos, charCodeAfterSlash, start = 0;
2002 lineBreakPos = code.indexOf('\n', start);
2003 while (true) {
2004 start = code.indexOf('/', start);
2005 if (start === -1 || start > lineBreakPos)
2006 return lineBreakPos;
2007 // With our assumption, '/' always starts a comment. Determine comment type:
2008 charCodeAfterSlash = code.charCodeAt(++start);
2009 if (charCodeAfterSlash === 47 /*"/"*/)
2010 return lineBreakPos;
2011 start = code.indexOf('*/', start + 2) + 2;
2012 if (start > lineBreakPos) {
2013 lineBreakPos = code.indexOf('\n', start);
2014 }
2015 }
2016}
2017function renderStatementList(statements, code, start, end, options) {
2018 let currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
2019 let nextNode = statements[0];
2020 let nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
2021 if (nextNodeNeedsBoundaries) {
2022 nextNodeStart =
2023 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start)) + 1;
2024 }
2025 for (let nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
2026 currentNode = nextNode;
2027 currentNodeStart = nextNodeStart;
2028 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
2029 nextNode = statements[nextIndex];
2030 nextNodeNeedsBoundaries =
2031 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
2032 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
2033 nextNodeStart =
2034 currentNode.end +
2035 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start)) +
2036 1;
2037 if (currentNode.included) {
2038 currentNodeNeedsBoundaries
2039 ? currentNode.render(code, options, {
2040 end: nextNodeStart,
2041 start: currentNodeStart
2042 })
2043 : currentNode.render(code, options);
2044 }
2045 else {
2046 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
2047 }
2048 }
2049 else {
2050 currentNode.render(code, options);
2051 }
2052 }
2053}
2054// This assumes that the first character is not part of the first node
2055function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
2056 const splitUpNodes = [];
2057 let node, nextNode, nextNodeStart, contentEnd, char;
2058 let separator = start - 1;
2059 for (let nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
2060 nextNode = nodes[nextIndex];
2061 if (node !== undefined) {
2062 separator =
2063 node.end +
2064 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
2065 }
2066 nextNodeStart = contentEnd =
2067 separator +
2068 2 +
2069 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start));
2070 while (((char = code.original.charCodeAt(nextNodeStart)),
2071 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
2072 nextNodeStart++;
2073 if (node !== undefined) {
2074 splitUpNodes.push({
2075 contentEnd,
2076 end: nextNodeStart,
2077 node,
2078 separator,
2079 start
2080 });
2081 }
2082 node = nextNode;
2083 start = nextNodeStart;
2084 }
2085 splitUpNodes.push({
2086 contentEnd: end,
2087 end,
2088 node: node,
2089 separator: null,
2090 start
2091 });
2092 return splitUpNodes;
2093}
2094// This assumes there are only white-space and comments between start and end
2095function removeLineBreaks(code, start, end) {
2096 while (true) {
2097 const lineBreakPos = findFirstLineBreakOutsideComment(code.original.slice(start, end));
2098 if (lineBreakPos === -1) {
2099 break;
2100 }
2101 start = start + lineBreakPos + 1;
2102 code.remove(start - 1, start);
2103 }
2104}
2105
2106const chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
2107const base = 64;
2108function toBase64(num) {
2109 let outStr = '';
2110 do {
2111 const curDigit = num % base;
2112 num = Math.floor(num / base);
2113 outStr = chars$1[curDigit] + outStr;
2114 } while (num !== 0);
2115 return outStr;
2116}
2117
2118// Verified on IE 6/7 that these keywords can't be used for object properties without escaping:
2119// break case catch class const continue debugger default delete do
2120// else enum export extends false finally for function if import
2121// in instanceof new null return super switch this throw true
2122// try typeof var void while with
2123const RESERVED_NAMES = Object.assign(Object.create(null), {
2124 await: true,
2125 break: true,
2126 case: true,
2127 catch: true,
2128 class: true,
2129 const: true,
2130 continue: true,
2131 debugger: true,
2132 default: true,
2133 delete: true,
2134 do: true,
2135 else: true,
2136 enum: true,
2137 eval: true,
2138 export: true,
2139 extends: true,
2140 false: true,
2141 finally: true,
2142 for: true,
2143 function: true,
2144 if: true,
2145 implements: true,
2146 import: true,
2147 in: true,
2148 instanceof: true,
2149 interface: true,
2150 let: true,
2151 new: true,
2152 null: true,
2153 package: true,
2154 private: true,
2155 protected: true,
2156 public: true,
2157 return: true,
2158 static: true,
2159 super: true,
2160 switch: true,
2161 this: true,
2162 throw: true,
2163 true: true,
2164 try: true,
2165 typeof: true,
2166 undefined: true,
2167 var: true,
2168 void: true,
2169 while: true,
2170 with: true,
2171 yield: true
2172});
2173
2174function getSafeName(baseName, usedNames) {
2175 let safeName = baseName;
2176 let count = 1;
2177 while (usedNames.has(safeName) || RESERVED_NAMES[safeName]) {
2178 safeName = `${baseName}$${toBase64(count++)}`;
2179 }
2180 usedNames.add(safeName);
2181 return safeName;
2182}
2183
2184const NO_ARGS = [];
2185
2186function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions = null) {
2187 return Object.create(inheritedDescriptions, memberDescriptions);
2188}
2189const UnknownValue = Symbol('Unknown Value');
2190const UNKNOWN_EXPRESSION = {
2191 deoptimizePath: () => { },
2192 getLiteralValueAtPath: () => UnknownValue,
2193 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
2194 hasEffectsWhenAccessedAtPath: path => path.length > 0,
2195 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2196 hasEffectsWhenCalledAtPath: () => true,
2197 include: () => { },
2198 includeCallArguments(context, args) {
2199 for (const arg of args) {
2200 arg.include(context, false);
2201 }
2202 },
2203 included: true,
2204 toString: () => '[[UNKNOWN]]'
2205};
2206const UNDEFINED_EXPRESSION = {
2207 deoptimizePath: () => { },
2208 getLiteralValueAtPath: () => undefined,
2209 getReturnExpressionWhenCalledAtPath: () => UNKNOWN_EXPRESSION,
2210 hasEffectsWhenAccessedAtPath: path => path.length > 0,
2211 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2212 hasEffectsWhenCalledAtPath: () => true,
2213 include: () => { },
2214 includeCallArguments() { },
2215 included: true,
2216 toString: () => 'undefined'
2217};
2218const returnsUnknown = {
2219 value: {
2220 callsArgs: null,
2221 mutatesSelf: false,
2222 returns: null,
2223 returnsPrimitive: UNKNOWN_EXPRESSION
2224 }
2225};
2226const mutatesSelfReturnsUnknown = {
2227 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
2228};
2229const callsArgReturnsUnknown = {
2230 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
2231};
2232class UnknownArrayExpression {
2233 constructor() {
2234 this.included = false;
2235 }
2236 deoptimizePath() { }
2237 getLiteralValueAtPath() {
2238 return UnknownValue;
2239 }
2240 getReturnExpressionWhenCalledAtPath(path) {
2241 if (path.length === 1) {
2242 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
2243 }
2244 return UNKNOWN_EXPRESSION;
2245 }
2246 hasEffectsWhenAccessedAtPath(path) {
2247 return path.length > 1;
2248 }
2249 hasEffectsWhenAssignedAtPath(path) {
2250 return path.length > 1;
2251 }
2252 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2253 if (path.length === 1) {
2254 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
2255 }
2256 return true;
2257 }
2258 include() {
2259 this.included = true;
2260 }
2261 includeCallArguments(context, args) {
2262 for (const arg of args) {
2263 arg.include(context, false);
2264 }
2265 }
2266 toString() {
2267 return '[[UNKNOWN ARRAY]]';
2268 }
2269}
2270const returnsArray = {
2271 value: {
2272 callsArgs: null,
2273 mutatesSelf: false,
2274 returns: UnknownArrayExpression,
2275 returnsPrimitive: null
2276 }
2277};
2278const mutatesSelfReturnsArray = {
2279 value: {
2280 callsArgs: null,
2281 mutatesSelf: true,
2282 returns: UnknownArrayExpression,
2283 returnsPrimitive: null
2284 }
2285};
2286const callsArgReturnsArray = {
2287 value: {
2288 callsArgs: [0],
2289 mutatesSelf: false,
2290 returns: UnknownArrayExpression,
2291 returnsPrimitive: null
2292 }
2293};
2294const callsArgMutatesSelfReturnsArray = {
2295 value: {
2296 callsArgs: [0],
2297 mutatesSelf: true,
2298 returns: UnknownArrayExpression,
2299 returnsPrimitive: null
2300 }
2301};
2302const UNKNOWN_LITERAL_BOOLEAN = {
2303 deoptimizePath: () => { },
2304 getLiteralValueAtPath: () => UnknownValue,
2305 getReturnExpressionWhenCalledAtPath: path => {
2306 if (path.length === 1) {
2307 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
2308 }
2309 return UNKNOWN_EXPRESSION;
2310 },
2311 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2312 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2313 hasEffectsWhenCalledAtPath: path => {
2314 if (path.length === 1) {
2315 const subPath = path[0];
2316 return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
2317 }
2318 return true;
2319 },
2320 include: () => { },
2321 includeCallArguments(context, args) {
2322 for (const arg of args) {
2323 arg.include(context, false);
2324 }
2325 },
2326 included: true,
2327 toString: () => '[[UNKNOWN BOOLEAN]]'
2328};
2329const returnsBoolean = {
2330 value: {
2331 callsArgs: null,
2332 mutatesSelf: false,
2333 returns: null,
2334 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2335 }
2336};
2337const callsArgReturnsBoolean = {
2338 value: {
2339 callsArgs: [0],
2340 mutatesSelf: false,
2341 returns: null,
2342 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2343 }
2344};
2345const UNKNOWN_LITERAL_NUMBER = {
2346 deoptimizePath: () => { },
2347 getLiteralValueAtPath: () => UnknownValue,
2348 getReturnExpressionWhenCalledAtPath: path => {
2349 if (path.length === 1) {
2350 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
2351 }
2352 return UNKNOWN_EXPRESSION;
2353 },
2354 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2355 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2356 hasEffectsWhenCalledAtPath: path => {
2357 if (path.length === 1) {
2358 const subPath = path[0];
2359 return typeof subPath !== 'string' || !literalNumberMembers[subPath];
2360 }
2361 return true;
2362 },
2363 include: () => { },
2364 includeCallArguments(context, args) {
2365 for (const arg of args) {
2366 arg.include(context, false);
2367 }
2368 },
2369 included: true,
2370 toString: () => '[[UNKNOWN NUMBER]]'
2371};
2372const returnsNumber = {
2373 value: {
2374 callsArgs: null,
2375 mutatesSelf: false,
2376 returns: null,
2377 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2378 }
2379};
2380const mutatesSelfReturnsNumber = {
2381 value: {
2382 callsArgs: null,
2383 mutatesSelf: true,
2384 returns: null,
2385 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2386 }
2387};
2388const callsArgReturnsNumber = {
2389 value: {
2390 callsArgs: [0],
2391 mutatesSelf: false,
2392 returns: null,
2393 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2394 }
2395};
2396const UNKNOWN_LITERAL_STRING = {
2397 deoptimizePath: () => { },
2398 getLiteralValueAtPath: () => UnknownValue,
2399 getReturnExpressionWhenCalledAtPath: path => {
2400 if (path.length === 1) {
2401 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
2402 }
2403 return UNKNOWN_EXPRESSION;
2404 },
2405 hasEffectsWhenAccessedAtPath: path => path.length > 1,
2406 hasEffectsWhenAssignedAtPath: path => path.length > 0,
2407 hasEffectsWhenCalledAtPath: (path, callOptions, context) => {
2408 if (path.length === 1) {
2409 return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, context);
2410 }
2411 return true;
2412 },
2413 include: () => { },
2414 includeCallArguments(context, args) {
2415 for (const arg of args) {
2416 arg.include(context, false);
2417 }
2418 },
2419 included: true,
2420 toString: () => '[[UNKNOWN STRING]]'
2421};
2422const returnsString = {
2423 value: {
2424 callsArgs: null,
2425 mutatesSelf: false,
2426 returns: null,
2427 returnsPrimitive: UNKNOWN_LITERAL_STRING
2428 }
2429};
2430class UnknownObjectExpression {
2431 constructor() {
2432 this.included = false;
2433 }
2434 deoptimizePath() { }
2435 getLiteralValueAtPath() {
2436 return UnknownValue;
2437 }
2438 getReturnExpressionWhenCalledAtPath(path) {
2439 if (path.length === 1) {
2440 return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
2441 }
2442 return UNKNOWN_EXPRESSION;
2443 }
2444 hasEffectsWhenAccessedAtPath(path) {
2445 return path.length > 1;
2446 }
2447 hasEffectsWhenAssignedAtPath(path) {
2448 return path.length > 1;
2449 }
2450 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2451 if (path.length === 1) {
2452 return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, context);
2453 }
2454 return true;
2455 }
2456 include() {
2457 this.included = true;
2458 }
2459 includeCallArguments(context, args) {
2460 for (const arg of args) {
2461 arg.include(context, false);
2462 }
2463 }
2464 toString() {
2465 return '[[UNKNOWN OBJECT]]';
2466 }
2467}
2468const objectMembers = assembleMemberDescriptions({
2469 hasOwnProperty: returnsBoolean,
2470 isPrototypeOf: returnsBoolean,
2471 propertyIsEnumerable: returnsBoolean,
2472 toLocaleString: returnsString,
2473 toString: returnsString,
2474 valueOf: returnsUnknown
2475});
2476const arrayMembers = assembleMemberDescriptions({
2477 concat: returnsArray,
2478 copyWithin: mutatesSelfReturnsArray,
2479 every: callsArgReturnsBoolean,
2480 fill: mutatesSelfReturnsArray,
2481 filter: callsArgReturnsArray,
2482 find: callsArgReturnsUnknown,
2483 findIndex: callsArgReturnsNumber,
2484 forEach: callsArgReturnsUnknown,
2485 includes: returnsBoolean,
2486 indexOf: returnsNumber,
2487 join: returnsString,
2488 lastIndexOf: returnsNumber,
2489 map: callsArgReturnsArray,
2490 pop: mutatesSelfReturnsUnknown,
2491 push: mutatesSelfReturnsNumber,
2492 reduce: callsArgReturnsUnknown,
2493 reduceRight: callsArgReturnsUnknown,
2494 reverse: mutatesSelfReturnsArray,
2495 shift: mutatesSelfReturnsUnknown,
2496 slice: returnsArray,
2497 some: callsArgReturnsBoolean,
2498 sort: callsArgMutatesSelfReturnsArray,
2499 splice: mutatesSelfReturnsArray,
2500 unshift: mutatesSelfReturnsNumber
2501}, objectMembers);
2502const literalBooleanMembers = assembleMemberDescriptions({
2503 valueOf: returnsBoolean
2504}, objectMembers);
2505const literalNumberMembers = assembleMemberDescriptions({
2506 toExponential: returnsString,
2507 toFixed: returnsString,
2508 toLocaleString: returnsString,
2509 toPrecision: returnsString,
2510 valueOf: returnsNumber
2511}, objectMembers);
2512const literalStringMembers = assembleMemberDescriptions({
2513 charAt: returnsString,
2514 charCodeAt: returnsNumber,
2515 codePointAt: returnsNumber,
2516 concat: returnsString,
2517 endsWith: returnsBoolean,
2518 includes: returnsBoolean,
2519 indexOf: returnsNumber,
2520 lastIndexOf: returnsNumber,
2521 localeCompare: returnsNumber,
2522 match: returnsBoolean,
2523 normalize: returnsString,
2524 padEnd: returnsString,
2525 padStart: returnsString,
2526 repeat: returnsString,
2527 replace: {
2528 value: {
2529 callsArgs: [1],
2530 mutatesSelf: false,
2531 returns: null,
2532 returnsPrimitive: UNKNOWN_LITERAL_STRING
2533 }
2534 },
2535 search: returnsNumber,
2536 slice: returnsString,
2537 split: returnsArray,
2538 startsWith: returnsBoolean,
2539 substr: returnsString,
2540 substring: returnsString,
2541 toLocaleLowerCase: returnsString,
2542 toLocaleUpperCase: returnsString,
2543 toLowerCase: returnsString,
2544 toUpperCase: returnsString,
2545 trim: returnsString,
2546 valueOf: returnsString
2547}, objectMembers);
2548function getLiteralMembersForValue(value) {
2549 switch (typeof value) {
2550 case 'boolean':
2551 return literalBooleanMembers;
2552 case 'number':
2553 return literalNumberMembers;
2554 case 'string':
2555 return literalStringMembers;
2556 default:
2557 return Object.create(null);
2558 }
2559}
2560function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, context) {
2561 if (typeof memberName !== 'string' ||
2562 !members[memberName] ||
2563 (members[memberName].mutatesSelf && parentIncluded))
2564 return true;
2565 if (!members[memberName].callsArgs)
2566 return false;
2567 for (const argIndex of members[memberName].callsArgs) {
2568 if (callOptions.args[argIndex] &&
2569 callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, {
2570 args: NO_ARGS,
2571 withNew: false
2572 }, context))
2573 return true;
2574 }
2575 return false;
2576}
2577function getMemberReturnExpressionWhenCalled(members, memberName) {
2578 if (typeof memberName !== 'string' || !members[memberName])
2579 return UNKNOWN_EXPRESSION;
2580 return members[memberName].returnsPrimitive !== null
2581 ? members[memberName].returnsPrimitive
2582 : new members[memberName].returns();
2583}
2584
2585class Variable {
2586 constructor(name) {
2587 this.alwaysRendered = false;
2588 this.exportName = null;
2589 this.included = false;
2590 this.isId = false;
2591 this.isReassigned = false;
2592 this.renderBaseName = null;
2593 this.renderName = null;
2594 this.safeExportName = null;
2595 this.name = name;
2596 }
2597 /**
2598 * Binds identifiers that reference this variable to this variable.
2599 * Necessary to be able to change variable names.
2600 */
2601 addReference(_identifier) { }
2602 deoptimizePath(_path) { }
2603 getBaseVariableName() {
2604 return this.renderBaseName || this.renderName || this.name;
2605 }
2606 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
2607 return UnknownValue;
2608 }
2609 getName() {
2610 const name = this.renderName || this.name;
2611 return this.renderBaseName ? `${this.renderBaseName}.${name}` : name;
2612 }
2613 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
2614 return UNKNOWN_EXPRESSION;
2615 }
2616 hasEffectsWhenAccessedAtPath(path, _context) {
2617 return path.length > 0;
2618 }
2619 hasEffectsWhenAssignedAtPath(_path, _context) {
2620 return true;
2621 }
2622 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
2623 return true;
2624 }
2625 /**
2626 * Marks this variable as being part of the bundle, which is usually the case when one of
2627 * its identifiers becomes part of the bundle. Returns true if it has not been included
2628 * previously.
2629 * Once a variable is included, it should take care all its declarations are included.
2630 */
2631 include(_context) {
2632 this.included = true;
2633 }
2634 includeCallArguments(context, args) {
2635 for (const arg of args) {
2636 arg.include(context, false);
2637 }
2638 }
2639 markCalledFromTryStatement() { }
2640 setRenderNames(baseName, name) {
2641 this.renderBaseName = baseName;
2642 this.renderName = name;
2643 }
2644 setSafeName(name) {
2645 this.renderName = name;
2646 }
2647 toString() {
2648 return this.name;
2649 }
2650}
2651
2652class ExternalVariable extends Variable {
2653 constructor(module, name) {
2654 super(name);
2655 this.module = module;
2656 this.isNamespace = name === '*';
2657 this.referenced = false;
2658 }
2659 addReference(identifier) {
2660 this.referenced = true;
2661 if (this.name === 'default' || this.name === '*') {
2662 this.module.suggestName(identifier.name);
2663 }
2664 }
2665 include() {
2666 if (!this.included) {
2667 this.included = true;
2668 this.module.used = true;
2669 }
2670 }
2671}
2672
2673const 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(' ');
2674const 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(' ');
2675const blacklisted = Object.create(null);
2676reservedWords.concat(builtins).forEach(word => (blacklisted[word] = true));
2677const illegalCharacters = /[^$_a-zA-Z0-9]/g;
2678const startsWithDigit = (str) => /\d/.test(str[0]);
2679function isLegal(str) {
2680 if (startsWithDigit(str) || blacklisted[str]) {
2681 return false;
2682 }
2683 return !illegalCharacters.test(str);
2684}
2685function makeLegal(str) {
2686 str = str.replace(/-(\w)/g, (_, letter) => letter.toUpperCase()).replace(illegalCharacters, '_');
2687 if (startsWithDigit(str) || blacklisted[str])
2688 str = `_${str}`;
2689 return str || '_';
2690}
2691
2692class ExternalModule {
2693 constructor(graph, id, moduleSideEffects) {
2694 this.exportsNames = false;
2695 this.exportsNamespace = false;
2696 this.mostCommonSuggestion = 0;
2697 this.reexported = false;
2698 this.renderPath = undefined;
2699 this.renormalizeRenderPath = false;
2700 this.used = false;
2701 this.graph = graph;
2702 this.id = id;
2703 this.execIndex = Infinity;
2704 this.moduleSideEffects = moduleSideEffects;
2705 const parts = id.split(/[\\/]/);
2706 this.variableName = makeLegal(parts.pop());
2707 this.nameSuggestions = Object.create(null);
2708 this.declarations = Object.create(null);
2709 this.exportedVariables = new Map();
2710 }
2711 getVariableForExportName(name) {
2712 if (name === '*') {
2713 this.exportsNamespace = true;
2714 }
2715 else if (name !== 'default') {
2716 this.exportsNames = true;
2717 }
2718 let declaration = this.declarations[name];
2719 if (declaration)
2720 return declaration;
2721 this.declarations[name] = declaration = new ExternalVariable(this, name);
2722 this.exportedVariables.set(declaration, name);
2723 return declaration;
2724 }
2725 setRenderPath(options, inputBase) {
2726 this.renderPath = '';
2727 if (options.paths) {
2728 this.renderPath =
2729 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
2730 }
2731 if (!this.renderPath) {
2732 if (!index.isAbsolute(this.id)) {
2733 this.renderPath = this.id;
2734 }
2735 else {
2736 this.renderPath = index.normalize(path.relative(inputBase, this.id));
2737 this.renormalizeRenderPath = true;
2738 }
2739 }
2740 return this.renderPath;
2741 }
2742 suggestName(name) {
2743 if (!this.nameSuggestions[name])
2744 this.nameSuggestions[name] = 0;
2745 this.nameSuggestions[name] += 1;
2746 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
2747 this.mostCommonSuggestion = this.nameSuggestions[name];
2748 this.variableName = name;
2749 }
2750 }
2751 warnUnusedImports() {
2752 const unused = Object.keys(this.declarations).filter(name => {
2753 if (name === '*')
2754 return false;
2755 const declaration = this.declarations[name];
2756 return !declaration.included && !this.reexported && !declaration.referenced;
2757 });
2758 if (unused.length === 0)
2759 return;
2760 const names = unused.length === 1
2761 ? `'${unused[0]}' is`
2762 : `${unused
2763 .slice(0, -1)
2764 .map(name => `'${name}'`)
2765 .join(', ')} and '${unused.slice(-1)}' are`;
2766 this.graph.warn({
2767 code: 'UNUSED_EXTERNAL_IMPORT',
2768 message: `${names} imported from external module '${this.id}' but never used`,
2769 names: unused,
2770 source: this.id
2771 });
2772 }
2773}
2774
2775function markModuleAndImpureDependenciesAsExecuted(baseModule) {
2776 baseModule.isExecuted = true;
2777 const modules = [baseModule];
2778 const visitedModules = new Set();
2779 for (const module of modules) {
2780 for (const dependency of module.dependencies) {
2781 if (!(dependency instanceof ExternalModule) &&
2782 !dependency.isExecuted &&
2783 dependency.moduleSideEffects &&
2784 !visitedModules.has(dependency.id)) {
2785 dependency.isExecuted = true;
2786 visitedModules.add(dependency.id);
2787 modules.push(dependency);
2788 }
2789 }
2790 }
2791}
2792
2793// To avoid infinite recursions
2794const MAX_PATH_DEPTH = 7;
2795class LocalVariable extends Variable {
2796 constructor(name, declarator, init, context) {
2797 super(name);
2798 this.additionalInitializers = null;
2799 this.calledFromTryStatement = false;
2800 this.expressionsToBeDeoptimized = [];
2801 this.declarations = declarator ? [declarator] : [];
2802 this.init = init;
2803 this.deoptimizationTracker = context.deoptimizationTracker;
2804 this.module = context.module;
2805 }
2806 addDeclaration(identifier, init) {
2807 this.declarations.push(identifier);
2808 if (this.additionalInitializers === null) {
2809 this.additionalInitializers = this.init === null ? [] : [this.init];
2810 this.init = UNKNOWN_EXPRESSION;
2811 this.isReassigned = true;
2812 }
2813 if (init !== null) {
2814 this.additionalInitializers.push(init);
2815 }
2816 }
2817 consolidateInitializers() {
2818 if (this.additionalInitializers !== null) {
2819 for (const initializer of this.additionalInitializers) {
2820 initializer.deoptimizePath(UNKNOWN_PATH);
2821 }
2822 this.additionalInitializers = null;
2823 }
2824 }
2825 deoptimizePath(path) {
2826 if (path.length > MAX_PATH_DEPTH || this.isReassigned)
2827 return;
2828 const trackedEntities = this.deoptimizationTracker.getEntities(path);
2829 if (trackedEntities.has(this))
2830 return;
2831 trackedEntities.add(this);
2832 if (path.length === 0) {
2833 if (!this.isReassigned) {
2834 this.isReassigned = true;
2835 for (const expression of this.expressionsToBeDeoptimized) {
2836 expression.deoptimizeCache();
2837 }
2838 if (this.init) {
2839 this.init.deoptimizePath(UNKNOWN_PATH);
2840 }
2841 }
2842 }
2843 else if (this.init) {
2844 this.init.deoptimizePath(path);
2845 }
2846 }
2847 getLiteralValueAtPath(path, recursionTracker, origin) {
2848 if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
2849 return UnknownValue;
2850 }
2851 const trackedEntities = recursionTracker.getEntities(path);
2852 if (trackedEntities.has(this.init)) {
2853 return UnknownValue;
2854 }
2855 this.expressionsToBeDeoptimized.push(origin);
2856 trackedEntities.add(this.init);
2857 const value = this.init.getLiteralValueAtPath(path, recursionTracker, origin);
2858 trackedEntities.delete(this.init);
2859 return value;
2860 }
2861 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
2862 if (this.isReassigned || !this.init || path.length > MAX_PATH_DEPTH) {
2863 return UNKNOWN_EXPRESSION;
2864 }
2865 const trackedEntities = recursionTracker.getEntities(path);
2866 if (trackedEntities.has(this.init)) {
2867 return UNKNOWN_EXPRESSION;
2868 }
2869 this.expressionsToBeDeoptimized.push(origin);
2870 trackedEntities.add(this.init);
2871 const value = this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
2872 trackedEntities.delete(this.init);
2873 return value;
2874 }
2875 hasEffectsWhenAccessedAtPath(path, context) {
2876 if (path.length === 0)
2877 return false;
2878 if (this.isReassigned || path.length > MAX_PATH_DEPTH)
2879 return true;
2880 const trackedExpressions = context.accessed.getEntities(path);
2881 if (trackedExpressions.has(this))
2882 return false;
2883 trackedExpressions.add(this);
2884 return (this.init && this.init.hasEffectsWhenAccessedAtPath(path, context));
2885 }
2886 hasEffectsWhenAssignedAtPath(path, context) {
2887 if (this.included || path.length > MAX_PATH_DEPTH)
2888 return true;
2889 if (path.length === 0)
2890 return false;
2891 if (this.isReassigned)
2892 return true;
2893 const trackedExpressions = context.assigned.getEntities(path);
2894 if (trackedExpressions.has(this))
2895 return false;
2896 trackedExpressions.add(this);
2897 return (this.init && this.init.hasEffectsWhenAssignedAtPath(path, context));
2898 }
2899 hasEffectsWhenCalledAtPath(path, callOptions, context) {
2900 if (path.length > MAX_PATH_DEPTH || this.isReassigned)
2901 return true;
2902 const trackedExpressions = (callOptions.withNew
2903 ? context.instantiated
2904 : context.called).getEntities(path);
2905 if (trackedExpressions.has(this))
2906 return false;
2907 trackedExpressions.add(this);
2908 return (this.init &&
2909 this.init.hasEffectsWhenCalledAtPath(path, callOptions, context));
2910 }
2911 include(context) {
2912 if (!this.included) {
2913 this.included = true;
2914 if (!this.module.isExecuted) {
2915 markModuleAndImpureDependenciesAsExecuted(this.module);
2916 }
2917 for (const declaration of this.declarations) {
2918 // If node is a default export, it can save a tree-shaking run to include the full declaration now
2919 if (!declaration.included)
2920 declaration.include(context, false);
2921 let node = declaration.parent;
2922 while (!node.included) {
2923 // We do not want to properly include parents in case they are part of a dead branch
2924 // in which case .include() might pull in more dead code
2925 node.included = true;
2926 if (node.type === Program)
2927 break;
2928 node = node.parent;
2929 }
2930 }
2931 }
2932 }
2933 includeCallArguments(context, args) {
2934 if (this.isReassigned) {
2935 for (const arg of args) {
2936 arg.include(context, false);
2937 }
2938 }
2939 else if (this.init) {
2940 this.init.includeCallArguments(context, args);
2941 }
2942 }
2943 markCalledFromTryStatement() {
2944 this.calledFromTryStatement = true;
2945 }
2946}
2947
2948class Scope {
2949 constructor() {
2950 this.children = [];
2951 this.variables = new Map();
2952 }
2953 addDeclaration(identifier, context, init = null, _isHoisted) {
2954 const name = identifier.name;
2955 let variable = this.variables.get(name);
2956 if (variable) {
2957 variable.addDeclaration(identifier, init);
2958 }
2959 else {
2960 variable = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
2961 this.variables.set(name, variable);
2962 }
2963 return variable;
2964 }
2965 contains(name) {
2966 return this.variables.has(name);
2967 }
2968 findVariable(_name) {
2969 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
2970 }
2971}
2972
2973class ChildScope extends Scope {
2974 constructor(parent) {
2975 super();
2976 this.accessedOutsideVariables = new Map();
2977 this.parent = parent;
2978 parent.children.push(this);
2979 }
2980 addAccessedGlobalsByFormat(globalsByFormat) {
2981 let accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat;
2982 if (!accessedGlobalVariablesByFormat) {
2983 accessedGlobalVariablesByFormat = this.accessedGlobalVariablesByFormat = new Map();
2984 }
2985 for (const format of Object.keys(globalsByFormat)) {
2986 let accessedGlobalVariables = accessedGlobalVariablesByFormat.get(format);
2987 if (!accessedGlobalVariables) {
2988 accessedGlobalVariables = new Set();
2989 accessedGlobalVariablesByFormat.set(format, accessedGlobalVariables);
2990 }
2991 for (const name of globalsByFormat[format]) {
2992 accessedGlobalVariables.add(name);
2993 }
2994 }
2995 if (this.parent instanceof ChildScope) {
2996 this.parent.addAccessedGlobalsByFormat(globalsByFormat);
2997 }
2998 }
2999 addNamespaceMemberAccess(name, variable) {
3000 this.accessedOutsideVariables.set(name, variable);
3001 if (this.parent instanceof ChildScope) {
3002 this.parent.addNamespaceMemberAccess(name, variable);
3003 }
3004 }
3005 addReturnExpression(expression) {
3006 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
3007 }
3008 contains(name) {
3009 return this.variables.has(name) || this.parent.contains(name);
3010 }
3011 deconflict(format) {
3012 const usedNames = new Set();
3013 for (const variable of this.accessedOutsideVariables.values()) {
3014 if (variable.included) {
3015 usedNames.add(variable.getBaseVariableName());
3016 if (variable.exportName && format === 'system') {
3017 usedNames.add('exports');
3018 }
3019 }
3020 }
3021 const accessedGlobalVariables = this.accessedGlobalVariablesByFormat && this.accessedGlobalVariablesByFormat.get(format);
3022 if (accessedGlobalVariables) {
3023 for (const name of accessedGlobalVariables) {
3024 usedNames.add(name);
3025 }
3026 }
3027 for (const [name, variable] of this.variables) {
3028 if (variable.included || variable.alwaysRendered) {
3029 variable.setSafeName(getSafeName(name, usedNames));
3030 }
3031 }
3032 for (const scope of this.children) {
3033 scope.deconflict(format);
3034 }
3035 }
3036 findLexicalBoundary() {
3037 return this.parent instanceof ChildScope ? this.parent.findLexicalBoundary() : this;
3038 }
3039 findVariable(name) {
3040 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
3041 if (knownVariable) {
3042 return knownVariable;
3043 }
3044 const variable = this.parent.findVariable(name);
3045 this.accessedOutsideVariables.set(name, variable);
3046 return variable;
3047 }
3048}
3049
3050function getLocator$1(source, options) {
3051 if (options === void 0) {
3052 options = {};
3053 }
3054 var offsetLine = options.offsetLine || 0;
3055 var offsetColumn = options.offsetColumn || 0;
3056 var originalLines = source.split('\n');
3057 var start = 0;
3058 var lineRanges = originalLines.map(function (line, i) {
3059 var end = start + line.length + 1;
3060 var range = { start: start, end: end, line: i };
3061 start = end;
3062 return range;
3063 });
3064 var i = 0;
3065 function rangeContains(range, index) {
3066 return range.start <= index && index < range.end;
3067 }
3068 function getLocation(range, index) {
3069 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
3070 }
3071 function locate(search, startIndex) {
3072 if (typeof search === 'string') {
3073 search = source.indexOf(search, startIndex || 0);
3074 }
3075 var range = lineRanges[i];
3076 var d = search >= range.end ? 1 : -1;
3077 while (range) {
3078 if (rangeContains(range, search))
3079 return getLocation(range, search);
3080 i += d;
3081 range = lineRanges[i];
3082 }
3083 }
3084 return locate;
3085}
3086function locate(source, search, options) {
3087 if (typeof options === 'number') {
3088 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
3089 }
3090 return getLocator$1(source, options)(search, options && options.startIndex);
3091}
3092
3093const keys = {
3094 Literal: [],
3095 Program: ['body']
3096};
3097function getAndCreateKeys(esTreeNode) {
3098 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(key => typeof esTreeNode[key] === 'object');
3099 return keys[esTreeNode.type];
3100}
3101
3102const INCLUDE_PARAMETERS = 'variables';
3103class NodeBase {
3104 constructor(esTreeNode, parent, parentScope) {
3105 this.included = false;
3106 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
3107 this.parent = parent;
3108 this.context = parent.context;
3109 this.createScope(parentScope);
3110 this.parseNode(esTreeNode);
3111 this.initialise();
3112 this.context.magicString.addSourcemapLocation(this.start);
3113 this.context.magicString.addSourcemapLocation(this.end);
3114 }
3115 /**
3116 * Override this to bind assignments to variables and do any initialisations that
3117 * require the scopes to be populated with variables.
3118 */
3119 bind() {
3120 for (const key of this.keys) {
3121 const value = this[key];
3122 if (value === null || key === 'annotations')
3123 continue;
3124 if (Array.isArray(value)) {
3125 for (const child of value) {
3126 if (child !== null)
3127 child.bind();
3128 }
3129 }
3130 else {
3131 value.bind();
3132 }
3133 }
3134 }
3135 /**
3136 * Override if this node should receive a different scope than the parent scope.
3137 */
3138 createScope(parentScope) {
3139 this.scope = parentScope;
3140 }
3141 declare(_kind, _init) {
3142 return [];
3143 }
3144 deoptimizePath(_path) { }
3145 getLiteralValueAtPath(_path, _recursionTracker, _origin) {
3146 return UnknownValue;
3147 }
3148 getReturnExpressionWhenCalledAtPath(_path, _recursionTracker, _origin) {
3149 return UNKNOWN_EXPRESSION;
3150 }
3151 hasEffects(context) {
3152 for (const key of this.keys) {
3153 const value = this[key];
3154 if (value === null || key === 'annotations')
3155 continue;
3156 if (Array.isArray(value)) {
3157 for (const child of value) {
3158 if (child !== null && child.hasEffects(context))
3159 return true;
3160 }
3161 }
3162 else if (value.hasEffects(context))
3163 return true;
3164 }
3165 return false;
3166 }
3167 hasEffectsWhenAccessedAtPath(path, _context) {
3168 return path.length > 0;
3169 }
3170 hasEffectsWhenAssignedAtPath(_path, _context) {
3171 return true;
3172 }
3173 hasEffectsWhenCalledAtPath(_path, _callOptions, _context) {
3174 return true;
3175 }
3176 include(context, includeChildrenRecursively) {
3177 this.included = true;
3178 for (const key of this.keys) {
3179 const value = this[key];
3180 if (value === null || key === 'annotations')
3181 continue;
3182 if (Array.isArray(value)) {
3183 for (const child of value) {
3184 if (child !== null)
3185 child.include(context, includeChildrenRecursively);
3186 }
3187 }
3188 else {
3189 value.include(context, includeChildrenRecursively);
3190 }
3191 }
3192 }
3193 includeCallArguments(context, args) {
3194 for (const arg of args) {
3195 arg.include(context, false);
3196 }
3197 }
3198 includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
3199 this.include(context, includeChildrenRecursively);
3200 }
3201 /**
3202 * Override to perform special initialisation steps after the scope is initialised
3203 */
3204 initialise() { }
3205 insertSemicolon(code) {
3206 if (code.original[this.end - 1] !== ';') {
3207 code.appendLeft(this.end, ';');
3208 }
3209 }
3210 locate() {
3211 // useful for debugging
3212 const location = locate(this.context.code, this.start, { offsetLine: 1 });
3213 location.file = this.context.fileName;
3214 location.toString = () => JSON.stringify(location);
3215 return location;
3216 }
3217 parseNode(esTreeNode) {
3218 for (const key of Object.keys(esTreeNode)) {
3219 // That way, we can override this function to add custom initialisation and then call super.parseNode
3220 if (this.hasOwnProperty(key))
3221 continue;
3222 const value = esTreeNode[key];
3223 if (typeof value !== 'object' || value === null || key === 'annotations') {
3224 this[key] = value;
3225 }
3226 else if (Array.isArray(value)) {
3227 this[key] = [];
3228 for (const child of value) {
3229 this[key].push(child === null
3230 ? null
3231 : new (this.context.nodeConstructors[child.type] ||
3232 this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
3233 }
3234 }
3235 else {
3236 this[key] = new (this.context.nodeConstructors[value.type] ||
3237 this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
3238 }
3239 }
3240 }
3241 render(code, options) {
3242 for (const key of this.keys) {
3243 const value = this[key];
3244 if (value === null || key === 'annotations')
3245 continue;
3246 if (Array.isArray(value)) {
3247 for (const child of value) {
3248 if (child !== null)
3249 child.render(code, options);
3250 }
3251 }
3252 else {
3253 value.render(code, options);
3254 }
3255 }
3256 }
3257 shouldBeIncluded(context) {
3258 return this.included || (!context.brokenFlow && this.hasEffects(createHasEffectsContext()));
3259 }
3260 toString() {
3261 return this.context.code.slice(this.start, this.end);
3262 }
3263}
3264
3265class ClassNode extends NodeBase {
3266 createScope(parentScope) {
3267 this.scope = new ChildScope(parentScope);
3268 }
3269 hasEffectsWhenAccessedAtPath(path) {
3270 return path.length > 1;
3271 }
3272 hasEffectsWhenAssignedAtPath(path) {
3273 return path.length > 1;
3274 }
3275 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3276 if (!callOptions.withNew)
3277 return true;
3278 return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
3279 (this.superClass !== null &&
3280 this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, context)));
3281 }
3282 initialise() {
3283 if (this.id !== null) {
3284 this.id.declare('class', this);
3285 }
3286 }
3287}
3288
3289class ClassDeclaration extends ClassNode {
3290 initialise() {
3291 super.initialise();
3292 if (this.id !== null) {
3293 this.id.variable.isId = true;
3294 }
3295 }
3296 parseNode(esTreeNode) {
3297 if (esTreeNode.id !== null) {
3298 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
3299 .parent);
3300 }
3301 super.parseNode(esTreeNode);
3302 }
3303 render(code, options) {
3304 if (options.format === 'system' && this.id && this.id.variable.exportName) {
3305 code.appendLeft(this.end, ` exports('${this.id.variable.exportName}', ${this.id.variable.getName()});`);
3306 }
3307 super.render(code, options);
3308 }
3309}
3310
3311class ArgumentsVariable extends LocalVariable {
3312 constructor(context) {
3313 super('arguments', null, UNKNOWN_EXPRESSION, context);
3314 }
3315 hasEffectsWhenAccessedAtPath(path) {
3316 return path.length > 1;
3317 }
3318 hasEffectsWhenAssignedAtPath() {
3319 return true;
3320 }
3321 hasEffectsWhenCalledAtPath() {
3322 return true;
3323 }
3324}
3325
3326class ThisVariable extends LocalVariable {
3327 constructor(context) {
3328 super('this', null, null, context);
3329 }
3330 getLiteralValueAtPath() {
3331 return UnknownValue;
3332 }
3333 hasEffectsWhenAccessedAtPath(path, context) {
3334 return (this.getInit(context).hasEffectsWhenAccessedAtPath(path, context) ||
3335 super.hasEffectsWhenAccessedAtPath(path, context));
3336 }
3337 hasEffectsWhenAssignedAtPath(path, context) {
3338 return (this.getInit(context).hasEffectsWhenAssignedAtPath(path, context) ||
3339 super.hasEffectsWhenAssignedAtPath(path, context));
3340 }
3341 hasEffectsWhenCalledAtPath(path, callOptions, context) {
3342 return (this.getInit(context).hasEffectsWhenCalledAtPath(path, callOptions, context) ||
3343 super.hasEffectsWhenCalledAtPath(path, callOptions, context));
3344 }
3345 getInit(context) {
3346 return context.replacedVariableInits.get(this) || UNKNOWN_EXPRESSION;
3347 }
3348}
3349
3350class ParameterScope extends ChildScope {
3351 constructor(parent, context) {
3352 super(parent);
3353 this.parameters = [];
3354 this.hasRest = false;
3355 this.context = context;
3356 this.hoistedBodyVarScope = new ChildScope(this);
3357 }
3358 /**
3359 * Adds a parameter to this scope. Parameters must be added in the correct
3360 * order, e.g. from left to right.
3361 */
3362 addParameterDeclaration(identifier) {
3363 const name = identifier.name;
3364 let variable = this.hoistedBodyVarScope.variables.get(name);
3365 if (variable) {
3366 variable.addDeclaration(identifier, null);
3367 }
3368 else {
3369 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
3370 }
3371 this.variables.set(name, variable);
3372 return variable;
3373 }
3374 addParameterVariables(parameters, hasRest) {
3375 this.parameters = parameters;
3376 for (const parameterList of parameters) {
3377 for (const parameter of parameterList) {
3378 parameter.alwaysRendered = true;
3379 }
3380 }
3381 this.hasRest = hasRest;
3382 }
3383 includeCallArguments(context, args) {
3384 let calledFromTryStatement = false;
3385 let argIncluded = false;
3386 const restParam = this.hasRest && this.parameters[this.parameters.length - 1];
3387 for (let index = args.length - 1; index >= 0; index--) {
3388 const paramVars = this.parameters[index] || restParam;
3389 const arg = args[index];
3390 if (paramVars) {
3391 calledFromTryStatement = false;
3392 for (const variable of paramVars) {
3393 if (variable.included) {
3394 argIncluded = true;
3395 }
3396 if (variable.calledFromTryStatement) {
3397 calledFromTryStatement = true;
3398 }
3399 }
3400 }
3401 if (!argIncluded && arg.shouldBeIncluded(context)) {
3402 argIncluded = true;
3403 }
3404 if (argIncluded) {
3405 arg.include(context, calledFromTryStatement);
3406 }
3407 }
3408 }
3409}
3410
3411class ReturnValueScope extends ParameterScope {
3412 constructor() {
3413 super(...arguments);
3414 this.returnExpression = null;
3415 this.returnExpressions = [];
3416 }
3417 addReturnExpression(expression) {
3418 this.returnExpressions.push(expression);
3419 }
3420 getReturnExpression() {
3421 if (this.returnExpression === null)
3422 this.updateReturnExpression();
3423 return this.returnExpression;
3424 }
3425 updateReturnExpression() {
3426 if (this.returnExpressions.length === 1) {
3427 this.returnExpression = this.returnExpressions[0];
3428 }
3429 else {
3430 this.returnExpression = UNKNOWN_EXPRESSION;
3431 for (const expression of this.returnExpressions) {
3432 expression.deoptimizePath(UNKNOWN_PATH);
3433 }
3434 }
3435 }
3436}
3437
3438class FunctionScope extends ReturnValueScope {
3439 constructor(parent, context) {
3440 super(parent, context);
3441 this.variables.set('arguments', (this.argumentsVariable = new ArgumentsVariable(context)));
3442 this.variables.set('this', (this.thisVariable = new ThisVariable(context)));
3443 }
3444 findLexicalBoundary() {
3445 return this;
3446 }
3447 includeCallArguments(context, args) {
3448 super.includeCallArguments(context, args);
3449 if (this.argumentsVariable.included) {
3450 for (const arg of args) {
3451 if (!arg.included) {
3452 arg.include(context, false);
3453 }
3454 }
3455 }
3456 }
3457}
3458
3459function isReference(node, parent) {
3460 if (node.type === 'MemberExpression') {
3461 return !node.computed && isReference(node.object, node);
3462 }
3463 if (node.type === 'Identifier') {
3464 if (!parent)
3465 return true;
3466 switch (parent.type) {
3467 // disregard `bar` in `foo.bar`
3468 case 'MemberExpression': return parent.computed || node === parent.object;
3469 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
3470 case 'MethodDefinition': return parent.computed;
3471 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
3472 case 'Property': return parent.computed || node === parent.value;
3473 // disregard the `bar` in `export { foo as bar }` or
3474 // the foo in `import { foo as bar }`
3475 case 'ExportSpecifier':
3476 case 'ImportSpecifier': return node === parent.local;
3477 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
3478 case 'LabeledStatement':
3479 case 'BreakStatement':
3480 case 'ContinueStatement': return false;
3481 default: return true;
3482 }
3483 }
3484 return false;
3485}
3486
3487const ValueProperties = Symbol('Value Properties');
3488const PURE = { pure: true };
3489const IMPURE = { pure: false };
3490// We use shortened variables to reduce file size here
3491/* OBJECT */
3492const O = {
3493 // @ts-ignore
3494 __proto__: null,
3495 [ValueProperties]: IMPURE
3496};
3497/* PURE FUNCTION */
3498const PF = {
3499 // @ts-ignore
3500 __proto__: null,
3501 [ValueProperties]: PURE
3502};
3503/* CONSTRUCTOR */
3504const C = {
3505 // @ts-ignore
3506 __proto__: null,
3507 [ValueProperties]: IMPURE,
3508 prototype: O
3509};
3510/* PURE CONSTRUCTOR */
3511const PC = {
3512 // @ts-ignore
3513 __proto__: null,
3514 [ValueProperties]: PURE,
3515 prototype: O
3516};
3517const ARRAY_TYPE = {
3518 // @ts-ignore
3519 __proto__: null,
3520 [ValueProperties]: PURE,
3521 from: PF,
3522 of: PF,
3523 prototype: O
3524};
3525const INTL_MEMBER = {
3526 // @ts-ignore
3527 __proto__: null,
3528 [ValueProperties]: PURE,
3529 supportedLocalesOf: PC
3530};
3531const knownGlobals = {
3532 // Placeholders for global objects to avoid shape mutations
3533 global: O,
3534 globalThis: O,
3535 self: O,
3536 window: O,
3537 // Common globals
3538 // @ts-ignore
3539 __proto__: null,
3540 [ValueProperties]: IMPURE,
3541 Array: {
3542 // @ts-ignore
3543 __proto__: null,
3544 [ValueProperties]: IMPURE,
3545 from: PF,
3546 isArray: PF,
3547 of: PF,
3548 prototype: O
3549 },
3550 ArrayBuffer: {
3551 // @ts-ignore
3552 __proto__: null,
3553 [ValueProperties]: PURE,
3554 isView: PF,
3555 prototype: O
3556 },
3557 Atomics: O,
3558 BigInt: C,
3559 BigInt64Array: C,
3560 BigUint64Array: C,
3561 Boolean: PC,
3562 // @ts-ignore
3563 constructor: C,
3564 DataView: PC,
3565 Date: {
3566 // @ts-ignore
3567 __proto__: null,
3568 [ValueProperties]: PURE,
3569 now: PF,
3570 parse: PF,
3571 prototype: O,
3572 UTC: PF
3573 },
3574 decodeURI: PF,
3575 decodeURIComponent: PF,
3576 encodeURI: PF,
3577 encodeURIComponent: PF,
3578 Error: PC,
3579 escape: PF,
3580 eval: O,
3581 EvalError: PC,
3582 Float32Array: ARRAY_TYPE,
3583 Float64Array: ARRAY_TYPE,
3584 Function: C,
3585 // @ts-ignore
3586 hasOwnProperty: O,
3587 Infinity: O,
3588 Int16Array: ARRAY_TYPE,
3589 Int32Array: ARRAY_TYPE,
3590 Int8Array: ARRAY_TYPE,
3591 isFinite: PF,
3592 isNaN: PF,
3593 // @ts-ignore
3594 isPrototypeOf: O,
3595 JSON: O,
3596 Map: PC,
3597 Math: {
3598 // @ts-ignore
3599 __proto__: null,
3600 [ValueProperties]: IMPURE,
3601 abs: PF,
3602 acos: PF,
3603 acosh: PF,
3604 asin: PF,
3605 asinh: PF,
3606 atan: PF,
3607 atan2: PF,
3608 atanh: PF,
3609 cbrt: PF,
3610 ceil: PF,
3611 clz32: PF,
3612 cos: PF,
3613 cosh: PF,
3614 exp: PF,
3615 expm1: PF,
3616 floor: PF,
3617 fround: PF,
3618 hypot: PF,
3619 imul: PF,
3620 log: PF,
3621 log10: PF,
3622 log1p: PF,
3623 log2: PF,
3624 max: PF,
3625 min: PF,
3626 pow: PF,
3627 random: PF,
3628 round: PF,
3629 sign: PF,
3630 sin: PF,
3631 sinh: PF,
3632 sqrt: PF,
3633 tan: PF,
3634 tanh: PF,
3635 trunc: PF
3636 },
3637 NaN: O,
3638 Number: {
3639 // @ts-ignore
3640 __proto__: null,
3641 [ValueProperties]: PURE,
3642 isFinite: PF,
3643 isInteger: PF,
3644 isNaN: PF,
3645 isSafeInteger: PF,
3646 parseFloat: PF,
3647 parseInt: PF,
3648 prototype: O
3649 },
3650 Object: {
3651 // @ts-ignore
3652 __proto__: null,
3653 [ValueProperties]: PURE,
3654 create: PF,
3655 getNotifier: PF,
3656 getOwn: PF,
3657 getOwnPropertyDescriptor: PF,
3658 getOwnPropertyNames: PF,
3659 getOwnPropertySymbols: PF,
3660 getPrototypeOf: PF,
3661 is: PF,
3662 isExtensible: PF,
3663 isFrozen: PF,
3664 isSealed: PF,
3665 keys: PF,
3666 prototype: O
3667 },
3668 parseFloat: PF,
3669 parseInt: PF,
3670 Promise: {
3671 // @ts-ignore
3672 __proto__: null,
3673 [ValueProperties]: IMPURE,
3674 all: PF,
3675 prototype: O,
3676 race: PF,
3677 resolve: PF
3678 },
3679 // @ts-ignore
3680 propertyIsEnumerable: O,
3681 Proxy: O,
3682 RangeError: PC,
3683 ReferenceError: PC,
3684 Reflect: O,
3685 RegExp: PC,
3686 Set: PC,
3687 SharedArrayBuffer: C,
3688 String: {
3689 // @ts-ignore
3690 __proto__: null,
3691 [ValueProperties]: PURE,
3692 fromCharCode: PF,
3693 fromCodePoint: PF,
3694 prototype: O,
3695 raw: PF
3696 },
3697 Symbol: {
3698 // @ts-ignore
3699 __proto__: null,
3700 [ValueProperties]: PURE,
3701 for: PF,
3702 keyFor: PF,
3703 prototype: O
3704 },
3705 SyntaxError: PC,
3706 // @ts-ignore
3707 toLocaleString: O,
3708 // @ts-ignore
3709 toString: O,
3710 TypeError: PC,
3711 Uint16Array: ARRAY_TYPE,
3712 Uint32Array: ARRAY_TYPE,
3713 Uint8Array: ARRAY_TYPE,
3714 Uint8ClampedArray: ARRAY_TYPE,
3715 // Technically, this is a global, but it needs special handling
3716 // undefined: ?,
3717 unescape: PF,
3718 URIError: PC,
3719 // @ts-ignore
3720 valueOf: O,
3721 WeakMap: PC,
3722 WeakSet: PC,
3723 // Additional globals shared by Node and Browser that are not strictly part of the language
3724 clearInterval: C,
3725 clearTimeout: C,
3726 console: O,
3727 Intl: {
3728 // @ts-ignore
3729 __proto__: null,
3730 [ValueProperties]: IMPURE,
3731 Collator: INTL_MEMBER,
3732 DateTimeFormat: INTL_MEMBER,
3733 ListFormat: INTL_MEMBER,
3734 NumberFormat: INTL_MEMBER,
3735 PluralRules: INTL_MEMBER,
3736 RelativeTimeFormat: INTL_MEMBER
3737 },
3738 setInterval: C,
3739 setTimeout: C,
3740 TextDecoder: C,
3741 TextEncoder: C,
3742 URL: C,
3743 URLSearchParams: C,
3744 // Browser specific globals
3745 AbortController: C,
3746 AbortSignal: C,
3747 addEventListener: O,
3748 alert: O,
3749 AnalyserNode: C,
3750 Animation: C,
3751 AnimationEvent: C,
3752 applicationCache: O,
3753 ApplicationCache: C,
3754 ApplicationCacheErrorEvent: C,
3755 atob: O,
3756 Attr: C,
3757 Audio: C,
3758 AudioBuffer: C,
3759 AudioBufferSourceNode: C,
3760 AudioContext: C,
3761 AudioDestinationNode: C,
3762 AudioListener: C,
3763 AudioNode: C,
3764 AudioParam: C,
3765 AudioProcessingEvent: C,
3766 AudioScheduledSourceNode: C,
3767 AudioWorkletNode: C,
3768 BarProp: C,
3769 BaseAudioContext: C,
3770 BatteryManager: C,
3771 BeforeUnloadEvent: C,
3772 BiquadFilterNode: C,
3773 Blob: C,
3774 BlobEvent: C,
3775 blur: O,
3776 BroadcastChannel: C,
3777 btoa: O,
3778 ByteLengthQueuingStrategy: C,
3779 Cache: C,
3780 caches: O,
3781 CacheStorage: C,
3782 cancelAnimationFrame: O,
3783 cancelIdleCallback: O,
3784 CanvasCaptureMediaStreamTrack: C,
3785 CanvasGradient: C,
3786 CanvasPattern: C,
3787 CanvasRenderingContext2D: C,
3788 ChannelMergerNode: C,
3789 ChannelSplitterNode: C,
3790 CharacterData: C,
3791 clientInformation: O,
3792 ClipboardEvent: C,
3793 close: O,
3794 closed: O,
3795 CloseEvent: C,
3796 Comment: C,
3797 CompositionEvent: C,
3798 confirm: O,
3799 ConstantSourceNode: C,
3800 ConvolverNode: C,
3801 CountQueuingStrategy: C,
3802 createImageBitmap: O,
3803 Credential: C,
3804 CredentialsContainer: C,
3805 crypto: O,
3806 Crypto: C,
3807 CryptoKey: C,
3808 CSS: C,
3809 CSSConditionRule: C,
3810 CSSFontFaceRule: C,
3811 CSSGroupingRule: C,
3812 CSSImportRule: C,
3813 CSSKeyframeRule: C,
3814 CSSKeyframesRule: C,
3815 CSSMediaRule: C,
3816 CSSNamespaceRule: C,
3817 CSSPageRule: C,
3818 CSSRule: C,
3819 CSSRuleList: C,
3820 CSSStyleDeclaration: C,
3821 CSSStyleRule: C,
3822 CSSStyleSheet: C,
3823 CSSSupportsRule: C,
3824 CustomElementRegistry: C,
3825 customElements: O,
3826 CustomEvent: C,
3827 DataTransfer: C,
3828 DataTransferItem: C,
3829 DataTransferItemList: C,
3830 defaultstatus: O,
3831 defaultStatus: O,
3832 DelayNode: C,
3833 DeviceMotionEvent: C,
3834 DeviceOrientationEvent: C,
3835 devicePixelRatio: O,
3836 dispatchEvent: O,
3837 document: O,
3838 Document: C,
3839 DocumentFragment: C,
3840 DocumentType: C,
3841 DOMError: C,
3842 DOMException: C,
3843 DOMImplementation: C,
3844 DOMMatrix: C,
3845 DOMMatrixReadOnly: C,
3846 DOMParser: C,
3847 DOMPoint: C,
3848 DOMPointReadOnly: C,
3849 DOMQuad: C,
3850 DOMRect: C,
3851 DOMRectReadOnly: C,
3852 DOMStringList: C,
3853 DOMStringMap: C,
3854 DOMTokenList: C,
3855 DragEvent: C,
3856 DynamicsCompressorNode: C,
3857 Element: C,
3858 ErrorEvent: C,
3859 Event: C,
3860 EventSource: C,
3861 EventTarget: C,
3862 external: O,
3863 fetch: O,
3864 File: C,
3865 FileList: C,
3866 FileReader: C,
3867 find: O,
3868 focus: O,
3869 FocusEvent: C,
3870 FontFace: C,
3871 FontFaceSetLoadEvent: C,
3872 FormData: C,
3873 frames: O,
3874 GainNode: C,
3875 Gamepad: C,
3876 GamepadButton: C,
3877 GamepadEvent: C,
3878 getComputedStyle: O,
3879 getSelection: O,
3880 HashChangeEvent: C,
3881 Headers: C,
3882 history: O,
3883 History: C,
3884 HTMLAllCollection: C,
3885 HTMLAnchorElement: C,
3886 HTMLAreaElement: C,
3887 HTMLAudioElement: C,
3888 HTMLBaseElement: C,
3889 HTMLBodyElement: C,
3890 HTMLBRElement: C,
3891 HTMLButtonElement: C,
3892 HTMLCanvasElement: C,
3893 HTMLCollection: C,
3894 HTMLContentElement: C,
3895 HTMLDataElement: C,
3896 HTMLDataListElement: C,
3897 HTMLDetailsElement: C,
3898 HTMLDialogElement: C,
3899 HTMLDirectoryElement: C,
3900 HTMLDivElement: C,
3901 HTMLDListElement: C,
3902 HTMLDocument: C,
3903 HTMLElement: C,
3904 HTMLEmbedElement: C,
3905 HTMLFieldSetElement: C,
3906 HTMLFontElement: C,
3907 HTMLFormControlsCollection: C,
3908 HTMLFormElement: C,
3909 HTMLFrameElement: C,
3910 HTMLFrameSetElement: C,
3911 HTMLHeadElement: C,
3912 HTMLHeadingElement: C,
3913 HTMLHRElement: C,
3914 HTMLHtmlElement: C,
3915 HTMLIFrameElement: C,
3916 HTMLImageElement: C,
3917 HTMLInputElement: C,
3918 HTMLLabelElement: C,
3919 HTMLLegendElement: C,
3920 HTMLLIElement: C,
3921 HTMLLinkElement: C,
3922 HTMLMapElement: C,
3923 HTMLMarqueeElement: C,
3924 HTMLMediaElement: C,
3925 HTMLMenuElement: C,
3926 HTMLMetaElement: C,
3927 HTMLMeterElement: C,
3928 HTMLModElement: C,
3929 HTMLObjectElement: C,
3930 HTMLOListElement: C,
3931 HTMLOptGroupElement: C,
3932 HTMLOptionElement: C,
3933 HTMLOptionsCollection: C,
3934 HTMLOutputElement: C,
3935 HTMLParagraphElement: C,
3936 HTMLParamElement: C,
3937 HTMLPictureElement: C,
3938 HTMLPreElement: C,
3939 HTMLProgressElement: C,
3940 HTMLQuoteElement: C,
3941 HTMLScriptElement: C,
3942 HTMLSelectElement: C,
3943 HTMLShadowElement: C,
3944 HTMLSlotElement: C,
3945 HTMLSourceElement: C,
3946 HTMLSpanElement: C,
3947 HTMLStyleElement: C,
3948 HTMLTableCaptionElement: C,
3949 HTMLTableCellElement: C,
3950 HTMLTableColElement: C,
3951 HTMLTableElement: C,
3952 HTMLTableRowElement: C,
3953 HTMLTableSectionElement: C,
3954 HTMLTemplateElement: C,
3955 HTMLTextAreaElement: C,
3956 HTMLTimeElement: C,
3957 HTMLTitleElement: C,
3958 HTMLTrackElement: C,
3959 HTMLUListElement: C,
3960 HTMLUnknownElement: C,
3961 HTMLVideoElement: C,
3962 IDBCursor: C,
3963 IDBCursorWithValue: C,
3964 IDBDatabase: C,
3965 IDBFactory: C,
3966 IDBIndex: C,
3967 IDBKeyRange: C,
3968 IDBObjectStore: C,
3969 IDBOpenDBRequest: C,
3970 IDBRequest: C,
3971 IDBTransaction: C,
3972 IDBVersionChangeEvent: C,
3973 IdleDeadline: C,
3974 IIRFilterNode: C,
3975 Image: C,
3976 ImageBitmap: C,
3977 ImageBitmapRenderingContext: C,
3978 ImageCapture: C,
3979 ImageData: C,
3980 indexedDB: O,
3981 innerHeight: O,
3982 innerWidth: O,
3983 InputEvent: C,
3984 IntersectionObserver: C,
3985 IntersectionObserverEntry: C,
3986 isSecureContext: O,
3987 KeyboardEvent: C,
3988 KeyframeEffect: C,
3989 length: O,
3990 localStorage: O,
3991 location: O,
3992 Location: C,
3993 locationbar: O,
3994 matchMedia: O,
3995 MediaDeviceInfo: C,
3996 MediaDevices: C,
3997 MediaElementAudioSourceNode: C,
3998 MediaEncryptedEvent: C,
3999 MediaError: C,
4000 MediaKeyMessageEvent: C,
4001 MediaKeySession: C,
4002 MediaKeyStatusMap: C,
4003 MediaKeySystemAccess: C,
4004 MediaList: C,
4005 MediaQueryList: C,
4006 MediaQueryListEvent: C,
4007 MediaRecorder: C,
4008 MediaSettingsRange: C,
4009 MediaSource: C,
4010 MediaStream: C,
4011 MediaStreamAudioDestinationNode: C,
4012 MediaStreamAudioSourceNode: C,
4013 MediaStreamEvent: C,
4014 MediaStreamTrack: C,
4015 MediaStreamTrackEvent: C,
4016 menubar: O,
4017 MessageChannel: C,
4018 MessageEvent: C,
4019 MessagePort: C,
4020 MIDIAccess: C,
4021 MIDIConnectionEvent: C,
4022 MIDIInput: C,
4023 MIDIInputMap: C,
4024 MIDIMessageEvent: C,
4025 MIDIOutput: C,
4026 MIDIOutputMap: C,
4027 MIDIPort: C,
4028 MimeType: C,
4029 MimeTypeArray: C,
4030 MouseEvent: C,
4031 moveBy: O,
4032 moveTo: O,
4033 MutationEvent: C,
4034 MutationObserver: C,
4035 MutationRecord: C,
4036 name: O,
4037 NamedNodeMap: C,
4038 NavigationPreloadManager: C,
4039 navigator: O,
4040 Navigator: C,
4041 NetworkInformation: C,
4042 Node: C,
4043 NodeFilter: O,
4044 NodeIterator: C,
4045 NodeList: C,
4046 Notification: C,
4047 OfflineAudioCompletionEvent: C,
4048 OfflineAudioContext: C,
4049 offscreenBuffering: O,
4050 OffscreenCanvas: C,
4051 open: O,
4052 openDatabase: O,
4053 Option: C,
4054 origin: O,
4055 OscillatorNode: C,
4056 outerHeight: O,
4057 outerWidth: O,
4058 PageTransitionEvent: C,
4059 pageXOffset: O,
4060 pageYOffset: O,
4061 PannerNode: C,
4062 parent: O,
4063 Path2D: C,
4064 PaymentAddress: C,
4065 PaymentRequest: C,
4066 PaymentRequestUpdateEvent: C,
4067 PaymentResponse: C,
4068 performance: O,
4069 Performance: C,
4070 PerformanceEntry: C,
4071 PerformanceLongTaskTiming: C,
4072 PerformanceMark: C,
4073 PerformanceMeasure: C,
4074 PerformanceNavigation: C,
4075 PerformanceNavigationTiming: C,
4076 PerformanceObserver: C,
4077 PerformanceObserverEntryList: C,
4078 PerformancePaintTiming: C,
4079 PerformanceResourceTiming: C,
4080 PerformanceTiming: C,
4081 PeriodicWave: C,
4082 Permissions: C,
4083 PermissionStatus: C,
4084 personalbar: O,
4085 PhotoCapabilities: C,
4086 Plugin: C,
4087 PluginArray: C,
4088 PointerEvent: C,
4089 PopStateEvent: C,
4090 postMessage: O,
4091 Presentation: C,
4092 PresentationAvailability: C,
4093 PresentationConnection: C,
4094 PresentationConnectionAvailableEvent: C,
4095 PresentationConnectionCloseEvent: C,
4096 PresentationConnectionList: C,
4097 PresentationReceiver: C,
4098 PresentationRequest: C,
4099 print: O,
4100 ProcessingInstruction: C,
4101 ProgressEvent: C,
4102 PromiseRejectionEvent: C,
4103 prompt: O,
4104 PushManager: C,
4105 PushSubscription: C,
4106 PushSubscriptionOptions: C,
4107 queueMicrotask: O,
4108 RadioNodeList: C,
4109 Range: C,
4110 ReadableStream: C,
4111 RemotePlayback: C,
4112 removeEventListener: O,
4113 Request: C,
4114 requestAnimationFrame: O,
4115 requestIdleCallback: O,
4116 resizeBy: O,
4117 ResizeObserver: C,
4118 ResizeObserverEntry: C,
4119 resizeTo: O,
4120 Response: C,
4121 RTCCertificate: C,
4122 RTCDataChannel: C,
4123 RTCDataChannelEvent: C,
4124 RTCDtlsTransport: C,
4125 RTCIceCandidate: C,
4126 RTCIceTransport: C,
4127 RTCPeerConnection: C,
4128 RTCPeerConnectionIceEvent: C,
4129 RTCRtpReceiver: C,
4130 RTCRtpSender: C,
4131 RTCSctpTransport: C,
4132 RTCSessionDescription: C,
4133 RTCStatsReport: C,
4134 RTCTrackEvent: C,
4135 screen: O,
4136 Screen: C,
4137 screenLeft: O,
4138 ScreenOrientation: C,
4139 screenTop: O,
4140 screenX: O,
4141 screenY: O,
4142 ScriptProcessorNode: C,
4143 scroll: O,
4144 scrollbars: O,
4145 scrollBy: O,
4146 scrollTo: O,
4147 scrollX: O,
4148 scrollY: O,
4149 SecurityPolicyViolationEvent: C,
4150 Selection: C,
4151 ServiceWorker: C,
4152 ServiceWorkerContainer: C,
4153 ServiceWorkerRegistration: C,
4154 sessionStorage: O,
4155 ShadowRoot: C,
4156 SharedWorker: C,
4157 SourceBuffer: C,
4158 SourceBufferList: C,
4159 speechSynthesis: O,
4160 SpeechSynthesisEvent: C,
4161 SpeechSynthesisUtterance: C,
4162 StaticRange: C,
4163 status: O,
4164 statusbar: O,
4165 StereoPannerNode: C,
4166 stop: O,
4167 Storage: C,
4168 StorageEvent: C,
4169 StorageManager: C,
4170 styleMedia: O,
4171 StyleSheet: C,
4172 StyleSheetList: C,
4173 SubtleCrypto: C,
4174 SVGAElement: C,
4175 SVGAngle: C,
4176 SVGAnimatedAngle: C,
4177 SVGAnimatedBoolean: C,
4178 SVGAnimatedEnumeration: C,
4179 SVGAnimatedInteger: C,
4180 SVGAnimatedLength: C,
4181 SVGAnimatedLengthList: C,
4182 SVGAnimatedNumber: C,
4183 SVGAnimatedNumberList: C,
4184 SVGAnimatedPreserveAspectRatio: C,
4185 SVGAnimatedRect: C,
4186 SVGAnimatedString: C,
4187 SVGAnimatedTransformList: C,
4188 SVGAnimateElement: C,
4189 SVGAnimateMotionElement: C,
4190 SVGAnimateTransformElement: C,
4191 SVGAnimationElement: C,
4192 SVGCircleElement: C,
4193 SVGClipPathElement: C,
4194 SVGComponentTransferFunctionElement: C,
4195 SVGDefsElement: C,
4196 SVGDescElement: C,
4197 SVGDiscardElement: C,
4198 SVGElement: C,
4199 SVGEllipseElement: C,
4200 SVGFEBlendElement: C,
4201 SVGFEColorMatrixElement: C,
4202 SVGFEComponentTransferElement: C,
4203 SVGFECompositeElement: C,
4204 SVGFEConvolveMatrixElement: C,
4205 SVGFEDiffuseLightingElement: C,
4206 SVGFEDisplacementMapElement: C,
4207 SVGFEDistantLightElement: C,
4208 SVGFEDropShadowElement: C,
4209 SVGFEFloodElement: C,
4210 SVGFEFuncAElement: C,
4211 SVGFEFuncBElement: C,
4212 SVGFEFuncGElement: C,
4213 SVGFEFuncRElement: C,
4214 SVGFEGaussianBlurElement: C,
4215 SVGFEImageElement: C,
4216 SVGFEMergeElement: C,
4217 SVGFEMergeNodeElement: C,
4218 SVGFEMorphologyElement: C,
4219 SVGFEOffsetElement: C,
4220 SVGFEPointLightElement: C,
4221 SVGFESpecularLightingElement: C,
4222 SVGFESpotLightElement: C,
4223 SVGFETileElement: C,
4224 SVGFETurbulenceElement: C,
4225 SVGFilterElement: C,
4226 SVGForeignObjectElement: C,
4227 SVGGElement: C,
4228 SVGGeometryElement: C,
4229 SVGGradientElement: C,
4230 SVGGraphicsElement: C,
4231 SVGImageElement: C,
4232 SVGLength: C,
4233 SVGLengthList: C,
4234 SVGLinearGradientElement: C,
4235 SVGLineElement: C,
4236 SVGMarkerElement: C,
4237 SVGMaskElement: C,
4238 SVGMatrix: C,
4239 SVGMetadataElement: C,
4240 SVGMPathElement: C,
4241 SVGNumber: C,
4242 SVGNumberList: C,
4243 SVGPathElement: C,
4244 SVGPatternElement: C,
4245 SVGPoint: C,
4246 SVGPointList: C,
4247 SVGPolygonElement: C,
4248 SVGPolylineElement: C,
4249 SVGPreserveAspectRatio: C,
4250 SVGRadialGradientElement: C,
4251 SVGRect: C,
4252 SVGRectElement: C,
4253 SVGScriptElement: C,
4254 SVGSetElement: C,
4255 SVGStopElement: C,
4256 SVGStringList: C,
4257 SVGStyleElement: C,
4258 SVGSVGElement: C,
4259 SVGSwitchElement: C,
4260 SVGSymbolElement: C,
4261 SVGTextContentElement: C,
4262 SVGTextElement: C,
4263 SVGTextPathElement: C,
4264 SVGTextPositioningElement: C,
4265 SVGTitleElement: C,
4266 SVGTransform: C,
4267 SVGTransformList: C,
4268 SVGTSpanElement: C,
4269 SVGUnitTypes: C,
4270 SVGUseElement: C,
4271 SVGViewElement: C,
4272 TaskAttributionTiming: C,
4273 Text: C,
4274 TextEvent: C,
4275 TextMetrics: C,
4276 TextTrack: C,
4277 TextTrackCue: C,
4278 TextTrackCueList: C,
4279 TextTrackList: C,
4280 TimeRanges: C,
4281 toolbar: O,
4282 top: O,
4283 Touch: C,
4284 TouchEvent: C,
4285 TouchList: C,
4286 TrackEvent: C,
4287 TransitionEvent: C,
4288 TreeWalker: C,
4289 UIEvent: C,
4290 ValidityState: C,
4291 visualViewport: O,
4292 VisualViewport: C,
4293 VTTCue: C,
4294 WaveShaperNode: C,
4295 WebAssembly: O,
4296 WebGL2RenderingContext: C,
4297 WebGLActiveInfo: C,
4298 WebGLBuffer: C,
4299 WebGLContextEvent: C,
4300 WebGLFramebuffer: C,
4301 WebGLProgram: C,
4302 WebGLQuery: C,
4303 WebGLRenderbuffer: C,
4304 WebGLRenderingContext: C,
4305 WebGLSampler: C,
4306 WebGLShader: C,
4307 WebGLShaderPrecisionFormat: C,
4308 WebGLSync: C,
4309 WebGLTexture: C,
4310 WebGLTransformFeedback: C,
4311 WebGLUniformLocation: C,
4312 WebGLVertexArrayObject: C,
4313 WebSocket: C,
4314 WheelEvent: C,
4315 Window: C,
4316 Worker: C,
4317 WritableStream: C,
4318 XMLDocument: C,
4319 XMLHttpRequest: C,
4320 XMLHttpRequestEventTarget: C,
4321 XMLHttpRequestUpload: C,
4322 XMLSerializer: C,
4323 XPathEvaluator: C,
4324 XPathExpression: C,
4325 XPathResult: C,
4326 XSLTProcessor: C
4327};
4328for (const global of ['window', 'global', 'self', 'globalThis']) {
4329 knownGlobals[global] = knownGlobals;
4330}
4331function getGlobalAtPath(path) {
4332 let currentGlobal = knownGlobals;
4333 for (const pathSegment of path) {
4334 if (typeof pathSegment !== 'string') {
4335 return null;
4336 }
4337 currentGlobal = currentGlobal[pathSegment];
4338 if (!currentGlobal) {
4339 return null;
4340 }
4341 }
4342 return currentGlobal[ValueProperties];
4343}
4344function isPureGlobal(path) {
4345 const globalAtPath = getGlobalAtPath(path);
4346 return globalAtPath !== null && globalAtPath.pure;
4347}
4348function isGlobalMember(path) {
4349 if (path.length === 1) {
4350 return path[0] === 'undefined' || getGlobalAtPath(path) !== null;
4351 }
4352 return getGlobalAtPath(path.slice(0, -1)) !== null;
4353}
4354
4355class GlobalVariable extends Variable {
4356 hasEffectsWhenAccessedAtPath(path) {
4357 return !isGlobalMember([this.name, ...path]);
4358 }
4359 hasEffectsWhenCalledAtPath(path) {
4360 return !isPureGlobal([this.name, ...path]);
4361 }
4362}
4363
4364class Identifier$1 extends NodeBase {
4365 constructor() {
4366 super(...arguments);
4367 this.variable = null;
4368 this.bound = false;
4369 }
4370 addExportedVariables(variables) {
4371 if (this.variable !== null && this.variable.exportName) {
4372 variables.push(this.variable);
4373 }
4374 }
4375 bind() {
4376 if (this.bound)
4377 return;
4378 this.bound = true;
4379 if (this.variable === null && isReference(this, this.parent)) {
4380 this.variable = this.scope.findVariable(this.name);
4381 this.variable.addReference(this);
4382 }
4383 if (this.variable !== null &&
4384 this.variable instanceof LocalVariable &&
4385 this.variable.additionalInitializers !== null) {
4386 this.variable.consolidateInitializers();
4387 }
4388 }
4389 declare(kind, init) {
4390 let variable;
4391 switch (kind) {
4392 case 'var':
4393 variable = this.scope.addDeclaration(this, this.context, init, true);
4394 break;
4395 case 'function':
4396 variable = this.scope.addDeclaration(this, this.context, init, 'function');
4397 break;
4398 case 'let':
4399 case 'const':
4400 case 'class':
4401 variable = this.scope.addDeclaration(this, this.context, init, false);
4402 break;
4403 case 'parameter':
4404 variable = this.scope.addParameterDeclaration(this);
4405 break;
4406 /* istanbul ignore next */
4407 default:
4408 /* istanbul ignore next */
4409 throw new Error(`Internal Error: Unexpected identifier kind ${kind}.`);
4410 }
4411 return [(this.variable = variable)];
4412 }
4413 deoptimizePath(path) {
4414 if (!this.bound)
4415 this.bind();
4416 if (path.length === 0 && !this.scope.contains(this.name)) {
4417 this.disallowImportReassignment();
4418 }
4419 this.variable.deoptimizePath(path);
4420 }
4421 getLiteralValueAtPath(path, recursionTracker, origin) {
4422 if (!this.bound)
4423 this.bind();
4424 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
4425 }
4426 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
4427 if (!this.bound)
4428 this.bind();
4429 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
4430 }
4431 hasEffects() {
4432 return (this.context.unknownGlobalSideEffects &&
4433 this.variable instanceof GlobalVariable &&
4434 this.variable.hasEffectsWhenAccessedAtPath(EMPTY_PATH));
4435 }
4436 hasEffectsWhenAccessedAtPath(path, context) {
4437 return this.variable !== null && this.variable.hasEffectsWhenAccessedAtPath(path, context);
4438 }
4439 hasEffectsWhenAssignedAtPath(path, context) {
4440 return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, context);
4441 }
4442 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4443 return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
4444 }
4445 include(context) {
4446 if (!this.included) {
4447 this.included = true;
4448 if (this.variable !== null) {
4449 this.context.includeVariable(context, this.variable);
4450 }
4451 }
4452 }
4453 includeCallArguments(context, args) {
4454 this.variable.includeCallArguments(context, args);
4455 }
4456 render(code, _options, { renderedParentType, isCalleeOfRenderedParent, isShorthandProperty } = BLANK) {
4457 if (this.variable) {
4458 const name = this.variable.getName();
4459 if (name !== this.name) {
4460 code.overwrite(this.start, this.end, name, {
4461 contentOnly: true,
4462 storeName: true
4463 });
4464 if (isShorthandProperty) {
4465 code.prependRight(this.start, `${this.name}: `);
4466 }
4467 }
4468 // In strict mode, any variable named "eval" must be the actual "eval" function
4469 if (name === 'eval' &&
4470 renderedParentType === CallExpression &&
4471 isCalleeOfRenderedParent) {
4472 code.appendRight(this.start, '0, ');
4473 }
4474 }
4475 }
4476 disallowImportReassignment() {
4477 this.context.error({
4478 code: 'ILLEGAL_REASSIGNMENT',
4479 message: `Illegal reassignment to import '${this.name}'`
4480 }, this.start);
4481 }
4482}
4483
4484class RestElement extends NodeBase {
4485 constructor() {
4486 super(...arguments);
4487 this.declarationInit = null;
4488 }
4489 addExportedVariables(variables) {
4490 this.argument.addExportedVariables(variables);
4491 }
4492 bind() {
4493 super.bind();
4494 if (this.declarationInit !== null) {
4495 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
4496 }
4497 }
4498 declare(kind, init) {
4499 this.declarationInit = init;
4500 return this.argument.declare(kind, UNKNOWN_EXPRESSION);
4501 }
4502 deoptimizePath(path) {
4503 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
4504 }
4505 hasEffectsWhenAssignedAtPath(path, context) {
4506 return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
4507 }
4508}
4509
4510class FunctionNode extends NodeBase {
4511 constructor() {
4512 super(...arguments);
4513 this.isPrototypeDeoptimized = false;
4514 }
4515 createScope(parentScope) {
4516 this.scope = new FunctionScope(parentScope, this.context);
4517 }
4518 deoptimizePath(path) {
4519 if (path.length === 1) {
4520 if (path[0] === 'prototype') {
4521 this.isPrototypeDeoptimized = true;
4522 }
4523 else if (path[0] === UnknownKey) {
4524 this.isPrototypeDeoptimized = true;
4525 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
4526 // which means the return expression needs to be reassigned as well
4527 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
4528 }
4529 }
4530 }
4531 getReturnExpressionWhenCalledAtPath(path) {
4532 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
4533 }
4534 hasEffects() {
4535 return this.id !== null && this.id.hasEffects();
4536 }
4537 hasEffectsWhenAccessedAtPath(path) {
4538 if (path.length <= 1)
4539 return false;
4540 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
4541 }
4542 hasEffectsWhenAssignedAtPath(path) {
4543 if (path.length <= 1) {
4544 return false;
4545 }
4546 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
4547 }
4548 hasEffectsWhenCalledAtPath(path, callOptions, context) {
4549 if (path.length > 0)
4550 return true;
4551 for (const param of this.params) {
4552 if (param.hasEffects(context))
4553 return true;
4554 }
4555 const thisInit = context.replacedVariableInits.get(this.scope.thisVariable);
4556 context.replacedVariableInits.set(this.scope.thisVariable, callOptions.withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION);
4557 const { brokenFlow, ignore } = context;
4558 context.ignore = {
4559 breaks: false,
4560 continues: false,
4561 labels: new Set(),
4562 returnAwaitYield: true
4563 };
4564 if (this.body.hasEffects(context))
4565 return true;
4566 context.brokenFlow = brokenFlow;
4567 if (thisInit) {
4568 context.replacedVariableInits.set(this.scope.thisVariable, thisInit);
4569 }
4570 else {
4571 context.replacedVariableInits.delete(this.scope.thisVariable);
4572 }
4573 context.ignore = ignore;
4574 return false;
4575 }
4576 include(context, includeChildrenRecursively) {
4577 this.included = true;
4578 if (this.id)
4579 this.id.include(context);
4580 const hasArguments = this.scope.argumentsVariable.included;
4581 for (const param of this.params) {
4582 if (!(param instanceof Identifier$1) || hasArguments) {
4583 param.include(context, includeChildrenRecursively);
4584 }
4585 }
4586 const { brokenFlow } = context;
4587 context.brokenFlow = BROKEN_FLOW_NONE;
4588 this.body.include(context, includeChildrenRecursively);
4589 context.brokenFlow = brokenFlow;
4590 }
4591 includeCallArguments(context, args) {
4592 this.scope.includeCallArguments(context, args);
4593 }
4594 initialise() {
4595 if (this.id !== null) {
4596 this.id.declare('function', this);
4597 }
4598 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
4599 this.body.addImplicitReturnExpressionToScope();
4600 }
4601 parseNode(esTreeNode) {
4602 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
4603 super.parseNode(esTreeNode);
4604 }
4605}
4606FunctionNode.prototype.preventChildBlockScope = true;
4607
4608class FunctionDeclaration extends FunctionNode {
4609 initialise() {
4610 super.initialise();
4611 if (this.id !== null) {
4612 this.id.variable.isId = true;
4613 }
4614 }
4615 parseNode(esTreeNode) {
4616 if (esTreeNode.id !== null) {
4617 this.id = new this.context.nodeConstructors.Identifier(esTreeNode.id, this, this.scope
4618 .parent);
4619 }
4620 super.parseNode(esTreeNode);
4621 }
4622}
4623
4624const WHITESPACE = /\s/;
4625// The header ends at the first non-white-space after "default"
4626function getDeclarationStart(code, start = 0) {
4627 start = findFirstOccurrenceOutsideComment(code, 'default', start) + 7;
4628 while (WHITESPACE.test(code[start]))
4629 start++;
4630 return start;
4631}
4632function getIdInsertPosition(code, declarationKeyword, start = 0) {
4633 const declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
4634 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '{', declarationEnd));
4635 const generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
4636 if (generatorStarPos === -1) {
4637 return declarationEnd;
4638 }
4639 return declarationEnd + generatorStarPos + 1;
4640}
4641class ExportDefaultDeclaration extends NodeBase {
4642 include(context, includeChildrenRecursively) {
4643 super.include(context, includeChildrenRecursively);
4644 if (includeChildrenRecursively) {
4645 this.context.includeVariable(context, this.variable);
4646 }
4647 }
4648 initialise() {
4649 const declaration = this.declaration;
4650 this.declarationName =
4651 (declaration.id && declaration.id.name) || this.declaration.name;
4652 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
4653 this.context.addExport(this);
4654 }
4655 render(code, options, { start, end } = BLANK) {
4656 const declarationStart = getDeclarationStart(code.original, this.start);
4657 if (this.declaration instanceof FunctionDeclaration) {
4658 this.renderNamedDeclaration(code, declarationStart, 'function', this.declaration.id === null, options);
4659 }
4660 else if (this.declaration instanceof ClassDeclaration) {
4661 this.renderNamedDeclaration(code, declarationStart, 'class', this.declaration.id === null, options);
4662 }
4663 else if (this.variable.getOriginalVariable() !== this.variable) {
4664 // Remove altogether to prevent re-declaring the same variable
4665 if (options.format === 'system' && this.variable.exportName) {
4666 code.overwrite(start, end, `exports('${this.variable.exportName}', ${this.variable.getName()});`);
4667 }
4668 else {
4669 treeshakeNode(this, code, start, end);
4670 }
4671 return;
4672 }
4673 else if (this.variable.included) {
4674 this.renderVariableDeclaration(code, declarationStart, options);
4675 }
4676 else {
4677 code.remove(this.start, declarationStart);
4678 this.declaration.render(code, options, {
4679 isCalleeOfRenderedParent: false,
4680 renderedParentType: ExpressionStatement
4681 });
4682 if (code.original[this.end - 1] !== ';') {
4683 code.appendLeft(this.end, ';');
4684 }
4685 return;
4686 }
4687 this.declaration.render(code, options);
4688 }
4689 renderNamedDeclaration(code, declarationStart, declarationKeyword, needsId, options) {
4690 const name = this.variable.getName();
4691 // Remove `export default`
4692 code.remove(this.start, declarationStart);
4693 if (needsId) {
4694 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, declarationStart), ` ${name}`);
4695 }
4696 if (options.format === 'system' &&
4697 this.declaration instanceof ClassDeclaration &&
4698 this.variable.exportName) {
4699 code.appendLeft(this.end, ` exports('${this.variable.exportName}', ${name});`);
4700 }
4701 }
4702 renderVariableDeclaration(code, declarationStart, options) {
4703 const systemBinding = options.format === 'system' && this.variable.exportName
4704 ? `exports('${this.variable.exportName}', `
4705 : '';
4706 code.overwrite(this.start, declarationStart, `${options.varOrConst} ${this.variable.getName()} = ${systemBinding}`);
4707 const hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
4708 if (systemBinding) {
4709 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
4710 }
4711 else if (!hasTrailingSemicolon) {
4712 code.appendLeft(this.end, ';');
4713 }
4714 }
4715}
4716ExportDefaultDeclaration.prototype.needsBoundaries = true;
4717
4718class ExportDefaultVariable extends LocalVariable {
4719 constructor(name, exportDefaultDeclaration, context) {
4720 super(name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context);
4721 this.hasId = false;
4722 // Not initialised during construction
4723 this.originalId = null;
4724 this.originalVariable = null;
4725 const declaration = exportDefaultDeclaration.declaration;
4726 if ((declaration instanceof FunctionDeclaration || declaration instanceof ClassDeclaration) &&
4727 declaration.id) {
4728 this.hasId = true;
4729 this.originalId = declaration.id;
4730 }
4731 else if (declaration instanceof Identifier$1) {
4732 this.originalId = declaration;
4733 }
4734 }
4735 addReference(identifier) {
4736 if (!this.hasId) {
4737 this.name = identifier.name;
4738 }
4739 }
4740 getAssignedVariableName() {
4741 return (this.originalId && this.originalId.name) || null;
4742 }
4743 getBaseVariableName() {
4744 const original = this.getOriginalVariable();
4745 if (original === this) {
4746 return super.getBaseVariableName();
4747 }
4748 else {
4749 return original.getBaseVariableName();
4750 }
4751 }
4752 getName() {
4753 const original = this.getOriginalVariable();
4754 if (original === this) {
4755 return super.getName();
4756 }
4757 else {
4758 return original.getName();
4759 }
4760 }
4761 getOriginalVariable() {
4762 if (this.originalVariable === null) {
4763 if (!this.originalId || (!this.hasId && this.originalId.variable.isReassigned)) {
4764 this.originalVariable = this;
4765 }
4766 else {
4767 const assignedOriginal = this.originalId.variable;
4768 this.originalVariable =
4769 assignedOriginal instanceof ExportDefaultVariable
4770 ? assignedOriginal.getOriginalVariable()
4771 : assignedOriginal;
4772 }
4773 }
4774 return this.originalVariable;
4775 }
4776 setRenderNames(baseName, name) {
4777 const original = this.getOriginalVariable();
4778 if (original === this) {
4779 super.setRenderNames(baseName, name);
4780 }
4781 else {
4782 original.setRenderNames(baseName, name);
4783 }
4784 }
4785 setSafeName(name) {
4786 const original = this.getOriginalVariable();
4787 if (original === this) {
4788 super.setSafeName(name);
4789 }
4790 else {
4791 original.setSafeName(name);
4792 }
4793 }
4794}
4795
4796const MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
4797const INTEROP_DEFAULT_VARIABLE = '_interopDefault';
4798const INTEROP_NAMESPACE_VARIABLE = '_interopNamespace';
4799
4800class ExportShimVariable extends Variable {
4801 constructor(module) {
4802 super(MISSING_EXPORT_SHIM_VARIABLE);
4803 this.module = module;
4804 }
4805}
4806
4807class NamespaceVariable extends Variable {
4808 constructor(context) {
4809 super(context.getModuleName());
4810 this.memberVariables = Object.create(null);
4811 this.containsExternalNamespace = false;
4812 this.referencedEarly = false;
4813 this.references = [];
4814 this.context = context;
4815 this.module = context.module;
4816 }
4817 addReference(identifier) {
4818 this.references.push(identifier);
4819 this.name = identifier.name;
4820 }
4821 // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
4822 // build fails due to an illegal namespace reassignment or MemberExpression already forwards
4823 // the reassignment to the right variable. This means we lost track of this variable and thus
4824 // need to reassign all exports.
4825 deoptimizePath() {
4826 for (const key in this.memberVariables) {
4827 this.memberVariables[key].deoptimizePath(UNKNOWN_PATH);
4828 }
4829 }
4830 include(context) {
4831 if (!this.included) {
4832 if (this.containsExternalNamespace) {
4833 this.context.error({
4834 code: 'NAMESPACE_CANNOT_CONTAIN_EXTERNAL',
4835 id: this.module.id,
4836 message: `Cannot create an explicit namespace object for module "${this.context.getModuleName()}" because it contains a reexported external namespace`
4837 }, undefined);
4838 }
4839 this.included = true;
4840 for (const identifier of this.references) {
4841 if (identifier.context.getModuleExecIndex() <= this.context.getModuleExecIndex()) {
4842 this.referencedEarly = true;
4843 break;
4844 }
4845 }
4846 if (this.context.preserveModules) {
4847 for (const memberName of Object.keys(this.memberVariables))
4848 this.memberVariables[memberName].include(context);
4849 }
4850 else {
4851 for (const memberName of Object.keys(this.memberVariables))
4852 this.context.includeVariable(context, this.memberVariables[memberName]);
4853 }
4854 }
4855 }
4856 initialise() {
4857 for (const name of this.context.getExports().concat(this.context.getReexports())) {
4858 if (name[0] === '*' && name.length > 1)
4859 this.containsExternalNamespace = true;
4860 this.memberVariables[name] = this.context.traceExport(name);
4861 }
4862 }
4863 renderBlock(options) {
4864 const _ = options.compact ? '' : ' ';
4865 const n = options.compact ? '' : '\n';
4866 const t = options.indent;
4867 const members = Object.keys(this.memberVariables).map(name => {
4868 const original = this.memberVariables[name];
4869 if (this.referencedEarly || original.isReassigned) {
4870 return `${t}get ${name}${_}()${_}{${_}return ${original.getName()}${options.compact ? '' : ';'}${_}}`;
4871 }
4872 const safeName = RESERVED_NAMES[name] ? `'${name}'` : name;
4873 return `${t}${safeName}: ${original.getName()}`;
4874 });
4875 members.unshift(`${t}__proto__:${_}null`);
4876 if (options.namespaceToStringTag) {
4877 members.unshift(`${t}[Symbol.toStringTag]:${_}'Module'`);
4878 }
4879 const name = this.getName();
4880 const callee = options.freeze ? `/*#__PURE__*/Object.freeze` : '';
4881 const membersStr = members.join(`,${n}`);
4882 let output = `${options.varOrConst} ${name}${_}=${_}${callee}({${n}${membersStr}${n}});`;
4883 if (options.format === 'system' && this.exportName) {
4884 output += `${n}exports('${this.exportName}',${_}${name});`;
4885 }
4886 return output;
4887 }
4888 renderFirst() {
4889 return this.referencedEarly;
4890 }
4891}
4892NamespaceVariable.prototype.isNamespace = true;
4893
4894const esModuleExport = `Object.defineProperty(exports, '__esModule', { value: true });`;
4895const compactEsModuleExport = `Object.defineProperty(exports,'__esModule',{value:true});`;
4896
4897function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, mechanism = 'return ') {
4898 const _ = compact ? '' : ' ';
4899 const n = compact ? '' : '\n';
4900 if (!namedExportsMode) {
4901 let local;
4902 if (exports.length > 0) {
4903 local = exports[0].local;
4904 }
4905 else {
4906 for (const dep of dependencies) {
4907 if (dep.reexports) {
4908 const expt = dep.reexports[0];
4909 local =
4910 dep.namedExportsMode && expt.imported !== '*' && expt.imported !== 'default'
4911 ? `${dep.name}.${expt.imported}`
4912 : dep.name;
4913 }
4914 }
4915 }
4916 return `${mechanism}${local};`;
4917 }
4918 let exportBlock = '';
4919 // star exports must always output first for precedence
4920 dependencies.forEach(({ name, reexports }) => {
4921 if (reexports && namedExportsMode) {
4922 reexports.forEach(specifier => {
4923 if (specifier.reexported === '*') {
4924 if (exportBlock)
4925 exportBlock += n;
4926 if (specifier.needsLiveBinding) {
4927 exportBlock +=
4928 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
4929 `${t}if${_}(k${_}!==${_}'default')${_}Object.defineProperty(exports,${_}k,${_}{${n}` +
4930 `${t}${t}enumerable:${_}true,${n}` +
4931 `${t}${t}get:${_}function${_}()${_}{${n}` +
4932 `${t}${t}${t}return ${name}[k];${n}` +
4933 `${t}${t}}${n}${t}});${n}});`;
4934 }
4935 else {
4936 exportBlock +=
4937 `Object.keys(${name}).forEach(function${_}(k)${_}{${n}` +
4938 `${t}if${_}(k${_}!==${_}'default')${_}exports[k]${_}=${_}${name}[k];${n}});`;
4939 }
4940 }
4941 });
4942 }
4943 });
4944 for (const { name, imports, reexports, isChunk, namedExportsMode: depNamedExportsMode, exportsNames } of dependencies) {
4945 if (reexports && namedExportsMode) {
4946 for (const specifier of reexports) {
4947 if (specifier.imported === 'default' && !isChunk) {
4948 if (exportBlock)
4949 exportBlock += n;
4950 if (exportsNames &&
4951 (reexports.some(specifier => specifier.imported === 'default'
4952 ? specifier.reexported === 'default'
4953 : specifier.imported !== '*') ||
4954 (imports && imports.some(specifier => specifier.imported !== 'default')))) {
4955 exportBlock += `exports.${specifier.reexported}${_}=${_}${name}${interop !== false ? '__default' : '.default'};`;
4956 }
4957 else {
4958 exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`;
4959 }
4960 }
4961 else if (specifier.imported !== '*') {
4962 if (exportBlock)
4963 exportBlock += n;
4964 const importName = specifier.imported === 'default' && !depNamedExportsMode
4965 ? name
4966 : `${name}.${specifier.imported}`;
4967 exportBlock += specifier.needsLiveBinding
4968 ? `Object.defineProperty(exports,${_}'${specifier.reexported}',${_}{${n}` +
4969 `${t}enumerable:${_}true,${n}` +
4970 `${t}get:${_}function${_}()${_}{${n}` +
4971 `${t}${t}return ${importName};${n}${t}}${n}});`
4972 : `exports.${specifier.reexported}${_}=${_}${importName};`;
4973 }
4974 else if (specifier.reexported !== '*') {
4975 if (exportBlock)
4976 exportBlock += n;
4977 exportBlock += `exports.${specifier.reexported}${_}=${_}${name};`;
4978 }
4979 }
4980 }
4981 }
4982 for (const expt of exports) {
4983 const lhs = `exports.${expt.exported}`;
4984 const rhs = expt.local;
4985 if (lhs !== rhs) {
4986 if (exportBlock)
4987 exportBlock += n;
4988 exportBlock += `${lhs}${_}=${_}${rhs};`;
4989 }
4990 }
4991 return exportBlock;
4992}
4993
4994function getInteropBlock(dependencies, options, varOrConst) {
4995 const _ = options.compact ? '' : ' ';
4996 return dependencies
4997 .map(({ name, exportsNames, exportsDefault, namedExportsMode }) => {
4998 if (!namedExportsMode || !exportsDefault || options.interop === false)
4999 return null;
5000 if (exportsNames) {
5001 return (`${varOrConst} ${name}__default${_}=${_}'default'${_}in ${name}${_}?` +
5002 `${_}${name}['default']${_}:${_}${name};`);
5003 }
5004 return (`${name}${_}=${_}${name}${_}&&${_}${name}.hasOwnProperty('default')${_}?` +
5005 `${_}${name}['default']${_}:${_}${name};`);
5006 })
5007 .filter(Boolean)
5008 .join(options.compact ? '' : '\n');
5009}
5010
5011function copyPropertyLiveBinding(_, n, t, i) {
5012 return (`${i}var d${_}=${_}Object.getOwnPropertyDescriptor(e,${_}k);${n}` +
5013 `${i}Object.defineProperty(n,${_}k,${_}d.get${_}?${_}d${_}:${_}{${n}` +
5014 `${i}${t}enumerable:${_}true,${n}` +
5015 `${i}${t}get:${_}function${_}()${_}{${n}` +
5016 `${i}${t}${t}return e[k];${n}` +
5017 `${i}${t}}${n}` +
5018 `${i}});${n}`);
5019}
5020function copyPropertyStatic(_, n, _t, i) {
5021 return `${i}n[k]${_}=e${_}[k];${n}`;
5022}
5023function getInteropNamespace(_, n, t, liveBindings) {
5024 return (`function ${INTEROP_NAMESPACE_VARIABLE}(e)${_}{${n}` +
5025 `${t}if${_}(e${_}&&${_}e.__esModule)${_}{${_}return e;${_}}${_}else${_}{${n}` +
5026 `${t}${t}var n${_}=${_}{};${n}` +
5027 `${t}${t}if${_}(e)${_}{${n}` +
5028 `${t}${t}${t}Object.keys(e).forEach(function${_}(k)${_}{${n}` +
5029 (liveBindings ? copyPropertyLiveBinding : copyPropertyStatic)(_, n, t, t + t + t + t) +
5030 `${t}${t}${t}});${n}` +
5031 `${t}${t}}${n}` +
5032 `${t}${t}n['default']${_}=${_}e;${n}` +
5033 `${t}${t}return n;${n}` +
5034 `${t}}${n}` +
5035 `}${n}${n}`);
5036}
5037
5038const builtins$1 = {
5039 assert: true,
5040 buffer: true,
5041 console: true,
5042 constants: true,
5043 domain: true,
5044 events: true,
5045 http: true,
5046 https: true,
5047 os: true,
5048 path: true,
5049 process: true,
5050 punycode: true,
5051 querystring: true,
5052 stream: true,
5053 string_decoder: true,
5054 timers: true,
5055 tty: true,
5056 url: true,
5057 util: true,
5058 vm: true,
5059 zlib: true
5060};
5061// Creating a browser chunk that depends on Node.js built-in modules ('util'). You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins
5062function warnOnBuiltins(warn, dependencies) {
5063 const externalBuiltins = dependencies.map(({ id }) => id).filter(id => id in builtins$1);
5064 if (!externalBuiltins.length)
5065 return;
5066 const detail = externalBuiltins.length === 1
5067 ? `module ('${externalBuiltins[0]}')`
5068 : `modules (${externalBuiltins
5069 .slice(0, -1)
5070 .map(name => `'${name}'`)
5071 .join(', ')} and '${externalBuiltins.slice(-1)}')`;
5072 warn({
5073 code: 'MISSING_NODE_BUILTINS',
5074 message: `Creating a browser bundle that depends on Node.js built-in ${detail}. You might need to include https://www.npmjs.com/package/rollup-plugin-node-builtins`,
5075 modules: externalBuiltins
5076 });
5077}
5078
5079// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
5080// The assumption is that this makes sense for all relative ids:
5081// https://requirejs.org/docs/api.html#jsfiles
5082function removeExtensionFromRelativeAmdId(id) {
5083 if (id[0] === '.' && id.endsWith('.js')) {
5084 return id.slice(0, -3);
5085 }
5086 return id;
5087}
5088function amd(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst, warn }, options) {
5089 warnOnBuiltins(warn, dependencies);
5090 const deps = dependencies.map(m => `'${removeExtensionFromRelativeAmdId(m.id)}'`);
5091 const args = dependencies.map(m => m.name);
5092 const n = options.compact ? '' : '\n';
5093 const _ = options.compact ? '' : ' ';
5094 if (namedExportsMode && hasExports) {
5095 args.unshift(`exports`);
5096 deps.unshift(`'exports'`);
5097 }
5098 if (accessedGlobals.has('require')) {
5099 args.unshift('require');
5100 deps.unshift(`'require'`);
5101 }
5102 if (accessedGlobals.has('module')) {
5103 args.unshift('module');
5104 deps.unshift(`'module'`);
5105 }
5106 const amdOptions = options.amd || {};
5107 const params = (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) +
5108 (deps.length ? `[${deps.join(`,${_}`)}],${_}` : ``);
5109 const useStrict = options.strict !== false ? `${_}'use strict';` : ``;
5110 const define = amdOptions.define || 'define';
5111 const wrapperStart = `${define}(${params}function${_}(${args.join(`,${_}`)})${_}{${useStrict}${n}${n}`;
5112 // var foo__default = 'default' in foo ? foo['default'] : foo;
5113 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
5114 if (interopBlock) {
5115 magicString.prepend(interopBlock + n + n);
5116 }
5117 if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
5118 magicString.prepend(getInteropNamespace(_, n, t, options.externalLiveBindings !== false));
5119 }
5120 if (intro)
5121 magicString.prepend(intro);
5122 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
5123 if (exportBlock)
5124 magicString.append(n + n + exportBlock);
5125 if (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule)
5126 magicString.append(`${n}${n}${options.compact ? compactEsModuleExport : esModuleExport}`);
5127 if (outro)
5128 magicString.append(outro);
5129 return magicString
5130 .indent(t)
5131 .append(n + n + '});')
5132 .prepend(wrapperStart);
5133}
5134
5135function cjs(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, isEntryModuleFacade, namedExportsMode, outro, varOrConst }, options) {
5136 const n = options.compact ? '' : '\n';
5137 const _ = options.compact ? '' : ' ';
5138 intro =
5139 (options.strict === false ? intro : `'use strict';${n}${n}${intro}`) +
5140 (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule
5141 ? `${options.compact ? compactEsModuleExport : esModuleExport}${n}${n}`
5142 : '');
5143 let needsInterop = false;
5144 const interop = options.interop !== false;
5145 let importBlock;
5146 let definingVariable = false;
5147 importBlock = '';
5148 for (const { id, namedExportsMode, isChunk, name, reexports, imports, exportsNames, exportsDefault } of dependencies) {
5149 if (!reexports && !imports) {
5150 if (importBlock) {
5151 importBlock += !options.compact || definingVariable ? `;${n}` : ',';
5152 }
5153 definingVariable = false;
5154 importBlock += `require('${id}')`;
5155 }
5156 else {
5157 importBlock +=
5158 options.compact && definingVariable ? ',' : `${importBlock ? `;${n}` : ''}${varOrConst} `;
5159 definingVariable = true;
5160 if (!interop || isChunk || !exportsDefault || !namedExportsMode) {
5161 importBlock += `${name}${_}=${_}require('${id}')`;
5162 }
5163 else {
5164 needsInterop = true;
5165 if (exportsNames)
5166 importBlock += `${name}${_}=${_}require('${id}')${options.compact ? ',' : `;\n${varOrConst} `}${name}__default${_}=${_}${INTEROP_DEFAULT_VARIABLE}(${name})`;
5167 else
5168 importBlock += `${name}${_}=${_}${INTEROP_DEFAULT_VARIABLE}(require('${id}'))`;
5169 }
5170 }
5171 }
5172 if (importBlock)
5173 importBlock += ';';
5174 if (needsInterop) {
5175 const ex = options.compact ? 'e' : 'ex';
5176 intro +=
5177 `function ${INTEROP_DEFAULT_VARIABLE}${_}(${ex})${_}{${_}return${_}` +
5178 `(${ex}${_}&&${_}(typeof ${ex}${_}===${_}'object')${_}&&${_}'default'${_}in ${ex})${_}` +
5179 `?${_}${ex}['default']${_}:${_}${ex}${options.compact ? '' : '; '}}${n}${n}`;
5180 }
5181 if (accessedGlobals.has(INTEROP_NAMESPACE_VARIABLE)) {
5182 intro += getInteropNamespace(_, n, t, options.externalLiveBindings !== false);
5183 }
5184 if (importBlock)
5185 intro += importBlock + n + n;
5186 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, `module.exports${_}=${_}`);
5187 magicString.prepend(intro);
5188 if (exportBlock)
5189 magicString.append(n + n + exportBlock);
5190 if (outro)
5191 magicString.append(outro);
5192 return magicString;
5193}
5194
5195function esm(magicString, { intro, outro, dependencies, exports }, options) {
5196 const _ = options.compact ? '' : ' ';
5197 const n = options.compact ? '' : '\n';
5198 const importBlock = dependencies
5199 .map(({ id, reexports, imports, name }) => {
5200 if (!reexports && !imports) {
5201 return `import${_}'${id}';`;
5202 }
5203 let output = '';
5204 if (imports) {
5205 const defaultImport = imports.find(specifier => specifier.imported === 'default');
5206 const starImport = imports.find(specifier => specifier.imported === '*');
5207 if (starImport) {
5208 output += `import${_}*${_}as ${starImport.local} from${_}'${id}';`;
5209 if (imports.length > 1)
5210 output += n;
5211 }
5212 if (defaultImport && imports.length === 1) {
5213 output += `import ${defaultImport.local} from${_}'${id}';`;
5214 }
5215 else if (!starImport || imports.length > 1) {
5216 output += `import ${defaultImport ? `${defaultImport.local},${_}` : ''}{${_}${imports
5217 .filter(specifier => specifier !== defaultImport && specifier !== starImport)
5218 .map(specifier => {
5219 if (specifier.imported === specifier.local) {
5220 return specifier.imported;
5221 }
5222 else {
5223 return `${specifier.imported} as ${specifier.local}`;
5224 }
5225 })
5226 .join(`,${_}`)}${_}}${_}from${_}'${id}';`;
5227 }
5228 }
5229 if (reexports) {
5230 if (imports)
5231 output += n;
5232 const starExport = reexports.find(specifier => specifier.reexported === '*');
5233 const namespaceReexport = reexports.find(specifier => specifier.imported === '*' && specifier.reexported !== '*');
5234 if (starExport) {
5235 output += `export${_}*${_}from${_}'${id}';`;
5236 if (reexports.length === 1) {
5237 return output;
5238 }
5239 output += n;
5240 }
5241 if (namespaceReexport) {
5242 if (!imports ||
5243 !imports.some(specifier => specifier.imported === '*' && specifier.local === name))
5244 output += `import${_}*${_}as ${name} from${_}'${id}';${n}`;
5245 output += `export${_}{${_}${name === namespaceReexport.reexported
5246 ? name
5247 : `${name} as ${namespaceReexport.reexported}`} };`;
5248 if (reexports.length === (starExport ? 2 : 1)) {
5249 return output;
5250 }
5251 output += n;
5252 }
5253 output += `export${_}{${_}${reexports
5254 .filter(specifier => specifier !== starExport && specifier !== namespaceReexport)
5255 .map(specifier => {
5256 if (specifier.imported === specifier.reexported) {
5257 return specifier.imported;
5258 }
5259 else {
5260 return `${specifier.imported} as ${specifier.reexported}`;
5261 }
5262 })
5263 .join(`,${_}`)}${_}}${_}from${_}'${id}';`;
5264 }
5265 return output;
5266 })
5267 .join(n);
5268 if (importBlock)
5269 intro += importBlock + n + n;
5270 if (intro)
5271 magicString.prepend(intro);
5272 const exportBlock = [];
5273 const exportDeclaration = [];
5274 exports.forEach(specifier => {
5275 if (specifier.exported === 'default') {
5276 exportBlock.push(`export default ${specifier.local};`);
5277 }
5278 else {
5279 exportDeclaration.push(specifier.exported === specifier.local
5280 ? specifier.local
5281 : `${specifier.local} as ${specifier.exported}`);
5282 }
5283 });
5284 if (exportDeclaration.length) {
5285 exportBlock.push(`export${_}{${_}${exportDeclaration.join(`,${_}`)}${_}};`);
5286 }
5287 if (exportBlock.length)
5288 magicString.append(n + n + exportBlock.join(n).trim());
5289 if (outro)
5290 magicString.append(outro);
5291 return magicString.trim();
5292}
5293
5294function spaces(i) {
5295 let result = '';
5296 while (i--)
5297 result += ' ';
5298 return result;
5299}
5300function tabsToSpaces(str) {
5301 return str.replace(/^\t+/, match => match.split('\t').join(' '));
5302}
5303function getCodeFrame(source, line, column) {
5304 let lines = source.split('\n');
5305 const frameStart = Math.max(0, line - 3);
5306 let frameEnd = Math.min(line + 2, lines.length);
5307 lines = lines.slice(frameStart, frameEnd);
5308 while (!/\S/.test(lines[lines.length - 1])) {
5309 lines.pop();
5310 frameEnd -= 1;
5311 }
5312 const digits = String(frameEnd).length;
5313 return lines
5314 .map((str, i) => {
5315 const isErrorLine = frameStart + i + 1 === line;
5316 let lineNum = String(i + frameStart + 1);
5317 while (lineNum.length < digits)
5318 lineNum = ` ${lineNum}`;
5319 if (isErrorLine) {
5320 const indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
5321 return `${lineNum}: ${tabsToSpaces(str)}\n${indicator}`;
5322 }
5323 return `${lineNum}: ${tabsToSpaces(str)}`;
5324 })
5325 .join('\n');
5326}
5327
5328function error(base, props) {
5329 if (!(base instanceof Error))
5330 base = Object.assign(new Error(base.message), base);
5331 if (props)
5332 Object.assign(base, props);
5333 throw base;
5334}
5335function augmentCodeLocation(object, pos, source, id) {
5336 if (typeof pos === 'object') {
5337 const { line, column } = pos;
5338 object.loc = { file: id, line, column };
5339 }
5340 else {
5341 object.pos = pos;
5342 const { line, column } = locate(source, pos, { offsetLine: 1 });
5343 object.loc = { file: id, line, column };
5344 }
5345 if (object.frame === undefined) {
5346 const { line, column } = object.loc;
5347 object.frame = getCodeFrame(source, line, column);
5348 }
5349}
5350var Errors;
5351(function (Errors) {
5352 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
5353 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
5354 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
5355 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
5356 Errors["BAD_LOADER"] = "BAD_LOADER";
5357 Errors["CANNOT_EMIT_FROM_OPTIONS_HOOK"] = "CANNOT_EMIT_FROM_OPTIONS_HOOK";
5358 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
5359 Errors["DEPRECATED_FEATURE"] = "DEPRECATED_FEATURE";
5360 Errors["FILE_NOT_FOUND"] = "FILE_NOT_FOUND";
5361 Errors["FILE_NAME_CONFLICT"] = "FILE_NAME_CONFLICT";
5362 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
5363 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
5364 Errors["INVALID_OPTION"] = "INVALID_OPTION";
5365 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
5366 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
5367 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
5368 Errors["PLUGIN_ERROR"] = "PLUGIN_ERROR";
5369 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
5370 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
5371 Errors["VALIDATION_ERROR"] = "VALIDATION_ERROR";
5372})(Errors || (Errors = {}));
5373function errAssetNotFinalisedForFileName(name) {
5374 return {
5375 code: Errors.ASSET_NOT_FINALISED,
5376 message: `Plugin error - Unable to get file name for asset "${name}". Ensure that the source is set and that generate is called first.`
5377 };
5378}
5379function errCannotEmitFromOptionsHook() {
5380 return {
5381 code: Errors.CANNOT_EMIT_FROM_OPTIONS_HOOK,
5382 message: `Cannot emit files or set asset sources in the "outputOptions" hook, use the "renderStart" hook instead.`
5383 };
5384}
5385function errChunkNotGeneratedForFileName(name) {
5386 return {
5387 code: Errors.CHUNK_NOT_GENERATED,
5388 message: `Plugin error - Unable to get file name for chunk "${name}". Ensure that generate is called first.`
5389 };
5390}
5391function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
5392 return {
5393 code: Errors.ASSET_NOT_FOUND,
5394 message: `Plugin error - Unable to set the source for unknown asset "${assetReferenceId}".`
5395 };
5396}
5397function errAssetSourceAlreadySet(name) {
5398 return {
5399 code: Errors.ASSET_SOURCE_ALREADY_SET,
5400 message: `Unable to set the source for asset "${name}", source already set.`
5401 };
5402}
5403function errNoAssetSourceSet(assetName) {
5404 return {
5405 code: Errors.ASSET_SOURCE_MISSING,
5406 message: `Plugin error creating asset "${assetName}" - no asset source set.`
5407 };
5408}
5409function errBadLoader(id) {
5410 return {
5411 code: Errors.BAD_LOADER,
5412 message: `Error loading ${index.relativeId(id)}: plugin load hook should return a string, a { code, map } object, or nothing/null`
5413 };
5414}
5415function errDeprecation(deprecation) {
5416 return Object.assign({ code: Errors.DEPRECATED_FEATURE }, (typeof deprecation === 'string' ? { message: deprecation } : deprecation));
5417}
5418function errFileReferenceIdNotFoundForFilename(assetReferenceId) {
5419 return {
5420 code: Errors.FILE_NOT_FOUND,
5421 message: `Plugin error - Unable to get file name for unknown file "${assetReferenceId}".`
5422 };
5423}
5424function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
5425 return {
5426 code: Errors.INVALID_CHUNK,
5427 message: `Cannot assign ${index.relativeId(moduleId)} to the "${assignToAlias}" chunk as it is already in the "${currentAlias}" chunk.`
5428 };
5429}
5430function errInternalIdCannotBeExternal(source, importer) {
5431 return {
5432 code: Errors.INVALID_EXTERNAL_ID,
5433 message: `'${source}' is imported as an external by ${index.relativeId(importer)}, but is already an existing non-external module id.`
5434 };
5435}
5436function errInvalidOption(option, explanation) {
5437 return {
5438 code: Errors.INVALID_OPTION,
5439 message: `Invalid value for option "${option}" - ${explanation}.`
5440 };
5441}
5442function errInvalidRollupPhaseForAddWatchFile() {
5443 return {
5444 code: Errors.INVALID_ROLLUP_PHASE,
5445 message: `Cannot call addWatchFile after the build has finished.`
5446 };
5447}
5448function errInvalidRollupPhaseForChunkEmission() {
5449 return {
5450 code: Errors.INVALID_ROLLUP_PHASE,
5451 message: `Cannot emit chunks after module loading has finished.`
5452 };
5453}
5454function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
5455 return {
5456 code: Errors.NAMESPACE_CONFLICT,
5457 message: `Conflicting namespaces: ${index.relativeId(reexportingModule.id)} re-exports '${name}' from both ${index.relativeId(reexportingModule.exportsAll[name])} and ${index.relativeId(additionalExportAllModule.exportsAll[name])} (will be ignored)`,
5458 name,
5459 reexporter: reexportingModule.id,
5460 sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
5461 };
5462}
5463function errEntryCannotBeExternal(unresolvedId) {
5464 return {
5465 code: Errors.UNRESOLVED_ENTRY,
5466 message: `Entry module cannot be external (${index.relativeId(unresolvedId)}).`
5467 };
5468}
5469function errUnresolvedEntry(unresolvedId) {
5470 return {
5471 code: Errors.UNRESOLVED_ENTRY,
5472 message: `Could not resolve entry module (${index.relativeId(unresolvedId)}).`
5473 };
5474}
5475function errUnresolvedImport(source, importer) {
5476 return {
5477 code: Errors.UNRESOLVED_IMPORT,
5478 message: `Could not resolve '${source}' from ${index.relativeId(importer)}`
5479 };
5480}
5481function errUnresolvedImportTreatedAsExternal(source, importer) {
5482 return {
5483 code: Errors.UNRESOLVED_IMPORT,
5484 importer: index.relativeId(importer),
5485 message: `'${source}' is imported by ${index.relativeId(importer)}, but could not be resolved – treating it as an external dependency`,
5486 source,
5487 url: 'https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency'
5488 };
5489}
5490function errFailedValidation(message) {
5491 return {
5492 code: Errors.VALIDATION_ERROR,
5493 message
5494 };
5495}
5496
5497// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
5498// if the property name isn't trivial
5499const shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
5500function property(prop) {
5501 return shouldUseDot.test(prop) ? `.${prop}` : `['${prop}']`;
5502}
5503function keypath(keypath) {
5504 return keypath
5505 .split('.')
5506 .map(property)
5507 .join('');
5508}
5509
5510function setupNamespace(name, root, globals, compact) {
5511 const parts = name.split('.');
5512 if (globals) {
5513 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
5514 }
5515 const _ = compact ? '' : ' ';
5516 parts.pop();
5517 let acc = root;
5518 return (parts
5519 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}${compact ? '' : ';'}`))
5520 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
5521}
5522function assignToDeepVariable(deepName, root, globals, compact, assignment) {
5523 const _ = compact ? '' : ' ';
5524 const parts = deepName.split('.');
5525 if (globals) {
5526 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
5527 }
5528 const last = parts.pop();
5529 let acc = root;
5530 let deepAssignment = parts
5531 .map(part => ((acc += property(part)), `${acc}${_}=${_}${acc}${_}||${_}{}`))
5532 .concat(`${acc}${property(last)}`)
5533 .join(`,${_}`)
5534 .concat(`${_}=${_}${assignment}`);
5535 if (parts.length > 0) {
5536 deepAssignment = `(${deepAssignment})`;
5537 }
5538 return deepAssignment;
5539}
5540
5541function trimEmptyImports(dependencies) {
5542 let i = dependencies.length;
5543 while (i--) {
5544 const dependency = dependencies[i];
5545 if (dependency.exportsDefault || dependency.exportsNames) {
5546 return dependencies.slice(0, i + 1);
5547 }
5548 }
5549 return [];
5550}
5551
5552const thisProp = (name) => `this${keypath(name)}`;
5553function iife(magicString, { dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, options) {
5554 const _ = options.compact ? '' : ' ';
5555 const n = options.compact ? '' : '\n';
5556 const { extend, name } = options;
5557 const isNamespaced = name && name.indexOf('.') !== -1;
5558 const useVariableAssignment = !extend && !isNamespaced;
5559 if (name && useVariableAssignment && !isLegal(name)) {
5560 error({
5561 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
5562 message: `Given name (${name}) is not legal JS identifier. If you need this you can try --extend option`
5563 });
5564 }
5565 warnOnBuiltins(warn, dependencies);
5566 const external = trimEmptyImports(dependencies);
5567 const deps = external.map(dep => dep.globalName || 'null');
5568 const args = external.map(m => m.name);
5569 if (hasExports && !name) {
5570 error({
5571 code: 'INVALID_OPTION',
5572 message: `You must supply "output.name" for IIFE bundles.`
5573 });
5574 }
5575 if (namedExportsMode && hasExports) {
5576 if (extend) {
5577 deps.unshift(`${thisProp(name)}${_}=${_}${thisProp(name)}${_}||${_}{}`);
5578 args.unshift('exports');
5579 }
5580 else {
5581 deps.unshift('{}');
5582 args.unshift('exports');
5583 }
5584 }
5585 const useStrict = options.strict !== false ? `${t}'use strict';${n}${n}` : ``;
5586 let wrapperIntro = `(function${_}(${args.join(`,${_}`)})${_}{${n}${useStrict}`;
5587 if (hasExports && (!extend || !namedExportsMode)) {
5588 wrapperIntro =
5589 (useVariableAssignment ? `${varOrConst} ${name}` : thisProp(name)) +
5590 `${_}=${_}${wrapperIntro}`;
5591 }
5592 if (isNamespaced && hasExports) {
5593 wrapperIntro =
5594 setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro;
5595 }
5596 let wrapperOutro = `${n}${n}}(${deps.join(`,${_}`)}));`;
5597 if (!extend && namedExportsMode && hasExports) {
5598 wrapperOutro = `${n}${n}${t}return exports;${wrapperOutro}`;
5599 }
5600 // var foo__default = 'default' in foo ? foo['default'] : foo;
5601 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
5602 if (interopBlock)
5603 magicString.prepend(interopBlock + n + n);
5604 if (intro)
5605 magicString.prepend(intro);
5606 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
5607 if (exportBlock)
5608 magicString.append(n + n + exportBlock);
5609 if (outro)
5610 magicString.append(outro);
5611 return magicString
5612 .indent(t)
5613 .prepend(wrapperIntro)
5614 .append(wrapperOutro);
5615}
5616
5617function getStarExcludes({ dependencies, exports }) {
5618 const starExcludes = new Set(exports.map(expt => expt.exported));
5619 if (!starExcludes.has('default'))
5620 starExcludes.add('default');
5621 // also include reexport names
5622 dependencies.forEach(({ reexports }) => {
5623 if (reexports)
5624 reexports.forEach(reexport => {
5625 if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
5626 starExcludes.add(reexport.reexported);
5627 });
5628 });
5629 return starExcludes;
5630}
5631const getStarExcludesBlock = (starExcludes, varOrConst, _, t, n) => starExcludes
5632 ? `${n}${t}${varOrConst} _starExcludes${_}=${_}{${_}${Array.from(starExcludes).join(`:${_}1,${_}`)}${starExcludes.size ? `:${_}1` : ''}${_}};`
5633 : '';
5634const getImportBindingsBlock = (importBindings, _, t, n) => (importBindings.length ? `${n}${t}var ${importBindings.join(`,${_}`)};` : '');
5635function getExportsBlock(exports, _, t, n) {
5636 if (exports.length === 0) {
5637 return '';
5638 }
5639 if (exports.length === 1) {
5640 return `${t}${t}${t}exports('${exports[0].name}',${_}${exports[0].value});${n}${n}`;
5641 }
5642 return (`${t}${t}${t}exports({${n}` +
5643 exports.map(({ name, value }) => `${t}${t}${t}${t}${name}:${_}${value}`).join(`,${n}`) +
5644 `${n}${t}${t}${t}});${n}${n}`);
5645}
5646const getHoistedExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5647 .filter(expt => expt.hoisted || expt.uninitialized)
5648 .map(expt => ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local })), _, t, n);
5649const getMissingExportsBlock = (exports, _, t, n) => getExportsBlock(exports
5650 .filter(expt => expt.local === MISSING_EXPORT_SHIM_VARIABLE)
5651 .map(expt => ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE })), _, t, n);
5652function system(magicString, { accessedGlobals, dependencies, exports, hasExports, indentString: t, intro, outro, usesTopLevelAwait, varOrConst }, options) {
5653 const n = options.compact ? '' : '\n';
5654 const _ = options.compact ? '' : ' ';
5655 const dependencyIds = dependencies.map(m => `'${m.id}'`);
5656 const importBindings = [];
5657 let starExcludes;
5658 const setters = [];
5659 dependencies.forEach(({ imports, reexports }) => {
5660 const setter = [];
5661 if (imports) {
5662 imports.forEach(specifier => {
5663 importBindings.push(specifier.local);
5664 if (specifier.imported === '*') {
5665 setter.push(`${specifier.local}${_}=${_}module;`);
5666 }
5667 else {
5668 setter.push(`${specifier.local}${_}=${_}module.${specifier.imported};`);
5669 }
5670 });
5671 }
5672 if (reexports) {
5673 let createdSetter = false;
5674 // bulk-reexport form
5675 if (reexports.length > 1 ||
5676 (reexports.length === 1 &&
5677 (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
5678 // star reexports
5679 reexports.forEach(specifier => {
5680 if (specifier.reexported !== '*')
5681 return;
5682 // need own exports list for deduping in star export case
5683 if (!starExcludes) {
5684 starExcludes = getStarExcludes({ dependencies, exports });
5685 }
5686 if (!createdSetter) {
5687 setter.push(`${varOrConst} _setter${_}=${_}{};`);
5688 createdSetter = true;
5689 }
5690 setter.push(`for${_}(var _$p${_}in${_}module)${_}{`);
5691 setter.push(`${t}if${_}(!_starExcludes[_$p])${_}_setter[_$p]${_}=${_}module[_$p];`);
5692 setter.push('}');
5693 });
5694 // star import reexport
5695 reexports.forEach(specifier => {
5696 if (specifier.imported !== '*' || specifier.reexported === '*')
5697 return;
5698 setter.push(`exports('${specifier.reexported}',${_}module);`);
5699 });
5700 // reexports
5701 reexports.forEach(specifier => {
5702 if (specifier.reexported === '*' || specifier.imported === '*')
5703 return;
5704 if (!createdSetter) {
5705 setter.push(`${varOrConst} _setter${_}=${_}{};`);
5706 createdSetter = true;
5707 }
5708 setter.push(`_setter.${specifier.reexported}${_}=${_}module.${specifier.imported};`);
5709 });
5710 if (createdSetter) {
5711 setter.push('exports(_setter);');
5712 }
5713 }
5714 else {
5715 // single reexport
5716 reexports.forEach(specifier => {
5717 setter.push(`exports('${specifier.reexported}',${_}module.${specifier.imported});`);
5718 });
5719 }
5720 }
5721 setters.push(setter.join(`${n}${t}${t}${t}`));
5722 });
5723 const registeredName = options.name ? `'${options.name}',${_}` : '';
5724 const wrapperParams = accessedGlobals.has('module')
5725 ? `exports,${_}module`
5726 : hasExports
5727 ? 'exports'
5728 : '';
5729 let wrapperStart = `System.register(${registeredName}[` +
5730 dependencyIds.join(`,${_}`) +
5731 `],${_}function${_}(${wrapperParams})${_}{${n}${t}${options.strict ? "'use strict';" : ''}` +
5732 getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
5733 getImportBindingsBlock(importBindings, _, t, n) +
5734 `${n}${t}return${_}{${setters.length
5735 ? `${n}${t}${t}setters:${_}[${setters
5736 .map(s => s
5737 ? `function${_}(module)${_}{${n}${t}${t}${t}${s}${n}${t}${t}}`
5738 : `function${_}()${_}{}`)
5739 .join(`,${_}`)}],`
5740 : ''}${n}`;
5741 wrapperStart +=
5742 `${t}${t}execute:${_}${usesTopLevelAwait ? `async${_}` : ''}function${_}()${_}{${n}${n}` +
5743 getHoistedExportsBlock(exports, _, t, n);
5744 const wrapperEnd = `${n}${n}` +
5745 getMissingExportsBlock(exports, _, t, n) +
5746 `${t}${t}}${n}${t}}${options.compact ? '' : ';'}${n}});`;
5747 if (intro)
5748 magicString.prepend(intro);
5749 if (outro)
5750 magicString.append(outro);
5751 return magicString
5752 .indent(`${t}${t}${t}`)
5753 .append(wrapperEnd)
5754 .prepend(wrapperStart);
5755}
5756
5757function globalProp(name, globalVar) {
5758 if (!name)
5759 return 'null';
5760 return `${globalVar}${keypath(name)}`;
5761}
5762function safeAccess(name, globalVar, _) {
5763 const parts = name.split('.');
5764 let acc = globalVar;
5765 return parts.map(part => ((acc += property(part)), acc)).join(`${_}&&${_}`);
5766}
5767function umd(magicString, { dependencies, exports, hasExports, indentString: t, intro, namedExportsMode, outro, varOrConst, warn }, options) {
5768 const _ = options.compact ? '' : ' ';
5769 const n = options.compact ? '' : '\n';
5770 const factoryVar = options.compact ? 'f' : 'factory';
5771 const globalVar = options.compact ? 'g' : 'global';
5772 if (hasExports && !options.name) {
5773 error({
5774 code: 'INVALID_OPTION',
5775 message: 'You must supply "output.name" for UMD bundles.'
5776 });
5777 }
5778 warnOnBuiltins(warn, dependencies);
5779 const amdDeps = dependencies.map(m => `'${m.id}'`);
5780 const cjsDeps = dependencies.map(m => `require('${m.id}')`);
5781 const trimmedImports = trimEmptyImports(dependencies);
5782 const globalDeps = trimmedImports.map(module => globalProp(module.globalName, globalVar));
5783 const factoryArgs = trimmedImports.map(m => m.name);
5784 if (namedExportsMode && (hasExports || options.noConflict === true)) {
5785 amdDeps.unshift(`'exports'`);
5786 cjsDeps.unshift(`exports`);
5787 globalDeps.unshift(assignToDeepVariable(options.name, globalVar, options.globals, options.compact, `${options.extend ? `${globalProp(options.name, globalVar)}${_}||${_}` : ''}{}`));
5788 factoryArgs.unshift('exports');
5789 }
5790 const amdOptions = options.amd || {};
5791 const amdParams = (amdOptions.id ? `'${amdOptions.id}',${_}` : ``) +
5792 (amdDeps.length ? `[${amdDeps.join(`,${_}`)}],${_}` : ``);
5793 const define = amdOptions.define || 'define';
5794 const cjsExport = !namedExportsMode && hasExports ? `module.exports${_}=${_}` : ``;
5795 const useStrict = options.strict !== false ? `${_}'use strict';${n}` : ``;
5796 let iifeExport;
5797 if (options.noConflict === true) {
5798 const noConflictExportsVar = options.compact ? 'e' : 'exports';
5799 let factory;
5800 if (!namedExportsMode && hasExports) {
5801 factory = `var ${noConflictExportsVar}${_}=${_}${assignToDeepVariable(options.name, globalVar, options.globals, options.compact, `${factoryVar}(${globalDeps.join(`,${_}`)})`)};`;
5802 }
5803 else if (namedExportsMode) {
5804 const module = globalDeps.shift();
5805 factory =
5806 `var ${noConflictExportsVar}${_}=${_}${module};${n}` +
5807 `${t}${t}${factoryVar}(${[noConflictExportsVar].concat(globalDeps).join(`,${_}`)});`;
5808 }
5809 iifeExport =
5810 `(function${_}()${_}{${n}` +
5811 `${t}${t}var current${_}=${_}${safeAccess(options.name, globalVar, _)};${n}` +
5812 `${t}${t}${factory}${n}` +
5813 `${t}${t}${noConflictExportsVar}.noConflict${_}=${_}function${_}()${_}{${_}` +
5814 `${globalProp(options.name, globalVar)}${_}=${_}current;${_}return ${noConflictExportsVar}${options.compact ? '' : '; '}};${n}` +
5815 `${t}}())`;
5816 }
5817 else {
5818 iifeExport = `${factoryVar}(${globalDeps.join(`,${_}`)})`;
5819 if (!namedExportsMode && hasExports) {
5820 iifeExport = assignToDeepVariable(options.name, globalVar, options.globals, options.compact, iifeExport);
5821 }
5822 }
5823 const iifeNeedsGlobal = hasExports || (options.noConflict === true && namedExportsMode) || globalDeps.length > 0;
5824 const globalParam = iifeNeedsGlobal ? `${globalVar},${_}` : '';
5825 const globalArg = iifeNeedsGlobal ? `this,${_}` : '';
5826 const iifeStart = iifeNeedsGlobal ? `(${globalVar}${_}=${_}${globalVar}${_}||${_}self,${_}` : '';
5827 const iifeEnd = iifeNeedsGlobal ? ')' : '';
5828 const cjsIntro = iifeNeedsGlobal
5829 ? `${t}typeof exports${_}===${_}'object'${_}&&${_}typeof module${_}!==${_}'undefined'${_}?` +
5830 `${_}${cjsExport}${factoryVar}(${cjsDeps.join(`,${_}`)})${_}:${n}`
5831 : '';
5832 // factory function should be wrapped by parentheses to avoid lazy parsing
5833 const wrapperIntro = `(function${_}(${globalParam}${factoryVar})${_}{${n}` +
5834 cjsIntro +
5835 `${t}typeof ${define}${_}===${_}'function'${_}&&${_}${define}.amd${_}?${_}${define}(${amdParams}${factoryVar})${_}:${n}` +
5836 `${t}${iifeStart}${iifeExport}${iifeEnd};${n}` +
5837 `}(${globalArg}(function${_}(${factoryArgs.join(', ')})${_}{${useStrict}${n}`;
5838 const wrapperOutro = n + n + '})));';
5839 // var foo__default = 'default' in foo ? foo['default'] : foo;
5840 const interopBlock = getInteropBlock(dependencies, options, varOrConst);
5841 if (interopBlock)
5842 magicString.prepend(interopBlock + n + n);
5843 if (intro)
5844 magicString.prepend(intro);
5845 const exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
5846 if (exportBlock)
5847 magicString.append(n + n + exportBlock);
5848 if (namedExportsMode && hasExports && options.esModule)
5849 magicString.append(n + n + (options.compact ? compactEsModuleExport : esModuleExport));
5850 if (outro)
5851 magicString.append(outro);
5852 return magicString
5853 .trim()
5854 .indent(t)
5855 .append(wrapperOutro)
5856 .prepend(wrapperIntro);
5857}
5858
5859var finalisers = { system, amd, cjs, es: esm, iife, umd };
5860
5861const extractors = {
5862 ArrayPattern(names, param) {
5863 for (const element of param.elements) {
5864 if (element)
5865 extractors[element.type](names, element);
5866 }
5867 },
5868 AssignmentPattern(names, param) {
5869 extractors[param.left.type](names, param.left);
5870 },
5871 Identifier(names, param) {
5872 names.push(param.name);
5873 },
5874 MemberExpression() { },
5875 ObjectPattern(names, param) {
5876 for (const prop of param.properties) {
5877 if (prop.type === 'RestElement') {
5878 extractors.RestElement(names, prop);
5879 }
5880 else {
5881 extractors[prop.value.type](names, prop.value);
5882 }
5883 }
5884 },
5885 RestElement(names, param) {
5886 extractors[param.argument.type](names, param.argument);
5887 }
5888};
5889const extractAssignedNames = function extractAssignedNames(param) {
5890 const names = [];
5891 extractors[param.type](names, param);
5892 return names;
5893};
5894
5895class ArrayExpression extends NodeBase {
5896 bind() {
5897 super.bind();
5898 for (const element of this.elements) {
5899 if (element !== null)
5900 element.deoptimizePath(UNKNOWN_PATH);
5901 }
5902 }
5903 getReturnExpressionWhenCalledAtPath(path) {
5904 if (path.length !== 1)
5905 return UNKNOWN_EXPRESSION;
5906 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
5907 }
5908 hasEffectsWhenAccessedAtPath(path) {
5909 return path.length > 1;
5910 }
5911 hasEffectsWhenCalledAtPath(path, callOptions, context) {
5912 if (path.length === 1) {
5913 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, context);
5914 }
5915 return true;
5916 }
5917}
5918
5919class ArrayPattern extends NodeBase {
5920 addExportedVariables(variables) {
5921 for (const element of this.elements) {
5922 if (element !== null) {
5923 element.addExportedVariables(variables);
5924 }
5925 }
5926 }
5927 declare(kind) {
5928 const variables = [];
5929 for (const element of this.elements) {
5930 if (element !== null) {
5931 variables.push(...element.declare(kind, UNKNOWN_EXPRESSION));
5932 }
5933 }
5934 return variables;
5935 }
5936 deoptimizePath(path) {
5937 if (path.length === 0) {
5938 for (const element of this.elements) {
5939 if (element !== null) {
5940 element.deoptimizePath(path);
5941 }
5942 }
5943 }
5944 }
5945 hasEffectsWhenAssignedAtPath(path, context) {
5946 if (path.length > 0)
5947 return true;
5948 for (const element of this.elements) {
5949 if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
5950 return true;
5951 }
5952 return false;
5953 }
5954}
5955
5956class BlockScope extends ChildScope {
5957 addDeclaration(identifier, context, init = null, isHoisted) {
5958 if (isHoisted) {
5959 return this.parent.addDeclaration(identifier, context, isHoisted === 'function' ? init : UNKNOWN_EXPRESSION, isHoisted);
5960 }
5961 else {
5962 return super.addDeclaration(identifier, context, init, false);
5963 }
5964 }
5965}
5966
5967class BlockStatement$1 extends NodeBase {
5968 addImplicitReturnExpressionToScope() {
5969 const lastStatement = this.body[this.body.length - 1];
5970 if (!lastStatement || lastStatement.type !== ReturnStatement) {
5971 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
5972 }
5973 }
5974 createScope(parentScope) {
5975 this.scope = this.parent.preventChildBlockScope
5976 ? parentScope
5977 : new BlockScope(parentScope);
5978 }
5979 hasEffects(context) {
5980 for (const node of this.body) {
5981 if (node.hasEffects(context))
5982 return true;
5983 if (context.brokenFlow)
5984 break;
5985 }
5986 return false;
5987 }
5988 include(context, includeChildrenRecursively) {
5989 this.included = true;
5990 for (const node of this.body) {
5991 if (includeChildrenRecursively || node.shouldBeIncluded(context))
5992 node.include(context, includeChildrenRecursively);
5993 }
5994 }
5995 render(code, options) {
5996 if (this.body.length) {
5997 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
5998 }
5999 else {
6000 super.render(code, options);
6001 }
6002 }
6003}
6004
6005class ArrowFunctionExpression extends NodeBase {
6006 createScope(parentScope) {
6007 this.scope = new ReturnValueScope(parentScope, this.context);
6008 }
6009 deoptimizePath(path) {
6010 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
6011 // which means the return expression needs to be reassigned
6012 if (path.length === 1 && path[0] === UnknownKey) {
6013 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
6014 }
6015 }
6016 getReturnExpressionWhenCalledAtPath(path) {
6017 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
6018 }
6019 hasEffects() {
6020 return false;
6021 }
6022 hasEffectsWhenAccessedAtPath(path) {
6023 return path.length > 1;
6024 }
6025 hasEffectsWhenAssignedAtPath(path) {
6026 return path.length > 1;
6027 }
6028 hasEffectsWhenCalledAtPath(path, _callOptions, context) {
6029 if (path.length > 0)
6030 return true;
6031 for (const param of this.params) {
6032 if (param.hasEffects(context))
6033 return true;
6034 }
6035 const { ignore, brokenFlow } = context;
6036 context.ignore = {
6037 breaks: false,
6038 continues: false,
6039 labels: new Set(),
6040 returnAwaitYield: true
6041 };
6042 if (this.body.hasEffects(context))
6043 return true;
6044 context.ignore = ignore;
6045 context.brokenFlow = brokenFlow;
6046 return false;
6047 }
6048 include(context, includeChildrenRecursively) {
6049 this.included = true;
6050 for (const param of this.params) {
6051 if (!(param instanceof Identifier$1)) {
6052 param.include(context, includeChildrenRecursively);
6053 }
6054 }
6055 const { brokenFlow } = context;
6056 context.brokenFlow = BROKEN_FLOW_NONE;
6057 this.body.include(context, includeChildrenRecursively);
6058 context.brokenFlow = brokenFlow;
6059 }
6060 includeCallArguments(context, args) {
6061 this.scope.includeCallArguments(context, args);
6062 }
6063 initialise() {
6064 this.scope.addParameterVariables(this.params.map(param => param.declare('parameter', UNKNOWN_EXPRESSION)), this.params[this.params.length - 1] instanceof RestElement);
6065 if (this.body instanceof BlockStatement$1) {
6066 this.body.addImplicitReturnExpressionToScope();
6067 }
6068 else {
6069 this.scope.addReturnExpression(this.body);
6070 }
6071 }
6072 parseNode(esTreeNode) {
6073 if (esTreeNode.body.type === BlockStatement) {
6074 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
6075 }
6076 super.parseNode(esTreeNode);
6077 }
6078}
6079ArrowFunctionExpression.prototype.preventChildBlockScope = true;
6080
6081function getSystemExportStatement(exportedVariables) {
6082 if (exportedVariables.length === 1) {
6083 return `exports('${exportedVariables[0].safeExportName ||
6084 exportedVariables[0].exportName}', ${exportedVariables[0].getName()});`;
6085 }
6086 else {
6087 return `exports({${exportedVariables
6088 .map(variable => `${variable.safeExportName || variable.exportName}: ${variable.getName()}`)
6089 .join(', ')}});`;
6090 }
6091}
6092
6093class AssignmentExpression extends NodeBase {
6094 bind() {
6095 super.bind();
6096 this.left.deoptimizePath(EMPTY_PATH);
6097 // We cannot propagate mutations of the new binding to the old binding with certainty
6098 this.right.deoptimizePath(UNKNOWN_PATH);
6099 }
6100 hasEffects(context) {
6101 return (this.right.hasEffects(context) ||
6102 this.left.hasEffects(context) ||
6103 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
6104 }
6105 hasEffectsWhenAccessedAtPath(path, context) {
6106 return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, context);
6107 }
6108 render(code, options) {
6109 this.left.render(code, options);
6110 this.right.render(code, options);
6111 if (options.format === 'system') {
6112 if (this.left.variable && this.left.variable.exportName) {
6113 code.prependLeft(code.original.indexOf('=', this.left.end) + 1, ` exports('${this.left.variable.exportName}',`);
6114 code.appendLeft(this.right.end, `)`);
6115 }
6116 else if ('addExportedVariables' in this.left) {
6117 const systemPatternExports = [];
6118 this.left.addExportedVariables(systemPatternExports);
6119 if (systemPatternExports.length > 0) {
6120 code.prependRight(this.start, `function (v) {${getSystemExportStatement(systemPatternExports)} return v;} (`);
6121 code.appendLeft(this.end, ')');
6122 }
6123 }
6124 }
6125 }
6126}
6127
6128class AssignmentPattern extends NodeBase {
6129 addExportedVariables(variables) {
6130 this.left.addExportedVariables(variables);
6131 }
6132 bind() {
6133 super.bind();
6134 this.left.deoptimizePath(EMPTY_PATH);
6135 this.right.deoptimizePath(UNKNOWN_PATH);
6136 }
6137 declare(kind, init) {
6138 return this.left.declare(kind, init);
6139 }
6140 deoptimizePath(path) {
6141 path.length === 0 && this.left.deoptimizePath(path);
6142 }
6143 hasEffectsWhenAssignedAtPath(path, context) {
6144 return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context);
6145 }
6146 render(code, options, { isShorthandProperty } = BLANK) {
6147 this.left.render(code, options, { isShorthandProperty });
6148 this.right.render(code, options);
6149 }
6150}
6151
6152class AwaitExpression extends NodeBase {
6153 hasEffects(context) {
6154 return !context.ignore.returnAwaitYield || this.argument.hasEffects(context);
6155 }
6156 include(context, includeChildrenRecursively) {
6157 if (!this.included) {
6158 this.included = true;
6159 checkTopLevelAwait: if (!this.context.usesTopLevelAwait) {
6160 let parent = this.parent;
6161 do {
6162 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
6163 break checkTopLevelAwait;
6164 } while ((parent = parent.parent));
6165 this.context.usesTopLevelAwait = true;
6166 }
6167 }
6168 this.argument.include(context, includeChildrenRecursively);
6169 }
6170}
6171
6172class ExpressionStatement$1 extends NodeBase {
6173 initialise() {
6174 if (this.directive &&
6175 this.directive !== 'use strict' &&
6176 this.parent.type === Program) {
6177 this.context.warn(
6178 // This is necessary, because either way (deleting or not) can lead to errors.
6179 {
6180 code: 'MODULE_LEVEL_DIRECTIVE',
6181 message: `Module level directives cause errors when bundled, '${this.directive}' was ignored.`
6182 }, this.start);
6183 }
6184 }
6185 render(code, options) {
6186 super.render(code, options);
6187 if (this.included)
6188 this.insertSemicolon(code);
6189 }
6190 shouldBeIncluded(context) {
6191 if (this.directive && this.directive !== 'use strict')
6192 return this.parent.type !== Program;
6193 return super.shouldBeIncluded(context);
6194 }
6195}
6196
6197const binaryOperators = {
6198 '!=': (left, right) => left != right,
6199 '!==': (left, right) => left !== right,
6200 '%': (left, right) => left % right,
6201 '&': (left, right) => left & right,
6202 '*': (left, right) => left * right,
6203 // At the moment, "**" will be transpiled to Math.pow
6204 '**': (left, right) => Math.pow(left, right),
6205 '+': (left, right) => left + right,
6206 '-': (left, right) => left - right,
6207 '/': (left, right) => left / right,
6208 '<': (left, right) => left < right,
6209 '<<': (left, right) => left << right,
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 in: () => UnknownValue,
6219 instanceof: () => UnknownValue,
6220 '|': (left, right) => left | right
6221};
6222class BinaryExpression extends NodeBase {
6223 deoptimizeCache() { }
6224 getLiteralValueAtPath(path, recursionTracker, origin) {
6225 if (path.length > 0)
6226 return UnknownValue;
6227 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6228 if (leftValue === UnknownValue)
6229 return UnknownValue;
6230 const rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
6231 if (rightValue === UnknownValue)
6232 return UnknownValue;
6233 const operatorFn = binaryOperators[this.operator];
6234 if (!operatorFn)
6235 return UnknownValue;
6236 return operatorFn(leftValue, rightValue);
6237 }
6238 hasEffects(context) {
6239 // support some implicit type coercion runtime errors
6240 if (this.operator === '+' &&
6241 this.parent instanceof ExpressionStatement$1 &&
6242 this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this) === '')
6243 return true;
6244 return super.hasEffects(context);
6245 }
6246 hasEffectsWhenAccessedAtPath(path) {
6247 return path.length > 1;
6248 }
6249}
6250
6251class BreakStatement extends NodeBase {
6252 hasEffects(context) {
6253 if (this.label) {
6254 if (!context.ignore.labels.has(this.label.name))
6255 return true;
6256 context.includedLabels.add(this.label.name);
6257 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
6258 }
6259 else {
6260 if (!context.ignore.breaks)
6261 return true;
6262 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
6263 }
6264 return false;
6265 }
6266 include(context) {
6267 this.included = true;
6268 if (this.label) {
6269 this.label.include(context);
6270 context.includedLabels.add(this.label.name);
6271 }
6272 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
6273 }
6274}
6275
6276class CallExpression$1 extends NodeBase {
6277 constructor() {
6278 super(...arguments);
6279 // We collect deoptimization information if returnExpression !== UNKNOWN_EXPRESSION
6280 this.expressionsToBeDeoptimized = [];
6281 this.returnExpression = null;
6282 }
6283 bind() {
6284 super.bind();
6285 if (this.callee instanceof Identifier$1) {
6286 const variable = this.scope.findVariable(this.callee.name);
6287 if (variable.isNamespace) {
6288 this.context.error({
6289 code: 'CANNOT_CALL_NAMESPACE',
6290 message: `Cannot call a namespace ('${this.callee.name}')`
6291 }, this.start);
6292 }
6293 if (this.callee.name === 'eval') {
6294 this.context.warn({
6295 code: 'EVAL',
6296 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
6297 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
6298 }, this.start);
6299 }
6300 }
6301 if (this.returnExpression === null) {
6302 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
6303 }
6304 for (const argument of this.arguments) {
6305 // This will make sure all properties of parameters behave as "unknown"
6306 argument.deoptimizePath(UNKNOWN_PATH);
6307 }
6308 }
6309 deoptimizeCache() {
6310 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
6311 this.returnExpression = UNKNOWN_EXPRESSION;
6312 for (const expression of this.expressionsToBeDeoptimized) {
6313 expression.deoptimizeCache();
6314 }
6315 }
6316 }
6317 deoptimizePath(path) {
6318 if (path.length === 0)
6319 return;
6320 const trackedEntities = this.context.deoptimizationTracker.getEntities(path);
6321 if (trackedEntities.has(this))
6322 return;
6323 trackedEntities.add(this);
6324 if (this.returnExpression === null) {
6325 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
6326 }
6327 this.returnExpression.deoptimizePath(path);
6328 }
6329 getLiteralValueAtPath(path, recursionTracker, origin) {
6330 if (this.returnExpression === null) {
6331 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
6332 }
6333 if (this.returnExpression === UNKNOWN_EXPRESSION) {
6334 return UnknownValue;
6335 }
6336 const trackedEntities = recursionTracker.getEntities(path);
6337 if (trackedEntities.has(this.returnExpression)) {
6338 return UnknownValue;
6339 }
6340 this.expressionsToBeDeoptimized.push(origin);
6341 trackedEntities.add(this.returnExpression);
6342 const value = this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
6343 trackedEntities.delete(this.returnExpression);
6344 return value;
6345 }
6346 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6347 if (this.returnExpression === null) {
6348 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
6349 }
6350 if (this.returnExpression === UNKNOWN_EXPRESSION) {
6351 return UNKNOWN_EXPRESSION;
6352 }
6353 const trackedEntities = recursionTracker.getEntities(path);
6354 if (trackedEntities.has(this.returnExpression)) {
6355 return UNKNOWN_EXPRESSION;
6356 }
6357 this.expressionsToBeDeoptimized.push(origin);
6358 trackedEntities.add(this.returnExpression);
6359 const value = this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6360 trackedEntities.delete(this.returnExpression);
6361 return value;
6362 }
6363 hasEffects(context) {
6364 for (const argument of this.arguments) {
6365 if (argument.hasEffects(context))
6366 return true;
6367 }
6368 if (this.context.annotations && this.annotatedPure)
6369 return false;
6370 return (this.callee.hasEffects(context) ||
6371 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
6372 }
6373 hasEffectsWhenAccessedAtPath(path, context) {
6374 if (path.length === 0)
6375 return false;
6376 const trackedExpressions = context.accessed.getEntities(path);
6377 if (trackedExpressions.has(this))
6378 return false;
6379 trackedExpressions.add(this);
6380 return this.returnExpression.hasEffectsWhenAccessedAtPath(path, context);
6381 }
6382 hasEffectsWhenAssignedAtPath(path, context) {
6383 if (path.length === 0)
6384 return true;
6385 const trackedExpressions = context.assigned.getEntities(path);
6386 if (trackedExpressions.has(this))
6387 return false;
6388 trackedExpressions.add(this);
6389 return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
6390 }
6391 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6392 const trackedExpressions = (callOptions.withNew
6393 ? context.instantiated
6394 : context.called).getEntities(path);
6395 if (trackedExpressions.has(this))
6396 return false;
6397 trackedExpressions.add(this);
6398 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
6399 }
6400 include(context, includeChildrenRecursively) {
6401 if (includeChildrenRecursively) {
6402 super.include(context, includeChildrenRecursively);
6403 if (includeChildrenRecursively === INCLUDE_PARAMETERS &&
6404 this.callee instanceof Identifier$1 &&
6405 this.callee.variable) {
6406 this.callee.variable.markCalledFromTryStatement();
6407 }
6408 }
6409 else {
6410 this.included = true;
6411 this.callee.include(context, false);
6412 }
6413 this.callee.includeCallArguments(context, this.arguments);
6414 if (!this.returnExpression.included) {
6415 this.returnExpression.include(context, false);
6416 }
6417 }
6418 initialise() {
6419 this.callOptions = {
6420 args: this.arguments,
6421 withNew: false
6422 };
6423 }
6424 render(code, options, { renderedParentType } = BLANK) {
6425 this.callee.render(code, options);
6426 if (this.arguments.length > 0) {
6427 if (this.arguments[this.arguments.length - 1].included) {
6428 for (const arg of this.arguments) {
6429 arg.render(code, options);
6430 }
6431 }
6432 else {
6433 let lastIncludedIndex = this.arguments.length - 2;
6434 while (lastIncludedIndex >= 0 && !this.arguments[lastIncludedIndex].included) {
6435 lastIncludedIndex--;
6436 }
6437 if (lastIncludedIndex >= 0) {
6438 for (let index = 0; index <= lastIncludedIndex; index++) {
6439 this.arguments[index].render(code, options);
6440 }
6441 code.remove(findFirstOccurrenceOutsideComment(code.original, ',', this.arguments[lastIncludedIndex].end), this.end - 1);
6442 }
6443 else {
6444 code.remove(findFirstOccurrenceOutsideComment(code.original, '(', this.callee.end) + 1, this.end - 1);
6445 }
6446 }
6447 }
6448 if (renderedParentType === ExpressionStatement &&
6449 this.callee.type === FunctionExpression) {
6450 code.appendRight(this.start, '(');
6451 code.prependLeft(this.end, ')');
6452 }
6453 }
6454}
6455
6456class CatchScope extends ParameterScope {
6457 addDeclaration(identifier, context, init, isHoisted) {
6458 if (isHoisted) {
6459 return this.parent.addDeclaration(identifier, context, init, isHoisted);
6460 }
6461 else {
6462 return super.addDeclaration(identifier, context, init, false);
6463 }
6464 }
6465}
6466
6467class CatchClause extends NodeBase {
6468 createScope(parentScope) {
6469 this.scope = new CatchScope(parentScope, this.context);
6470 }
6471 initialise() {
6472 if (this.param) {
6473 this.param.declare('parameter', UNKNOWN_EXPRESSION);
6474 }
6475 }
6476 parseNode(esTreeNode) {
6477 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope);
6478 super.parseNode(esTreeNode);
6479 }
6480}
6481CatchClause.prototype.preventChildBlockScope = true;
6482
6483class ClassBody extends NodeBase {
6484 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6485 if (path.length > 0)
6486 return true;
6487 return (this.classConstructor !== null &&
6488 this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
6489 }
6490 initialise() {
6491 for (const method of this.body) {
6492 if (method.kind === 'constructor') {
6493 this.classConstructor = method;
6494 return;
6495 }
6496 }
6497 this.classConstructor = null;
6498 }
6499}
6500
6501class ClassExpression extends ClassNode {
6502}
6503
6504class MultiExpression {
6505 constructor(expressions) {
6506 this.included = false;
6507 this.expressions = expressions;
6508 }
6509 deoptimizePath(path) {
6510 for (const expression of this.expressions) {
6511 expression.deoptimizePath(path);
6512 }
6513 }
6514 getLiteralValueAtPath() {
6515 return UnknownValue;
6516 }
6517 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6518 return new MultiExpression(this.expressions.map(expression => expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)));
6519 }
6520 hasEffectsWhenAccessedAtPath(path, context) {
6521 for (const expression of this.expressions) {
6522 if (expression.hasEffectsWhenAccessedAtPath(path, context))
6523 return true;
6524 }
6525 return false;
6526 }
6527 hasEffectsWhenAssignedAtPath(path, context) {
6528 for (const expression of this.expressions) {
6529 if (expression.hasEffectsWhenAssignedAtPath(path, context))
6530 return true;
6531 }
6532 return false;
6533 }
6534 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6535 for (const expression of this.expressions) {
6536 if (expression.hasEffectsWhenCalledAtPath(path, callOptions, context))
6537 return true;
6538 }
6539 return false;
6540 }
6541 include() { }
6542 includeCallArguments() { }
6543}
6544
6545class ConditionalExpression extends NodeBase {
6546 constructor() {
6547 super(...arguments);
6548 // We collect deoptimization information if usedBranch !== null
6549 this.expressionsToBeDeoptimized = [];
6550 this.isBranchResolutionAnalysed = false;
6551 this.unusedBranch = null;
6552 this.usedBranch = null;
6553 }
6554 bind() {
6555 super.bind();
6556 if (!this.isBranchResolutionAnalysed)
6557 this.analyseBranchResolution();
6558 }
6559 deoptimizeCache() {
6560 if (this.usedBranch !== null) {
6561 // We did not track if there were reassignments to the previous branch.
6562 // Also, the return value might need to be reassigned.
6563 this.usedBranch = null;
6564 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
6565 for (const expression of this.expressionsToBeDeoptimized) {
6566 expression.deoptimizeCache();
6567 }
6568 }
6569 }
6570 deoptimizePath(path) {
6571 if (path.length > 0) {
6572 if (!this.isBranchResolutionAnalysed)
6573 this.analyseBranchResolution();
6574 if (this.usedBranch === null) {
6575 this.consequent.deoptimizePath(path);
6576 this.alternate.deoptimizePath(path);
6577 }
6578 else {
6579 this.usedBranch.deoptimizePath(path);
6580 }
6581 }
6582 }
6583 getLiteralValueAtPath(path, recursionTracker, origin) {
6584 if (!this.isBranchResolutionAnalysed)
6585 this.analyseBranchResolution();
6586 if (this.usedBranch === null)
6587 return UnknownValue;
6588 this.expressionsToBeDeoptimized.push(origin);
6589 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
6590 }
6591 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
6592 if (!this.isBranchResolutionAnalysed)
6593 this.analyseBranchResolution();
6594 if (this.usedBranch === null)
6595 return new MultiExpression([
6596 this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
6597 this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
6598 ]);
6599 this.expressionsToBeDeoptimized.push(origin);
6600 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
6601 }
6602 hasEffects(context) {
6603 if (this.test.hasEffects(context))
6604 return true;
6605 if (this.usedBranch === null) {
6606 return this.consequent.hasEffects(context) || this.alternate.hasEffects(context);
6607 }
6608 return this.usedBranch.hasEffects(context);
6609 }
6610 hasEffectsWhenAccessedAtPath(path, context) {
6611 if (path.length === 0)
6612 return false;
6613 if (this.usedBranch === null) {
6614 return (this.consequent.hasEffectsWhenAccessedAtPath(path, context) ||
6615 this.alternate.hasEffectsWhenAccessedAtPath(path, context));
6616 }
6617 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
6618 }
6619 hasEffectsWhenAssignedAtPath(path, context) {
6620 if (path.length === 0)
6621 return true;
6622 if (this.usedBranch === null) {
6623 return (this.consequent.hasEffectsWhenAssignedAtPath(path, context) ||
6624 this.alternate.hasEffectsWhenAssignedAtPath(path, context));
6625 }
6626 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
6627 }
6628 hasEffectsWhenCalledAtPath(path, callOptions, context) {
6629 if (this.usedBranch === null) {
6630 return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
6631 this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, context));
6632 }
6633 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
6634 }
6635 include(context, includeChildrenRecursively) {
6636 this.included = true;
6637 if (includeChildrenRecursively ||
6638 this.usedBranch === null ||
6639 this.test.shouldBeIncluded(context)) {
6640 this.test.include(context, includeChildrenRecursively);
6641 this.consequent.include(context, includeChildrenRecursively);
6642 this.alternate.include(context, includeChildrenRecursively);
6643 }
6644 else {
6645 this.usedBranch.include(context, includeChildrenRecursively);
6646 }
6647 }
6648 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
6649 if (!this.test.included) {
6650 const colonPos = findFirstOccurrenceOutsideComment(code.original, ':', this.consequent.end);
6651 const inclusionStart = (this.consequent.included
6652 ? findFirstOccurrenceOutsideComment(code.original, '?', this.test.end)
6653 : colonPos) + 1;
6654 if (preventASI) {
6655 removeLineBreaks(code, inclusionStart, this.usedBranch.start);
6656 }
6657 code.remove(this.start, inclusionStart);
6658 if (this.consequent.included) {
6659 code.remove(colonPos, this.end);
6660 }
6661 removeAnnotations(this, code);
6662 this.usedBranch.render(code, options, {
6663 isCalleeOfRenderedParent: renderedParentType
6664 ? isCalleeOfRenderedParent
6665 : this.parent.callee === this,
6666 renderedParentType: renderedParentType || this.parent.type
6667 });
6668 }
6669 else {
6670 super.render(code, options);
6671 }
6672 }
6673 analyseBranchResolution() {
6674 this.isBranchResolutionAnalysed = true;
6675 const testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
6676 if (testValue !== UnknownValue) {
6677 if (testValue) {
6678 this.usedBranch = this.consequent;
6679 this.unusedBranch = this.alternate;
6680 }
6681 else {
6682 this.usedBranch = this.alternate;
6683 this.unusedBranch = this.consequent;
6684 }
6685 }
6686 }
6687}
6688
6689class ContinueStatement extends NodeBase {
6690 hasEffects(context) {
6691 if (this.label) {
6692 if (!context.ignore.labels.has(this.label.name))
6693 return true;
6694 context.includedLabels.add(this.label.name);
6695 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
6696 }
6697 else {
6698 if (!context.ignore.continues)
6699 return true;
6700 context.brokenFlow = BROKEN_FLOW_BREAK_CONTINUE;
6701 }
6702 return false;
6703 }
6704 include(context) {
6705 this.included = true;
6706 if (this.label) {
6707 this.label.include(context);
6708 context.includedLabels.add(this.label.name);
6709 }
6710 context.brokenFlow = this.label ? BROKEN_FLOW_ERROR_RETURN_LABEL : BROKEN_FLOW_BREAK_CONTINUE;
6711 }
6712}
6713
6714class DoWhileStatement extends NodeBase {
6715 hasEffects(context) {
6716 if (this.test.hasEffects(context))
6717 return true;
6718 const { brokenFlow, ignore: { breaks, continues } } = context;
6719 context.ignore.breaks = true;
6720 context.ignore.continues = true;
6721 if (this.body.hasEffects(context))
6722 return true;
6723 context.ignore.breaks = breaks;
6724 context.ignore.continues = continues;
6725 context.brokenFlow = brokenFlow;
6726 return false;
6727 }
6728 include(context, includeChildrenRecursively) {
6729 this.included = true;
6730 this.test.include(context, includeChildrenRecursively);
6731 const { brokenFlow } = context;
6732 this.body.include(context, includeChildrenRecursively);
6733 context.brokenFlow = brokenFlow;
6734 }
6735}
6736
6737class EmptyStatement extends NodeBase {
6738 hasEffects() {
6739 return false;
6740 }
6741}
6742
6743class ExportAllDeclaration$1 extends NodeBase {
6744 hasEffects() {
6745 return false;
6746 }
6747 initialise() {
6748 this.context.addExport(this);
6749 }
6750 render(code, _options, { start, end } = BLANK) {
6751 code.remove(start, end);
6752 }
6753}
6754ExportAllDeclaration$1.prototype.needsBoundaries = true;
6755
6756class ExportNamedDeclaration extends NodeBase {
6757 bind() {
6758 // Do not bind specifiers
6759 if (this.declaration !== null)
6760 this.declaration.bind();
6761 }
6762 hasEffects(context) {
6763 return this.declaration !== null && this.declaration.hasEffects(context);
6764 }
6765 initialise() {
6766 this.context.addExport(this);
6767 }
6768 render(code, options, { start, end } = BLANK) {
6769 if (this.declaration === null) {
6770 code.remove(start, end);
6771 }
6772 else {
6773 code.remove(this.start, this.declaration.start);
6774 this.declaration.render(code, options, { start, end });
6775 }
6776 }
6777}
6778ExportNamedDeclaration.prototype.needsBoundaries = true;
6779
6780class ForInStatement extends NodeBase {
6781 bind() {
6782 this.left.bind();
6783 this.left.deoptimizePath(EMPTY_PATH);
6784 this.right.bind();
6785 this.body.bind();
6786 }
6787 createScope(parentScope) {
6788 this.scope = new BlockScope(parentScope);
6789 }
6790 hasEffects(context) {
6791 if ((this.left &&
6792 (this.left.hasEffects(context) ||
6793 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))) ||
6794 (this.right && this.right.hasEffects(context)))
6795 return true;
6796 const { brokenFlow, ignore: { breaks, continues } } = context;
6797 context.ignore.breaks = true;
6798 context.ignore.continues = true;
6799 if (this.body.hasEffects(context))
6800 return true;
6801 context.ignore.breaks = breaks;
6802 context.ignore.continues = continues;
6803 context.brokenFlow = brokenFlow;
6804 return false;
6805 }
6806 include(context, includeChildrenRecursively) {
6807 this.included = true;
6808 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
6809 this.left.deoptimizePath(EMPTY_PATH);
6810 this.right.include(context, includeChildrenRecursively);
6811 const { brokenFlow } = context;
6812 this.body.include(context, includeChildrenRecursively);
6813 context.brokenFlow = brokenFlow;
6814 }
6815 render(code, options) {
6816 this.left.render(code, options, NO_SEMICOLON);
6817 this.right.render(code, options, NO_SEMICOLON);
6818 // handle no space between "in" and the right side
6819 if (code.original.charCodeAt(this.right.start - 1) === 110 /* n */) {
6820 code.prependLeft(this.right.start, ' ');
6821 }
6822 this.body.render(code, options);
6823 }
6824}
6825
6826class ForOfStatement extends NodeBase {
6827 bind() {
6828 this.left.bind();
6829 this.left.deoptimizePath(EMPTY_PATH);
6830 this.right.bind();
6831 this.body.bind();
6832 }
6833 createScope(parentScope) {
6834 this.scope = new BlockScope(parentScope);
6835 }
6836 hasEffects() {
6837 // Placeholder until proper Symbol.Iterator support
6838 return true;
6839 }
6840 include(context, includeChildrenRecursively) {
6841 this.included = true;
6842 this.left.includeWithAllDeclaredVariables(includeChildrenRecursively, context);
6843 this.left.deoptimizePath(EMPTY_PATH);
6844 this.right.include(context, includeChildrenRecursively);
6845 const { brokenFlow } = context;
6846 this.body.include(context, includeChildrenRecursively);
6847 context.brokenFlow = brokenFlow;
6848 }
6849 render(code, options) {
6850 this.left.render(code, options, NO_SEMICOLON);
6851 this.right.render(code, options, NO_SEMICOLON);
6852 // handle no space between "of" and the right side
6853 if (code.original.charCodeAt(this.right.start - 1) === 102 /* f */) {
6854 code.prependLeft(this.right.start, ' ');
6855 }
6856 this.body.render(code, options);
6857 }
6858}
6859
6860class ForStatement extends NodeBase {
6861 createScope(parentScope) {
6862 this.scope = new BlockScope(parentScope);
6863 }
6864 hasEffects(context) {
6865 if ((this.init && this.init.hasEffects(context)) ||
6866 (this.test && this.test.hasEffects(context)) ||
6867 (this.update && this.update.hasEffects(context)))
6868 return true;
6869 const { brokenFlow, ignore: { breaks, continues } } = context;
6870 context.ignore.breaks = true;
6871 context.ignore.continues = true;
6872 if (this.body.hasEffects(context))
6873 return true;
6874 context.ignore.breaks = breaks;
6875 context.ignore.continues = continues;
6876 context.brokenFlow = brokenFlow;
6877 return false;
6878 }
6879 include(context, includeChildrenRecursively) {
6880 this.included = true;
6881 if (this.init)
6882 this.init.include(context, includeChildrenRecursively);
6883 if (this.test)
6884 this.test.include(context, includeChildrenRecursively);
6885 const { brokenFlow } = context;
6886 if (this.update)
6887 this.update.include(context, includeChildrenRecursively);
6888 this.body.include(context, includeChildrenRecursively);
6889 context.brokenFlow = brokenFlow;
6890 }
6891 render(code, options) {
6892 if (this.init)
6893 this.init.render(code, options, NO_SEMICOLON);
6894 if (this.test)
6895 this.test.render(code, options, NO_SEMICOLON);
6896 if (this.update)
6897 this.update.render(code, options, NO_SEMICOLON);
6898 this.body.render(code, options);
6899 }
6900}
6901
6902class FunctionExpression$1 extends FunctionNode {
6903}
6904
6905class IfStatement extends NodeBase {
6906 bind() {
6907 super.bind();
6908 this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
6909 }
6910 deoptimizeCache() {
6911 this.testValue = UnknownValue;
6912 }
6913 hasEffects(context) {
6914 if (this.test.hasEffects(context))
6915 return true;
6916 if (this.testValue === UnknownValue) {
6917 const { brokenFlow } = context;
6918 if (this.consequent.hasEffects(context))
6919 return true;
6920 const consequentBrokenFlow = context.brokenFlow;
6921 context.brokenFlow = brokenFlow;
6922 if (this.alternate === null)
6923 return false;
6924 if (this.alternate.hasEffects(context))
6925 return true;
6926 context.brokenFlow =
6927 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
6928 return false;
6929 }
6930 return this.testValue
6931 ? this.consequent.hasEffects(context)
6932 : this.alternate !== null && this.alternate.hasEffects(context);
6933 }
6934 include(context, includeChildrenRecursively) {
6935 this.included = true;
6936 if (includeChildrenRecursively) {
6937 this.includeRecursively(includeChildrenRecursively, context);
6938 }
6939 else if (this.testValue === UnknownValue) {
6940 this.includeUnknownTest(context);
6941 }
6942 else {
6943 this.includeKnownTest(context);
6944 }
6945 }
6946 render(code, options) {
6947 // Note that unknown test values are always included
6948 if (!this.test.included &&
6949 (this.testValue
6950 ? this.alternate === null || !this.alternate.included
6951 : !this.consequent.included)) {
6952 const singleRetainedBranch = (this.testValue
6953 ? this.consequent
6954 : this.alternate);
6955 code.remove(this.start, singleRetainedBranch.start);
6956 code.remove(singleRetainedBranch.end, this.end);
6957 removeAnnotations(this, code);
6958 singleRetainedBranch.render(code, options);
6959 }
6960 else {
6961 if (this.test.included) {
6962 this.test.render(code, options);
6963 }
6964 else {
6965 code.overwrite(this.test.start, this.test.end, this.testValue ? 'true' : 'false');
6966 }
6967 if (this.consequent.included) {
6968 this.consequent.render(code, options);
6969 }
6970 else {
6971 code.overwrite(this.consequent.start, this.consequent.end, ';');
6972 }
6973 if (this.alternate !== null) {
6974 if (this.alternate.included) {
6975 this.alternate.render(code, options);
6976 }
6977 else {
6978 code.remove(this.consequent.end, this.alternate.end);
6979 }
6980 }
6981 }
6982 }
6983 includeKnownTest(context) {
6984 if (this.test.shouldBeIncluded(context)) {
6985 this.test.include(context, false);
6986 }
6987 if (this.testValue && this.consequent.shouldBeIncluded(context)) {
6988 this.consequent.include(context, false);
6989 }
6990 if (this.alternate !== null && !this.testValue && this.alternate.shouldBeIncluded(context)) {
6991 this.alternate.include(context, false);
6992 }
6993 }
6994 includeRecursively(includeChildrenRecursively, context) {
6995 this.test.include(context, includeChildrenRecursively);
6996 this.consequent.include(context, includeChildrenRecursively);
6997 if (this.alternate !== null) {
6998 this.alternate.include(context, includeChildrenRecursively);
6999 }
7000 }
7001 includeUnknownTest(context) {
7002 this.test.include(context, false);
7003 const { brokenFlow } = context;
7004 let consequentBrokenFlow = BROKEN_FLOW_NONE;
7005 if (this.consequent.shouldBeIncluded(context)) {
7006 this.consequent.include(context, false);
7007 consequentBrokenFlow = context.brokenFlow;
7008 context.brokenFlow = brokenFlow;
7009 }
7010 if (this.alternate !== null && this.alternate.shouldBeIncluded(context)) {
7011 this.alternate.include(context, false);
7012 context.brokenFlow =
7013 context.brokenFlow < consequentBrokenFlow ? context.brokenFlow : consequentBrokenFlow;
7014 }
7015 }
7016}
7017
7018class ImportDeclaration extends NodeBase {
7019 bind() { }
7020 hasEffects() {
7021 return false;
7022 }
7023 initialise() {
7024 this.context.addImport(this);
7025 }
7026 render(code, _options, { start, end } = BLANK) {
7027 code.remove(start, end);
7028 }
7029}
7030ImportDeclaration.prototype.needsBoundaries = true;
7031
7032class Import extends NodeBase {
7033 constructor() {
7034 super(...arguments);
7035 this.exportMode = 'auto';
7036 }
7037 hasEffects() {
7038 return true;
7039 }
7040 include(context, includeChildrenRecursively) {
7041 if (!this.included) {
7042 this.included = true;
7043 this.context.includeDynamicImport(this);
7044 }
7045 this.source.include(context, includeChildrenRecursively);
7046 }
7047 initialise() {
7048 this.context.addDynamicImport(this);
7049 }
7050 render(code, options) {
7051 if (this.inlineNamespace) {
7052 const _ = options.compact ? '' : ' ';
7053 const s = options.compact ? '' : ';';
7054 code.overwrite(this.start, this.end, `Promise.resolve().then(function${_}()${_}{${_}return ${this.inlineNamespace.getName()}${s}${_}})`);
7055 return;
7056 }
7057 const importMechanism = this.getDynamicImportMechanism(options);
7058 if (importMechanism) {
7059 code.overwrite(this.start, findFirstOccurrenceOutsideComment(code.original, '(', this.start + 6) + 1, importMechanism.left);
7060 code.overwrite(this.end - 1, this.end, importMechanism.right);
7061 }
7062 this.source.render(code, options);
7063 }
7064 renderFinalResolution(code, resolution, format) {
7065 if (this.included) {
7066 if (format === 'amd' && resolution.startsWith("'.") && resolution.endsWith(".js'")) {
7067 resolution = resolution.slice(0, -4) + "'";
7068 }
7069 code.overwrite(this.source.start, this.source.end, resolution);
7070 }
7071 }
7072 setResolution(exportMode, inlineNamespace) {
7073 this.exportMode = exportMode;
7074 if (inlineNamespace) {
7075 this.inlineNamespace = inlineNamespace;
7076 }
7077 else {
7078 this.scope.addAccessedGlobalsByFormat({
7079 amd: ['require'],
7080 cjs: ['require'],
7081 system: ['module']
7082 });
7083 if (exportMode === 'auto') {
7084 this.scope.addAccessedGlobalsByFormat({
7085 amd: [INTEROP_NAMESPACE_VARIABLE],
7086 cjs: [INTEROP_NAMESPACE_VARIABLE]
7087 });
7088 }
7089 }
7090 }
7091 getDynamicImportMechanism(options) {
7092 switch (options.format) {
7093 case 'cjs': {
7094 const _ = options.compact ? '' : ' ';
7095 const resolve = options.compact ? 'c' : 'resolve';
7096 switch (this.exportMode) {
7097 case 'default':
7098 return {
7099 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}({${_}'default':${_}require(`,
7100 right: `)${_}});${_}})`
7101 };
7102 case 'auto':
7103 return {
7104 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}(${INTEROP_NAMESPACE_VARIABLE}(require(`,
7105 right: `)));${_}})`
7106 };
7107 default:
7108 return {
7109 left: `new Promise(function${_}(${resolve})${_}{${_}${resolve}(require(`,
7110 right: `));${_}})`
7111 };
7112 }
7113 }
7114 case 'amd': {
7115 const _ = options.compact ? '' : ' ';
7116 const resolve = options.compact ? 'c' : 'resolve';
7117 const reject = options.compact ? 'e' : 'reject';
7118 const resolveNamespace = this.exportMode === 'default'
7119 ? `function${_}(m)${_}{${_}${resolve}({${_}'default':${_}m${_}});${_}}`
7120 : this.exportMode === 'auto'
7121 ? `function${_}(m)${_}{${_}${resolve}(${INTEROP_NAMESPACE_VARIABLE}(m));${_}}`
7122 : resolve;
7123 return {
7124 left: `new Promise(function${_}(${resolve},${_}${reject})${_}{${_}require([`,
7125 right: `],${_}${resolveNamespace},${_}${reject})${_}})`
7126 };
7127 }
7128 case 'system':
7129 return {
7130 left: 'module.import(',
7131 right: ')'
7132 };
7133 case 'es':
7134 if (options.dynamicImportFunction) {
7135 return {
7136 left: `${options.dynamicImportFunction}(`,
7137 right: ')'
7138 };
7139 }
7140 }
7141 return null;
7142 }
7143}
7144
7145class LabeledStatement extends NodeBase {
7146 hasEffects(context) {
7147 const brokenFlow = context.brokenFlow;
7148 context.ignore.labels.add(this.label.name);
7149 if (this.body.hasEffects(context))
7150 return true;
7151 context.ignore.labels.delete(this.label.name);
7152 if (context.includedLabels.has(this.label.name)) {
7153 context.includedLabels.delete(this.label.name);
7154 context.brokenFlow = brokenFlow;
7155 }
7156 return false;
7157 }
7158 include(context, includeChildrenRecursively) {
7159 this.included = true;
7160 const brokenFlow = context.brokenFlow;
7161 this.body.include(context, includeChildrenRecursively);
7162 if (context.includedLabels.has(this.label.name)) {
7163 this.label.include(context);
7164 context.includedLabels.delete(this.label.name);
7165 context.brokenFlow = brokenFlow;
7166 }
7167 }
7168 render(code, options) {
7169 if (this.label.included) {
7170 this.label.render(code, options);
7171 }
7172 else {
7173 code.remove(this.start, findFirstOccurrenceOutsideComment(code.original, ':', this.label.end) + 1);
7174 }
7175 this.body.render(code, options);
7176 }
7177}
7178
7179class Literal extends NodeBase {
7180 getLiteralValueAtPath(path) {
7181 if (path.length > 0 ||
7182 // unknown literals can also be null but do not start with an "n"
7183 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
7184 typeof this.value === 'bigint' ||
7185 // to support shims for regular expressions
7186 this.context.code.charCodeAt(this.start) === 47) {
7187 return UnknownValue;
7188 }
7189 return this.value;
7190 }
7191 getReturnExpressionWhenCalledAtPath(path) {
7192 if (path.length !== 1)
7193 return UNKNOWN_EXPRESSION;
7194 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
7195 }
7196 hasEffectsWhenAccessedAtPath(path) {
7197 if (this.value === null) {
7198 return path.length > 0;
7199 }
7200 return path.length > 1;
7201 }
7202 hasEffectsWhenAssignedAtPath(path) {
7203 return path.length > 0;
7204 }
7205 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7206 if (path.length === 1) {
7207 return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, context);
7208 }
7209 return true;
7210 }
7211 initialise() {
7212 this.members = getLiteralMembersForValue(this.value);
7213 }
7214 render(code) {
7215 if (typeof this.value === 'string') {
7216 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
7217 }
7218 }
7219}
7220
7221class LogicalExpression extends NodeBase {
7222 constructor() {
7223 super(...arguments);
7224 // We collect deoptimization information if usedBranch !== null
7225 this.expressionsToBeDeoptimized = [];
7226 this.isBranchResolutionAnalysed = false;
7227 this.unusedBranch = null;
7228 this.usedBranch = null;
7229 }
7230 bind() {
7231 super.bind();
7232 if (!this.isBranchResolutionAnalysed)
7233 this.analyseBranchResolution();
7234 }
7235 deoptimizeCache() {
7236 if (this.usedBranch !== null) {
7237 // We did not track if there were reassignments to any of the branches.
7238 // Also, the return values might need reassignment.
7239 this.usedBranch = null;
7240 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
7241 for (const expression of this.expressionsToBeDeoptimized) {
7242 expression.deoptimizeCache();
7243 }
7244 }
7245 }
7246 deoptimizePath(path) {
7247 if (path.length > 0) {
7248 if (!this.isBranchResolutionAnalysed)
7249 this.analyseBranchResolution();
7250 if (this.usedBranch === null) {
7251 this.left.deoptimizePath(path);
7252 this.right.deoptimizePath(path);
7253 }
7254 else {
7255 this.usedBranch.deoptimizePath(path);
7256 }
7257 }
7258 }
7259 getLiteralValueAtPath(path, recursionTracker, origin) {
7260 if (!this.isBranchResolutionAnalysed)
7261 this.analyseBranchResolution();
7262 if (this.usedBranch === null)
7263 return UnknownValue;
7264 this.expressionsToBeDeoptimized.push(origin);
7265 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
7266 }
7267 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
7268 if (!this.isBranchResolutionAnalysed)
7269 this.analyseBranchResolution();
7270 if (this.usedBranch === null)
7271 return new MultiExpression([
7272 this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
7273 this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
7274 ]);
7275 this.expressionsToBeDeoptimized.push(origin);
7276 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
7277 }
7278 hasEffects(context) {
7279 if (this.usedBranch === null) {
7280 return this.left.hasEffects(context) || this.right.hasEffects(context);
7281 }
7282 return this.usedBranch.hasEffects(context);
7283 }
7284 hasEffectsWhenAccessedAtPath(path, context) {
7285 if (path.length === 0)
7286 return false;
7287 if (this.usedBranch === null) {
7288 return (this.left.hasEffectsWhenAccessedAtPath(path, context) ||
7289 this.right.hasEffectsWhenAccessedAtPath(path, context));
7290 }
7291 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, context);
7292 }
7293 hasEffectsWhenAssignedAtPath(path, context) {
7294 if (path.length === 0)
7295 return true;
7296 if (this.usedBranch === null) {
7297 return (this.left.hasEffectsWhenAssignedAtPath(path, context) ||
7298 this.right.hasEffectsWhenAssignedAtPath(path, context));
7299 }
7300 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, context);
7301 }
7302 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7303 if (this.usedBranch === null) {
7304 return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, context) ||
7305 this.right.hasEffectsWhenCalledAtPath(path, callOptions, context));
7306 }
7307 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, context);
7308 }
7309 include(context, includeChildrenRecursively) {
7310 this.included = true;
7311 if (includeChildrenRecursively ||
7312 this.usedBranch === null ||
7313 this.unusedBranch.shouldBeIncluded(context)) {
7314 this.left.include(context, includeChildrenRecursively);
7315 this.right.include(context, includeChildrenRecursively);
7316 }
7317 else {
7318 this.usedBranch.include(context, includeChildrenRecursively);
7319 }
7320 }
7321 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
7322 if (!this.left.included || !this.right.included) {
7323 const operatorPos = findFirstOccurrenceOutsideComment(code.original, this.operator, this.left.end);
7324 if (this.right.included) {
7325 code.remove(this.start, operatorPos + 2);
7326 if (preventASI) {
7327 removeLineBreaks(code, operatorPos + 2, this.right.start);
7328 }
7329 }
7330 else {
7331 code.remove(operatorPos, this.end);
7332 }
7333 removeAnnotations(this, code);
7334 this.usedBranch.render(code, options, {
7335 isCalleeOfRenderedParent: renderedParentType
7336 ? isCalleeOfRenderedParent
7337 : this.parent.callee === this,
7338 renderedParentType: renderedParentType || this.parent.type
7339 });
7340 }
7341 else {
7342 super.render(code, options);
7343 }
7344 }
7345 analyseBranchResolution() {
7346 this.isBranchResolutionAnalysed = true;
7347 const leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
7348 if (leftValue !== UnknownValue) {
7349 if (this.operator === '||' ? leftValue : !leftValue) {
7350 this.usedBranch = this.left;
7351 this.unusedBranch = this.right;
7352 }
7353 else {
7354 this.usedBranch = this.right;
7355 this.unusedBranch = this.left;
7356 }
7357 }
7358 }
7359}
7360
7361function getResolvablePropertyKey(memberExpression) {
7362 return memberExpression.computed
7363 ? getResolvableComputedPropertyKey(memberExpression.property)
7364 : memberExpression.property.name;
7365}
7366function getResolvableComputedPropertyKey(propertyKey) {
7367 if (propertyKey instanceof Literal) {
7368 return String(propertyKey.value);
7369 }
7370 return null;
7371}
7372function getPathIfNotComputed(memberExpression) {
7373 const nextPathKey = memberExpression.propertyKey;
7374 const object = memberExpression.object;
7375 if (typeof nextPathKey === 'string') {
7376 if (object instanceof Identifier$1) {
7377 return [
7378 { key: object.name, pos: object.start },
7379 { key: nextPathKey, pos: memberExpression.property.start }
7380 ];
7381 }
7382 if (object instanceof MemberExpression) {
7383 const parentPath = getPathIfNotComputed(object);
7384 return (parentPath && [...parentPath, { key: nextPathKey, pos: memberExpression.property.start }]);
7385 }
7386 }
7387 return null;
7388}
7389function getStringFromPath(path) {
7390 let pathString = path[0].key;
7391 for (let index = 1; index < path.length; index++) {
7392 pathString += '.' + path[index].key;
7393 }
7394 return pathString;
7395}
7396class MemberExpression extends NodeBase {
7397 constructor() {
7398 super(...arguments);
7399 this.variable = null;
7400 this.bound = false;
7401 this.expressionsToBeDeoptimized = [];
7402 this.replacement = null;
7403 }
7404 addExportedVariables() { }
7405 bind() {
7406 if (this.bound)
7407 return;
7408 this.bound = true;
7409 const path = getPathIfNotComputed(this);
7410 const baseVariable = path && this.scope.findVariable(path[0].key);
7411 if (baseVariable && baseVariable.isNamespace) {
7412 const resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
7413 if (!resolvedVariable) {
7414 super.bind();
7415 }
7416 else if (typeof resolvedVariable === 'string') {
7417 this.replacement = resolvedVariable;
7418 }
7419 else {
7420 if (resolvedVariable instanceof ExternalVariable && resolvedVariable.module) {
7421 resolvedVariable.module.suggestName(path[0].key);
7422 }
7423 this.variable = resolvedVariable;
7424 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
7425 }
7426 }
7427 else {
7428 super.bind();
7429 if (this.propertyKey === null)
7430 this.analysePropertyKey();
7431 }
7432 }
7433 deoptimizeCache() {
7434 for (const expression of this.expressionsToBeDeoptimized) {
7435 expression.deoptimizeCache();
7436 }
7437 }
7438 deoptimizePath(path) {
7439 if (!this.bound)
7440 this.bind();
7441 if (path.length === 0)
7442 this.disallowNamespaceReassignment();
7443 if (this.variable) {
7444 this.variable.deoptimizePath(path);
7445 }
7446 else {
7447 if (this.propertyKey === null)
7448 this.analysePropertyKey();
7449 this.object.deoptimizePath([this.propertyKey, ...path]);
7450 }
7451 }
7452 getLiteralValueAtPath(path, recursionTracker, origin) {
7453 if (!this.bound)
7454 this.bind();
7455 if (this.variable !== null) {
7456 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
7457 }
7458 if (this.propertyKey === null)
7459 this.analysePropertyKey();
7460 this.expressionsToBeDeoptimized.push(origin);
7461 return this.object.getLiteralValueAtPath([this.propertyKey, ...path], recursionTracker, origin);
7462 }
7463 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
7464 if (!this.bound)
7465 this.bind();
7466 if (this.variable !== null) {
7467 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
7468 }
7469 if (this.propertyKey === null)
7470 this.analysePropertyKey();
7471 this.expressionsToBeDeoptimized.push(origin);
7472 return this.object.getReturnExpressionWhenCalledAtPath([this.propertyKey, ...path], recursionTracker, origin);
7473 }
7474 hasEffects(context) {
7475 return (this.property.hasEffects(context) ||
7476 this.object.hasEffects(context) ||
7477 (this.context.propertyReadSideEffects &&
7478 this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], context)));
7479 }
7480 hasEffectsWhenAccessedAtPath(path, context) {
7481 if (path.length === 0)
7482 return false;
7483 if (this.variable !== null) {
7484 return this.variable.hasEffectsWhenAccessedAtPath(path, context);
7485 }
7486 return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey, ...path], context);
7487 }
7488 hasEffectsWhenAssignedAtPath(path, context) {
7489 if (this.variable !== null) {
7490 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
7491 }
7492 return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey, ...path], context);
7493 }
7494 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7495 if (this.variable !== null) {
7496 return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, context);
7497 }
7498 return this.object.hasEffectsWhenCalledAtPath([this.propertyKey, ...path], callOptions, context);
7499 }
7500 include(context, includeChildrenRecursively) {
7501 if (!this.included) {
7502 this.included = true;
7503 if (this.variable !== null) {
7504 this.context.includeVariable(context, this.variable);
7505 }
7506 }
7507 this.object.include(context, includeChildrenRecursively);
7508 this.property.include(context, includeChildrenRecursively);
7509 }
7510 includeCallArguments(context, args) {
7511 if (this.variable) {
7512 this.variable.includeCallArguments(context, args);
7513 }
7514 else {
7515 super.includeCallArguments(context, args);
7516 }
7517 }
7518 initialise() {
7519 this.propertyKey = getResolvablePropertyKey(this);
7520 }
7521 render(code, options, { renderedParentType, isCalleeOfRenderedParent } = BLANK) {
7522 const isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
7523 if (this.variable || this.replacement) {
7524 let replacement = this.variable ? this.variable.getName() : this.replacement;
7525 if (isCalleeOfDifferentParent)
7526 replacement = '0, ' + replacement;
7527 code.overwrite(this.start, this.end, replacement, {
7528 contentOnly: true,
7529 storeName: true
7530 });
7531 }
7532 else {
7533 if (isCalleeOfDifferentParent) {
7534 code.appendRight(this.start, '0, ');
7535 }
7536 super.render(code, options);
7537 }
7538 }
7539 analysePropertyKey() {
7540 this.propertyKey = UnknownKey;
7541 const value = this.property.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
7542 this.propertyKey = value === UnknownValue ? UnknownKey : String(value);
7543 }
7544 disallowNamespaceReassignment() {
7545 if (this.object instanceof Identifier$1 &&
7546 this.scope.findVariable(this.object.name).isNamespace) {
7547 this.context.error({
7548 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
7549 message: `Illegal reassignment to import '${this.object.name}'`
7550 }, this.start);
7551 }
7552 }
7553 resolveNamespaceVariables(baseVariable, path) {
7554 if (path.length === 0)
7555 return baseVariable;
7556 if (!baseVariable.isNamespace)
7557 return null;
7558 const exportName = path[0].key;
7559 const variable = baseVariable instanceof ExternalVariable
7560 ? baseVariable.module.getVariableForExportName(exportName)
7561 : baseVariable.context.traceExport(exportName);
7562 if (!variable) {
7563 const fileName = baseVariable instanceof ExternalVariable
7564 ? baseVariable.module.id
7565 : baseVariable.context.fileName;
7566 this.context.warn({
7567 code: 'MISSING_EXPORT',
7568 exporter: index.relativeId(fileName),
7569 importer: index.relativeId(this.context.fileName),
7570 message: `'${exportName}' is not exported by '${index.relativeId(fileName)}'`,
7571 missing: exportName,
7572 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
7573 }, path[0].pos);
7574 return 'undefined';
7575 }
7576 return this.resolveNamespaceVariables(variable, path.slice(1));
7577 }
7578}
7579
7580const readFile = (file) => new Promise((fulfil, reject) => fs.readFile(file, 'utf-8', (err, contents) => (err ? reject(err) : fulfil(contents))));
7581function mkdirpath(path$1) {
7582 const dir = path.dirname(path$1);
7583 try {
7584 fs.readdirSync(dir);
7585 }
7586 catch (err) {
7587 mkdirpath(dir);
7588 try {
7589 fs.mkdirSync(dir);
7590 }
7591 catch (err2) {
7592 if (err2.code !== 'EEXIST') {
7593 throw err2;
7594 }
7595 }
7596 }
7597}
7598function writeFile(dest, data) {
7599 return new Promise((fulfil, reject) => {
7600 mkdirpath(dest);
7601 fs.writeFile(dest, data, err => {
7602 if (err) {
7603 reject(err);
7604 }
7605 else {
7606 fulfil();
7607 }
7608 });
7609 });
7610}
7611
7612function getRollupDefaultPlugin(preserveSymlinks) {
7613 return {
7614 name: 'Rollup Core',
7615 resolveId: createResolveId(preserveSymlinks),
7616 load(id) {
7617 return readFile(id);
7618 },
7619 resolveFileUrl({ relativePath, format }) {
7620 return relativeUrlMechanisms[format](relativePath);
7621 },
7622 resolveImportMeta(prop, { chunkId, format }) {
7623 const mechanism = importMetaMechanisms[format] && importMetaMechanisms[format](prop, chunkId);
7624 if (mechanism) {
7625 return mechanism;
7626 }
7627 }
7628 };
7629}
7630function findFile(file, preserveSymlinks) {
7631 try {
7632 const stats = fs.lstatSync(file);
7633 if (!preserveSymlinks && stats.isSymbolicLink())
7634 return findFile(fs.realpathSync(file), preserveSymlinks);
7635 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
7636 // check case
7637 const name = path.basename(file);
7638 const files = fs.readdirSync(path.dirname(file));
7639 if (files.indexOf(name) !== -1)
7640 return file;
7641 }
7642 }
7643 catch (err) {
7644 // suppress
7645 }
7646}
7647function addJsExtensionIfNecessary(file, preserveSymlinks) {
7648 let found = findFile(file, preserveSymlinks);
7649 if (found)
7650 return found;
7651 found = findFile(file + '.mjs', preserveSymlinks);
7652 if (found)
7653 return found;
7654 found = findFile(file + '.js', preserveSymlinks);
7655 return found;
7656}
7657function createResolveId(preserveSymlinks) {
7658 return function (source, importer) {
7659 if (typeof process === 'undefined') {
7660 error({
7661 code: 'MISSING_PROCESS',
7662 message: `It looks like you're using Rollup in a non-Node.js environment. This means you must supply a plugin with custom resolveId and load functions`,
7663 url: 'https://rollupjs.org/guide/en/#a-simple-example'
7664 });
7665 }
7666 // external modules (non-entry modules that start with neither '.' or '/')
7667 // are skipped at this stage.
7668 if (importer !== undefined && !index.isAbsolute(source) && source[0] !== '.')
7669 return null;
7670 // `resolve` processes paths from right to left, prepending them until an
7671 // absolute path is created. Absolute importees therefore shortcircuit the
7672 // resolve call and require no special handing on our part.
7673 // See https://nodejs.org/api/path.html#path_path_resolve_paths
7674 return addJsExtensionIfNecessary(path.resolve(importer ? path.dirname(importer) : path.resolve(), source), preserveSymlinks);
7675 };
7676}
7677const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
7678const getUrlFromDocument = (chunkId) => `(document.currentScript && document.currentScript.src || new URL('${chunkId}', document.baseURI).href)`;
7679const getGenericImportMetaMechanism = (getUrl) => (prop, chunkId) => {
7680 const urlMechanism = getUrl(chunkId);
7681 return prop === null ? `({ url: ${urlMechanism} })` : prop === 'url' ? urlMechanism : 'undefined';
7682};
7683const importMetaMechanisms = {
7684 amd: getGenericImportMetaMechanism(() => getResolveUrl(`module.uri, document.baseURI`)),
7685 cjs: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`),
7686 iife: getGenericImportMetaMechanism(chunkId => getUrlFromDocument(chunkId)),
7687 system: prop => (prop === null ? `module.meta` : `module.meta.${prop}`),
7688 umd: getGenericImportMetaMechanism(chunkId => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __filename`, `(require('u' + 'rl').URL)`)} : ${getUrlFromDocument(chunkId)})`)
7689};
7690const getRelativeUrlFromDocument = (relativePath) => getResolveUrl(`'${relativePath}', document.currentScript && document.currentScript.src || document.baseURI`);
7691const relativeUrlMechanisms = {
7692 amd: relativePath => {
7693 if (relativePath[0] !== '.')
7694 relativePath = './' + relativePath;
7695 return getResolveUrl(`require.toUrl('${relativePath}'), document.baseURI`);
7696 },
7697 cjs: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`,
7698 es: relativePath => getResolveUrl(`'${relativePath}', import.meta.url`),
7699 iife: relativePath => getRelativeUrlFromDocument(relativePath),
7700 system: relativePath => getResolveUrl(`'${relativePath}', module.meta.url`),
7701 umd: relativePath => `(typeof document === 'undefined' ? ${getResolveUrl(`'file:' + __dirname + '/${relativePath}'`, `(require('u' + 'rl').URL)`)} : ${getRelativeUrlFromDocument(relativePath)})`
7702};
7703const accessedMetaUrlGlobals = {
7704 amd: ['document', 'module', 'URL'],
7705 cjs: ['document', 'require', 'URL'],
7706 iife: ['document', 'URL'],
7707 system: ['module'],
7708 umd: ['document', 'require', 'URL']
7709};
7710const accessedFileUrlGlobals = {
7711 amd: ['document', 'require', 'URL'],
7712 cjs: ['document', 'require', 'URL'],
7713 iife: ['document', 'URL'],
7714 system: ['module', 'URL'],
7715 umd: ['document', 'require', 'URL']
7716};
7717
7718const ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
7719const CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
7720const FILE_PREFIX = 'ROLLUP_FILE_URL_';
7721class MetaProperty extends NodeBase {
7722 hasEffects() {
7723 return false;
7724 }
7725 hasEffectsWhenAccessedAtPath(path) {
7726 return path.length > 1;
7727 }
7728 include() {
7729 if (!this.included) {
7730 this.included = true;
7731 const parent = this.parent;
7732 const metaProperty = (this.metaProperty =
7733 parent instanceof MemberExpression && typeof parent.propertyKey === 'string'
7734 ? parent.propertyKey
7735 : null);
7736 if (metaProperty) {
7737 if (metaProperty.startsWith(FILE_PREFIX) ||
7738 metaProperty.startsWith(ASSET_PREFIX) ||
7739 metaProperty.startsWith(CHUNK_PREFIX)) {
7740 this.scope.addAccessedGlobalsByFormat(accessedFileUrlGlobals);
7741 }
7742 else {
7743 this.scope.addAccessedGlobalsByFormat(accessedMetaUrlGlobals);
7744 }
7745 }
7746 }
7747 }
7748 initialise() {
7749 if (this.meta.name === 'import') {
7750 this.context.addImportMeta(this);
7751 }
7752 }
7753 renderFinalMechanism(code, chunkId, format, pluginDriver) {
7754 if (!this.included)
7755 return;
7756 const parent = this.parent;
7757 const metaProperty = this.metaProperty;
7758 if (metaProperty &&
7759 (metaProperty.startsWith(FILE_PREFIX) ||
7760 metaProperty.startsWith(ASSET_PREFIX) ||
7761 metaProperty.startsWith(CHUNK_PREFIX))) {
7762 let referenceId = null;
7763 let assetReferenceId = null;
7764 let chunkReferenceId = null;
7765 let fileName;
7766 if (metaProperty.startsWith(FILE_PREFIX)) {
7767 referenceId = metaProperty.substr(FILE_PREFIX.length);
7768 fileName = this.context.getFileName(referenceId);
7769 }
7770 else if (metaProperty.startsWith(ASSET_PREFIX)) {
7771 this.context.warnDeprecation(`Using the "${ASSET_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
7772 assetReferenceId = metaProperty.substr(ASSET_PREFIX.length);
7773 fileName = this.context.getFileName(assetReferenceId);
7774 }
7775 else {
7776 this.context.warnDeprecation(`Using the "${CHUNK_PREFIX}" prefix to reference files is deprecated. Use the "${FILE_PREFIX}" prefix instead.`, false);
7777 chunkReferenceId = metaProperty.substr(CHUNK_PREFIX.length);
7778 fileName = this.context.getFileName(chunkReferenceId);
7779 }
7780 const relativePath = index.normalize(path.relative(path.dirname(chunkId), fileName));
7781 let replacement;
7782 if (assetReferenceId !== null) {
7783 replacement = pluginDriver.hookFirstSync('resolveAssetUrl', [
7784 {
7785 assetFileName: fileName,
7786 chunkId,
7787 format,
7788 moduleId: this.context.module.id,
7789 relativeAssetPath: relativePath
7790 }
7791 ]);
7792 }
7793 if (!replacement) {
7794 replacement = pluginDriver.hookFirstSync('resolveFileUrl', [
7795 {
7796 assetReferenceId,
7797 chunkId,
7798 chunkReferenceId,
7799 fileName,
7800 format,
7801 moduleId: this.context.module.id,
7802 referenceId: referenceId || assetReferenceId || chunkReferenceId,
7803 relativePath
7804 }
7805 ]);
7806 }
7807 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
7808 return;
7809 }
7810 const replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
7811 metaProperty,
7812 {
7813 chunkId,
7814 format,
7815 moduleId: this.context.module.id
7816 }
7817 ]);
7818 if (typeof replacement === 'string') {
7819 if (parent instanceof MemberExpression) {
7820 code.overwrite(parent.start, parent.end, replacement, { contentOnly: true });
7821 }
7822 else {
7823 code.overwrite(this.start, this.end, replacement, { contentOnly: true });
7824 }
7825 }
7826 }
7827}
7828
7829class MethodDefinition extends NodeBase {
7830 hasEffects(context) {
7831 return this.key.hasEffects(context);
7832 }
7833 hasEffectsWhenCalledAtPath(path, callOptions, context) {
7834 return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, context));
7835 }
7836}
7837
7838class NewExpression extends NodeBase {
7839 bind() {
7840 super.bind();
7841 for (const argument of this.arguments) {
7842 // This will make sure all properties of parameters behave as "unknown"
7843 argument.deoptimizePath(UNKNOWN_PATH);
7844 }
7845 }
7846 hasEffects(context) {
7847 for (const argument of this.arguments) {
7848 if (argument.hasEffects(context))
7849 return true;
7850 }
7851 if (this.context.annotations && this.annotatedPure)
7852 return false;
7853 return (this.callee.hasEffects(context) ||
7854 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
7855 }
7856 hasEffectsWhenAccessedAtPath(path) {
7857 return path.length > 1;
7858 }
7859 initialise() {
7860 this.callOptions = {
7861 args: this.arguments,
7862 withNew: true
7863 };
7864 }
7865}
7866
7867class SpreadElement extends NodeBase {
7868 bind() {
7869 super.bind();
7870 // Only properties of properties of the argument could become subject to reassignment
7871 // This will also reassign the return values of iterators
7872 this.argument.deoptimizePath([UnknownKey, UnknownKey]);
7873 }
7874}
7875
7876class ObjectExpression extends NodeBase {
7877 constructor() {
7878 super(...arguments);
7879 this.deoptimizedPaths = new Set();
7880 // We collect deoptimization information if we can resolve a computed property access
7881 this.expressionsToBeDeoptimized = new Map();
7882 this.hasUnknownDeoptimizedProperty = false;
7883 this.propertyMap = null;
7884 this.unmatchablePropertiesRead = [];
7885 this.unmatchablePropertiesWrite = [];
7886 }
7887 bind() {
7888 super.bind();
7889 if (this.propertyMap === null)
7890 this.buildPropertyMap();
7891 }
7892 // We could also track this per-property but this would quickly become much more complex
7893 deoptimizeCache() {
7894 if (!this.hasUnknownDeoptimizedProperty)
7895 this.deoptimizeAllProperties();
7896 }
7897 deoptimizePath(path) {
7898 if (this.hasUnknownDeoptimizedProperty)
7899 return;
7900 if (this.propertyMap === null)
7901 this.buildPropertyMap();
7902 if (path.length === 0) {
7903 this.deoptimizeAllProperties();
7904 return;
7905 }
7906 const key = path[0];
7907 if (path.length === 1) {
7908 if (typeof key !== 'string') {
7909 this.deoptimizeAllProperties();
7910 return;
7911 }
7912 if (!this.deoptimizedPaths.has(key)) {
7913 this.deoptimizedPaths.add(key);
7914 // we only deoptimizeCache exact matches as in all other cases,
7915 // we do not return a literal value or return expression
7916 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
7917 if (expressionsToBeDeoptimized) {
7918 for (const expression of expressionsToBeDeoptimized) {
7919 expression.deoptimizeCache();
7920 }
7921 }
7922 }
7923 }
7924 const subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
7925 for (const property of typeof key === 'string'
7926 ? this.propertyMap[key]
7927 ? this.propertyMap[key].propertiesRead
7928 : []
7929 : this.properties) {
7930 property.deoptimizePath(subPath);
7931 }
7932 }
7933 getLiteralValueAtPath(path, recursionTracker, origin) {
7934 if (this.propertyMap === null)
7935 this.buildPropertyMap();
7936 const key = path[0];
7937 if (path.length === 0 ||
7938 this.hasUnknownDeoptimizedProperty ||
7939 typeof key !== 'string' ||
7940 this.deoptimizedPaths.has(key))
7941 return UnknownValue;
7942 if (path.length === 1 &&
7943 !this.propertyMap[key] &&
7944 !objectMembers[key] &&
7945 this.unmatchablePropertiesRead.length === 0) {
7946 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
7947 if (expressionsToBeDeoptimized) {
7948 expressionsToBeDeoptimized.push(origin);
7949 }
7950 else {
7951 this.expressionsToBeDeoptimized.set(key, [origin]);
7952 }
7953 return undefined;
7954 }
7955 if (!this.propertyMap[key] ||
7956 this.propertyMap[key].exactMatchRead === null ||
7957 this.propertyMap[key].propertiesRead.length > 1) {
7958 return UnknownValue;
7959 }
7960 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
7961 if (expressionsToBeDeoptimized) {
7962 expressionsToBeDeoptimized.push(origin);
7963 }
7964 else {
7965 this.expressionsToBeDeoptimized.set(key, [origin]);
7966 }
7967 return this.propertyMap[key]
7968 .exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
7969 }
7970 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
7971 if (this.propertyMap === null)
7972 this.buildPropertyMap();
7973 const key = path[0];
7974 if (path.length === 0 ||
7975 this.hasUnknownDeoptimizedProperty ||
7976 typeof key !== 'string' ||
7977 this.deoptimizedPaths.has(key))
7978 return UNKNOWN_EXPRESSION;
7979 if (path.length === 1 &&
7980 objectMembers[key] &&
7981 this.unmatchablePropertiesRead.length === 0 &&
7982 (!this.propertyMap[key] ||
7983 this.propertyMap[key].exactMatchRead === null))
7984 return getMemberReturnExpressionWhenCalled(objectMembers, key);
7985 if (!this.propertyMap[key] ||
7986 this.propertyMap[key].exactMatchRead === null ||
7987 this.propertyMap[key].propertiesRead.length > 1)
7988 return UNKNOWN_EXPRESSION;
7989 const expressionsToBeDeoptimized = this.expressionsToBeDeoptimized.get(key);
7990 if (expressionsToBeDeoptimized) {
7991 expressionsToBeDeoptimized.push(origin);
7992 }
7993 else {
7994 this.expressionsToBeDeoptimized.set(key, [origin]);
7995 }
7996 return this.propertyMap[key]
7997 .exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
7998 }
7999 hasEffectsWhenAccessedAtPath(path, context) {
8000 if (path.length === 0)
8001 return false;
8002 const key = path[0];
8003 if (path.length > 1 &&
8004 (this.hasUnknownDeoptimizedProperty ||
8005 typeof key !== 'string' ||
8006 this.deoptimizedPaths.has(key) ||
8007 !this.propertyMap[key] ||
8008 this.propertyMap[key].exactMatchRead === null))
8009 return true;
8010 const subPath = path.slice(1);
8011 for (const property of typeof key !== 'string'
8012 ? this.properties
8013 : this.propertyMap[key]
8014 ? this.propertyMap[key].propertiesRead
8015 : []) {
8016 if (property.hasEffectsWhenAccessedAtPath(subPath, context))
8017 return true;
8018 }
8019 return false;
8020 }
8021 hasEffectsWhenAssignedAtPath(path, context) {
8022 if (path.length === 0)
8023 return false;
8024 const key = path[0];
8025 if (path.length > 1 &&
8026 (this.hasUnknownDeoptimizedProperty ||
8027 typeof key !== 'string' ||
8028 this.deoptimizedPaths.has(key) ||
8029 !this.propertyMap[key] ||
8030 this.propertyMap[key].exactMatchRead === null))
8031 return true;
8032 const subPath = path.slice(1);
8033 for (const property of typeof key !== 'string'
8034 ? this.properties
8035 : path.length > 1
8036 ? this.propertyMap[key].propertiesRead
8037 : this.propertyMap[key]
8038 ? this.propertyMap[key].propertiesSet
8039 : []) {
8040 if (property.hasEffectsWhenAssignedAtPath(subPath, context))
8041 return true;
8042 }
8043 return false;
8044 }
8045 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8046 const key = path[0];
8047 if (path.length === 0 ||
8048 this.hasUnknownDeoptimizedProperty ||
8049 typeof key !== 'string' ||
8050 this.deoptimizedPaths.has(key) ||
8051 (this.propertyMap[key]
8052 ? !this.propertyMap[key].exactMatchRead
8053 : path.length > 1 || !objectMembers[key]))
8054 return true;
8055 const subPath = path.slice(1);
8056 for (const property of this.propertyMap[key]
8057 ? this.propertyMap[key].propertiesRead
8058 : []) {
8059 if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, context))
8060 return true;
8061 }
8062 if (path.length === 1 && objectMembers[key])
8063 return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, context);
8064 return false;
8065 }
8066 render(code, options, { renderedParentType } = BLANK) {
8067 super.render(code, options);
8068 if (renderedParentType === ExpressionStatement) {
8069 code.appendRight(this.start, '(');
8070 code.prependLeft(this.end, ')');
8071 }
8072 }
8073 buildPropertyMap() {
8074 this.propertyMap = Object.create(null);
8075 for (let index = this.properties.length - 1; index >= 0; index--) {
8076 const property = this.properties[index];
8077 if (property instanceof SpreadElement) {
8078 this.unmatchablePropertiesRead.push(property);
8079 continue;
8080 }
8081 const isWrite = property.kind !== 'get';
8082 const isRead = property.kind !== 'set';
8083 let key;
8084 if (property.computed) {
8085 const keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
8086 if (keyValue === UnknownValue) {
8087 if (isRead) {
8088 this.unmatchablePropertiesRead.push(property);
8089 }
8090 else {
8091 this.unmatchablePropertiesWrite.push(property);
8092 }
8093 continue;
8094 }
8095 key = String(keyValue);
8096 }
8097 else if (property.key instanceof Identifier$1) {
8098 key = property.key.name;
8099 }
8100 else {
8101 key = String(property.key.value);
8102 }
8103 const propertyMapProperty = this.propertyMap[key];
8104 if (!propertyMapProperty) {
8105 this.propertyMap[key] = {
8106 exactMatchRead: isRead ? property : null,
8107 exactMatchWrite: isWrite ? property : null,
8108 propertiesRead: isRead ? [property, ...this.unmatchablePropertiesRead] : [],
8109 propertiesSet: isWrite && !isRead ? [property, ...this.unmatchablePropertiesWrite] : []
8110 };
8111 continue;
8112 }
8113 if (isRead && propertyMapProperty.exactMatchRead === null) {
8114 propertyMapProperty.exactMatchRead = property;
8115 propertyMapProperty.propertiesRead.push(property, ...this.unmatchablePropertiesRead);
8116 }
8117 if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
8118 propertyMapProperty.exactMatchWrite = property;
8119 propertyMapProperty.propertiesSet.push(property, ...this.unmatchablePropertiesWrite);
8120 }
8121 }
8122 }
8123 deoptimizeAllProperties() {
8124 this.hasUnknownDeoptimizedProperty = true;
8125 for (const property of this.properties) {
8126 property.deoptimizePath(UNKNOWN_PATH);
8127 }
8128 for (const expressionsToBeDeoptimized of this.expressionsToBeDeoptimized.values()) {
8129 for (const expression of expressionsToBeDeoptimized) {
8130 expression.deoptimizeCache();
8131 }
8132 }
8133 }
8134}
8135
8136class ObjectPattern extends NodeBase {
8137 addExportedVariables(variables) {
8138 for (const property of this.properties) {
8139 if (property.type === Property) {
8140 property.value.addExportedVariables(variables);
8141 }
8142 else {
8143 property.argument.addExportedVariables(variables);
8144 }
8145 }
8146 }
8147 declare(kind, init) {
8148 const variables = [];
8149 for (const property of this.properties) {
8150 variables.push(...property.declare(kind, init));
8151 }
8152 return variables;
8153 }
8154 deoptimizePath(path) {
8155 if (path.length === 0) {
8156 for (const property of this.properties) {
8157 property.deoptimizePath(path);
8158 }
8159 }
8160 }
8161 hasEffectsWhenAssignedAtPath(path, context) {
8162 if (path.length > 0)
8163 return true;
8164 for (const property of this.properties) {
8165 if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context))
8166 return true;
8167 }
8168 return false;
8169 }
8170}
8171
8172class Program$1 extends NodeBase {
8173 hasEffects(context) {
8174 for (const node of this.body) {
8175 if (node.hasEffects(context))
8176 return true;
8177 }
8178 return false;
8179 }
8180 include(context, includeChildrenRecursively) {
8181 this.included = true;
8182 for (const node of this.body) {
8183 if (includeChildrenRecursively || node.shouldBeIncluded(context)) {
8184 node.include(context, includeChildrenRecursively);
8185 }
8186 }
8187 }
8188 render(code, options) {
8189 if (this.body.length) {
8190 renderStatementList(this.body, code, this.start, this.end, options);
8191 }
8192 else {
8193 super.render(code, options);
8194 }
8195 }
8196}
8197
8198class Property$1 extends NodeBase {
8199 constructor() {
8200 super(...arguments);
8201 this.declarationInit = null;
8202 this.returnExpression = null;
8203 }
8204 bind() {
8205 super.bind();
8206 if (this.kind === 'get' && this.returnExpression === null)
8207 this.updateReturnExpression();
8208 if (this.declarationInit !== null) {
8209 this.declarationInit.deoptimizePath([UnknownKey, UnknownKey]);
8210 }
8211 }
8212 declare(kind, init) {
8213 this.declarationInit = init;
8214 return this.value.declare(kind, UNKNOWN_EXPRESSION);
8215 }
8216 deoptimizeCache() {
8217 // As getter properties directly receive their values from function expressions that always
8218 // have a fixed return value, there is no known situation where a getter is deoptimized.
8219 throw new Error('Unexpected deoptimization');
8220 }
8221 deoptimizePath(path) {
8222 if (this.kind === 'get') {
8223 if (path.length > 0) {
8224 if (this.returnExpression === null)
8225 this.updateReturnExpression();
8226 this.returnExpression.deoptimizePath(path);
8227 }
8228 }
8229 else if (this.kind !== 'set') {
8230 this.value.deoptimizePath(path);
8231 }
8232 }
8233 getLiteralValueAtPath(path, recursionTracker, origin) {
8234 if (this.kind === 'get') {
8235 if (this.returnExpression === null)
8236 this.updateReturnExpression();
8237 return this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
8238 }
8239 return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
8240 }
8241 getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin) {
8242 if (this.kind === 'get') {
8243 if (this.returnExpression === null)
8244 this.updateReturnExpression();
8245 return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8246 }
8247 return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
8248 }
8249 hasEffects(context) {
8250 return this.key.hasEffects(context) || this.value.hasEffects(context);
8251 }
8252 hasEffectsWhenAccessedAtPath(path, context) {
8253 if (this.kind === 'get') {
8254 const trackedExpressions = context.accessed.getEntities(path);
8255 if (trackedExpressions.has(this))
8256 return false;
8257 trackedExpressions.add(this);
8258 return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context) ||
8259 (path.length > 0 &&
8260 this.returnExpression.hasEffectsWhenAccessedAtPath(path, context)));
8261 }
8262 return this.value.hasEffectsWhenAccessedAtPath(path, context);
8263 }
8264 hasEffectsWhenAssignedAtPath(path, context) {
8265 if (this.kind === 'get') {
8266 const trackedExpressions = context.assigned.getEntities(path);
8267 if (trackedExpressions.has(this))
8268 return false;
8269 trackedExpressions.add(this);
8270 return this.returnExpression.hasEffectsWhenAssignedAtPath(path, context);
8271 }
8272 if (this.kind === 'set') {
8273 const trackedExpressions = context.assigned.getEntities(path);
8274 if (trackedExpressions.has(this))
8275 return false;
8276 trackedExpressions.add(this);
8277 return this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, context);
8278 }
8279 return this.value.hasEffectsWhenAssignedAtPath(path, context);
8280 }
8281 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8282 if (this.kind === 'get') {
8283 const trackedExpressions = (callOptions.withNew
8284 ? context.instantiated
8285 : context.called).getEntities(path);
8286 if (trackedExpressions.has(this))
8287 return false;
8288 trackedExpressions.add(this);
8289 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, context);
8290 }
8291 return this.value.hasEffectsWhenCalledAtPath(path, callOptions, context);
8292 }
8293 initialise() {
8294 this.accessorCallOptions = {
8295 args: NO_ARGS,
8296 withNew: false
8297 };
8298 }
8299 render(code, options) {
8300 if (!this.shorthand) {
8301 this.key.render(code, options);
8302 }
8303 this.value.render(code, options, { isShorthandProperty: this.shorthand });
8304 }
8305 updateReturnExpression() {
8306 this.returnExpression = UNKNOWN_EXPRESSION;
8307 this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
8308 }
8309}
8310
8311class ReturnStatement$1 extends NodeBase {
8312 hasEffects(context) {
8313 if (!context.ignore.returnAwaitYield ||
8314 (this.argument !== null && this.argument.hasEffects(context)))
8315 return true;
8316 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8317 return false;
8318 }
8319 include(context, includeChildrenRecursively) {
8320 this.included = true;
8321 if (this.argument) {
8322 this.argument.include(context, includeChildrenRecursively);
8323 }
8324 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8325 }
8326 initialise() {
8327 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
8328 }
8329 render(code, options) {
8330 if (this.argument) {
8331 this.argument.render(code, options, { preventASI: true });
8332 if (this.argument.start === this.start + 6 /* 'return'.length */) {
8333 code.prependLeft(this.start + 6, ' ');
8334 }
8335 }
8336 }
8337}
8338
8339class SequenceExpression extends NodeBase {
8340 deoptimizePath(path) {
8341 if (path.length > 0)
8342 this.expressions[this.expressions.length - 1].deoptimizePath(path);
8343 }
8344 getLiteralValueAtPath(path, recursionTracker, origin) {
8345 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
8346 }
8347 hasEffects(context) {
8348 for (const expression of this.expressions) {
8349 if (expression.hasEffects(context))
8350 return true;
8351 }
8352 return false;
8353 }
8354 hasEffectsWhenAccessedAtPath(path, context) {
8355 return (path.length > 0 &&
8356 this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, context));
8357 }
8358 hasEffectsWhenAssignedAtPath(path, context) {
8359 return (path.length === 0 ||
8360 this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, context));
8361 }
8362 hasEffectsWhenCalledAtPath(path, callOptions, context) {
8363 return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, context);
8364 }
8365 include(context, includeChildrenRecursively) {
8366 this.included = true;
8367 for (let i = 0; i < this.expressions.length - 1; i++) {
8368 const node = this.expressions[i];
8369 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8370 node.include(context, includeChildrenRecursively);
8371 }
8372 this.expressions[this.expressions.length - 1].include(context, includeChildrenRecursively);
8373 }
8374 render(code, options, { renderedParentType, isCalleeOfRenderedParent, preventASI } = BLANK) {
8375 let includedNodes = 0;
8376 for (const { node, start, end } of getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end)) {
8377 if (!node.included) {
8378 treeshakeNode(node, code, start, end);
8379 continue;
8380 }
8381 includedNodes++;
8382 if (includedNodes === 1 && preventASI) {
8383 removeLineBreaks(code, start, node.start);
8384 }
8385 if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
8386 node.render(code, options, {
8387 isCalleeOfRenderedParent: renderedParentType
8388 ? isCalleeOfRenderedParent
8389 : this.parent.callee === this,
8390 renderedParentType: renderedParentType || this.parent.type
8391 });
8392 }
8393 else {
8394 node.render(code, options);
8395 }
8396 }
8397 }
8398}
8399
8400class SwitchCase extends NodeBase {
8401 hasEffects(context) {
8402 if (this.test && this.test.hasEffects(context))
8403 return true;
8404 for (const node of this.consequent) {
8405 if (context.brokenFlow)
8406 break;
8407 if (node.hasEffects(context))
8408 return true;
8409 }
8410 return false;
8411 }
8412 include(context, includeChildrenRecursively) {
8413 this.included = true;
8414 if (this.test)
8415 this.test.include(context, includeChildrenRecursively);
8416 for (const node of this.consequent) {
8417 if (includeChildrenRecursively || node.shouldBeIncluded(context))
8418 node.include(context, includeChildrenRecursively);
8419 }
8420 }
8421 render(code, options, nodeRenderOptions) {
8422 if (this.consequent.length) {
8423 this.test && this.test.render(code, options);
8424 const testEnd = this.test
8425 ? this.test.end
8426 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
8427 const consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
8428 renderStatementList(this.consequent, code, consequentStart, nodeRenderOptions.end, options);
8429 }
8430 else {
8431 super.render(code, options);
8432 }
8433 }
8434}
8435SwitchCase.prototype.needsBoundaries = true;
8436
8437class SwitchStatement extends NodeBase {
8438 createScope(parentScope) {
8439 this.scope = new BlockScope(parentScope);
8440 }
8441 hasEffects(context) {
8442 if (this.discriminant.hasEffects(context))
8443 return true;
8444 const { brokenFlow, ignore: { breaks } } = context;
8445 let minBrokenFlow = Infinity;
8446 context.ignore.breaks = true;
8447 for (const switchCase of this.cases) {
8448 if (switchCase.hasEffects(context))
8449 return true;
8450 minBrokenFlow = context.brokenFlow < minBrokenFlow ? context.brokenFlow : minBrokenFlow;
8451 context.brokenFlow = brokenFlow;
8452 }
8453 if (this.defaultCase !== null && !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8454 context.brokenFlow = minBrokenFlow;
8455 }
8456 context.ignore.breaks = breaks;
8457 return false;
8458 }
8459 include(context, includeChildrenRecursively) {
8460 this.included = true;
8461 this.discriminant.include(context, includeChildrenRecursively);
8462 const { brokenFlow } = context;
8463 let minBrokenFlow = Infinity;
8464 let isCaseIncluded = includeChildrenRecursively ||
8465 (this.defaultCase !== null && this.defaultCase < this.cases.length - 1);
8466 for (let caseIndex = this.cases.length - 1; caseIndex >= 0; caseIndex--) {
8467 const switchCase = this.cases[caseIndex];
8468 if (switchCase.included) {
8469 isCaseIncluded = true;
8470 }
8471 if (!isCaseIncluded) {
8472 const hasEffectsContext = createHasEffectsContext();
8473 hasEffectsContext.ignore.breaks = true;
8474 isCaseIncluded = switchCase.hasEffects(hasEffectsContext);
8475 }
8476 if (isCaseIncluded) {
8477 switchCase.include(context, includeChildrenRecursively);
8478 minBrokenFlow = minBrokenFlow < context.brokenFlow ? minBrokenFlow : context.brokenFlow;
8479 context.brokenFlow = brokenFlow;
8480 }
8481 }
8482 if (isCaseIncluded &&
8483 this.defaultCase !== null &&
8484 !(minBrokenFlow === BROKEN_FLOW_BREAK_CONTINUE)) {
8485 context.brokenFlow = minBrokenFlow;
8486 }
8487 }
8488 initialise() {
8489 for (let caseIndex = 0; caseIndex < this.cases.length; caseIndex++) {
8490 if (this.cases[caseIndex].test === null) {
8491 this.defaultCase = caseIndex;
8492 return;
8493 }
8494 }
8495 this.defaultCase = null;
8496 }
8497 render(code, options) {
8498 this.discriminant.render(code, options);
8499 if (this.cases.length > 0) {
8500 renderStatementList(this.cases, code, this.cases[0].start, this.end - 1, options);
8501 }
8502 }
8503}
8504
8505class TaggedTemplateExpression extends NodeBase {
8506 bind() {
8507 super.bind();
8508 if (this.tag.type === Identifier) {
8509 const variable = this.scope.findVariable(this.tag.name);
8510 if (variable.isNamespace) {
8511 this.context.error({
8512 code: 'CANNOT_CALL_NAMESPACE',
8513 message: `Cannot call a namespace ('${this.tag.name}')`
8514 }, this.start);
8515 }
8516 if (this.tag.name === 'eval') {
8517 this.context.warn({
8518 code: 'EVAL',
8519 message: `Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification`,
8520 url: 'https://rollupjs.org/guide/en/#avoiding-eval'
8521 }, this.start);
8522 }
8523 }
8524 }
8525 hasEffects(context) {
8526 return (super.hasEffects(context) ||
8527 this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, context));
8528 }
8529 initialise() {
8530 this.callOptions = {
8531 args: NO_ARGS,
8532 withNew: false
8533 };
8534 }
8535}
8536
8537class TemplateElement extends NodeBase {
8538 hasEffects() {
8539 return false;
8540 }
8541}
8542
8543class TemplateLiteral extends NodeBase {
8544 getLiteralValueAtPath(path) {
8545 if (path.length > 0 || this.quasis.length !== 1) {
8546 return UnknownValue;
8547 }
8548 return this.quasis[0].value.cooked;
8549 }
8550 render(code, options) {
8551 code.indentExclusionRanges.push([this.start, this.end]);
8552 super.render(code, options);
8553 }
8554}
8555
8556class ModuleScope extends ChildScope {
8557 constructor(parent, context) {
8558 super(parent);
8559 this.context = context;
8560 this.variables.set('this', new LocalVariable('this', null, UNDEFINED_EXPRESSION, context));
8561 }
8562 addExportDefaultDeclaration(name, exportDefaultDeclaration, context) {
8563 const variable = new ExportDefaultVariable(name, exportDefaultDeclaration, context);
8564 this.variables.set('default', variable);
8565 return variable;
8566 }
8567 addNamespaceMemberAccess(_name, variable) {
8568 if (variable instanceof GlobalVariable) {
8569 this.accessedOutsideVariables.set(variable.name, variable);
8570 }
8571 }
8572 deconflict(format) {
8573 // all module level variables are already deconflicted when deconflicting the chunk
8574 for (const scope of this.children)
8575 scope.deconflict(format);
8576 }
8577 findLexicalBoundary() {
8578 return this;
8579 }
8580 findVariable(name) {
8581 const knownVariable = this.variables.get(name) || this.accessedOutsideVariables.get(name);
8582 if (knownVariable) {
8583 return knownVariable;
8584 }
8585 const variable = this.context.traceVariable(name) || this.parent.findVariable(name);
8586 if (variable instanceof GlobalVariable) {
8587 this.accessedOutsideVariables.set(name, variable);
8588 }
8589 return variable;
8590 }
8591}
8592
8593class ThisExpression extends NodeBase {
8594 bind() {
8595 super.bind();
8596 this.variable = this.scope.findVariable('this');
8597 }
8598 hasEffectsWhenAccessedAtPath(path, context) {
8599 return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, context);
8600 }
8601 hasEffectsWhenAssignedAtPath(path, context) {
8602 return this.variable.hasEffectsWhenAssignedAtPath(path, context);
8603 }
8604 initialise() {
8605 this.alias =
8606 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
8607 if (this.alias === 'undefined') {
8608 this.context.warn({
8609 code: 'THIS_IS_UNDEFINED',
8610 message: `The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten`,
8611 url: `https://rollupjs.org/guide/en/#error-this-is-undefined`
8612 }, this.start);
8613 }
8614 }
8615 render(code) {
8616 if (this.alias !== null) {
8617 code.overwrite(this.start, this.end, this.alias, {
8618 contentOnly: false,
8619 storeName: true
8620 });
8621 }
8622 }
8623}
8624
8625class ThrowStatement extends NodeBase {
8626 hasEffects() {
8627 return true;
8628 }
8629 include(context, includeChildrenRecursively) {
8630 this.included = true;
8631 this.argument.include(context, includeChildrenRecursively);
8632 context.brokenFlow = BROKEN_FLOW_ERROR_RETURN_LABEL;
8633 }
8634 render(code, options) {
8635 this.argument.render(code, options, { preventASI: true });
8636 if (this.argument.start === this.start + 5 /* 'throw'.length */) {
8637 code.prependLeft(this.start + 5, ' ');
8638 }
8639 }
8640}
8641
8642class TryStatement extends NodeBase {
8643 constructor() {
8644 super(...arguments);
8645 this.directlyIncluded = false;
8646 }
8647 hasEffects(context) {
8648 return ((this.context.tryCatchDeoptimization
8649 ? this.block.body.length > 0
8650 : this.block.hasEffects(context)) ||
8651 (this.finalizer !== null && this.finalizer.hasEffects(context)));
8652 }
8653 include(context, includeChildrenRecursively) {
8654 const { brokenFlow } = context;
8655 if (!this.directlyIncluded || !this.context.tryCatchDeoptimization) {
8656 this.included = true;
8657 this.directlyIncluded = true;
8658 this.block.include(context, this.context.tryCatchDeoptimization ? INCLUDE_PARAMETERS : includeChildrenRecursively);
8659 context.brokenFlow = brokenFlow;
8660 }
8661 if (this.handler !== null) {
8662 this.handler.include(context, includeChildrenRecursively);
8663 context.brokenFlow = brokenFlow;
8664 }
8665 if (this.finalizer !== null) {
8666 this.finalizer.include(context, includeChildrenRecursively);
8667 }
8668 }
8669}
8670
8671const unaryOperators = {
8672 '!': value => !value,
8673 '+': value => +value,
8674 '-': value => -value,
8675 delete: () => UnknownValue,
8676 typeof: value => typeof value,
8677 void: () => undefined,
8678 '~': value => ~value
8679};
8680class UnaryExpression extends NodeBase {
8681 bind() {
8682 super.bind();
8683 if (this.operator === 'delete') {
8684 this.argument.deoptimizePath(EMPTY_PATH);
8685 }
8686 }
8687 getLiteralValueAtPath(path, recursionTracker, origin) {
8688 if (path.length > 0)
8689 return UnknownValue;
8690 const argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
8691 if (argumentValue === UnknownValue)
8692 return UnknownValue;
8693 return unaryOperators[this.operator](argumentValue);
8694 }
8695 hasEffects(context) {
8696 if (this.operator === 'typeof' && this.argument instanceof Identifier$1)
8697 return false;
8698 return (this.argument.hasEffects(context) ||
8699 (this.operator === 'delete' &&
8700 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context)));
8701 }
8702 hasEffectsWhenAccessedAtPath(path) {
8703 if (this.operator === 'void') {
8704 return path.length > 0;
8705 }
8706 return path.length > 1;
8707 }
8708}
8709
8710class UnknownNode extends NodeBase {
8711 hasEffects() {
8712 return true;
8713 }
8714 include(context) {
8715 super.include(context, true);
8716 }
8717}
8718
8719class UpdateExpression extends NodeBase {
8720 bind() {
8721 super.bind();
8722 this.argument.deoptimizePath(EMPTY_PATH);
8723 if (this.argument instanceof Identifier$1) {
8724 const variable = this.scope.findVariable(this.argument.name);
8725 variable.isReassigned = true;
8726 }
8727 }
8728 hasEffects(context) {
8729 return (this.argument.hasEffects(context) ||
8730 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, context));
8731 }
8732 hasEffectsWhenAccessedAtPath(path) {
8733 return path.length > 1;
8734 }
8735 render(code, options) {
8736 this.argument.render(code, options);
8737 const variable = this.argument.variable;
8738 if (options.format === 'system' && variable && variable.exportName) {
8739 const name = variable.getName();
8740 if (this.prefix) {
8741 code.overwrite(this.start, this.end, `exports('${variable.exportName}', ${this.operator}${name})`);
8742 }
8743 else {
8744 let op;
8745 switch (this.operator) {
8746 case '++':
8747 op = `${name} + 1`;
8748 break;
8749 case '--':
8750 op = `${name} - 1`;
8751 break;
8752 }
8753 code.overwrite(this.start, this.end, `(exports('${variable.exportName}', ${op}), ${name}${this.operator})`);
8754 }
8755 }
8756 }
8757}
8758
8759function isReassignedExportsMember(variable) {
8760 return variable.renderBaseName !== null && variable.exportName !== null && variable.isReassigned;
8761}
8762function areAllDeclarationsIncludedAndNotExported(declarations) {
8763 for (const declarator of declarations) {
8764 if (!declarator.included)
8765 return false;
8766 if (declarator.id.type === Identifier) {
8767 if (declarator.id.variable.exportName)
8768 return false;
8769 }
8770 else {
8771 const exportedVariables = [];
8772 declarator.id.addExportedVariables(exportedVariables);
8773 if (exportedVariables.length > 0)
8774 return false;
8775 }
8776 }
8777 return true;
8778}
8779class VariableDeclaration$1 extends NodeBase {
8780 deoptimizePath() {
8781 for (const declarator of this.declarations) {
8782 declarator.deoptimizePath(EMPTY_PATH);
8783 }
8784 }
8785 hasEffectsWhenAssignedAtPath() {
8786 return false;
8787 }
8788 include(context, includeChildrenRecursively) {
8789 this.included = true;
8790 for (const declarator of this.declarations) {
8791 if (includeChildrenRecursively || declarator.shouldBeIncluded(context))
8792 declarator.include(context, includeChildrenRecursively);
8793 }
8794 }
8795 includeWithAllDeclaredVariables(includeChildrenRecursively, context) {
8796 this.included = true;
8797 for (const declarator of this.declarations) {
8798 declarator.include(context, includeChildrenRecursively);
8799 }
8800 }
8801 initialise() {
8802 for (const declarator of this.declarations) {
8803 declarator.declareDeclarator(this.kind);
8804 }
8805 }
8806 render(code, options, nodeRenderOptions = BLANK) {
8807 if (areAllDeclarationsIncludedAndNotExported(this.declarations)) {
8808 for (const declarator of this.declarations) {
8809 declarator.render(code, options);
8810 }
8811 if (!nodeRenderOptions.isNoStatement &&
8812 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
8813 code.appendLeft(this.end, ';');
8814 }
8815 }
8816 else {
8817 this.renderReplacedDeclarations(code, options, nodeRenderOptions);
8818 }
8819 }
8820 renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports) {
8821 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
8822 code.remove(this.end - 1, this.end);
8823 }
8824 if (addSemicolon) {
8825 separatorString += ';';
8826 }
8827 if (lastSeparatorPos !== null) {
8828 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
8829 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
8830 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
8831 actualContentEnd--;
8832 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
8833 actualContentEnd--;
8834 }
8835 }
8836 if (actualContentEnd === lastSeparatorPos + 1) {
8837 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
8838 }
8839 else {
8840 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
8841 code.remove(actualContentEnd, renderedContentEnd);
8842 }
8843 }
8844 else {
8845 code.appendLeft(renderedContentEnd, separatorString);
8846 }
8847 if (systemPatternExports.length > 0) {
8848 code.appendLeft(renderedContentEnd, ' ' + getSystemExportStatement(systemPatternExports));
8849 }
8850 }
8851 renderReplacedDeclarations(code, options, { start = this.start, end = this.end, isNoStatement }) {
8852 const separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
8853 let actualContentEnd, renderedContentEnd;
8854 if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
8855 renderedContentEnd = this.start + this.kind.length;
8856 }
8857 else {
8858 renderedContentEnd = separatedNodes[0].start;
8859 }
8860 let lastSeparatorPos = renderedContentEnd - 1;
8861 code.remove(this.start, lastSeparatorPos);
8862 let isInDeclaration = false;
8863 let hasRenderedContent = false;
8864 let separatorString = '', leadingString, nextSeparatorString;
8865 const systemPatternExports = [];
8866 for (const { node, start, separator, contentEnd, end } of separatedNodes) {
8867 if (!node.included ||
8868 (node.id instanceof Identifier$1 &&
8869 isReassignedExportsMember(node.id.variable) &&
8870 node.init === null)) {
8871 code.remove(start, end);
8872 continue;
8873 }
8874 leadingString = '';
8875 nextSeparatorString = '';
8876 if (node.id instanceof Identifier$1 &&
8877 isReassignedExportsMember(node.id.variable)) {
8878 if (hasRenderedContent) {
8879 separatorString += ';';
8880 }
8881 isInDeclaration = false;
8882 }
8883 else {
8884 if (options.format === 'system' && node.init !== null) {
8885 if (node.id.type !== Identifier) {
8886 node.id.addExportedVariables(systemPatternExports);
8887 }
8888 else if (node.id.variable.exportName) {
8889 code.prependLeft(code.original.indexOf('=', node.id.end) + 1, ` exports('${node.id.variable.safeExportName ||
8890 node.id.variable.exportName}',`);
8891 nextSeparatorString += ')';
8892 }
8893 }
8894 if (isInDeclaration) {
8895 separatorString += ',';
8896 }
8897 else {
8898 if (hasRenderedContent) {
8899 separatorString += ';';
8900 }
8901 leadingString += `${this.kind} `;
8902 isInDeclaration = true;
8903 }
8904 }
8905 if (renderedContentEnd === lastSeparatorPos + 1) {
8906 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
8907 }
8908 else {
8909 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
8910 code.appendLeft(renderedContentEnd, leadingString);
8911 }
8912 node.render(code, options);
8913 actualContentEnd = contentEnd;
8914 renderedContentEnd = end;
8915 hasRenderedContent = true;
8916 lastSeparatorPos = separator;
8917 separatorString = nextSeparatorString;
8918 }
8919 if (hasRenderedContent) {
8920 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports);
8921 }
8922 else {
8923 code.remove(start, end);
8924 }
8925 }
8926}
8927
8928class VariableDeclarator extends NodeBase {
8929 declareDeclarator(kind) {
8930 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
8931 }
8932 deoptimizePath(path) {
8933 this.id.deoptimizePath(path);
8934 }
8935 render(code, options) {
8936 // This can happen for hoisted variables in dead branches
8937 if (this.init !== null && !this.init.included) {
8938 code.remove(this.id.end, this.end);
8939 this.id.render(code, options);
8940 }
8941 else {
8942 super.render(code, options);
8943 }
8944 }
8945}
8946
8947class WhileStatement extends NodeBase {
8948 hasEffects(context) {
8949 if (this.test.hasEffects(context))
8950 return true;
8951 const { brokenFlow, ignore: { breaks, continues } } = context;
8952 context.ignore.breaks = true;
8953 context.ignore.continues = true;
8954 if (this.body.hasEffects(context))
8955 return true;
8956 context.ignore.breaks = breaks;
8957 context.ignore.continues = continues;
8958 context.brokenFlow = brokenFlow;
8959 return false;
8960 }
8961 include(context, includeChildrenRecursively) {
8962 this.included = true;
8963 this.test.include(context, includeChildrenRecursively);
8964 const { brokenFlow } = context;
8965 this.body.include(context, includeChildrenRecursively);
8966 context.brokenFlow = brokenFlow;
8967 }
8968}
8969
8970class YieldExpression extends NodeBase {
8971 bind() {
8972 super.bind();
8973 if (this.argument !== null) {
8974 this.argument.deoptimizePath(UNKNOWN_PATH);
8975 }
8976 }
8977 hasEffects(context) {
8978 return (!context.ignore.returnAwaitYield ||
8979 (this.argument !== null && this.argument.hasEffects(context)));
8980 }
8981 render(code, options) {
8982 if (this.argument) {
8983 this.argument.render(code, options);
8984 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
8985 code.prependLeft(this.start + 5, ' ');
8986 }
8987 }
8988 }
8989}
8990
8991const nodeConstructors = {
8992 ArrayExpression,
8993 ArrayPattern,
8994 ArrowFunctionExpression,
8995 AssignmentExpression,
8996 AssignmentPattern,
8997 AwaitExpression,
8998 BinaryExpression,
8999 BlockStatement: BlockStatement$1,
9000 BreakStatement,
9001 CallExpression: CallExpression$1,
9002 CatchClause,
9003 ClassBody,
9004 ClassDeclaration,
9005 ClassExpression,
9006 ConditionalExpression,
9007 ContinueStatement,
9008 DoWhileStatement,
9009 EmptyStatement,
9010 ExportAllDeclaration: ExportAllDeclaration$1,
9011 ExportDefaultDeclaration,
9012 ExportNamedDeclaration,
9013 ExpressionStatement: ExpressionStatement$1,
9014 ForInStatement,
9015 ForOfStatement,
9016 ForStatement,
9017 FunctionDeclaration,
9018 FunctionExpression: FunctionExpression$1,
9019 Identifier: Identifier$1,
9020 IfStatement,
9021 ImportDeclaration,
9022 ImportExpression: Import,
9023 LabeledStatement,
9024 Literal,
9025 LogicalExpression,
9026 MemberExpression,
9027 MetaProperty,
9028 MethodDefinition,
9029 NewExpression,
9030 ObjectExpression,
9031 ObjectPattern,
9032 Program: Program$1,
9033 Property: Property$1,
9034 RestElement,
9035 ReturnStatement: ReturnStatement$1,
9036 SequenceExpression,
9037 SpreadElement,
9038 SwitchCase,
9039 SwitchStatement,
9040 TaggedTemplateExpression,
9041 TemplateElement,
9042 TemplateLiteral,
9043 ThisExpression,
9044 ThrowStatement,
9045 TryStatement,
9046 UnaryExpression,
9047 UnknownNode,
9048 UpdateExpression,
9049 VariableDeclaration: VariableDeclaration$1,
9050 VariableDeclarator,
9051 WhileStatement,
9052 YieldExpression
9053};
9054
9055function getOriginalLocation(sourcemapChain, location) {
9056 // This cast is guaranteed. If it were a missing Map, it wouldn't have a mappings.
9057 const filteredSourcemapChain = sourcemapChain.filter(sourcemap => sourcemap.mappings);
9058 while (filteredSourcemapChain.length > 0) {
9059 const sourcemap = filteredSourcemapChain.pop();
9060 const line = sourcemap.mappings[location.line - 1];
9061 let locationFound = false;
9062 if (line !== undefined) {
9063 for (const segment of line) {
9064 if (segment[0] >= location.column) {
9065 if (segment.length === 1)
9066 break;
9067 location = {
9068 column: segment[3],
9069 line: segment[2] + 1,
9070 name: segment.length === 5 ? sourcemap.names[segment[4]] : undefined,
9071 source: sourcemap.sources[segment[1]]
9072 };
9073 locationFound = true;
9074 break;
9075 }
9076 }
9077 }
9078 if (!locationFound) {
9079 throw new Error("Can't resolve original location of error.");
9080 }
9081 }
9082 return location;
9083}
9084
9085// AST walker module for Mozilla Parser API compatible trees
9086
9087function skipThrough(node, st, c) { c(node, st); }
9088function ignore(_node, _st, _c) {}
9089
9090// Node walkers.
9091
9092var base$1 = {};
9093
9094base$1.Program = base$1.BlockStatement = function (node, st, c) {
9095 for (var i = 0, list = node.body; i < list.length; i += 1)
9096 {
9097 var stmt = list[i];
9098
9099 c(stmt, st, "Statement");
9100 }
9101};
9102base$1.Statement = skipThrough;
9103base$1.EmptyStatement = ignore;
9104base$1.ExpressionStatement = base$1.ParenthesizedExpression =
9105 function (node, st, c) { return c(node.expression, st, "Expression"); };
9106base$1.IfStatement = function (node, st, c) {
9107 c(node.test, st, "Expression");
9108 c(node.consequent, st, "Statement");
9109 if (node.alternate) { c(node.alternate, st, "Statement"); }
9110};
9111base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
9112base$1.BreakStatement = base$1.ContinueStatement = ignore;
9113base$1.WithStatement = function (node, st, c) {
9114 c(node.object, st, "Expression");
9115 c(node.body, st, "Statement");
9116};
9117base$1.SwitchStatement = function (node, st, c) {
9118 c(node.discriminant, st, "Expression");
9119 for (var i$1 = 0, list$1 = node.cases; i$1 < list$1.length; i$1 += 1) {
9120 var cs = list$1[i$1];
9121
9122 if (cs.test) { c(cs.test, st, "Expression"); }
9123 for (var i = 0, list = cs.consequent; i < list.length; i += 1)
9124 {
9125 var cons = list[i];
9126
9127 c(cons, st, "Statement");
9128 }
9129 }
9130};
9131base$1.SwitchCase = function (node, st, c) {
9132 if (node.test) { c(node.test, st, "Expression"); }
9133 for (var i = 0, list = node.consequent; i < list.length; i += 1)
9134 {
9135 var cons = list[i];
9136
9137 c(cons, st, "Statement");
9138 }
9139};
9140base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
9141 if (node.argument) { c(node.argument, st, "Expression"); }
9142};
9143base$1.ThrowStatement = base$1.SpreadElement =
9144 function (node, st, c) { return c(node.argument, st, "Expression"); };
9145base$1.TryStatement = function (node, st, c) {
9146 c(node.block, st, "Statement");
9147 if (node.handler) { c(node.handler, st); }
9148 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
9149};
9150base$1.CatchClause = function (node, st, c) {
9151 if (node.param) { c(node.param, st, "Pattern"); }
9152 c(node.body, st, "Statement");
9153};
9154base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
9155 c(node.test, st, "Expression");
9156 c(node.body, st, "Statement");
9157};
9158base$1.ForStatement = function (node, st, c) {
9159 if (node.init) { c(node.init, st, "ForInit"); }
9160 if (node.test) { c(node.test, st, "Expression"); }
9161 if (node.update) { c(node.update, st, "Expression"); }
9162 c(node.body, st, "Statement");
9163};
9164base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
9165 c(node.left, st, "ForInit");
9166 c(node.right, st, "Expression");
9167 c(node.body, st, "Statement");
9168};
9169base$1.ForInit = function (node, st, c) {
9170 if (node.type === "VariableDeclaration") { c(node, st); }
9171 else { c(node, st, "Expression"); }
9172};
9173base$1.DebuggerStatement = ignore;
9174
9175base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
9176base$1.VariableDeclaration = function (node, st, c) {
9177 for (var i = 0, list = node.declarations; i < list.length; i += 1)
9178 {
9179 var decl = list[i];
9180
9181 c(decl, st);
9182 }
9183};
9184base$1.VariableDeclarator = function (node, st, c) {
9185 c(node.id, st, "Pattern");
9186 if (node.init) { c(node.init, st, "Expression"); }
9187};
9188
9189base$1.Function = function (node, st, c) {
9190 if (node.id) { c(node.id, st, "Pattern"); }
9191 for (var i = 0, list = node.params; i < list.length; i += 1)
9192 {
9193 var param = list[i];
9194
9195 c(param, st, "Pattern");
9196 }
9197 c(node.body, st, node.expression ? "Expression" : "Statement");
9198};
9199
9200base$1.Pattern = function (node, st, c) {
9201 if (node.type === "Identifier")
9202 { c(node, st, "VariablePattern"); }
9203 else if (node.type === "MemberExpression")
9204 { c(node, st, "MemberPattern"); }
9205 else
9206 { c(node, st); }
9207};
9208base$1.VariablePattern = ignore;
9209base$1.MemberPattern = skipThrough;
9210base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
9211base$1.ArrayPattern = function (node, st, c) {
9212 for (var i = 0, list = node.elements; i < list.length; i += 1) {
9213 var elt = list[i];
9214
9215 if (elt) { c(elt, st, "Pattern"); }
9216 }
9217};
9218base$1.ObjectPattern = function (node, st, c) {
9219 for (var i = 0, list = node.properties; i < list.length; i += 1) {
9220 var prop = list[i];
9221
9222 if (prop.type === "Property") {
9223 if (prop.computed) { c(prop.key, st, "Expression"); }
9224 c(prop.value, st, "Pattern");
9225 } else if (prop.type === "RestElement") {
9226 c(prop.argument, st, "Pattern");
9227 }
9228 }
9229};
9230
9231base$1.Expression = skipThrough;
9232base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
9233base$1.ArrayExpression = function (node, st, c) {
9234 for (var i = 0, list = node.elements; i < list.length; i += 1) {
9235 var elt = list[i];
9236
9237 if (elt) { c(elt, st, "Expression"); }
9238 }
9239};
9240base$1.ObjectExpression = function (node, st, c) {
9241 for (var i = 0, list = node.properties; i < list.length; i += 1)
9242 {
9243 var prop = list[i];
9244
9245 c(prop, st);
9246 }
9247};
9248base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
9249base$1.SequenceExpression = function (node, st, c) {
9250 for (var i = 0, list = node.expressions; i < list.length; i += 1)
9251 {
9252 var expr = list[i];
9253
9254 c(expr, st, "Expression");
9255 }
9256};
9257base$1.TemplateLiteral = function (node, st, c) {
9258 for (var i = 0, list = node.quasis; i < list.length; i += 1)
9259 {
9260 var quasi = list[i];
9261
9262 c(quasi, st);
9263 }
9264
9265 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
9266 {
9267 var expr = list$1[i$1];
9268
9269 c(expr, st, "Expression");
9270 }
9271};
9272base$1.TemplateElement = ignore;
9273base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
9274 c(node.argument, st, "Expression");
9275};
9276base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
9277 c(node.left, st, "Expression");
9278 c(node.right, st, "Expression");
9279};
9280base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
9281 c(node.left, st, "Pattern");
9282 c(node.right, st, "Expression");
9283};
9284base$1.ConditionalExpression = function (node, st, c) {
9285 c(node.test, st, "Expression");
9286 c(node.consequent, st, "Expression");
9287 c(node.alternate, st, "Expression");
9288};
9289base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
9290 c(node.callee, st, "Expression");
9291 if (node.arguments)
9292 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
9293 {
9294 var arg = list[i];
9295
9296 c(arg, st, "Expression");
9297 } }
9298};
9299base$1.MemberExpression = function (node, st, c) {
9300 c(node.object, st, "Expression");
9301 if (node.computed) { c(node.property, st, "Expression"); }
9302};
9303base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
9304 if (node.declaration)
9305 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
9306 if (node.source) { c(node.source, st, "Expression"); }
9307};
9308base$1.ExportAllDeclaration = function (node, st, c) {
9309 c(node.source, st, "Expression");
9310};
9311base$1.ImportDeclaration = function (node, st, c) {
9312 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
9313 {
9314 var spec = list[i];
9315
9316 c(spec, st);
9317 }
9318 c(node.source, st, "Expression");
9319};
9320base$1.ImportExpression = function (node, st, c) {
9321 c(node.source, st, "Expression");
9322};
9323base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
9324
9325base$1.TaggedTemplateExpression = function (node, st, c) {
9326 c(node.tag, st, "Expression");
9327 c(node.quasi, st, "Expression");
9328};
9329base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
9330base$1.Class = function (node, st, c) {
9331 if (node.id) { c(node.id, st, "Pattern"); }
9332 if (node.superClass) { c(node.superClass, st, "Expression"); }
9333 c(node.body, st);
9334};
9335base$1.ClassBody = function (node, st, c) {
9336 for (var i = 0, list = node.body; i < list.length; i += 1)
9337 {
9338 var elt = list[i];
9339
9340 c(elt, st);
9341 }
9342};
9343base$1.MethodDefinition = base$1.Property = function (node, st, c) {
9344 if (node.computed) { c(node.key, st, "Expression"); }
9345 c(node.value, st, "Expression");
9346};
9347
9348// @ts-ignore
9349function handlePureAnnotationsOfNode(node, state, type = node.type) {
9350 let commentNode = state.commentNodes[state.commentIndex];
9351 while (commentNode && node.start >= commentNode.end) {
9352 markPureNode(node, commentNode);
9353 commentNode = state.commentNodes[++state.commentIndex];
9354 }
9355 if (commentNode && commentNode.end <= node.end) {
9356 base$1[type](node, state, handlePureAnnotationsOfNode);
9357 }
9358}
9359function markPureNode(node, comment) {
9360 if (node.annotations) {
9361 node.annotations.push(comment);
9362 }
9363 else {
9364 node.annotations = [comment];
9365 }
9366 if (node.type === 'ExpressionStatement') {
9367 node = node.expression;
9368 }
9369 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
9370 node.annotatedPure = true;
9371 }
9372}
9373const pureCommentRegex = /[@#]__PURE__/;
9374const isPureComment = (comment) => pureCommentRegex.test(comment.text);
9375function markPureCallExpressions(comments, esTreeAst) {
9376 handlePureAnnotationsOfNode(esTreeAst, {
9377 commentIndex: 0,
9378 commentNodes: comments.filter(isPureComment)
9379 });
9380}
9381
9382// this looks ridiculous, but it prevents sourcemap tooling from mistaking
9383// this for an actual sourceMappingURL
9384let SOURCEMAPPING_URL = 'sourceMa';
9385SOURCEMAPPING_URL += 'ppingURL';
9386const SOURCEMAPPING_URL_RE = new RegExp(`^#\\s+${SOURCEMAPPING_URL}=.+\\n?`);
9387
9388const NOOP = () => { };
9389let getStartTime = () => [0, 0];
9390let getElapsedTime = () => 0;
9391let getMemory = () => 0;
9392let timers = {};
9393const normalizeHrTime = (time) => time[0] * 1e3 + time[1] / 1e6;
9394function setTimeHelpers() {
9395 if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
9396 getStartTime = process.hrtime.bind(process);
9397 getElapsedTime = previous => normalizeHrTime(process.hrtime(previous));
9398 }
9399 else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
9400 getStartTime = () => [performance.now(), 0];
9401 getElapsedTime = previous => performance.now() - previous[0];
9402 }
9403 if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
9404 getMemory = () => process.memoryUsage().heapUsed;
9405 }
9406}
9407function getPersistedLabel(label, level) {
9408 switch (level) {
9409 case 1:
9410 return `# ${label}`;
9411 case 2:
9412 return `## ${label}`;
9413 case 3:
9414 return label;
9415 default:
9416 return `${' '.repeat(level - 4)}- ${label}`;
9417 }
9418}
9419function timeStartImpl(label, level = 3) {
9420 label = getPersistedLabel(label, level);
9421 if (!timers.hasOwnProperty(label)) {
9422 timers[label] = {
9423 memory: 0,
9424 startMemory: undefined,
9425 startTime: undefined,
9426 time: 0,
9427 totalMemory: 0
9428 };
9429 }
9430 const currentMemory = getMemory();
9431 timers[label].startTime = getStartTime();
9432 timers[label].startMemory = currentMemory;
9433}
9434function timeEndImpl(label, level = 3) {
9435 label = getPersistedLabel(label, level);
9436 if (timers.hasOwnProperty(label)) {
9437 const currentMemory = getMemory();
9438 timers[label].time += getElapsedTime(timers[label].startTime);
9439 timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
9440 timers[label].memory += currentMemory - timers[label].startMemory;
9441 }
9442}
9443function getTimings() {
9444 const newTimings = {};
9445 Object.keys(timers).forEach(label => {
9446 newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
9447 });
9448 return newTimings;
9449}
9450let timeStart = NOOP, timeEnd = NOOP;
9451const TIMED_PLUGIN_HOOKS = {
9452 load: true,
9453 ongenerate: true,
9454 onwrite: true,
9455 resolveDynamicImport: true,
9456 resolveId: true,
9457 transform: true,
9458 transformBundle: true
9459};
9460function getPluginWithTimers(plugin, index) {
9461 const timedPlugin = {};
9462 for (const hook of Object.keys(plugin)) {
9463 if (TIMED_PLUGIN_HOOKS[hook] === true) {
9464 let timerLabel = `plugin ${index}`;
9465 if (plugin.name) {
9466 timerLabel += ` (${plugin.name})`;
9467 }
9468 timerLabel += ` - ${hook}`;
9469 timedPlugin[hook] = function () {
9470 timeStart(timerLabel, 4);
9471 const result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
9472 timeEnd(timerLabel, 4);
9473 if (result && typeof result.then === 'function') {
9474 timeStart(`${timerLabel} (async)`, 4);
9475 result.then(() => timeEnd(`${timerLabel} (async)`, 4));
9476 }
9477 return result;
9478 };
9479 }
9480 else {
9481 timedPlugin[hook] = plugin[hook];
9482 }
9483 }
9484 return timedPlugin;
9485}
9486function initialiseTimers(inputOptions) {
9487 if (inputOptions.perf) {
9488 timers = {};
9489 setTimeHelpers();
9490 timeStart = timeStartImpl;
9491 timeEnd = timeEndImpl;
9492 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
9493 }
9494 else {
9495 timeStart = NOOP;
9496 timeEnd = NOOP;
9497 }
9498}
9499
9500const defaultAcornOptions = {
9501 ecmaVersion: 2020,
9502 preserveParens: false,
9503 sourceType: 'module'
9504};
9505function tryParse(module, Parser, acornOptions) {
9506 try {
9507 return Parser.parse(module.code, Object.assign(Object.assign(Object.assign({}, defaultAcornOptions), acornOptions), { onComment: (block, text, start, end) => module.comments.push({ block, text, start, end }) }));
9508 }
9509 catch (err) {
9510 let message = err.message.replace(/ \(\d+:\d+\)$/, '');
9511 if (module.id.endsWith('.json')) {
9512 message += ' (Note that you need rollup-plugin-json to import JSON files)';
9513 }
9514 else if (!module.id.endsWith('.js')) {
9515 message += ' (Note that you need plugins to import files that are not JavaScript)';
9516 }
9517 module.error({
9518 code: 'PARSE_ERROR',
9519 message,
9520 parserError: err
9521 }, err.pos);
9522 }
9523}
9524function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
9525 importingModule.error({
9526 code: 'MISSING_EXPORT',
9527 message: `'${exportName}' is not exported by ${index.relativeId(importedModule)}`,
9528 url: `https://rollupjs.org/guide/en/#error-name-is-not-exported-by-module`
9529 }, importerStart);
9530}
9531const MISSING_EXPORT_SHIM_DESCRIPTION = {
9532 identifier: null,
9533 localName: MISSING_EXPORT_SHIM_VARIABLE
9534};
9535class Module {
9536 constructor(graph, id, moduleSideEffects, isEntry) {
9537 this.chunkFileNames = new Set();
9538 this.chunkName = null;
9539 this.comments = [];
9540 this.dependencies = [];
9541 this.dynamicallyImportedBy = [];
9542 this.dynamicDependencies = [];
9543 this.dynamicImports = [];
9544 this.entryPointsHash = new Uint8Array(10);
9545 this.execIndex = Infinity;
9546 this.exportAllModules = null;
9547 this.exportAllSources = [];
9548 this.exports = Object.create(null);
9549 this.exportsAll = Object.create(null);
9550 this.exportShimVariable = new ExportShimVariable(this);
9551 this.facadeChunk = null;
9552 this.importDescriptions = Object.create(null);
9553 this.importMetas = [];
9554 this.imports = new Set();
9555 this.isExecuted = false;
9556 this.isUserDefinedEntryPoint = false;
9557 this.manualChunkAlias = null;
9558 this.reexports = Object.create(null);
9559 this.sources = [];
9560 this.userChunkNames = new Set();
9561 this.usesTopLevelAwait = false;
9562 this.namespaceVariable = undefined;
9563 this.transformDependencies = [];
9564 this.id = id;
9565 this.graph = graph;
9566 this.excludeFromSourcemap = /\0/.test(id);
9567 this.context = graph.getModuleContext(id);
9568 this.moduleSideEffects = moduleSideEffects;
9569 this.isEntryPoint = isEntry;
9570 }
9571 basename() {
9572 const base = path.basename(this.id);
9573 const ext = path.extname(this.id);
9574 return makeLegal(ext ? base.slice(0, -ext.length) : base);
9575 }
9576 bindReferences() {
9577 this.ast.bind();
9578 }
9579 error(props, pos) {
9580 if (pos !== undefined) {
9581 props.pos = pos;
9582 let location = locate(this.code, pos, { offsetLine: 1 });
9583 try {
9584 location = getOriginalLocation(this.sourcemapChain, location);
9585 }
9586 catch (e) {
9587 this.warn({
9588 code: 'SOURCEMAP_ERROR',
9589 loc: {
9590 column: location.column,
9591 file: this.id,
9592 line: location.line
9593 },
9594 message: `Error when using sourcemap for reporting an error: ${e.message}`,
9595 pos
9596 }, undefined);
9597 }
9598 props.loc = {
9599 column: location.column,
9600 file: this.id,
9601 line: location.line
9602 };
9603 props.frame = getCodeFrame(this.originalCode, location.line, location.column);
9604 }
9605 props.watchFiles = Object.keys(this.graph.watchFiles);
9606 error(props);
9607 }
9608 getAllExportNames() {
9609 if (this.allExportNames) {
9610 return this.allExportNames;
9611 }
9612 const allExportNames = (this.allExportNames = new Set());
9613 for (const name of Object.keys(this.exports)) {
9614 allExportNames.add(name);
9615 }
9616 for (const name of Object.keys(this.reexports)) {
9617 allExportNames.add(name);
9618 }
9619 for (const module of this.exportAllModules) {
9620 if (module instanceof ExternalModule) {
9621 allExportNames.add(`*${module.id}`);
9622 continue;
9623 }
9624 for (const name of module.getAllExportNames()) {
9625 if (name !== 'default')
9626 allExportNames.add(name);
9627 }
9628 }
9629 return allExportNames;
9630 }
9631 getDynamicImportExpressions() {
9632 return this.dynamicImports.map(({ node }) => {
9633 const importArgument = node.source;
9634 if (importArgument instanceof TemplateLiteral &&
9635 importArgument.quasis.length === 1 &&
9636 importArgument.quasis[0].value.cooked) {
9637 return importArgument.quasis[0].value.cooked;
9638 }
9639 if (importArgument instanceof Literal && typeof importArgument.value === 'string') {
9640 return importArgument.value;
9641 }
9642 return importArgument;
9643 });
9644 }
9645 getExportNamesByVariable() {
9646 const exportNamesByVariable = new Map();
9647 for (const exportName of this.getAllExportNames()) {
9648 const tracedVariable = this.getVariableForExportName(exportName);
9649 if (!tracedVariable ||
9650 !(tracedVariable.included || tracedVariable instanceof ExternalVariable)) {
9651 continue;
9652 }
9653 const existingExportNames = exportNamesByVariable.get(tracedVariable);
9654 if (existingExportNames) {
9655 existingExportNames.push(exportName);
9656 }
9657 else {
9658 exportNamesByVariable.set(tracedVariable, [exportName]);
9659 }
9660 }
9661 return exportNamesByVariable;
9662 }
9663 getExports() {
9664 return Object.keys(this.exports);
9665 }
9666 getOrCreateNamespace() {
9667 if (!this.namespaceVariable) {
9668 this.namespaceVariable = new NamespaceVariable(this.astContext);
9669 this.namespaceVariable.initialise();
9670 }
9671 return this.namespaceVariable;
9672 }
9673 getReexports() {
9674 if (this.transitiveReexports) {
9675 return this.transitiveReexports;
9676 }
9677 // to avoid infinite recursion when using circular `export * from X`
9678 this.transitiveReexports = [];
9679 const reexports = new Set();
9680 for (const name in this.reexports) {
9681 reexports.add(name);
9682 }
9683 for (const module of this.exportAllModules) {
9684 if (module instanceof ExternalModule) {
9685 reexports.add(`*${module.id}`);
9686 }
9687 else {
9688 for (const name of module.getExports().concat(module.getReexports())) {
9689 if (name !== 'default')
9690 reexports.add(name);
9691 }
9692 }
9693 }
9694 return (this.transitiveReexports = Array.from(reexports));
9695 }
9696 getRenderedExports() {
9697 // only direct exports are counted here, not reexports at all
9698 const renderedExports = [];
9699 const removedExports = [];
9700 for (const exportName in this.exports) {
9701 const variable = this.getVariableForExportName(exportName);
9702 (variable && variable.included ? renderedExports : removedExports).push(exportName);
9703 }
9704 return { renderedExports, removedExports };
9705 }
9706 getTransitiveDependencies() {
9707 return this.dependencies.concat(this.getReexports().map(exportName => this.getVariableForExportName(exportName).module));
9708 }
9709 getVariableForExportName(name, isExportAllSearch) {
9710 if (name[0] === '*') {
9711 if (name.length === 1) {
9712 return this.getOrCreateNamespace();
9713 }
9714 else {
9715 // export * from 'external'
9716 const module = this.graph.moduleById.get(name.slice(1));
9717 return module.getVariableForExportName('*');
9718 }
9719 }
9720 // export { foo } from './other'
9721 const reexportDeclaration = this.reexports[name];
9722 if (reexportDeclaration) {
9723 const declaration = reexportDeclaration.module.getVariableForExportName(reexportDeclaration.localName);
9724 if (!declaration) {
9725 handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
9726 }
9727 return declaration;
9728 }
9729 const exportDeclaration = this.exports[name];
9730 if (exportDeclaration) {
9731 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
9732 return this.exportShimVariable;
9733 }
9734 const name = exportDeclaration.localName;
9735 return this.traceVariable(name) || this.graph.scope.findVariable(name);
9736 }
9737 if (name !== 'default') {
9738 for (const module of this.exportAllModules) {
9739 const declaration = module.getVariableForExportName(name, true);
9740 if (declaration)
9741 return declaration;
9742 }
9743 }
9744 // we don't want to create shims when we are just
9745 // probing export * modules for exports
9746 if (this.graph.shimMissingExports && !isExportAllSearch) {
9747 this.shimMissingExport(name);
9748 return this.exportShimVariable;
9749 }
9750 return undefined;
9751 }
9752 include() {
9753 const context = createInclusionContext();
9754 if (this.ast.shouldBeIncluded(context))
9755 this.ast.include(context, false);
9756 }
9757 includeAllExports() {
9758 if (!this.isExecuted) {
9759 this.graph.needsTreeshakingPass = true;
9760 markModuleAndImpureDependenciesAsExecuted(this);
9761 }
9762 const context = createInclusionContext();
9763 for (const exportName of this.getExports()) {
9764 const variable = this.getVariableForExportName(exportName);
9765 variable.deoptimizePath(UNKNOWN_PATH);
9766 if (!variable.included) {
9767 variable.include(context);
9768 this.graph.needsTreeshakingPass = true;
9769 }
9770 }
9771 for (const name of this.getReexports()) {
9772 const variable = this.getVariableForExportName(name);
9773 variable.deoptimizePath(UNKNOWN_PATH);
9774 if (!variable.included) {
9775 variable.include(context);
9776 this.graph.needsTreeshakingPass = true;
9777 }
9778 if (variable instanceof ExternalVariable) {
9779 variable.module.reexported = true;
9780 }
9781 }
9782 }
9783 includeAllInBundle() {
9784 this.ast.include(createInclusionContext(), true);
9785 }
9786 isIncluded() {
9787 return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included);
9788 }
9789 linkDependencies() {
9790 for (const source of this.sources) {
9791 const id = this.resolvedIds[source].id;
9792 if (id) {
9793 const module = this.graph.moduleById.get(id);
9794 this.dependencies.push(module);
9795 }
9796 }
9797 for (const { resolution } of this.dynamicImports) {
9798 if (resolution instanceof Module || resolution instanceof ExternalModule) {
9799 this.dynamicDependencies.push(resolution);
9800 }
9801 }
9802 this.addModulesToSpecifiers(this.importDescriptions);
9803 this.addModulesToSpecifiers(this.reexports);
9804 this.exportAllModules = this.exportAllSources
9805 .map(source => {
9806 const id = this.resolvedIds[source].id;
9807 return this.graph.moduleById.get(id);
9808 })
9809 .sort((moduleA, moduleB) => {
9810 const aExternal = moduleA instanceof ExternalModule;
9811 const bExternal = moduleB instanceof ExternalModule;
9812 return aExternal === bExternal ? 0 : aExternal ? 1 : -1;
9813 });
9814 }
9815 render(options) {
9816 const magicString = this.magicString.clone();
9817 this.ast.render(magicString, options);
9818 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
9819 return magicString;
9820 }
9821 setSource({ ast, code, customTransformCache, moduleSideEffects, originalCode, originalSourcemap, resolvedIds, sourcemapChain, transformDependencies, transformFiles }) {
9822 this.code = code;
9823 this.originalCode = originalCode;
9824 this.originalSourcemap = originalSourcemap;
9825 this.sourcemapChain = sourcemapChain;
9826 if (transformFiles) {
9827 this.transformFiles = transformFiles;
9828 }
9829 this.transformDependencies = transformDependencies;
9830 this.customTransformCache = customTransformCache;
9831 if (typeof moduleSideEffects === 'boolean') {
9832 this.moduleSideEffects = moduleSideEffects;
9833 }
9834 timeStart('generate ast', 3);
9835 this.esTreeAst = ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions);
9836 markPureCallExpressions(this.comments, this.esTreeAst);
9837 timeEnd('generate ast', 3);
9838 this.resolvedIds = resolvedIds || Object.create(null);
9839 // By default, `id` is the file name. Custom resolvers and loaders
9840 // can change that, but it makes sense to use it for the source file name
9841 const fileName = this.id;
9842 this.magicString = new MagicString(code, {
9843 filename: (this.excludeFromSourcemap ? null : fileName),
9844 indentExclusionRanges: []
9845 });
9846 this.removeExistingSourceMap();
9847 timeStart('analyse ast', 3);
9848 this.astContext = {
9849 addDynamicImport: this.addDynamicImport.bind(this),
9850 addExport: this.addExport.bind(this),
9851 addImport: this.addImport.bind(this),
9852 addImportMeta: this.addImportMeta.bind(this),
9853 annotations: (this.graph.treeshakingOptions &&
9854 this.graph.treeshakingOptions.annotations),
9855 code,
9856 deoptimizationTracker: this.graph.deoptimizationTracker,
9857 error: this.error.bind(this),
9858 fileName,
9859 getExports: this.getExports.bind(this),
9860 getFileName: this.graph.pluginDriver.getFileName,
9861 getModuleExecIndex: () => this.execIndex,
9862 getModuleName: this.basename.bind(this),
9863 getReexports: this.getReexports.bind(this),
9864 importDescriptions: this.importDescriptions,
9865 includeDynamicImport: this.includeDynamicImport.bind(this),
9866 includeVariable: this.includeVariable.bind(this),
9867 isCrossChunkImport: importDescription => importDescription.module.chunk !== this.chunk,
9868 magicString: this.magicString,
9869 module: this,
9870 moduleContext: this.context,
9871 nodeConstructors,
9872 preserveModules: this.graph.preserveModules,
9873 propertyReadSideEffects: (!this.graph.treeshakingOptions ||
9874 this.graph.treeshakingOptions.propertyReadSideEffects),
9875 traceExport: this.getVariableForExportName.bind(this),
9876 traceVariable: this.traceVariable.bind(this),
9877 treeshake: !!this.graph.treeshakingOptions,
9878 tryCatchDeoptimization: (!this.graph.treeshakingOptions ||
9879 this.graph.treeshakingOptions.tryCatchDeoptimization),
9880 unknownGlobalSideEffects: (!this.graph.treeshakingOptions ||
9881 this.graph.treeshakingOptions.unknownGlobalSideEffects),
9882 usesTopLevelAwait: false,
9883 warn: this.warn.bind(this),
9884 warnDeprecation: this.graph.warnDeprecation.bind(this.graph)
9885 };
9886 this.scope = new ModuleScope(this.graph.scope, this.astContext);
9887 this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
9888 timeEnd('analyse ast', 3);
9889 }
9890 toJSON() {
9891 return {
9892 ast: this.esTreeAst,
9893 code: this.code,
9894 customTransformCache: this.customTransformCache,
9895 dependencies: this.dependencies.map(module => module.id),
9896 id: this.id,
9897 moduleSideEffects: this.moduleSideEffects,
9898 originalCode: this.originalCode,
9899 originalSourcemap: this.originalSourcemap,
9900 resolvedIds: this.resolvedIds,
9901 sourcemapChain: this.sourcemapChain,
9902 transformDependencies: this.transformDependencies,
9903 transformFiles: this.transformFiles
9904 };
9905 }
9906 traceVariable(name) {
9907 const localVariable = this.scope.variables.get(name);
9908 if (localVariable) {
9909 return localVariable;
9910 }
9911 if (name in this.importDescriptions) {
9912 const importDeclaration = this.importDescriptions[name];
9913 const otherModule = importDeclaration.module;
9914 if (otherModule instanceof Module && importDeclaration.name === '*') {
9915 return otherModule.getOrCreateNamespace();
9916 }
9917 const declaration = otherModule.getVariableForExportName(importDeclaration.name);
9918 if (!declaration) {
9919 handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
9920 }
9921 return declaration;
9922 }
9923 return null;
9924 }
9925 warn(warning, pos) {
9926 if (pos !== undefined) {
9927 warning.pos = pos;
9928 const { line, column } = locate(this.code, pos, { offsetLine: 1 }); // TODO trace sourcemaps, cf. error()
9929 warning.loc = { file: this.id, line, column };
9930 warning.frame = getCodeFrame(this.code, line, column);
9931 }
9932 warning.id = this.id;
9933 this.graph.warn(warning);
9934 }
9935 addDynamicImport(node) {
9936 this.dynamicImports.push({ node, resolution: null });
9937 }
9938 addExport(node) {
9939 const source = node.source && node.source.value;
9940 // export { name } from './other'
9941 if (source) {
9942 if (this.sources.indexOf(source) === -1)
9943 this.sources.push(source);
9944 if (node.type === ExportAllDeclaration) {
9945 // Store `export * from '...'` statements in an array of delegates.
9946 // When an unknown import is encountered, we see if one of them can satisfy it.
9947 this.exportAllSources.push(source);
9948 }
9949 else {
9950 for (const specifier of node.specifiers) {
9951 const name = specifier.exported.name;
9952 if (this.exports[name] || this.reexports[name]) {
9953 this.error({
9954 code: 'DUPLICATE_EXPORT',
9955 message: `A module cannot have multiple exports with the same name ('${name}')`
9956 }, specifier.start);
9957 }
9958 this.reexports[name] = {
9959 localName: specifier.local.name,
9960 module: null,
9961 source,
9962 start: specifier.start
9963 };
9964 }
9965 }
9966 }
9967 else if (node instanceof ExportDefaultDeclaration) {
9968 // export default function foo () {}
9969 // export default foo;
9970 // export default 42;
9971 if (this.exports.default) {
9972 this.error({
9973 code: 'DUPLICATE_EXPORT',
9974 message: `A module can only have one default export`
9975 }, node.start);
9976 }
9977 this.exports.default = {
9978 identifier: node.variable.getAssignedVariableName(),
9979 localName: 'default'
9980 };
9981 }
9982 else if (node.declaration) {
9983 // export var { foo, bar } = ...
9984 // export var foo = 42;
9985 // export var a = 1, b = 2, c = 3;
9986 // export function foo () {}
9987 const declaration = node.declaration;
9988 if (declaration.type === VariableDeclaration) {
9989 for (const decl of declaration.declarations) {
9990 for (const localName of extractAssignedNames(decl.id)) {
9991 this.exports[localName] = { identifier: null, localName };
9992 }
9993 }
9994 }
9995 else {
9996 // export function foo () {}
9997 const localName = declaration.id.name;
9998 this.exports[localName] = { identifier: null, localName };
9999 }
10000 }
10001 else {
10002 // export { foo, bar, baz }
10003 for (const specifier of node.specifiers) {
10004 const localName = specifier.local.name;
10005 const exportedName = specifier.exported.name;
10006 if (this.exports[exportedName] || this.reexports[exportedName]) {
10007 this.error({
10008 code: 'DUPLICATE_EXPORT',
10009 message: `A module cannot have multiple exports with the same name ('${exportedName}')`
10010 }, specifier.start);
10011 }
10012 this.exports[exportedName] = { identifier: null, localName };
10013 }
10014 }
10015 }
10016 addImport(node) {
10017 const source = node.source.value;
10018 if (this.sources.indexOf(source) === -1)
10019 this.sources.push(source);
10020 for (const specifier of node.specifiers) {
10021 const localName = specifier.local.name;
10022 if (this.importDescriptions[localName]) {
10023 this.error({
10024 code: 'DUPLICATE_IMPORT',
10025 message: `Duplicated import '${localName}'`
10026 }, specifier.start);
10027 }
10028 const isDefault = specifier.type === ImportDefaultSpecifier;
10029 const isNamespace = specifier.type === ImportNamespaceSpecifier;
10030 const name = isDefault
10031 ? 'default'
10032 : isNamespace
10033 ? '*'
10034 : specifier.imported.name;
10035 this.importDescriptions[localName] = { source, start: specifier.start, name, module: null };
10036 }
10037 }
10038 addImportMeta(node) {
10039 this.importMetas.push(node);
10040 }
10041 addModulesToSpecifiers(specifiers) {
10042 for (const name of Object.keys(specifiers)) {
10043 const specifier = specifiers[name];
10044 const id = this.resolvedIds[specifier.source].id;
10045 specifier.module = this.graph.moduleById.get(id);
10046 }
10047 }
10048 includeDynamicImport(node) {
10049 const resolution = this.dynamicImports.find(dynamicImport => dynamicImport.node === node).resolution;
10050 if (resolution instanceof Module) {
10051 resolution.dynamicallyImportedBy.push(this);
10052 resolution.includeAllExports();
10053 }
10054 }
10055 includeVariable(context, variable) {
10056 const variableModule = variable.module;
10057 if (!variable.included) {
10058 variable.include(context);
10059 this.graph.needsTreeshakingPass = true;
10060 }
10061 if (variableModule && variableModule !== this) {
10062 this.imports.add(variable);
10063 }
10064 }
10065 removeExistingSourceMap() {
10066 for (const comment of this.comments) {
10067 if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
10068 this.magicString.remove(comment.start, comment.end);
10069 }
10070 }
10071 }
10072 shimMissingExport(name) {
10073 if (!this.exports[name]) {
10074 this.graph.warn({
10075 code: 'SHIMMED_EXPORT',
10076 exporter: index.relativeId(this.id),
10077 exportName: name,
10078 message: `Missing export "${name}" has been shimmed in module ${index.relativeId(this.id)}.`
10079 });
10080 this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
10081 }
10082 }
10083}
10084
10085class Source {
10086 constructor(filename, content) {
10087 this.isOriginal = true;
10088 this.filename = filename;
10089 this.content = content;
10090 }
10091 traceSegment(line, column, name) {
10092 return { line, column, name, source: this };
10093 }
10094}
10095class Link {
10096 constructor(map, sources) {
10097 this.sources = sources;
10098 this.names = map.names;
10099 this.mappings = map.mappings;
10100 }
10101 traceMappings() {
10102 const sources = [];
10103 const sourcesContent = [];
10104 const names = [];
10105 const mappings = [];
10106 for (const line of this.mappings) {
10107 const tracedLine = [];
10108 for (const segment of line) {
10109 if (segment.length == 1)
10110 continue;
10111 const source = this.sources[segment[1]];
10112 if (!source)
10113 continue;
10114 const traced = source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : '');
10115 if (traced) {
10116 // newer sources are more likely to be used, so search backwards.
10117 let sourceIndex = sources.lastIndexOf(traced.source.filename);
10118 if (sourceIndex === -1) {
10119 sourceIndex = sources.length;
10120 sources.push(traced.source.filename);
10121 sourcesContent[sourceIndex] = traced.source.content;
10122 }
10123 else if (sourcesContent[sourceIndex] == null) {
10124 sourcesContent[sourceIndex] = traced.source.content;
10125 }
10126 else if (traced.source.content != null &&
10127 sourcesContent[sourceIndex] !== traced.source.content) {
10128 error({
10129 message: `Multiple conflicting contents for sourcemap source ${traced.source.filename}`
10130 });
10131 }
10132 const tracedSegment = [
10133 segment[0],
10134 sourceIndex,
10135 traced.line,
10136 traced.column
10137 ];
10138 if (traced.name) {
10139 let nameIndex = names.indexOf(traced.name);
10140 if (nameIndex === -1) {
10141 nameIndex = names.length;
10142 names.push(traced.name);
10143 }
10144 tracedSegment[4] = nameIndex;
10145 }
10146 tracedLine.push(tracedSegment);
10147 }
10148 }
10149 mappings.push(tracedLine);
10150 }
10151 return { sources, sourcesContent, names, mappings };
10152 }
10153 traceSegment(line, column, name) {
10154 const segments = this.mappings[line];
10155 if (!segments)
10156 return null;
10157 // binary search through segments for the given column
10158 let i = 0;
10159 let j = segments.length - 1;
10160 while (i <= j) {
10161 const m = (i + j) >> 1;
10162 const segment = segments[m];
10163 if (segment[0] === column) {
10164 if (segment.length == 1)
10165 return null;
10166 const source = this.sources[segment[1]];
10167 if (!source)
10168 return null;
10169 return source.traceSegment(segment[2], segment[3], segment.length === 5 ? this.names[segment[4]] : name);
10170 }
10171 if (segment[0] > column) {
10172 j = m - 1;
10173 }
10174 else {
10175 i = m + 1;
10176 }
10177 }
10178 return null;
10179 }
10180}
10181function getLinkMap(graph) {
10182 return function linkMap(source, map) {
10183 if (map.mappings) {
10184 return new Link(map, [source]);
10185 }
10186 graph.warn({
10187 code: 'SOURCEMAP_BROKEN',
10188 message: `Sourcemap is likely to be incorrect: a plugin${map.plugin ? ` ('${map.plugin}')` : ``} was used to transform files, but didn't generate a sourcemap for the transformation. Consult the plugin documentation for help`,
10189 plugin: map.plugin,
10190 url: `https://rollupjs.org/guide/en/#warning-sourcemap-is-likely-to-be-incorrect`
10191 });
10192 return new Link({
10193 mappings: [],
10194 names: []
10195 }, [source]);
10196 };
10197}
10198function getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, linkMap) {
10199 let source;
10200 if (!originalSourcemap) {
10201 source = new Source(id, originalCode);
10202 }
10203 else {
10204 const sources = originalSourcemap.sources;
10205 const sourcesContent = originalSourcemap.sourcesContent || [];
10206 // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
10207 const directory = path.dirname(id) || '.';
10208 const sourceRoot = originalSourcemap.sourceRoot || '.';
10209 const baseSources = sources.map((source, i) => new Source(path.resolve(directory, sourceRoot, source), sourcesContent[i]));
10210 source = new Link(originalSourcemap, baseSources);
10211 }
10212 return sourcemapChain.reduce(linkMap, source);
10213}
10214function collapseSourcemaps(bundle, file, map, modules, bundleSourcemapChain, excludeContent) {
10215 const linkMap = getLinkMap(bundle.graph);
10216 const moduleSources = modules
10217 .filter(module => !module.excludeFromSourcemap)
10218 .map(module => getCollapsedSourcemap(module.id, module.originalCode, module.originalSourcemap, module.sourcemapChain, linkMap));
10219 // DecodedSourceMap (from magic-string) uses a number[] instead of the more
10220 // correct SourceMapSegment tuples. Cast it here to gain type safety.
10221 let source = new Link(map, moduleSources);
10222 source = bundleSourcemapChain.reduce(linkMap, source);
10223 let { sources, sourcesContent, names, mappings } = source.traceMappings();
10224 if (file) {
10225 const directory = path.dirname(file);
10226 sources = sources.map((source) => path.relative(directory, source));
10227 file = path.basename(file);
10228 }
10229 sourcesContent = (excludeContent ? null : sourcesContent);
10230 return new SourceMap({ file, sources, sourcesContent, names, mappings });
10231}
10232function collapseSourcemap(graph, id, originalCode, originalSourcemap, sourcemapChain) {
10233 if (!sourcemapChain.length) {
10234 return originalSourcemap;
10235 }
10236 const source = getCollapsedSourcemap(id, originalCode, originalSourcemap, sourcemapChain, getLinkMap(graph));
10237 const map = source.traceMappings();
10238 return Object.assign({ version: 3 }, map);
10239}
10240
10241const DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
10242 amd: deconflictImportsOther,
10243 cjs: deconflictImportsOther,
10244 es: deconflictImportsEsm,
10245 iife: deconflictImportsOther,
10246 system: deconflictImportsEsm,
10247 umd: deconflictImportsOther
10248};
10249function deconflictChunk(modules, dependencies, imports, usedNames, format, interop, preserveModules) {
10250 addUsedGlobalNames(usedNames, modules, format);
10251 deconflictTopLevelVariables(usedNames, modules);
10252 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependencies, interop, preserveModules);
10253 for (const module of modules) {
10254 module.scope.deconflict(format);
10255 }
10256}
10257function addUsedGlobalNames(usedNames, modules, format) {
10258 for (const module of modules) {
10259 const moduleScope = module.scope;
10260 for (const [name, variable] of moduleScope.accessedOutsideVariables) {
10261 if (variable.included) {
10262 usedNames.add(name);
10263 }
10264 }
10265 const accessedGlobalVariables = moduleScope.accessedGlobalVariablesByFormat &&
10266 moduleScope.accessedGlobalVariablesByFormat.get(format);
10267 if (accessedGlobalVariables) {
10268 for (const name of accessedGlobalVariables) {
10269 usedNames.add(name);
10270 }
10271 }
10272 }
10273}
10274function deconflictImportsEsm(usedNames, imports, _dependencies, interop) {
10275 for (const variable of imports) {
10276 const module = variable.module;
10277 const name = variable.name;
10278 let proposedName;
10279 if (module instanceof ExternalModule && (name === '*' || name === 'default')) {
10280 if (name === 'default' && interop && module.exportsNamespace) {
10281 proposedName = module.variableName + '__default';
10282 }
10283 else {
10284 proposedName = module.variableName;
10285 }
10286 }
10287 else {
10288 proposedName = name;
10289 }
10290 variable.setRenderNames(null, getSafeName(proposedName, usedNames));
10291 }
10292}
10293function deconflictImportsOther(usedNames, imports, dependencies, interop, preserveModules) {
10294 for (const chunkOrExternalModule of dependencies) {
10295 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.variableName, usedNames);
10296 }
10297 for (const variable of imports) {
10298 const module = variable.module;
10299 if (module instanceof ExternalModule) {
10300 const name = variable.name;
10301 if (name === 'default' && interop && (module.exportsNamespace || module.exportsNames)) {
10302 variable.setRenderNames(null, module.variableName + '__default');
10303 }
10304 else if (name === '*' || name === 'default') {
10305 variable.setRenderNames(null, module.variableName);
10306 }
10307 else {
10308 variable.setRenderNames(module.variableName, null);
10309 }
10310 }
10311 else {
10312 const chunk = module.chunk;
10313 if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) {
10314 variable.setRenderNames(null, chunk.variableName);
10315 }
10316 else {
10317 variable.setRenderNames(chunk.variableName, chunk.getVariableExportName(variable));
10318 }
10319 }
10320 }
10321}
10322function deconflictTopLevelVariables(usedNames, modules) {
10323 for (const module of modules) {
10324 for (const variable of module.scope.variables.values()) {
10325 if (variable.included &&
10326 // this will only happen for exports in some formats
10327 !(variable.renderBaseName ||
10328 (variable instanceof ExportDefaultVariable && variable.getOriginalVariable() !== variable))) {
10329 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
10330 }
10331 }
10332 const namespace = module.getOrCreateNamespace();
10333 if (namespace.included) {
10334 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
10335 }
10336 }
10337}
10338
10339const compareExecIndex = (unitA, unitB) => unitA.execIndex > unitB.execIndex ? 1 : -1;
10340function sortByExecutionOrder(units) {
10341 units.sort(compareExecIndex);
10342}
10343function analyseModuleExecution(entryModules) {
10344 let nextExecIndex = 0;
10345 const cyclePaths = [];
10346 const analysedModules = {};
10347 const orderedModules = [];
10348 const dynamicImports = [];
10349 const parents = {};
10350 const analyseModule = (module) => {
10351 if (analysedModules[module.id])
10352 return;
10353 if (module instanceof ExternalModule) {
10354 module.execIndex = nextExecIndex++;
10355 analysedModules[module.id] = true;
10356 return;
10357 }
10358 for (const dependency of module.dependencies) {
10359 if (dependency.id in parents) {
10360 if (!analysedModules[dependency.id]) {
10361 cyclePaths.push(getCyclePath(dependency.id, module.id, parents));
10362 }
10363 continue;
10364 }
10365 parents[dependency.id] = module.id;
10366 analyseModule(dependency);
10367 }
10368 for (const { resolution } of module.dynamicImports) {
10369 if (resolution instanceof Module && dynamicImports.indexOf(resolution) === -1) {
10370 dynamicImports.push(resolution);
10371 }
10372 }
10373 module.execIndex = nextExecIndex++;
10374 analysedModules[module.id] = true;
10375 orderedModules.push(module);
10376 };
10377 for (const curEntry of entryModules) {
10378 if (!parents[curEntry.id]) {
10379 parents[curEntry.id] = null;
10380 analyseModule(curEntry);
10381 }
10382 }
10383 for (const curEntry of dynamicImports) {
10384 if (!parents[curEntry.id]) {
10385 parents[curEntry.id] = null;
10386 analyseModule(curEntry);
10387 }
10388 }
10389 return { orderedModules, cyclePaths };
10390}
10391function getCyclePath(id, parentId, parents) {
10392 const path = [index.relativeId(id)];
10393 let curId = parentId;
10394 while (curId !== id) {
10395 path.push(index.relativeId(curId));
10396 curId = parents[curId];
10397 if (!curId)
10398 break;
10399 }
10400 path.push(path[0]);
10401 path.reverse();
10402 return path;
10403}
10404
10405function guessIndentString(code) {
10406 const lines = code.split('\n');
10407 const tabbed = lines.filter(line => /^\t+/.test(line));
10408 const spaced = lines.filter(line => /^ {2,}/.test(line));
10409 if (tabbed.length === 0 && spaced.length === 0) {
10410 return null;
10411 }
10412 // More lines tabbed than spaced? Assume tabs, and
10413 // default to tabs in the case of a tie (or nothing
10414 // to go on)
10415 if (tabbed.length >= spaced.length) {
10416 return '\t';
10417 }
10418 // Otherwise, we need to guess the multiple
10419 const min = spaced.reduce((previous, current) => {
10420 const numSpaces = /^ +/.exec(current)[0].length;
10421 return Math.min(numSpaces, previous);
10422 }, Infinity);
10423 return new Array(min + 1).join(' ');
10424}
10425function getIndentString(modules, options) {
10426 if (options.indent !== true)
10427 return options.indent || '';
10428 for (let i = 0; i < modules.length; i++) {
10429 const indent = guessIndentString(modules[i].originalCode);
10430 if (indent !== null)
10431 return indent;
10432 }
10433 return '\t';
10434}
10435
10436function decodedSourcemap(map) {
10437 if (!map)
10438 return null;
10439 if (typeof map === 'string') {
10440 map = JSON.parse(map);
10441 }
10442 if (map.mappings === '') {
10443 return {
10444 mappings: [],
10445 names: [],
10446 sources: [],
10447 version: 3
10448 };
10449 }
10450 let mappings;
10451 if (typeof map.mappings === 'string') {
10452 mappings = decode(map.mappings);
10453 }
10454 else {
10455 mappings = map.mappings;
10456 }
10457 return Object.assign(Object.assign({}, map), { mappings });
10458}
10459
10460function renderChunk({ graph, chunk, renderChunk, code, sourcemapChain, options }) {
10461 const renderChunkReducer = (code, result, plugin) => {
10462 if (result == null)
10463 return code;
10464 if (typeof result === 'string')
10465 result = {
10466 code: result,
10467 map: undefined
10468 };
10469 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
10470 if (result.map !== null) {
10471 const map = decodedSourcemap(result.map);
10472 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
10473 }
10474 return result.code;
10475 };
10476 let inTransformBundle = false;
10477 let inRenderChunk = true;
10478 return graph.pluginDriver
10479 .hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer)
10480 .then(code => {
10481 inRenderChunk = false;
10482 return graph.pluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer);
10483 })
10484 .then(code => {
10485 inTransformBundle = true;
10486 return graph.pluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer);
10487 })
10488 .catch(err => {
10489 if (inRenderChunk)
10490 throw err;
10491 return error(err, {
10492 code: inTransformBundle ? 'BAD_BUNDLE_TRANSFORMER' : 'BAD_CHUNK_TRANSFORMER',
10493 message: `Error transforming ${(inTransformBundle ? 'bundle' : 'chunk') +
10494 (err.plugin ? ` with '${err.plugin}' plugin` : '')}: ${err.message}`,
10495 plugin: err.plugin
10496 });
10497 });
10498}
10499
10500function renderNamePattern(pattern, patternName, replacements) {
10501 if (!index.isPlainPathFragment(pattern))
10502 return error(errFailedValidation(`Invalid pattern "${pattern}" for "${patternName}", patterns can be neither absolute nor relative paths and must not contain invalid characters.`));
10503 return pattern.replace(/\[(\w+)\]/g, (_match, type) => {
10504 if (!replacements.hasOwnProperty(type)) {
10505 return error(errFailedValidation(`"[${type}]" is not a valid placeholder in "${patternName}" pattern.`));
10506 }
10507 const replacement = replacements[type]();
10508 if (!index.isPlainPathFragment(replacement))
10509 return error(errFailedValidation(`Invalid substitution "${replacement}" for placeholder "[${type}]" in "${patternName}" pattern, can be neither absolute nor relative path.`));
10510 return replacement;
10511 });
10512}
10513function makeUnique(name, existingNames) {
10514 if (name in existingNames === false)
10515 return name;
10516 const ext = path.extname(name);
10517 name = name.substr(0, name.length - ext.length);
10518 let uniqueName, uniqueIndex = 1;
10519 while (existingNames[(uniqueName = name + ++uniqueIndex + ext)])
10520 ;
10521 return uniqueName;
10522}
10523
10524const NON_ASSET_EXTENSIONS = ['.js', '.jsx', '.ts', '.tsx'];
10525function getGlobalName(module, globals, graph, hasExports) {
10526 let globalName;
10527 if (typeof globals === 'function') {
10528 globalName = globals(module.id);
10529 }
10530 else if (globals) {
10531 globalName = globals[module.id];
10532 }
10533 if (globalName) {
10534 return globalName;
10535 }
10536 if (hasExports) {
10537 graph.warn({
10538 code: 'MISSING_GLOBAL_NAME',
10539 guess: module.variableName,
10540 message: `No name was provided for external module '${module.id}' in output.globals – guessing '${module.variableName}'`,
10541 source: module.id
10542 });
10543 return module.variableName;
10544 }
10545}
10546function isChunkRendered(chunk) {
10547 return !chunk.isEmpty || chunk.entryModules.length > 0 || chunk.manualChunkAlias !== null;
10548}
10549class Chunk$1 {
10550 constructor(graph, orderedModules) {
10551 this.entryModules = [];
10552 this.exportMode = 'named';
10553 this.facadeModule = null;
10554 this.id = null;
10555 this.indentString = undefined;
10556 this.manualChunkAlias = null;
10557 this.usedModules = undefined;
10558 this.variableName = 'chunk';
10559 this.dependencies = undefined;
10560 this.dynamicDependencies = undefined;
10561 this.exportNames = Object.create(null);
10562 this.exports = new Set();
10563 this.fileName = null;
10564 this.imports = new Set();
10565 this.name = null;
10566 this.needsExportsShim = false;
10567 this.renderedDeclarations = undefined;
10568 this.renderedHash = undefined;
10569 this.renderedModuleSources = new Map();
10570 this.renderedSource = null;
10571 this.renderedSourceLength = undefined;
10572 this.sortedExportNames = null;
10573 this.graph = graph;
10574 this.orderedModules = orderedModules;
10575 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
10576 this.isEmpty = true;
10577 for (const module of orderedModules) {
10578 if (this.isEmpty && module.isIncluded()) {
10579 this.isEmpty = false;
10580 }
10581 if (module.manualChunkAlias) {
10582 this.manualChunkAlias = module.manualChunkAlias;
10583 }
10584 module.chunk = this;
10585 if (module.isEntryPoint ||
10586 module.dynamicallyImportedBy.some(module => orderedModules.indexOf(module) === -1)) {
10587 this.entryModules.push(module);
10588 }
10589 }
10590 const moduleForNaming = this.entryModules[0] || this.orderedModules[this.orderedModules.length - 1];
10591 if (moduleForNaming) {
10592 this.variableName = makeLegal(path.basename(moduleForNaming.chunkName ||
10593 moduleForNaming.manualChunkAlias ||
10594 index.getAliasName(moduleForNaming.id)));
10595 }
10596 }
10597 static generateFacade(graph, facadedModule, facadeName) {
10598 const chunk = new Chunk$1(graph, []);
10599 chunk.assignFacadeName(facadeName, facadedModule);
10600 if (!facadedModule.facadeChunk) {
10601 facadedModule.facadeChunk = chunk;
10602 }
10603 chunk.dependencies = [facadedModule.chunk];
10604 chunk.dynamicDependencies = [];
10605 chunk.facadeModule = facadedModule;
10606 for (const exportName of facadedModule.getAllExportNames()) {
10607 const tracedVariable = facadedModule.getVariableForExportName(exportName);
10608 chunk.exports.add(tracedVariable);
10609 chunk.exportNames[exportName] = tracedVariable;
10610 }
10611 return chunk;
10612 }
10613 canModuleBeFacade(moduleExportNamesByVariable) {
10614 for (const exposedVariable of this.exports) {
10615 if (!moduleExportNamesByVariable.has(exposedVariable)) {
10616 return false;
10617 }
10618 }
10619 return true;
10620 }
10621 generateFacades() {
10622 const facades = [];
10623 for (const module of this.entryModules) {
10624 const requiredFacades = Array.from(module.userChunkNames).map(name => ({
10625 name
10626 }));
10627 if (requiredFacades.length === 0 && module.isUserDefinedEntryPoint) {
10628 requiredFacades.push({});
10629 }
10630 requiredFacades.push(...Array.from(module.chunkFileNames).map(fileName => ({ fileName })));
10631 if (requiredFacades.length === 0) {
10632 requiredFacades.push({});
10633 }
10634 if (!this.facadeModule) {
10635 const exportNamesByVariable = module.getExportNamesByVariable();
10636 if (this.graph.preserveModules || this.canModuleBeFacade(exportNamesByVariable)) {
10637 this.facadeModule = module;
10638 module.facadeChunk = this;
10639 for (const [variable, exportNames] of exportNamesByVariable) {
10640 for (const exportName of exportNames) {
10641 this.exportNames[exportName] = variable;
10642 }
10643 }
10644 this.assignFacadeName(requiredFacades.shift(), module);
10645 }
10646 }
10647 for (const facadeName of requiredFacades) {
10648 facades.push(Chunk$1.generateFacade(this.graph, module, facadeName));
10649 }
10650 }
10651 return facades;
10652 }
10653 generateId(addons, options, existingNames, includeHash) {
10654 if (this.fileName !== null) {
10655 return this.fileName;
10656 }
10657 const [pattern, patternName] = this.facadeModule && this.facadeModule.isUserDefinedEntryPoint
10658 ? [options.entryFileNames || '[name].js', 'output.entryFileNames']
10659 : [options.chunkFileNames || '[name]-[hash].js', 'output.chunkFileNames'];
10660 return makeUnique(renderNamePattern(pattern, patternName, {
10661 format: () => (options.format === 'es' ? 'esm' : options.format),
10662 hash: () => includeHash
10663 ? this.computeContentHashWithDependencies(addons, options, existingNames)
10664 : '[hash]',
10665 name: () => this.getChunkName()
10666 }), existingNames);
10667 }
10668 generateIdPreserveModules(preserveModulesRelativeDir, options, existingNames) {
10669 const id = this.orderedModules[0].id;
10670 const sanitizedId = index.sanitizeFileName(id);
10671 let path$1;
10672 if (index.isAbsolute(id)) {
10673 const extension = path.extname(id);
10674 const name = renderNamePattern(options.entryFileNames ||
10675 (NON_ASSET_EXTENSIONS.includes(extension) ? '[name].js' : '[name][extname].js'), 'output.entryFileNames', {
10676 ext: () => extension.substr(1),
10677 extname: () => extension,
10678 format: () => (options.format === 'es' ? 'esm' : options.format),
10679 name: () => this.getChunkName()
10680 });
10681 path$1 = relative(preserveModulesRelativeDir, `${path.dirname(sanitizedId)}/${name}`);
10682 }
10683 else {
10684 path$1 = `_virtual/${path.basename(sanitizedId)}`;
10685 }
10686 return makeUnique(index.normalize(path$1), existingNames);
10687 }
10688 generateInternalExports(options) {
10689 if (this.facadeModule !== null)
10690 return;
10691 const mangle = options.format === 'system' || options.format === 'es' || options.compact;
10692 let i = 0, safeExportName;
10693 this.exportNames = Object.create(null);
10694 this.sortedExportNames = null;
10695 if (mangle) {
10696 for (const variable of this.exports) {
10697 const suggestedName = variable.name[0];
10698 if (!this.exportNames[suggestedName]) {
10699 this.exportNames[suggestedName] = variable;
10700 }
10701 else {
10702 do {
10703 safeExportName = toBase64(++i);
10704 // skip past leading number identifiers
10705 if (safeExportName.charCodeAt(0) === 49 /* '1' */) {
10706 i += 9 * Math.pow(64, (safeExportName.length - 1));
10707 safeExportName = toBase64(i);
10708 }
10709 } while (RESERVED_NAMES[safeExportName] || this.exportNames[safeExportName]);
10710 this.exportNames[safeExportName] = variable;
10711 }
10712 }
10713 }
10714 else {
10715 for (const variable of this.exports) {
10716 i = 0;
10717 safeExportName = variable.name;
10718 while (this.exportNames[safeExportName]) {
10719 safeExportName = variable.name + '$' + ++i;
10720 }
10721 this.exportNames[safeExportName] = variable;
10722 }
10723 }
10724 }
10725 getChunkName() {
10726 return this.name || (this.name = index.sanitizeFileName(this.getFallbackChunkName()));
10727 }
10728 getDynamicImportIds() {
10729 return this.dynamicDependencies.map(chunk => chunk.id).filter(Boolean);
10730 }
10731 getExportNames() {
10732 return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort()));
10733 }
10734 getImportIds() {
10735 return this.dependencies.map(chunk => chunk.id).filter(Boolean);
10736 }
10737 getRenderedHash() {
10738 if (this.renderedHash)
10739 return this.renderedHash;
10740 if (!this.renderedSource)
10741 return '';
10742 const hash = _256();
10743 const hashAugmentation = this.calculateHashAugmentation();
10744 hash.update(hashAugmentation);
10745 hash.update(this.renderedSource.toString());
10746 hash.update(this.getExportNames()
10747 .map(exportName => {
10748 const variable = this.exportNames[exportName];
10749 return `${index.relativeId(variable.module.id).replace(/\\/g, '/')}:${variable.name}:${exportName}`;
10750 })
10751 .join(','));
10752 return (this.renderedHash = hash.digest('hex'));
10753 }
10754 getRenderedSourceLength() {
10755 if (this.renderedSourceLength !== undefined)
10756 return this.renderedSourceLength;
10757 return (this.renderedSourceLength = this.renderedSource.length());
10758 }
10759 getVariableExportName(variable) {
10760 if (this.graph.preserveModules && variable instanceof NamespaceVariable) {
10761 return '*';
10762 }
10763 for (const exportName of Object.keys(this.exportNames)) {
10764 if (this.exportNames[exportName] === variable)
10765 return exportName;
10766 }
10767 throw new Error(`Internal Error: Could not find export name for variable ${variable.name}.`);
10768 }
10769 link() {
10770 const dependencies = new Set();
10771 const dynamicDependencies = new Set();
10772 for (const module of this.orderedModules) {
10773 this.addDependenciesToChunk(module.getTransitiveDependencies(), dependencies);
10774 this.addDependenciesToChunk(module.dynamicDependencies, dynamicDependencies);
10775 this.setUpChunkImportsAndExportsForModule(module);
10776 }
10777 this.dependencies = Array.from(dependencies);
10778 this.dynamicDependencies = Array.from(dynamicDependencies);
10779 }
10780 /*
10781 * Performs a full merge of another chunk into this chunk
10782 * chunkList allows updating references in other chunks for the merged chunk to this chunk
10783 * A new facade will be added to chunkList if tainting exports of either as an entry point
10784 */
10785 merge(chunk, chunkList, options, inputBase) {
10786 if (this.facadeModule !== null || chunk.facadeModule !== null)
10787 throw new Error('Internal error: Code splitting chunk merges not supported for facades');
10788 for (const module of chunk.orderedModules) {
10789 module.chunk = this;
10790 this.orderedModules.push(module);
10791 }
10792 for (const variable of chunk.imports) {
10793 if (!this.imports.has(variable) && variable.module.chunk !== this) {
10794 this.imports.add(variable);
10795 }
10796 }
10797 // NB detect when exported variables are orphaned by the merge itself
10798 // (involves reverse tracing dependents)
10799 for (const variable of chunk.exports) {
10800 if (!this.exports.has(variable)) {
10801 this.exports.add(variable);
10802 }
10803 }
10804 const thisOldExportNames = this.exportNames;
10805 // regenerate internal names
10806 this.generateInternalExports(options);
10807 const updateRenderedDeclaration = (dep, oldExportNames) => {
10808 if (dep.imports) {
10809 for (const impt of dep.imports) {
10810 impt.imported = this.getVariableExportName(oldExportNames[impt.imported]);
10811 }
10812 }
10813 if (dep.reexports) {
10814 for (const reexport of dep.reexports) {
10815 reexport.imported = this.getVariableExportName(oldExportNames[reexport.imported]);
10816 }
10817 }
10818 };
10819 const mergeRenderedDeclaration = (into, from) => {
10820 if (from.imports) {
10821 if (!into.imports) {
10822 into.imports = from.imports;
10823 }
10824 else {
10825 into.imports = into.imports.concat(from.imports);
10826 }
10827 }
10828 if (from.reexports) {
10829 if (!into.reexports) {
10830 into.reexports = from.reexports;
10831 }
10832 else {
10833 into.reexports = into.reexports.concat(from.reexports);
10834 }
10835 }
10836 if (!into.exportsNames && from.exportsNames) {
10837 into.exportsNames = true;
10838 }
10839 if (!into.exportsDefault && from.exportsDefault) {
10840 into.exportsDefault = true;
10841 }
10842 into.name = this.variableName;
10843 };
10844 // go through the other chunks and update their dependencies
10845 // also update their import and reexport names in the process
10846 for (const c of chunkList) {
10847 let includedDeclaration = undefined;
10848 for (let i = 0; i < c.dependencies.length; i++) {
10849 const dep = c.dependencies[i];
10850 if ((dep === chunk || dep === this) && includedDeclaration) {
10851 const duplicateDeclaration = c.renderedDeclarations.dependencies[i];
10852 updateRenderedDeclaration(duplicateDeclaration, dep === chunk ? chunk.exportNames : thisOldExportNames);
10853 mergeRenderedDeclaration(includedDeclaration, duplicateDeclaration);
10854 c.renderedDeclarations.dependencies.splice(i, 1);
10855 c.dependencies.splice(i--, 1);
10856 }
10857 else if (dep === chunk) {
10858 c.dependencies[i] = this;
10859 includedDeclaration = c.renderedDeclarations.dependencies[i];
10860 updateRenderedDeclaration(includedDeclaration, chunk.exportNames);
10861 }
10862 else if (dep === this) {
10863 includedDeclaration = c.renderedDeclarations.dependencies[i];
10864 updateRenderedDeclaration(includedDeclaration, thisOldExportNames);
10865 }
10866 }
10867 }
10868 // re-render the merged chunk
10869 this.preRender(options, inputBase);
10870 }
10871 // prerender allows chunk hashes and names to be generated before finalizing
10872 preRender(options, inputBase) {
10873 timeStart('render modules', 3);
10874 const magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
10875 this.usedModules = [];
10876 this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options);
10877 const n = options.compact ? '' : '\n';
10878 const _ = options.compact ? '' : ' ';
10879 const renderOptions = {
10880 compact: options.compact,
10881 dynamicImportFunction: options.dynamicImportFunction,
10882 format: options.format,
10883 freeze: options.freeze !== false,
10884 indent: this.indentString,
10885 namespaceToStringTag: options.namespaceToStringTag === true,
10886 varOrConst: options.preferConst ? 'const' : 'var'
10887 };
10888 // Make sure the direct dependencies of a chunk are present to maintain execution order
10889 for (const { module } of this.imports) {
10890 const chunkOrExternal = (module instanceof Module ? module.chunk : module);
10891 if (this.dependencies.indexOf(chunkOrExternal) === -1) {
10892 this.dependencies.push(chunkOrExternal);
10893 }
10894 }
10895 // for static and dynamic entry points, inline the execution list to avoid loading latency
10896 if (!this.graph.preserveModules && this.facadeModule !== null) {
10897 for (const dep of this.dependencies) {
10898 if (dep instanceof Chunk$1)
10899 this.inlineChunkDependencies(dep, true);
10900 }
10901 }
10902 // prune empty dependency chunks, inlining their side-effect dependencies
10903 for (let i = 0; i < this.dependencies.length; i++) {
10904 const dep = this.dependencies[i];
10905 if (dep instanceof Chunk$1 && dep.isEmpty) {
10906 this.dependencies.splice(i--, 1);
10907 this.inlineChunkDependencies(dep, false);
10908 }
10909 }
10910 sortByExecutionOrder(this.dependencies);
10911 this.prepareDynamicImports();
10912 this.setIdentifierRenderResolutions(options);
10913 let hoistedSource = '';
10914 const renderedModules = (this.renderedModules = Object.create(null));
10915 for (const module of this.orderedModules) {
10916 let renderedLength = 0;
10917 if (module.isIncluded()) {
10918 const source = module.render(renderOptions).trim();
10919 if (options.compact && source.lastLine().indexOf('//') !== -1)
10920 source.append('\n');
10921 const namespace = module.getOrCreateNamespace();
10922 if (namespace.included || source.length() > 0) {
10923 renderedLength = source.length();
10924 this.renderedModuleSources.set(module, source);
10925 magicString.addSource(source);
10926 this.usedModules.push(module);
10927 if (namespace.included && !this.graph.preserveModules) {
10928 const rendered = namespace.renderBlock(renderOptions);
10929 if (namespace.renderFirst())
10930 hoistedSource += n + rendered;
10931 else
10932 magicString.addSource(new MagicString(rendered));
10933 }
10934 }
10935 }
10936 const { renderedExports, removedExports } = module.getRenderedExports();
10937 renderedModules[module.id] = {
10938 originalLength: module.originalCode.length,
10939 removedExports,
10940 renderedExports,
10941 renderedLength
10942 };
10943 }
10944 if (hoistedSource)
10945 magicString.prepend(hoistedSource + n + n);
10946 if (this.needsExportsShim) {
10947 magicString.prepend(`${n}${renderOptions.varOrConst} ${MISSING_EXPORT_SHIM_VARIABLE}${_}=${_}void 0;${n}${n}`);
10948 }
10949 if (options.compact) {
10950 this.renderedSource = magicString;
10951 }
10952 else {
10953 this.renderedSource = magicString.trim();
10954 }
10955 this.renderedSourceLength = undefined;
10956 this.renderedHash = undefined;
10957 if (this.getExportNames().length === 0 && this.getImportIds().length === 0 && this.isEmpty) {
10958 this.graph.warn({
10959 code: 'EMPTY_BUNDLE',
10960 message: 'Generated an empty bundle'
10961 });
10962 }
10963 this.setExternalRenderPaths(options, inputBase);
10964 this.renderedDeclarations = {
10965 dependencies: this.getChunkDependencyDeclarations(options),
10966 exports: this.exportMode === 'none' ? [] : this.getChunkExportDeclarations()
10967 };
10968 timeEnd('render modules', 3);
10969 }
10970 render(options, addons, outputChunk) {
10971 timeStart('render format', 3);
10972 if (!this.renderedSource)
10973 throw new Error('Internal error: Chunk render called before preRender');
10974 const format = options.format;
10975 const finalise = finalisers[format];
10976 if (!finalise) {
10977 error({
10978 code: 'INVALID_OPTION',
10979 message: `Invalid format: ${format} - valid options are ${Object.keys(finalisers).join(', ')}.`
10980 });
10981 }
10982 if (options.dynamicImportFunction && format !== 'es') {
10983 this.graph.warn({
10984 code: 'INVALID_OPTION',
10985 message: '"output.dynamicImportFunction" is ignored for formats other than "esm".'
10986 });
10987 }
10988 // populate ids in the rendered declarations only here
10989 // as chunk ids known only after prerender
10990 for (let i = 0; i < this.dependencies.length; i++) {
10991 const dep = this.dependencies[i];
10992 if (dep instanceof ExternalModule && !dep.renormalizeRenderPath)
10993 continue;
10994 const renderedDependency = this.renderedDeclarations.dependencies[i];
10995 const depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id;
10996 if (dep instanceof Chunk$1)
10997 renderedDependency.namedExportsMode = dep.exportMode !== 'default';
10998 renderedDependency.id = this.getRelativePath(depId);
10999 }
11000 this.finaliseDynamicImports(format);
11001 this.finaliseImportMetas(format);
11002 const hasExports = this.renderedDeclarations.exports.length !== 0 ||
11003 this.renderedDeclarations.dependencies.some(dep => (dep.reexports && dep.reexports.length !== 0));
11004 let usesTopLevelAwait = false;
11005 const accessedGlobals = new Set();
11006 for (const module of this.orderedModules) {
11007 if (module.usesTopLevelAwait) {
11008 usesTopLevelAwait = true;
11009 }
11010 const accessedGlobalVariablesByFormat = module.scope.accessedGlobalVariablesByFormat;
11011 const accessedGlobalVariables = accessedGlobalVariablesByFormat && accessedGlobalVariablesByFormat.get(format);
11012 if (accessedGlobalVariables) {
11013 for (const name of accessedGlobalVariables) {
11014 accessedGlobals.add(name);
11015 }
11016 }
11017 }
11018 if (usesTopLevelAwait && format !== 'es' && format !== 'system') {
11019 error({
11020 code: 'INVALID_TLA_FORMAT',
11021 message: `Module format ${format} does not support top-level await. Use the "es" or "system" output formats rather.`
11022 });
11023 }
11024 const magicString = finalise(this.renderedSource, {
11025 accessedGlobals,
11026 dependencies: this.renderedDeclarations.dependencies,
11027 exports: this.renderedDeclarations.exports,
11028 hasExports,
11029 indentString: this.indentString,
11030 intro: addons.intro,
11031 isEntryModuleFacade: this.facadeModule !== null && this.facadeModule.isEntryPoint,
11032 namedExportsMode: this.exportMode !== 'default',
11033 outro: addons.outro,
11034 usesTopLevelAwait,
11035 varOrConst: options.preferConst ? 'const' : 'var',
11036 warn: this.graph.warn.bind(this.graph)
11037 }, options);
11038 if (addons.banner)
11039 magicString.prepend(addons.banner);
11040 if (addons.footer)
11041 magicString.append(addons.footer);
11042 const prevCode = magicString.toString();
11043 timeEnd('render format', 3);
11044 let map = null;
11045 const chunkSourcemapChain = [];
11046 return renderChunk({
11047 chunk: this,
11048 code: prevCode,
11049 graph: this.graph,
11050 options,
11051 renderChunk: outputChunk,
11052 sourcemapChain: chunkSourcemapChain
11053 }).then((code) => {
11054 if (options.sourcemap) {
11055 timeStart('sourcemap', 3);
11056 let file;
11057 if (options.file)
11058 file = path.resolve(options.sourcemapFile || options.file);
11059 else if (options.dir)
11060 file = path.resolve(options.dir, this.id);
11061 else
11062 file = path.resolve(this.id);
11063 const decodedMap = magicString.generateDecodedMap({});
11064 map = collapseSourcemaps(this, file, decodedMap, this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
11065 map.sources = map.sources.map(sourcePath => index.normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath));
11066 timeEnd('sourcemap', 3);
11067 }
11068 if (options.compact !== true && code[code.length - 1] !== '\n')
11069 code += '\n';
11070 return { code, map };
11071 });
11072 }
11073 visitDependencies(handleDependency) {
11074 const toBeVisited = [this];
11075 const visited = new Set();
11076 for (const current of toBeVisited) {
11077 handleDependency(current);
11078 if (current instanceof ExternalModule)
11079 continue;
11080 for (const dependency of current.dependencies.concat(current.dynamicDependencies)) {
11081 if (!visited.has(dependency)) {
11082 visited.add(dependency);
11083 toBeVisited.push(dependency);
11084 }
11085 }
11086 }
11087 }
11088 visitStaticDependenciesUntilCondition(isConditionSatisfied) {
11089 const seen = new Set();
11090 function visitDep(dep) {
11091 if (seen.has(dep))
11092 return undefined;
11093 seen.add(dep);
11094 if (dep instanceof Chunk$1) {
11095 for (const subDep of dep.dependencies) {
11096 if (visitDep(subDep))
11097 return true;
11098 }
11099 }
11100 return isConditionSatisfied(dep) === true;
11101 }
11102 return visitDep(this);
11103 }
11104 addDependenciesToChunk(moduleDependencies, chunkDependencies) {
11105 for (const depModule of moduleDependencies) {
11106 if (depModule.chunk === this) {
11107 continue;
11108 }
11109 let dependency;
11110 if (depModule instanceof Module) {
11111 dependency = depModule.chunk;
11112 }
11113 else {
11114 if (!(depModule.used || depModule.moduleSideEffects)) {
11115 continue;
11116 }
11117 dependency = depModule;
11118 }
11119 chunkDependencies.add(dependency);
11120 }
11121 }
11122 assignFacadeName({ fileName, name }, facadedModule) {
11123 if (fileName) {
11124 this.fileName = fileName;
11125 }
11126 else {
11127 this.name = index.sanitizeFileName(name || facadedModule.chunkName || index.getAliasName(facadedModule.id));
11128 }
11129 }
11130 calculateHashAugmentation() {
11131 const facadeModule = this.facadeModule;
11132 const getChunkName = this.getChunkName.bind(this);
11133 const preRenderedChunk = {
11134 dynamicImports: this.getDynamicImportIds(),
11135 exports: this.getExportNames(),
11136 facadeModuleId: facadeModule && facadeModule.id,
11137 imports: this.getImportIds(),
11138 isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
11139 isEntry: facadeModule !== null && facadeModule.isEntryPoint,
11140 modules: this.renderedModules,
11141 get name() {
11142 return getChunkName();
11143 }
11144 };
11145 const hashAugmentation = this.graph.pluginDriver.hookReduceValueSync('augmentChunkHash', '', [preRenderedChunk], (hashAugmentation, pluginHash) => {
11146 if (pluginHash) {
11147 hashAugmentation += pluginHash;
11148 }
11149 return hashAugmentation;
11150 });
11151 return hashAugmentation;
11152 }
11153 computeContentHashWithDependencies(addons, options, existingNames) {
11154 const hash = _256();
11155 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(addon => addon || '').join(':'));
11156 hash.update(options.format);
11157 this.visitDependencies(dep => {
11158 if (dep instanceof ExternalModule) {
11159 hash.update(':' + dep.renderPath);
11160 }
11161 else {
11162 hash.update(dep.getRenderedHash());
11163 hash.update(dep.generateId(addons, options, existingNames, false));
11164 }
11165 });
11166 return hash.digest('hex').substr(0, 8);
11167 }
11168 finaliseDynamicImports(format) {
11169 for (const [module, code] of this.renderedModuleSources) {
11170 for (const { node, resolution } of module.dynamicImports) {
11171 if (!resolution)
11172 continue;
11173 if (resolution instanceof Module) {
11174 if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) {
11175 const resolutionChunk = resolution.facadeChunk || resolution.chunk;
11176 node.renderFinalResolution(code, `'${this.getRelativePath(resolutionChunk.id)}'`, format);
11177 }
11178 }
11179 else {
11180 node.renderFinalResolution(code, resolution instanceof ExternalModule
11181 ? `'${resolution.renormalizeRenderPath
11182 ? this.getRelativePath(resolution.renderPath)
11183 : resolution.id}'`
11184 : resolution, format);
11185 }
11186 }
11187 }
11188 }
11189 finaliseImportMetas(format) {
11190 for (const [module, code] of this.renderedModuleSources) {
11191 for (const importMeta of module.importMetas) {
11192 importMeta.renderFinalMechanism(code, this.id, format, this.graph.pluginDriver);
11193 }
11194 }
11195 }
11196 getChunkDependencyDeclarations(options) {
11197 const reexportDeclarations = new Map();
11198 for (let exportName of this.getExportNames()) {
11199 let exportChunk;
11200 let importName;
11201 let needsLiveBinding = false;
11202 if (exportName[0] === '*') {
11203 needsLiveBinding = options.externalLiveBindings !== false;
11204 exportChunk = this.graph.moduleById.get(exportName.substr(1));
11205 importName = exportName = '*';
11206 }
11207 else {
11208 const variable = this.exportNames[exportName];
11209 const module = variable.module;
11210 // skip local exports
11211 if (!module || module.chunk === this)
11212 continue;
11213 if (module instanceof Module) {
11214 exportChunk = module.chunk;
11215 importName = exportChunk.getVariableExportName(variable);
11216 needsLiveBinding = variable.isReassigned;
11217 }
11218 else {
11219 exportChunk = module;
11220 importName = variable.name;
11221 needsLiveBinding = options.externalLiveBindings !== false;
11222 }
11223 }
11224 let reexportDeclaration = reexportDeclarations.get(exportChunk);
11225 if (!reexportDeclaration)
11226 reexportDeclarations.set(exportChunk, (reexportDeclaration = []));
11227 reexportDeclaration.push({ imported: importName, reexported: exportName, needsLiveBinding });
11228 }
11229 const renderedImports = new Set();
11230 const dependencies = [];
11231 for (const dep of this.dependencies) {
11232 const imports = [];
11233 for (const variable of this.imports) {
11234 const renderedVariable = variable instanceof ExportDefaultVariable ? variable.getOriginalVariable() : variable;
11235 if ((variable.module instanceof Module
11236 ? variable.module.chunk === dep
11237 : variable.module === dep) &&
11238 !renderedImports.has(renderedVariable)) {
11239 renderedImports.add(renderedVariable);
11240 imports.push({
11241 imported: variable.module instanceof ExternalModule
11242 ? variable.name
11243 : variable.module.chunk.getVariableExportName(variable),
11244 local: variable.getName()
11245 });
11246 }
11247 }
11248 const reexports = reexportDeclarations.get(dep);
11249 let exportsNames, exportsDefault;
11250 let namedExportsMode = true;
11251 if (dep instanceof ExternalModule) {
11252 exportsNames = dep.exportsNames || dep.exportsNamespace;
11253 exportsDefault = 'default' in dep.declarations;
11254 }
11255 else {
11256 exportsNames = true;
11257 // we don't want any interop patterns to trigger
11258 exportsDefault = false;
11259 namedExportsMode = dep.exportMode !== 'default';
11260 }
11261 let id = undefined;
11262 let globalName = undefined;
11263 if (dep instanceof ExternalModule) {
11264 id = dep.renderPath;
11265 if (options.format === 'umd' || options.format === 'iife') {
11266 globalName = getGlobalName(dep, options.globals, this.graph, exportsNames || exportsDefault);
11267 }
11268 }
11269 dependencies.push({
11270 exportsDefault,
11271 exportsNames,
11272 globalName,
11273 id,
11274 imports: imports.length > 0 ? imports : null,
11275 isChunk: dep instanceof Chunk$1,
11276 name: dep.variableName,
11277 namedExportsMode,
11278 reexports
11279 });
11280 }
11281 return dependencies;
11282 }
11283 getChunkExportDeclarations() {
11284 const exports = [];
11285 for (const exportName of this.getExportNames()) {
11286 if (exportName[0] === '*')
11287 continue;
11288 const variable = this.exportNames[exportName];
11289 const module = variable.module;
11290 if (module && module.chunk !== this)
11291 continue;
11292 let hoisted = false;
11293 let uninitialized = false;
11294 if (variable instanceof LocalVariable) {
11295 if (variable.init === UNDEFINED_EXPRESSION) {
11296 uninitialized = true;
11297 }
11298 for (const declaration of variable.declarations) {
11299 if (declaration.parent instanceof FunctionDeclaration ||
11300 (declaration instanceof ExportDefaultDeclaration &&
11301 declaration.declaration instanceof FunctionDeclaration)) {
11302 hoisted = true;
11303 break;
11304 }
11305 }
11306 }
11307 else if (variable instanceof GlobalVariable) {
11308 hoisted = true;
11309 }
11310 const localName = variable.getName();
11311 exports.push({
11312 exported: exportName === '*' ? localName : exportName,
11313 hoisted,
11314 local: localName,
11315 uninitialized
11316 });
11317 }
11318 return exports;
11319 }
11320 getFallbackChunkName() {
11321 if (this.manualChunkAlias) {
11322 return this.manualChunkAlias;
11323 }
11324 if (this.fileName) {
11325 return index.getAliasName(this.fileName);
11326 }
11327 return index.getAliasName(this.orderedModules[this.orderedModules.length - 1].id);
11328 }
11329 getRelativePath(targetPath) {
11330 const relativePath = index.normalize(relative(path.dirname(this.id), targetPath));
11331 return relativePath.startsWith('../') ? relativePath : './' + relativePath;
11332 }
11333 inlineChunkDependencies(chunk, deep) {
11334 for (const dep of chunk.dependencies) {
11335 if (dep instanceof ExternalModule) {
11336 if (this.dependencies.indexOf(dep) === -1)
11337 this.dependencies.push(dep);
11338 }
11339 else {
11340 if (dep === this || this.dependencies.indexOf(dep) !== -1)
11341 continue;
11342 if (!dep.isEmpty)
11343 this.dependencies.push(dep);
11344 if (deep)
11345 this.inlineChunkDependencies(dep, true);
11346 }
11347 }
11348 }
11349 prepareDynamicImports() {
11350 for (const module of this.orderedModules) {
11351 for (const { node, resolution } of module.dynamicImports) {
11352 if (!node.included)
11353 continue;
11354 if (resolution instanceof Module) {
11355 if (resolution.chunk === this) {
11356 const namespace = resolution.getOrCreateNamespace();
11357 node.setResolution('named', namespace);
11358 }
11359 else {
11360 node.setResolution(resolution.chunk.exportMode);
11361 }
11362 }
11363 else {
11364 node.setResolution('auto');
11365 }
11366 }
11367 }
11368 }
11369 setExternalRenderPaths(options, inputBase) {
11370 for (const dependency of this.dependencies.concat(this.dynamicDependencies)) {
11371 if (dependency instanceof ExternalModule) {
11372 dependency.setRenderPath(options, inputBase);
11373 }
11374 }
11375 }
11376 setIdentifierRenderResolutions(options) {
11377 for (const exportName of this.getExportNames()) {
11378 const exportVariable = this.exportNames[exportName];
11379 if (exportVariable) {
11380 if (exportVariable instanceof ExportShimVariable) {
11381 this.needsExportsShim = true;
11382 }
11383 exportVariable.exportName = exportName;
11384 if (options.format !== 'es' &&
11385 options.format !== 'system' &&
11386 exportVariable.isReassigned &&
11387 !exportVariable.isId &&
11388 !(exportVariable instanceof ExportDefaultVariable && exportVariable.hasId)) {
11389 exportVariable.setRenderNames('exports', exportName);
11390 }
11391 else {
11392 exportVariable.setRenderNames(null, null);
11393 }
11394 }
11395 }
11396 const usedNames = new Set();
11397 if (this.needsExportsShim) {
11398 usedNames.add(MISSING_EXPORT_SHIM_VARIABLE);
11399 }
11400 if (options.format !== 'es') {
11401 usedNames.add('exports');
11402 if (options.format === 'cjs') {
11403 usedNames
11404 .add(INTEROP_DEFAULT_VARIABLE)
11405 .add('require')
11406 .add('module')
11407 .add('__filename')
11408 .add('__dirname');
11409 }
11410 }
11411 deconflictChunk(this.orderedModules, this.dependencies, this.imports, usedNames, options.format, options.interop !== false, this.graph.preserveModules);
11412 }
11413 setUpChunkImportsAndExportsForModule(module) {
11414 for (const variable of module.imports) {
11415 if (variable.module.chunk !== this) {
11416 this.imports.add(variable);
11417 if (variable.module instanceof Module) {
11418 variable.module.chunk.exports.add(variable);
11419 }
11420 }
11421 }
11422 if (module.isEntryPoint ||
11423 module.dynamicallyImportedBy.some(importer => importer.chunk !== this)) {
11424 const map = module.getExportNamesByVariable();
11425 for (const exportedVariable of map.keys()) {
11426 this.exports.add(exportedVariable);
11427 const exportingModule = exportedVariable.module;
11428 if (exportingModule && exportingModule.chunk && exportingModule.chunk !== this) {
11429 exportingModule.chunk.exports.add(exportedVariable);
11430 }
11431 }
11432 }
11433 if (module.getOrCreateNamespace().included) {
11434 for (const reexportName of Object.keys(module.reexports)) {
11435 const reexport = module.reexports[reexportName];
11436 const variable = reexport.module.getVariableForExportName(reexport.localName);
11437 if (variable.module.chunk !== this) {
11438 this.imports.add(variable);
11439 if (variable.module instanceof Module) {
11440 variable.module.chunk.exports.add(variable);
11441 }
11442 }
11443 }
11444 }
11445 const context = createInclusionContext();
11446 for (const { node, resolution } of module.dynamicImports) {
11447 if (node.included && resolution instanceof Module && resolution.chunk === this)
11448 resolution.getOrCreateNamespace().include(context);
11449 }
11450 }
11451}
11452
11453/*
11454 * Given a chunk list, perform optimizations on that chunk list
11455 * to reduce the mumber of chunks. Mutates the chunks array.
11456 *
11457 * Manual chunks (with chunk.chunkAlias already set) are preserved
11458 * Entry points are carefully preserved as well
11459 *
11460 */
11461function optimizeChunks(chunks, options, CHUNK_GROUPING_SIZE, inputBase) {
11462 for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
11463 const mainChunk = chunks[chunkIndex];
11464 const execGroup = [];
11465 mainChunk.visitStaticDependenciesUntilCondition(dep => {
11466 if (dep instanceof Chunk$1) {
11467 execGroup.push(dep);
11468 }
11469 });
11470 if (execGroup.length < 2) {
11471 continue;
11472 }
11473 let execGroupIndex = 1;
11474 let seekingFirstMergeCandidate = true;
11475 let lastChunk = undefined, chunk = execGroup[0], nextChunk = execGroup[1];
11476 const isMergeCandidate = (chunk) => {
11477 if (chunk.facadeModule !== null || chunk.manualChunkAlias !== null) {
11478 return false;
11479 }
11480 if (!nextChunk || nextChunk.facadeModule !== null) {
11481 return false;
11482 }
11483 if (chunk.getRenderedSourceLength() > CHUNK_GROUPING_SIZE) {
11484 return false;
11485 }
11486 // if (!chunk.isPure()) continue;
11487 return true;
11488 };
11489 do {
11490 if (seekingFirstMergeCandidate) {
11491 if (isMergeCandidate(chunk)) {
11492 seekingFirstMergeCandidate = false;
11493 }
11494 continue;
11495 }
11496 let remainingSize = CHUNK_GROUPING_SIZE - lastChunk.getRenderedSourceLength() - chunk.getRenderedSourceLength();
11497 if (remainingSize <= 0) {
11498 if (!isMergeCandidate(chunk)) {
11499 seekingFirstMergeCandidate = true;
11500 }
11501 continue;
11502 }
11503 // if (!chunk.isPure()) continue;
11504 const chunkDependencies = new Set();
11505 chunk.visitStaticDependenciesUntilCondition(dep => chunkDependencies.add(dep));
11506 const ignoreSizeChunks = new Set([chunk, lastChunk]);
11507 if (lastChunk.visitStaticDependenciesUntilCondition(dep => {
11508 if (dep === chunk || dep === lastChunk) {
11509 return false;
11510 }
11511 if (chunkDependencies.has(dep)) {
11512 return false;
11513 }
11514 if (dep instanceof ExternalModule) {
11515 return true;
11516 }
11517 remainingSize -= dep.getRenderedSourceLength();
11518 if (remainingSize <= 0) {
11519 return true;
11520 }
11521 ignoreSizeChunks.add(dep);
11522 })) {
11523 if (!isMergeCandidate(chunk)) {
11524 seekingFirstMergeCandidate = true;
11525 }
11526 continue;
11527 }
11528 if (chunk.visitStaticDependenciesUntilCondition(dep => {
11529 if (ignoreSizeChunks.has(dep)) {
11530 return false;
11531 }
11532 if (dep instanceof ExternalModule) {
11533 return true;
11534 }
11535 remainingSize -= dep.getRenderedSourceLength();
11536 if (remainingSize <= 0) {
11537 return true;
11538 }
11539 })) {
11540 if (!isMergeCandidate(chunk)) {
11541 seekingFirstMergeCandidate = true;
11542 }
11543 continue;
11544 }
11545 // within the size limit -> merge!
11546 const optimizedChunkIndex = chunks.indexOf(chunk);
11547 if (optimizedChunkIndex <= chunkIndex)
11548 chunkIndex--;
11549 chunks.splice(optimizedChunkIndex, 1);
11550 lastChunk.merge(chunk, chunks, options, inputBase);
11551 execGroup.splice(--execGroupIndex, 1);
11552 chunk = lastChunk;
11553 // keep going to see if we can merge this with the next again
11554 if (nextChunk && !isMergeCandidate(nextChunk)) {
11555 seekingFirstMergeCandidate = true;
11556 }
11557 } while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk));
11558 }
11559 return chunks;
11560}
11561
11562const tt = acorn.tokTypes;
11563const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
11564const nextTokenIsDot = parser => {
11565 skipWhiteSpace.lastIndex = parser.pos;
11566 let skip = skipWhiteSpace.exec(parser.input);
11567 let next = parser.pos + skip[0].length;
11568 return parser.input.slice(next, next + 1) === ".";
11569};
11570var acornImportMeta = function (Parser) {
11571 return class extends Parser {
11572 parseExprAtom(refDestructuringErrors) {
11573 if (this.type !== tt._import || !nextTokenIsDot(this))
11574 return super.parseExprAtom(refDestructuringErrors);
11575 if (!this.options.allowImportExportEverywhere && !this.inModule) {
11576 this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
11577 }
11578 let node = this.startNode();
11579 node.meta = this.parseIdent(true);
11580 this.expect(tt.dot);
11581 node.property = this.parseIdent(true);
11582 if (node.property.name !== "meta") {
11583 this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta");
11584 }
11585 if (this.containsEsc) {
11586 this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences");
11587 }
11588 return this.finishNode(node, "MetaProperty");
11589 }
11590 parseStatement(context, topLevel, exports) {
11591 if (this.type !== tt._import || !nextTokenIsDot(this)) {
11592 return super.parseStatement(context, topLevel, exports);
11593 }
11594 let node = this.startNode();
11595 let expr = this.parseExpression();
11596 return this.parseExpressionStatement(node, expr);
11597 }
11598 };
11599};
11600
11601class UndefinedVariable extends Variable {
11602 constructor() {
11603 super('undefined');
11604 }
11605 getLiteralValueAtPath() {
11606 return undefined;
11607 }
11608}
11609
11610class GlobalScope extends Scope {
11611 constructor() {
11612 super();
11613 this.variables.set('undefined', new UndefinedVariable());
11614 }
11615 findVariable(name) {
11616 let variable = this.variables.get(name);
11617 if (!variable) {
11618 variable = new GlobalVariable(name);
11619 this.variables.set(name, variable);
11620 }
11621 return variable;
11622 }
11623}
11624
11625var BuildPhase;
11626(function (BuildPhase) {
11627 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
11628 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
11629 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
11630})(BuildPhase || (BuildPhase = {}));
11631
11632function generateAssetFileName(name, source, output) {
11633 const emittedName = name || 'asset';
11634 return makeUnique(renderNamePattern(output.assetFileNames, 'output.assetFileNames', {
11635 hash() {
11636 const hash = _256();
11637 hash.update(emittedName);
11638 hash.update(':');
11639 hash.update(source);
11640 return hash.digest('hex').substr(0, 8);
11641 },
11642 ext: () => path.extname(emittedName).substr(1),
11643 extname: () => path.extname(emittedName),
11644 name: () => emittedName.substr(0, emittedName.length - path.extname(emittedName).length)
11645 }), output.bundle);
11646}
11647function reserveFileNameInBundle(fileName, bundle) {
11648 // TODO this should warn if the fileName is already in the bundle,
11649 // but until #3174 is fixed, this raises spurious warnings and is disabled
11650 bundle[fileName] = FILE_PLACEHOLDER;
11651}
11652const FILE_PLACEHOLDER = {
11653 type: 'placeholder'
11654};
11655function hasValidType(emittedFile) {
11656 return (emittedFile &&
11657 (emittedFile.type === 'asset' ||
11658 emittedFile.type === 'chunk'));
11659}
11660function hasValidName(emittedFile) {
11661 const validatedName = emittedFile.fileName || emittedFile.name;
11662 return (!validatedName || (typeof validatedName === 'string' && index.isPlainPathFragment(validatedName)));
11663}
11664function getValidSource(source, emittedFile, fileReferenceId) {
11665 if (typeof source !== 'string' && !Buffer.isBuffer(source)) {
11666 const assetName = emittedFile.fileName || emittedFile.name || fileReferenceId;
11667 return error(errFailedValidation(`Could not set source for ${typeof assetName === 'string' ? `asset "${assetName}"` : 'unnamed asset'}, asset source needs to be a string of Buffer.`));
11668 }
11669 return source;
11670}
11671function getAssetFileName(file, referenceId) {
11672 if (typeof file.fileName !== 'string') {
11673 return error(errAssetNotFinalisedForFileName(file.name || referenceId));
11674 }
11675 return file.fileName;
11676}
11677function getChunkFileName(file) {
11678 const fileName = file.fileName || (file.module && file.module.facadeChunk.id);
11679 if (!fileName)
11680 return error(errChunkNotGeneratedForFileName(file.fileName || file.name));
11681 return fileName;
11682}
11683class FileEmitter {
11684 constructor(graph) {
11685 this.filesByReferenceId = new Map();
11686 // tslint:disable member-ordering
11687 this.buildFilesByReferenceId = this.filesByReferenceId;
11688 this.output = null;
11689 this.emitFile = (emittedFile) => {
11690 if (!hasValidType(emittedFile)) {
11691 return error(errFailedValidation(`Emitted files must be of type "asset" or "chunk", received "${emittedFile &&
11692 emittedFile.type}".`));
11693 }
11694 if (!hasValidName(emittedFile)) {
11695 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 ||
11696 emittedFile.name}".`));
11697 }
11698 if (emittedFile.type === 'chunk') {
11699 return this.emitChunk(emittedFile);
11700 }
11701 else {
11702 return this.emitAsset(emittedFile);
11703 }
11704 };
11705 this.getFileName = (fileReferenceId) => {
11706 const emittedFile = this.filesByReferenceId.get(fileReferenceId);
11707 if (!emittedFile)
11708 return error(errFileReferenceIdNotFoundForFilename(fileReferenceId));
11709 if (emittedFile.type === 'chunk') {
11710 return getChunkFileName(emittedFile);
11711 }
11712 else {
11713 return getAssetFileName(emittedFile, fileReferenceId);
11714 }
11715 };
11716 this.setAssetSource = (referenceId, requestedSource) => {
11717 const consumedFile = this.filesByReferenceId.get(referenceId);
11718 if (!consumedFile)
11719 return error(errAssetReferenceIdNotFoundForSetSource(referenceId));
11720 if (consumedFile.type !== 'asset') {
11721 return error(errFailedValidation(`Asset sources can only be set for emitted assets but "${referenceId}" is an emitted chunk.`));
11722 }
11723 if (consumedFile.source !== undefined) {
11724 return error(errAssetSourceAlreadySet(consumedFile.name || referenceId));
11725 }
11726 const source = getValidSource(requestedSource, consumedFile, referenceId);
11727 if (this.output) {
11728 this.finalizeAsset(consumedFile, source, referenceId, this.output);
11729 }
11730 else {
11731 consumedFile.source = source;
11732 }
11733 };
11734 this.graph = graph;
11735 }
11736 startOutput(outputBundle, assetFileNames) {
11737 this.filesByReferenceId = new Map(this.buildFilesByReferenceId);
11738 this.output = {
11739 assetFileNames,
11740 bundle: outputBundle
11741 };
11742 for (const emittedFile of this.filesByReferenceId.values()) {
11743 if (emittedFile.fileName) {
11744 reserveFileNameInBundle(emittedFile.fileName, this.output.bundle);
11745 }
11746 }
11747 for (const [referenceId, consumedFile] of this.filesByReferenceId.entries()) {
11748 if (consumedFile.type === 'asset' && consumedFile.source !== undefined) {
11749 this.finalizeAsset(consumedFile, consumedFile.source, referenceId, this.output);
11750 }
11751 }
11752 }
11753 assertAssetsFinalized() {
11754 for (const [referenceId, emittedFile] of this.filesByReferenceId.entries()) {
11755 if (emittedFile.type === 'asset' && typeof emittedFile.fileName !== 'string')
11756 error(errNoAssetSourceSet(emittedFile.name || referenceId));
11757 }
11758 }
11759 emitAsset(emittedAsset) {
11760 const source = typeof emittedAsset.source !== 'undefined'
11761 ? getValidSource(emittedAsset.source, emittedAsset, null)
11762 : undefined;
11763 const consumedAsset = {
11764 fileName: emittedAsset.fileName,
11765 name: emittedAsset.name,
11766 source,
11767 type: 'asset'
11768 };
11769 const referenceId = this.assignReferenceId(consumedAsset, emittedAsset.fileName || emittedAsset.name || emittedAsset.type);
11770 if (this.output) {
11771 if (emittedAsset.fileName) {
11772 reserveFileNameInBundle(emittedAsset.fileName, this.output.bundle);
11773 }
11774 if (source !== undefined) {
11775 this.finalizeAsset(consumedAsset, source, referenceId, this.output);
11776 }
11777 }
11778 return referenceId;
11779 }
11780 emitChunk(emittedChunk) {
11781 if (this.graph.phase > BuildPhase.LOAD_AND_PARSE) {
11782 error(errInvalidRollupPhaseForChunkEmission());
11783 }
11784 if (typeof emittedChunk.id !== 'string') {
11785 return error(errFailedValidation(`Emitted chunks need to have a valid string id, received "${emittedChunk.id}"`));
11786 }
11787 const consumedChunk = {
11788 fileName: emittedChunk.fileName,
11789 module: null,
11790 name: emittedChunk.name || emittedChunk.id,
11791 type: 'chunk'
11792 };
11793 this.graph.moduleLoader
11794 .addEntryModules([
11795 {
11796 fileName: emittedChunk.fileName || null,
11797 id: emittedChunk.id,
11798 name: emittedChunk.name || null
11799 }
11800 ], false)
11801 .then(({ newEntryModules: [module] }) => {
11802 consumedChunk.module = module;
11803 })
11804 .catch(() => {
11805 // Avoid unhandled Promise rejection as the error will be thrown later
11806 // once module loading has finished
11807 });
11808 return this.assignReferenceId(consumedChunk, emittedChunk.id);
11809 }
11810 assignReferenceId(file, idBase) {
11811 let referenceId;
11812 do {
11813 const hash = _256();
11814 if (referenceId) {
11815 hash.update(referenceId);
11816 }
11817 else {
11818 hash.update(idBase);
11819 }
11820 referenceId = hash.digest('hex').substr(0, 8);
11821 } while (this.filesByReferenceId.has(referenceId));
11822 this.filesByReferenceId.set(referenceId, file);
11823 return referenceId;
11824 }
11825 finalizeAsset(consumedFile, source, referenceId, output) {
11826 const fileName = consumedFile.fileName ||
11827 this.findExistingAssetFileNameWithSource(output.bundle, source) ||
11828 generateAssetFileName(consumedFile.name, source, output);
11829 // We must not modify the original assets to avoid interaction between outputs
11830 const assetWithFileName = Object.assign(Object.assign({}, consumedFile), { source, fileName });
11831 this.filesByReferenceId.set(referenceId, assetWithFileName);
11832 const graph = this.graph;
11833 output.bundle[fileName] = {
11834 fileName,
11835 get isAsset() {
11836 graph.warnDeprecation('Accessing "isAsset" on files in the bundle is deprecated, please use "type === \'asset\'" instead', false);
11837 return true;
11838 },
11839 source,
11840 type: 'asset'
11841 };
11842 }
11843 findExistingAssetFileNameWithSource(bundle, source) {
11844 for (const fileName of Object.keys(bundle)) {
11845 const outputFile = bundle[fileName];
11846 if (outputFile.type === 'asset' &&
11847 (Buffer.isBuffer(source) && Buffer.isBuffer(outputFile.source)
11848 ? source.equals(outputFile.source)
11849 : source === outputFile.source))
11850 return fileName;
11851 }
11852 return null;
11853 }
11854}
11855
11856const ANONYMOUS_PLUGIN_PREFIX = 'at position ';
11857const deprecatedHooks = [
11858 { active: true, deprecated: 'ongenerate', replacement: 'generateBundle' },
11859 { active: true, deprecated: 'onwrite', replacement: 'generateBundle/writeBundle' },
11860 { active: true, deprecated: 'transformBundle', replacement: 'renderChunk' },
11861 { active: true, deprecated: 'transformChunk', replacement: 'renderChunk' },
11862 { active: false, deprecated: 'resolveAssetUrl', replacement: 'resolveFileUrl' }
11863];
11864function warnDeprecatedHooks(plugins, graph) {
11865 for (const { active, deprecated, replacement } of deprecatedHooks) {
11866 for (const plugin of plugins) {
11867 if (deprecated in plugin) {
11868 graph.warnDeprecation({
11869 message: `The "${deprecated}" hook used by plugin ${plugin.name} is deprecated. The "${replacement}" hook should be used instead.`,
11870 plugin: plugin.name
11871 }, active);
11872 }
11873 }
11874 }
11875}
11876function throwPluginError(err, plugin, { hook, id } = {}) {
11877 if (typeof err === 'string')
11878 err = { message: err };
11879 if (err.code && err.code !== Errors.PLUGIN_ERROR) {
11880 err.pluginCode = err.code;
11881 }
11882 err.code = Errors.PLUGIN_ERROR;
11883 err.plugin = plugin;
11884 if (hook) {
11885 err.hook = hook;
11886 }
11887 if (id) {
11888 err.id = id;
11889 }
11890 return error(err);
11891}
11892function createPluginDriver(graph, options, pluginCache, watcher) {
11893 warnDeprecatedHooks(options.plugins, graph);
11894 function getDeprecatedHookHandler(handler, handlerName, newHandlerName, pluginName, acitveDeprecation) {
11895 let deprecationWarningShown = false;
11896 return ((...args) => {
11897 if (!deprecationWarningShown) {
11898 deprecationWarningShown = true;
11899 graph.warnDeprecation({
11900 message: `The "this.${handlerName}" plugin context function used by plugin ${pluginName} is deprecated. The "this.${newHandlerName}" plugin context function should be used instead.`,
11901 plugin: pluginName
11902 }, acitveDeprecation);
11903 }
11904 return handler(...args);
11905 });
11906 }
11907 const plugins = [
11908 ...options.plugins,
11909 getRollupDefaultPlugin(options.preserveSymlinks)
11910 ];
11911 const fileEmitter = new FileEmitter(graph);
11912 const existingPluginKeys = new Set();
11913 const pluginContexts = plugins.map((plugin, pidx) => {
11914 let cacheable = true;
11915 if (typeof plugin.cacheKey !== 'string') {
11916 if (plugin.name.startsWith(ANONYMOUS_PLUGIN_PREFIX) || existingPluginKeys.has(plugin.name)) {
11917 cacheable = false;
11918 }
11919 else {
11920 existingPluginKeys.add(plugin.name);
11921 }
11922 }
11923 let cacheInstance;
11924 if (!pluginCache) {
11925 cacheInstance = noCache;
11926 }
11927 else if (cacheable) {
11928 const cacheKey = plugin.cacheKey || plugin.name;
11929 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
11930 }
11931 else {
11932 cacheInstance = uncacheablePlugin(plugin.name);
11933 }
11934 const context = {
11935 addWatchFile(id) {
11936 if (graph.phase >= BuildPhase.GENERATE)
11937 this.error(errInvalidRollupPhaseForAddWatchFile());
11938 graph.watchFiles[id] = true;
11939 },
11940 cache: cacheInstance,
11941 emitAsset: getDeprecatedHookHandler((name, source) => fileEmitter.emitFile({ type: 'asset', name, source }), 'emitAsset', 'emitFile', plugin.name, false),
11942 emitChunk: getDeprecatedHookHandler((id, options) => fileEmitter.emitFile({ type: 'chunk', id, name: options && options.name }), 'emitChunk', 'emitFile', plugin.name, false),
11943 emitFile: fileEmitter.emitFile,
11944 error(err) {
11945 return throwPluginError(err, plugin.name);
11946 },
11947 getAssetFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getAssetFileName', 'getFileName', plugin.name, false),
11948 getChunkFileName: getDeprecatedHookHandler(fileEmitter.getFileName, 'getChunkFileName', 'getFileName', plugin.name, false),
11949 getFileName: fileEmitter.getFileName,
11950 getModuleInfo(moduleId) {
11951 const foundModule = graph.moduleById.get(moduleId);
11952 if (foundModule == null) {
11953 throw new Error(`Unable to find module ${moduleId}`);
11954 }
11955 return {
11956 hasModuleSideEffects: foundModule.moduleSideEffects,
11957 id: foundModule.id,
11958 importedIds: foundModule instanceof ExternalModule
11959 ? []
11960 : foundModule.sources.map(id => foundModule.resolvedIds[id].id),
11961 isEntry: foundModule instanceof Module && foundModule.isEntryPoint,
11962 isExternal: foundModule instanceof ExternalModule
11963 };
11964 },
11965 isExternal: getDeprecatedHookHandler((id, parentId, isResolved = false) => graph.moduleLoader.isExternal(id, parentId, isResolved), 'isExternal', 'resolve', plugin.name, false),
11966 meta: {
11967 rollupVersion: index.version
11968 },
11969 get moduleIds() {
11970 return graph.moduleById.keys();
11971 },
11972 parse: graph.contextParse,
11973 resolve(source, importer, options) {
11974 return graph.moduleLoader.resolveId(source, importer, options && options.skipSelf ? pidx : null);
11975 },
11976 resolveId: getDeprecatedHookHandler((source, importer) => graph.moduleLoader
11977 .resolveId(source, importer)
11978 .then(resolveId => resolveId && resolveId.id), 'resolveId', 'resolve', plugin.name, false),
11979 setAssetSource: fileEmitter.setAssetSource,
11980 warn(warning) {
11981 if (typeof warning === 'string')
11982 warning = { message: warning };
11983 if (warning.code)
11984 warning.pluginCode = warning.code;
11985 warning.code = 'PLUGIN_WARNING';
11986 warning.plugin = plugin.name;
11987 graph.warn(warning);
11988 },
11989 watcher: watcher
11990 ? (() => {
11991 let deprecationWarningShown = false;
11992 function deprecatedWatchListener(event, handler) {
11993 if (!deprecationWarningShown) {
11994 context.warn({
11995 code: 'PLUGIN_WATCHER_DEPRECATED',
11996 message: `this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead.`
11997 });
11998 deprecationWarningShown = true;
11999 }
12000 return watcher.on(event, handler);
12001 }
12002 return Object.assign(Object.assign({}, watcher), { addListener: deprecatedWatchListener, on: deprecatedWatchListener });
12003 })()
12004 : undefined
12005 };
12006 return context;
12007 });
12008 function runHookSync(hookName, args, pluginIndex, permitValues = false, hookContext) {
12009 const plugin = plugins[pluginIndex];
12010 let context = pluginContexts[pluginIndex];
12011 const hook = plugin[hookName];
12012 if (!hook)
12013 return undefined;
12014 if (hookContext) {
12015 context = hookContext(context, plugin);
12016 if (!context || context === pluginContexts[pluginIndex])
12017 throw new Error('Internal Rollup error: hookContext must return a new context object.');
12018 }
12019 try {
12020 // permit values allows values to be returned instead of a functional hook
12021 if (typeof hook !== 'function') {
12022 if (permitValues)
12023 return hook;
12024 error({
12025 code: 'INVALID_PLUGIN_HOOK',
12026 message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
12027 });
12028 }
12029 return hook.apply(context, args);
12030 }
12031 catch (err) {
12032 return throwPluginError(err, plugin.name, { hook: hookName });
12033 }
12034 }
12035 function runHook(hookName, args, pluginIndex, permitValues = false, hookContext) {
12036 const plugin = plugins[pluginIndex];
12037 let context = pluginContexts[pluginIndex];
12038 const hook = plugin[hookName];
12039 if (!hook)
12040 return undefined;
12041 if (hookContext) {
12042 context = hookContext(context, plugin);
12043 if (!context || context === pluginContexts[pluginIndex])
12044 throw new Error('Internal Rollup error: hookContext must return a new context object.');
12045 }
12046 return Promise.resolve()
12047 .then(() => {
12048 // permit values allows values to be returned instead of a functional hook
12049 if (typeof hook !== 'function') {
12050 if (permitValues)
12051 return hook;
12052 error({
12053 code: 'INVALID_PLUGIN_HOOK',
12054 message: `Error running plugin hook ${hookName} for ${plugin.name}, expected a function hook.`
12055 });
12056 }
12057 return hook.apply(context, args);
12058 })
12059 .catch(err => throwPluginError(err, plugin.name, { hook: hookName }));
12060 }
12061 const pluginDriver = {
12062 emitFile: fileEmitter.emitFile,
12063 finaliseAssets() {
12064 fileEmitter.assertAssetsFinalized();
12065 },
12066 getFileName: fileEmitter.getFileName,
12067 // chains, ignores returns
12068 hookSeq(name, args, hookContext) {
12069 let promise = Promise.resolve();
12070 for (let i = 0; i < plugins.length; i++)
12071 promise = promise.then(() => runHook(name, args, i, false, hookContext));
12072 return promise;
12073 },
12074 // chains, ignores returns
12075 hookSeqSync(name, args, hookContext) {
12076 for (let i = 0; i < plugins.length; i++)
12077 runHookSync(name, args, i, false, hookContext);
12078 },
12079 // chains, first non-null result stops and returns
12080 hookFirst(name, args, hookContext, skip) {
12081 let promise = Promise.resolve();
12082 for (let i = 0; i < plugins.length; i++) {
12083 if (skip === i)
12084 continue;
12085 promise = promise.then((result) => {
12086 if (result != null)
12087 return result;
12088 return runHook(name, args, i, false, hookContext);
12089 });
12090 }
12091 return promise;
12092 },
12093 // chains synchronously, first non-null result stops and returns
12094 hookFirstSync(name, args, hookContext) {
12095 for (let i = 0; i < plugins.length; i++) {
12096 const result = runHookSync(name, args, i, false, hookContext);
12097 if (result != null)
12098 return result;
12099 }
12100 return null;
12101 },
12102 // parallel, ignores returns
12103 hookParallel(name, args, hookContext) {
12104 const promises = [];
12105 for (let i = 0; i < plugins.length; i++) {
12106 const hookPromise = runHook(name, args, i, false, hookContext);
12107 if (!hookPromise)
12108 continue;
12109 promises.push(hookPromise);
12110 }
12111 return Promise.all(promises).then(() => { });
12112 },
12113 // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument
12114 hookReduceArg0(name, [arg0, ...args], reduce, hookContext) {
12115 let promise = Promise.resolve(arg0);
12116 for (let i = 0; i < plugins.length; i++) {
12117 promise = promise.then(arg0 => {
12118 const hookPromise = runHook(name, [arg0, ...args], i, false, hookContext);
12119 if (!hookPromise)
12120 return arg0;
12121 return hookPromise.then((result) => reduce.call(pluginContexts[i], arg0, result, plugins[i]));
12122 });
12123 }
12124 return promise;
12125 },
12126 // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument
12127 hookReduceArg0Sync(name, [arg0, ...args], reduce, hookContext) {
12128 for (let i = 0; i < plugins.length; i++) {
12129 const result = runHookSync(name, [arg0, ...args], i, false, hookContext);
12130 arg0 = reduce.call(pluginContexts[i], arg0, result, plugins[i]);
12131 }
12132 return arg0;
12133 },
12134 // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
12135 hookReduceValue(name, initial, args, reduce, hookContext) {
12136 let promise = Promise.resolve(initial);
12137 for (let i = 0; i < plugins.length; i++) {
12138 promise = promise.then(value => {
12139 const hookPromise = runHook(name, args, i, true, hookContext);
12140 if (!hookPromise)
12141 return value;
12142 return hookPromise.then((result) => reduce.call(pluginContexts[i], value, result, plugins[i]));
12143 });
12144 }
12145 return promise;
12146 },
12147 // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
12148 hookReduceValueSync(name, initial, args, reduce, hookContext) {
12149 let acc = initial;
12150 for (let i = 0; i < plugins.length; i++) {
12151 const result = runHookSync(name, args, i, true, hookContext);
12152 acc = reduce.call(pluginContexts[i], acc, result, plugins[i]);
12153 }
12154 return acc;
12155 },
12156 startOutput(outputBundle, assetFileNames) {
12157 fileEmitter.startOutput(outputBundle, assetFileNames);
12158 }
12159 };
12160 return pluginDriver;
12161}
12162function createPluginCache(cache) {
12163 return {
12164 has(id) {
12165 const item = cache[id];
12166 if (!item)
12167 return false;
12168 item[0] = 0;
12169 return true;
12170 },
12171 get(id) {
12172 const item = cache[id];
12173 if (!item)
12174 return undefined;
12175 item[0] = 0;
12176 return item[1];
12177 },
12178 set(id, value) {
12179 cache[id] = [0, value];
12180 },
12181 delete(id) {
12182 return delete cache[id];
12183 }
12184 };
12185}
12186function trackPluginCache(pluginCache) {
12187 const result = { used: false, cache: undefined };
12188 result.cache = {
12189 has(id) {
12190 result.used = true;
12191 return pluginCache.has(id);
12192 },
12193 get(id) {
12194 result.used = true;
12195 return pluginCache.get(id);
12196 },
12197 set(id, value) {
12198 result.used = true;
12199 return pluginCache.set(id, value);
12200 },
12201 delete(id) {
12202 result.used = true;
12203 return pluginCache.delete(id);
12204 }
12205 };
12206 return result;
12207}
12208const noCache = {
12209 has() {
12210 return false;
12211 },
12212 get() {
12213 return undefined;
12214 },
12215 set() { },
12216 delete() {
12217 return false;
12218 }
12219};
12220function uncacheablePluginError(pluginName) {
12221 if (pluginName.startsWith(ANONYMOUS_PLUGIN_PREFIX))
12222 error({
12223 code: 'ANONYMOUS_PLUGIN_CACHE',
12224 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
12225 });
12226 else
12227 error({
12228 code: 'DUPLICATE_PLUGIN_NAME',
12229 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).`
12230 });
12231}
12232const uncacheablePlugin = pluginName => ({
12233 has() {
12234 uncacheablePluginError(pluginName);
12235 return false;
12236 },
12237 get() {
12238 uncacheablePluginError(pluginName);
12239 return undefined;
12240 },
12241 set() {
12242 uncacheablePluginError(pluginName);
12243 },
12244 delete() {
12245 uncacheablePluginError(pluginName);
12246 return false;
12247 }
12248});
12249
12250function transform(graph, source, module) {
12251 const id = module.id;
12252 const sourcemapChain = [];
12253 let originalSourcemap = source.map === null ? null : decodedSourcemap(source.map);
12254 const originalCode = source.code;
12255 let ast = source.ast;
12256 const transformDependencies = [];
12257 const emittedFiles = [];
12258 let customTransformCache = false;
12259 let moduleSideEffects = null;
12260 let trackedPluginCache;
12261 let curPlugin;
12262 const curSource = source.code;
12263 function transformReducer(code, result, plugin) {
12264 // track which plugins use the custom this.cache to opt-out of transform caching
12265 if (!customTransformCache && trackedPluginCache.used)
12266 customTransformCache = true;
12267 if (customTransformCache) {
12268 if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
12269 for (const dep of result.dependencies) {
12270 graph.watchFiles[path.resolve(path.dirname(id), dep)] = true;
12271 }
12272 }
12273 }
12274 else {
12275 // files emitted by a transform hook need to be emitted again if the hook is skipped
12276 if (emittedFiles.length)
12277 module.transformFiles = emittedFiles;
12278 if (result && typeof result === 'object' && Array.isArray(result.dependencies)) {
12279 // not great, but a useful way to track this without assuming WeakMap
12280 if (!curPlugin.warnedTransformDependencies)
12281 graph.warnDeprecation(`Returning "dependencies" from the "transform" hook as done by plugin ${plugin.name} is deprecated. The "this.addWatchFile" plugin context function should be used instead.`, true);
12282 curPlugin.warnedTransformDependencies = true;
12283 for (const dep of result.dependencies)
12284 transformDependencies.push(path.resolve(path.dirname(id), dep));
12285 }
12286 }
12287 if (typeof result === 'string') {
12288 result = {
12289 ast: undefined,
12290 code: result,
12291 map: undefined
12292 };
12293 }
12294 else if (result && typeof result === 'object') {
12295 if (typeof result.map === 'string') {
12296 result.map = JSON.parse(result.map);
12297 }
12298 if (typeof result.moduleSideEffects === 'boolean') {
12299 moduleSideEffects = result.moduleSideEffects;
12300 }
12301 }
12302 else {
12303 return code;
12304 }
12305 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
12306 if (result.map !== null) {
12307 const map = decodedSourcemap(result.map);
12308 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
12309 }
12310 ast = result.ast;
12311 return result.code;
12312 }
12313 let setAssetSourceErr;
12314 return graph.pluginDriver
12315 .hookReduceArg0('transform', [curSource, id], transformReducer, (pluginContext, plugin) => {
12316 curPlugin = plugin;
12317 if (curPlugin.cacheKey)
12318 customTransformCache = true;
12319 else
12320 trackedPluginCache = trackPluginCache(pluginContext.cache);
12321 return Object.assign(Object.assign({}, pluginContext), { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn(warning, pos) {
12322 if (typeof warning === 'string')
12323 warning = { message: warning };
12324 if (pos)
12325 augmentCodeLocation(warning, pos, curSource, id);
12326 warning.id = id;
12327 warning.hook = 'transform';
12328 pluginContext.warn(warning);
12329 },
12330 error(err, pos) {
12331 if (typeof err === 'string')
12332 err = { message: err };
12333 if (pos)
12334 augmentCodeLocation(err, pos, curSource, id);
12335 err.id = id;
12336 err.hook = 'transform';
12337 return pluginContext.error(err);
12338 },
12339 emitAsset(name, source) {
12340 const emittedFile = { type: 'asset', name, source };
12341 emittedFiles.push(Object.assign({}, emittedFile));
12342 return graph.pluginDriver.emitFile(emittedFile);
12343 },
12344 emitChunk(id, options) {
12345 const emittedFile = { type: 'chunk', id, name: options && options.name };
12346 emittedFiles.push(Object.assign({}, emittedFile));
12347 return graph.pluginDriver.emitFile(emittedFile);
12348 },
12349 emitFile(emittedFile) {
12350 emittedFiles.push(emittedFile);
12351 return graph.pluginDriver.emitFile(emittedFile);
12352 },
12353 addWatchFile(id) {
12354 transformDependencies.push(id);
12355 pluginContext.addWatchFile(id);
12356 },
12357 setAssetSource(assetReferenceId, source) {
12358 pluginContext.setAssetSource(assetReferenceId, source);
12359 if (!customTransformCache && !setAssetSourceErr) {
12360 try {
12361 this.error({
12362 code: 'INVALID_SETASSETSOURCE',
12363 message: `setAssetSource cannot be called in transform for caching reasons. Use emitFile with a source, or call setAssetSource in another hook.`
12364 });
12365 }
12366 catch (err) {
12367 setAssetSourceErr = err;
12368 }
12369 }
12370 },
12371 getCombinedSourcemap() {
12372 const combinedMap = collapseSourcemap(graph, id, originalCode, originalSourcemap, sourcemapChain);
12373 if (!combinedMap) {
12374 const magicString = new MagicString(originalCode);
12375 return magicString.generateMap({ includeContent: true, hires: true, source: id });
12376 }
12377 if (originalSourcemap !== combinedMap) {
12378 originalSourcemap = combinedMap;
12379 sourcemapChain.length = 0;
12380 }
12381 return new SourceMap(Object.assign(Object.assign({}, combinedMap), { file: null, sourcesContent: combinedMap.sourcesContent }));
12382 } });
12383 })
12384 .catch(err => throwPluginError(err, curPlugin.name, { hook: 'transform', id }))
12385 .then(code => {
12386 if (!customTransformCache && setAssetSourceErr)
12387 throw setAssetSourceErr;
12388 return {
12389 ast: ast,
12390 code,
12391 customTransformCache,
12392 moduleSideEffects,
12393 originalCode,
12394 originalSourcemap,
12395 sourcemapChain,
12396 transformDependencies
12397 };
12398 });
12399}
12400
12401function normalizeRelativeExternalId(importer, source) {
12402 return index.isRelative(source) ? path.resolve(importer, '..', source) : source;
12403}
12404function getIdMatcher(option) {
12405 if (option === true) {
12406 return () => true;
12407 }
12408 if (typeof option === 'function') {
12409 return (id, ...args) => (!id.startsWith('\0') && option(id, ...args)) || false;
12410 }
12411 if (option) {
12412 const ids = new Set(Array.isArray(option) ? option : option ? [option] : []);
12413 return (id => ids.has(id));
12414 }
12415 return () => false;
12416}
12417function getHasModuleSideEffects(moduleSideEffectsOption, pureExternalModules, graph) {
12418 if (typeof moduleSideEffectsOption === 'boolean') {
12419 return () => moduleSideEffectsOption;
12420 }
12421 if (moduleSideEffectsOption === 'no-external') {
12422 return (_id, external) => !external;
12423 }
12424 if (typeof moduleSideEffectsOption === 'function') {
12425 return (id, external) => !id.startsWith('\0') ? moduleSideEffectsOption(id, external) !== false : true;
12426 }
12427 if (Array.isArray(moduleSideEffectsOption)) {
12428 const ids = new Set(moduleSideEffectsOption);
12429 return id => ids.has(id);
12430 }
12431 if (moduleSideEffectsOption) {
12432 graph.warn(errInvalidOption('treeshake.moduleSideEffects', 'please use one of false, "no-external", a function or an array'));
12433 }
12434 const isPureExternalModule = getIdMatcher(pureExternalModules);
12435 return (id, external) => !(external && isPureExternalModule(id));
12436}
12437class ModuleLoader {
12438 constructor(graph, modulesById, pluginDriver, external, getManualChunk, moduleSideEffects, pureExternalModules) {
12439 this.indexedEntryModules = [];
12440 this.latestLoadModulesPromise = Promise.resolve();
12441 this.manualChunkModules = {};
12442 this.nextEntryModuleIndex = 0;
12443 this.loadEntryModule = (unresolvedId, isEntry) => this.pluginDriver.hookFirst('resolveId', [unresolvedId, undefined]).then(resolveIdResult => {
12444 if (resolveIdResult === false ||
12445 (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external)) {
12446 return error(errEntryCannotBeExternal(unresolvedId));
12447 }
12448 const id = resolveIdResult && typeof resolveIdResult === 'object'
12449 ? resolveIdResult.id
12450 : resolveIdResult;
12451 if (typeof id === 'string') {
12452 return this.fetchModule(id, undefined, true, isEntry);
12453 }
12454 return error(errUnresolvedEntry(unresolvedId));
12455 });
12456 this.graph = graph;
12457 this.modulesById = modulesById;
12458 this.pluginDriver = pluginDriver;
12459 this.isExternal = getIdMatcher(external);
12460 this.hasModuleSideEffects = getHasModuleSideEffects(moduleSideEffects, pureExternalModules, graph);
12461 this.getManualChunk = typeof getManualChunk === 'function' ? getManualChunk : () => null;
12462 }
12463 addEntryModules(unresolvedEntryModules, isUserDefined) {
12464 const firstEntryModuleIndex = this.nextEntryModuleIndex;
12465 this.nextEntryModuleIndex += unresolvedEntryModules.length;
12466 const loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(({ fileName, id, name }) => this.loadEntryModule(id, true).then(module => {
12467 if (fileName !== null) {
12468 module.chunkFileNames.add(fileName);
12469 }
12470 else if (name !== null) {
12471 if (module.chunkName === null) {
12472 module.chunkName = name;
12473 }
12474 if (isUserDefined) {
12475 module.userChunkNames.add(name);
12476 }
12477 }
12478 return module;
12479 }))).then(entryModules => {
12480 let moduleIndex = firstEntryModuleIndex;
12481 for (const entryModule of entryModules) {
12482 entryModule.isUserDefinedEntryPoint = entryModule.isUserDefinedEntryPoint || isUserDefined;
12483 const existingIndexModule = this.indexedEntryModules.find(indexedModule => indexedModule.module.id === entryModule.id);
12484 if (!existingIndexModule) {
12485 this.indexedEntryModules.push({ module: entryModule, index: moduleIndex });
12486 }
12487 else {
12488 existingIndexModule.index = Math.min(existingIndexModule.index, moduleIndex);
12489 }
12490 moduleIndex++;
12491 }
12492 this.indexedEntryModules.sort(({ index: indexA }, { index: indexB }) => indexA > indexB ? 1 : -1);
12493 return entryModules;
12494 });
12495 return this.awaitLoadModulesPromise(loadNewEntryModulesPromise).then(newEntryModules => ({
12496 entryModules: this.indexedEntryModules.map(({ module }) => module),
12497 manualChunkModulesByAlias: this.manualChunkModules,
12498 newEntryModules
12499 }));
12500 }
12501 addManualChunks(manualChunks) {
12502 const unresolvedManualChunks = [];
12503 for (const alias of Object.keys(manualChunks)) {
12504 const manualChunkIds = manualChunks[alias];
12505 for (const id of manualChunkIds) {
12506 unresolvedManualChunks.push({ id, alias });
12507 }
12508 }
12509 const loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(({ id }) => this.loadEntryModule(id, false))).then(manualChunkModules => {
12510 for (let index = 0; index < manualChunkModules.length; index++) {
12511 this.addModuleToManualChunk(unresolvedManualChunks[index].alias, manualChunkModules[index]);
12512 }
12513 });
12514 return this.awaitLoadModulesPromise(loadNewManualChunkModulesPromise);
12515 }
12516 resolveId(source, importer, skip) {
12517 return __awaiter(this, void 0, void 0, function* () {
12518 return this.normalizeResolveIdResult(this.isExternal(source, importer, false)
12519 ? false
12520 : yield this.pluginDriver.hookFirst('resolveId', [source, importer], null, skip), importer, source);
12521 });
12522 }
12523 addModuleToManualChunk(alias, module) {
12524 if (module.manualChunkAlias !== null && module.manualChunkAlias !== alias) {
12525 error(errCannotAssignModuleToChunk(module.id, alias, module.manualChunkAlias));
12526 }
12527 module.manualChunkAlias = alias;
12528 if (!this.manualChunkModules[alias]) {
12529 this.manualChunkModules[alias] = [];
12530 }
12531 this.manualChunkModules[alias].push(module);
12532 }
12533 awaitLoadModulesPromise(loadNewModulesPromise) {
12534 this.latestLoadModulesPromise = Promise.all([
12535 loadNewModulesPromise,
12536 this.latestLoadModulesPromise
12537 ]);
12538 const getCombinedPromise = () => {
12539 const startingPromise = this.latestLoadModulesPromise;
12540 return startingPromise.then(() => {
12541 if (this.latestLoadModulesPromise !== startingPromise) {
12542 return getCombinedPromise();
12543 }
12544 });
12545 };
12546 return getCombinedPromise().then(() => loadNewModulesPromise);
12547 }
12548 fetchAllDependencies(module) {
12549 const fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map((specifier, index$1) => this.resolveDynamicImport(module, specifier, module.id).then(resolvedId => {
12550 if (resolvedId === null)
12551 return;
12552 const dynamicImport = module.dynamicImports[index$1];
12553 if (typeof resolvedId === 'string') {
12554 dynamicImport.resolution = resolvedId;
12555 return;
12556 }
12557 return this.fetchResolvedDependency(index.relativeId(resolvedId.id), module.id, resolvedId).then(module => {
12558 dynamicImport.resolution = module;
12559 });
12560 })));
12561 fetchDynamicImportsPromise.catch(() => { });
12562 return Promise.all(module.sources.map(source => this.resolveAndFetchDependency(module, source))).then(() => fetchDynamicImportsPromise);
12563 }
12564 fetchModule(id, importer, moduleSideEffects, isEntry) {
12565 const existingModule = this.modulesById.get(id);
12566 if (existingModule) {
12567 if (existingModule instanceof ExternalModule)
12568 throw new Error(`Cannot fetch external module ${id}`);
12569 existingModule.isEntryPoint = existingModule.isEntryPoint || isEntry;
12570 return Promise.resolve(existingModule);
12571 }
12572 const module = new Module(this.graph, id, moduleSideEffects, isEntry);
12573 this.modulesById.set(id, module);
12574 this.graph.watchFiles[id] = true;
12575 const manualChunkAlias = this.getManualChunk(id);
12576 if (typeof manualChunkAlias === 'string') {
12577 this.addModuleToManualChunk(manualChunkAlias, module);
12578 }
12579 timeStart('load modules', 3);
12580 return Promise.resolve(this.pluginDriver.hookFirst('load', [id]))
12581 .catch((err) => {
12582 timeEnd('load modules', 3);
12583 let msg = `Could not load ${id}`;
12584 if (importer)
12585 msg += ` (imported by ${importer})`;
12586 msg += `: ${err.message}`;
12587 err.message = msg;
12588 throw err;
12589 })
12590 .then(source => {
12591 timeEnd('load modules', 3);
12592 if (typeof source === 'string')
12593 return { code: source };
12594 if (source && typeof source === 'object' && typeof source.code === 'string')
12595 return source;
12596 return error(errBadLoader(id));
12597 })
12598 .then(sourceDescription => {
12599 const cachedModule = this.graph.cachedModules.get(id);
12600 if (cachedModule &&
12601 !cachedModule.customTransformCache &&
12602 cachedModule.originalCode === sourceDescription.code) {
12603 if (cachedModule.transformFiles) {
12604 for (const emittedFile of cachedModule.transformFiles)
12605 this.pluginDriver.emitFile(emittedFile);
12606 }
12607 return cachedModule;
12608 }
12609 if (typeof sourceDescription.moduleSideEffects === 'boolean') {
12610 module.moduleSideEffects = sourceDescription.moduleSideEffects;
12611 }
12612 return transform(this.graph, sourceDescription, module);
12613 })
12614 .then((source) => {
12615 module.setSource(source);
12616 this.modulesById.set(id, module);
12617 return this.fetchAllDependencies(module).then(() => {
12618 for (const name in module.exports) {
12619 if (name !== 'default') {
12620 module.exportsAll[name] = module.id;
12621 }
12622 }
12623 module.exportAllSources.forEach(source => {
12624 const id = module.resolvedIds[source].id;
12625 const exportAllModule = this.modulesById.get(id);
12626 if (exportAllModule instanceof ExternalModule)
12627 return;
12628 for (const name in exportAllModule.exportsAll) {
12629 if (name in module.exportsAll) {
12630 this.graph.warn(errNamespaceConflict(name, module, exportAllModule));
12631 }
12632 else {
12633 module.exportsAll[name] = exportAllModule.exportsAll[name];
12634 }
12635 }
12636 });
12637 return module;
12638 });
12639 });
12640 }
12641 fetchResolvedDependency(source, importer, resolvedId) {
12642 if (resolvedId.external) {
12643 if (!this.modulesById.has(resolvedId.id)) {
12644 this.modulesById.set(resolvedId.id, new ExternalModule(this.graph, resolvedId.id, resolvedId.moduleSideEffects));
12645 }
12646 const externalModule = this.modulesById.get(resolvedId.id);
12647 if (!(externalModule instanceof ExternalModule)) {
12648 return error(errInternalIdCannotBeExternal(source, importer));
12649 }
12650 return Promise.resolve(externalModule);
12651 }
12652 else {
12653 return this.fetchModule(resolvedId.id, importer, resolvedId.moduleSideEffects, false);
12654 }
12655 }
12656 handleMissingImports(resolvedId, source, importer) {
12657 if (resolvedId === null) {
12658 if (index.isRelative(source)) {
12659 error(errUnresolvedImport(source, importer));
12660 }
12661 this.graph.warn(errUnresolvedImportTreatedAsExternal(source, importer));
12662 return {
12663 external: true,
12664 id: source,
12665 moduleSideEffects: this.hasModuleSideEffects(source, true)
12666 };
12667 }
12668 return resolvedId;
12669 }
12670 normalizeResolveIdResult(resolveIdResult, importer, source) {
12671 let id = '';
12672 let external = false;
12673 let moduleSideEffects = null;
12674 if (resolveIdResult) {
12675 if (typeof resolveIdResult === 'object') {
12676 id = resolveIdResult.id;
12677 if (resolveIdResult.external) {
12678 external = true;
12679 }
12680 if (typeof resolveIdResult.moduleSideEffects === 'boolean') {
12681 moduleSideEffects = resolveIdResult.moduleSideEffects;
12682 }
12683 }
12684 else {
12685 if (this.isExternal(resolveIdResult, importer, true)) {
12686 external = true;
12687 }
12688 id = external ? normalizeRelativeExternalId(importer, resolveIdResult) : resolveIdResult;
12689 }
12690 }
12691 else {
12692 id = normalizeRelativeExternalId(importer, source);
12693 if (resolveIdResult !== false && !this.isExternal(id, importer, true)) {
12694 return null;
12695 }
12696 external = true;
12697 }
12698 return {
12699 external,
12700 id,
12701 moduleSideEffects: typeof moduleSideEffects === 'boolean'
12702 ? moduleSideEffects
12703 : this.hasModuleSideEffects(id, external)
12704 };
12705 }
12706 resolveAndFetchDependency(module, source) {
12707 return __awaiter(this, void 0, void 0, function* () {
12708 return this.fetchResolvedDependency(source, module.id, (module.resolvedIds[source] =
12709 module.resolvedIds[source] ||
12710 this.handleMissingImports(yield this.resolveId(source, module.id), source, module.id)));
12711 });
12712 }
12713 resolveDynamicImport(module, specifier, importer) {
12714 return __awaiter(this, void 0, void 0, function* () {
12715 // TODO we only should expose the acorn AST here
12716 const resolution = yield this.pluginDriver.hookFirst('resolveDynamicImport', [
12717 specifier,
12718 importer
12719 ]);
12720 if (typeof specifier !== 'string') {
12721 if (typeof resolution === 'string') {
12722 return resolution;
12723 }
12724 if (!resolution) {
12725 return null;
12726 }
12727 return Object.assign({ external: false, moduleSideEffects: true }, resolution);
12728 }
12729 if (resolution == null) {
12730 return (module.resolvedIds[specifier] =
12731 module.resolvedIds[specifier] ||
12732 this.handleMissingImports(yield this.resolveId(specifier, module.id), specifier, module.id));
12733 }
12734 return this.handleMissingImports(this.normalizeResolveIdResult(resolution, importer, specifier), specifier, importer);
12735 });
12736 }
12737}
12738
12739const CHAR_CODE_A = 97;
12740const CHAR_CODE_0 = 48;
12741function intToHex(num) {
12742 if (num < 10)
12743 return String.fromCharCode(CHAR_CODE_0 + num);
12744 else
12745 return String.fromCharCode(CHAR_CODE_A + (num - 10));
12746}
12747function Uint8ArrayToHexString(buffer) {
12748 let str = '';
12749 // hex conversion - 2 chars per 8 bit component
12750 for (let i = 0; i < buffer.length; i++) {
12751 const num = buffer[i];
12752 // big endian conversion, but whatever
12753 str += intToHex(num >> 4);
12754 str += intToHex(num & 0xf);
12755 }
12756 return str;
12757}
12758function Uint8ArrayXor(to, from) {
12759 for (let i = 0; i < to.length; i++)
12760 to[i] = to[i] ^ from[i];
12761 return to;
12762}
12763function randomUint8Array(len) {
12764 const buffer = new Uint8Array(len);
12765 for (let i = 0; i < buffer.length; i++)
12766 buffer[i] = Math.random() * (2 << 8);
12767 return buffer;
12768}
12769
12770function assignChunkColouringHashes(entryModules, manualChunkModules) {
12771 let currentEntry, currentEntryHash;
12772 let modulesVisitedForCurrentEntry;
12773 const handledEntryPoints = new Set();
12774 const dynamicImports = [];
12775 const addCurrentEntryColourToModule = (module) => {
12776 if (currentEntry.manualChunkAlias) {
12777 module.manualChunkAlias = currentEntry.manualChunkAlias;
12778 module.entryPointsHash = currentEntryHash;
12779 }
12780 else {
12781 Uint8ArrayXor(module.entryPointsHash, currentEntryHash);
12782 }
12783 for (const dependency of module.dependencies) {
12784 if (dependency instanceof ExternalModule ||
12785 modulesVisitedForCurrentEntry.has(dependency.id)) {
12786 continue;
12787 }
12788 modulesVisitedForCurrentEntry.add(dependency.id);
12789 if (!handledEntryPoints.has(dependency.id) && !dependency.manualChunkAlias) {
12790 addCurrentEntryColourToModule(dependency);
12791 }
12792 }
12793 for (const { resolution } of module.dynamicImports) {
12794 if (resolution instanceof Module &&
12795 resolution.dynamicallyImportedBy.length > 0 &&
12796 !resolution.manualChunkAlias) {
12797 dynamicImports.push(resolution);
12798 }
12799 }
12800 };
12801 if (manualChunkModules) {
12802 for (const chunkName of Object.keys(manualChunkModules)) {
12803 currentEntryHash = randomUint8Array(10);
12804 for (currentEntry of manualChunkModules[chunkName]) {
12805 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
12806 addCurrentEntryColourToModule(currentEntry);
12807 }
12808 }
12809 }
12810 for (currentEntry of entryModules) {
12811 handledEntryPoints.add(currentEntry.id);
12812 currentEntryHash = randomUint8Array(10);
12813 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
12814 if (!currentEntry.manualChunkAlias) {
12815 addCurrentEntryColourToModule(currentEntry);
12816 }
12817 }
12818 for (currentEntry of dynamicImports) {
12819 if (handledEntryPoints.has(currentEntry.id)) {
12820 continue;
12821 }
12822 handledEntryPoints.add(currentEntry.id);
12823 currentEntryHash = randomUint8Array(10);
12824 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
12825 addCurrentEntryColourToModule(currentEntry);
12826 }
12827}
12828
12829function makeOnwarn() {
12830 const warned = Object.create(null);
12831 return (warning) => {
12832 const str = warning.toString();
12833 if (str in warned)
12834 return;
12835 console.error(str);
12836 warned[str] = true;
12837 };
12838}
12839function normalizeEntryModules(entryModules) {
12840 if (typeof entryModules === 'string') {
12841 return [{ fileName: null, name: null, id: entryModules }];
12842 }
12843 if (Array.isArray(entryModules)) {
12844 return entryModules.map(id => ({ fileName: null, name: null, id }));
12845 }
12846 return Object.keys(entryModules).map(name => ({
12847 fileName: null,
12848 id: entryModules[name],
12849 name
12850 }));
12851}
12852class Graph {
12853 constructor(options, watcher) {
12854 this.moduleById = new Map();
12855 this.needsTreeshakingPass = false;
12856 this.phase = BuildPhase.LOAD_AND_PARSE;
12857 this.watchFiles = Object.create(null);
12858 this.externalModules = [];
12859 this.modules = [];
12860 this.onwarn = options.onwarn || makeOnwarn();
12861 this.deoptimizationTracker = new PathTracker();
12862 this.cachedModules = new Map();
12863 if (options.cache) {
12864 if (options.cache.modules)
12865 for (const module of options.cache.modules)
12866 this.cachedModules.set(module.id, module);
12867 }
12868 if (options.cache !== false) {
12869 this.pluginCache = (options.cache && options.cache.plugins) || Object.create(null);
12870 // increment access counter
12871 for (const name in this.pluginCache) {
12872 const cache = this.pluginCache[name];
12873 for (const key of Object.keys(cache))
12874 cache[key][0]++;
12875 }
12876 }
12877 this.preserveModules = options.preserveModules;
12878 this.strictDeprecations = options.strictDeprecations;
12879 this.cacheExpiry = options.experimentalCacheExpiry;
12880 if (options.treeshake !== false) {
12881 this.treeshakingOptions = options.treeshake
12882 ? {
12883 annotations: options.treeshake.annotations !== false,
12884 moduleSideEffects: options.treeshake.moduleSideEffects,
12885 propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
12886 pureExternalModules: options.treeshake.pureExternalModules,
12887 tryCatchDeoptimization: options.treeshake.tryCatchDeoptimization !== false,
12888 unknownGlobalSideEffects: options.treeshake.unknownGlobalSideEffects !== false
12889 }
12890 : {
12891 annotations: true,
12892 moduleSideEffects: true,
12893 propertyReadSideEffects: true,
12894 tryCatchDeoptimization: true,
12895 unknownGlobalSideEffects: true
12896 };
12897 if (typeof this.treeshakingOptions.pureExternalModules !== 'undefined') {
12898 this.warnDeprecation(`The "treeshake.pureExternalModules" option is deprecated. The "treeshake.moduleSideEffects" option should be used instead. "treeshake.pureExternalModules: true" is equivalent to "treeshake.moduleSideEffects: 'no-external'"`, false);
12899 }
12900 }
12901 this.contextParse = (code, options = {}) => this.acornParser.parse(code, Object.assign(Object.assign(Object.assign({}, defaultAcornOptions), options), this.acornOptions));
12902 this.pluginDriver = createPluginDriver(this, options, this.pluginCache, watcher);
12903 if (watcher) {
12904 const handleChange = (id) => this.pluginDriver.hookSeqSync('watchChange', [id]);
12905 watcher.on('change', handleChange);
12906 watcher.once('restart', () => {
12907 watcher.removeListener('change', handleChange);
12908 });
12909 }
12910 this.shimMissingExports = options.shimMissingExports;
12911 this.scope = new GlobalScope();
12912 this.context = String(options.context);
12913 const optionsModuleContext = options.moduleContext;
12914 if (typeof optionsModuleContext === 'function') {
12915 this.getModuleContext = id => optionsModuleContext(id) || this.context;
12916 }
12917 else if (typeof optionsModuleContext === 'object') {
12918 const moduleContext = new Map();
12919 for (const key in optionsModuleContext) {
12920 moduleContext.set(path.resolve(key), optionsModuleContext[key]);
12921 }
12922 this.getModuleContext = id => moduleContext.get(id) || this.context;
12923 }
12924 else {
12925 this.getModuleContext = () => this.context;
12926 }
12927 this.acornOptions = options.acorn ? Object.assign({}, options.acorn) : {};
12928 const acornPluginsToInject = [];
12929 acornPluginsToInject.push(acornImportMeta);
12930 if (options.experimentalTopLevelAwait) {
12931 this.acornOptions.allowAwaitOutsideFunction = true;
12932 }
12933 const acornInjectPlugins = options.acornInjectPlugins;
12934 acornPluginsToInject.push(...(Array.isArray(acornInjectPlugins)
12935 ? acornInjectPlugins
12936 : acornInjectPlugins
12937 ? [acornInjectPlugins]
12938 : []));
12939 this.acornParser = acorn.Parser.extend(...acornPluginsToInject);
12940 this.moduleLoader = new ModuleLoader(this, this.moduleById, this.pluginDriver, options.external, (typeof options.manualChunks === 'function' && options.manualChunks), (this.treeshakingOptions
12941 ? this.treeshakingOptions.moduleSideEffects
12942 : null), (this.treeshakingOptions
12943 ? this.treeshakingOptions.pureExternalModules
12944 : false));
12945 }
12946 build(entryModules, manualChunks, inlineDynamicImports) {
12947 // Phase 1 – discovery. We load the entry module and find which
12948 // modules it imports, and import those, until we have all
12949 // of the entry module's dependencies
12950 timeStart('parse modules', 2);
12951 return Promise.all([
12952 this.moduleLoader.addEntryModules(normalizeEntryModules(entryModules), true),
12953 (manualChunks &&
12954 typeof manualChunks === 'object' &&
12955 this.moduleLoader.addManualChunks(manualChunks))
12956 ]).then(([{ entryModules, manualChunkModulesByAlias }]) => {
12957 if (entryModules.length === 0) {
12958 throw new Error('You must supply options.input to rollup');
12959 }
12960 for (const module of this.moduleById.values()) {
12961 if (module instanceof Module) {
12962 this.modules.push(module);
12963 }
12964 else {
12965 this.externalModules.push(module);
12966 }
12967 }
12968 timeEnd('parse modules', 2);
12969 this.phase = BuildPhase.ANALYSE;
12970 // Phase 2 - linking. We populate the module dependency links and
12971 // determine the topological execution order for the bundle
12972 timeStart('analyse dependency graph', 2);
12973 this.link(entryModules);
12974 timeEnd('analyse dependency graph', 2);
12975 // Phase 3 – marking. We include all statements that should be included
12976 timeStart('mark included statements', 2);
12977 if (inlineDynamicImports) {
12978 if (entryModules.length > 1) {
12979 throw new Error('Internal Error: can only inline dynamic imports for single-file builds.');
12980 }
12981 }
12982 for (const module of entryModules) {
12983 module.includeAllExports();
12984 }
12985 this.includeMarked(this.modules);
12986 // check for unused external imports
12987 for (const externalModule of this.externalModules)
12988 externalModule.warnUnusedImports();
12989 timeEnd('mark included statements', 2);
12990 // Phase 4 – we construct the chunks, working out the optimal chunking using
12991 // entry point graph colouring, before generating the import and export facades
12992 timeStart('generate chunks', 2);
12993 if (!this.preserveModules && !inlineDynamicImports) {
12994 assignChunkColouringHashes(entryModules, manualChunkModulesByAlias);
12995 }
12996 // TODO: there is one special edge case unhandled here and that is that any module
12997 // exposed as an unresolvable export * (to a graph external export *,
12998 // either as a namespace import reexported or top-level export *)
12999 // should be made to be its own entry point module before chunking
13000 let chunks = [];
13001 if (this.preserveModules) {
13002 for (const module of this.modules) {
13003 const chunk = new Chunk$1(this, [module]);
13004 if (module.isEntryPoint || !chunk.isEmpty) {
13005 chunk.entryModules = [module];
13006 }
13007 chunks.push(chunk);
13008 }
13009 }
13010 else {
13011 const chunkModules = {};
13012 for (const module of this.modules) {
13013 const entryPointsHashStr = Uint8ArrayToHexString(module.entryPointsHash);
13014 const curChunk = chunkModules[entryPointsHashStr];
13015 if (curChunk) {
13016 curChunk.push(module);
13017 }
13018 else {
13019 chunkModules[entryPointsHashStr] = [module];
13020 }
13021 }
13022 for (const entryHashSum in chunkModules) {
13023 const chunkModulesOrdered = chunkModules[entryHashSum];
13024 sortByExecutionOrder(chunkModulesOrdered);
13025 const chunk = new Chunk$1(this, chunkModulesOrdered);
13026 chunks.push(chunk);
13027 }
13028 }
13029 for (const chunk of chunks) {
13030 chunk.link();
13031 }
13032 chunks = chunks.filter(isChunkRendered);
13033 const facades = [];
13034 for (const chunk of chunks) {
13035 facades.push(...chunk.generateFacades());
13036 }
13037 timeEnd('generate chunks', 2);
13038 this.phase = BuildPhase.GENERATE;
13039 return chunks.concat(facades);
13040 });
13041 }
13042 getCache() {
13043 // handle plugin cache eviction
13044 for (const name in this.pluginCache) {
13045 const cache = this.pluginCache[name];
13046 let allDeleted = true;
13047 for (const key of Object.keys(cache)) {
13048 if (cache[key][0] >= this.cacheExpiry)
13049 delete cache[key];
13050 else
13051 allDeleted = false;
13052 }
13053 if (allDeleted)
13054 delete this.pluginCache[name];
13055 }
13056 return {
13057 modules: this.modules.map(module => module.toJSON()),
13058 plugins: this.pluginCache
13059 };
13060 }
13061 includeMarked(modules) {
13062 if (this.treeshakingOptions) {
13063 let treeshakingPass = 1;
13064 do {
13065 timeStart(`treeshaking pass ${treeshakingPass}`, 3);
13066 this.needsTreeshakingPass = false;
13067 for (const module of modules) {
13068 if (module.isExecuted)
13069 module.include();
13070 }
13071 timeEnd(`treeshaking pass ${treeshakingPass++}`, 3);
13072 } while (this.needsTreeshakingPass);
13073 }
13074 else {
13075 // Necessary to properly replace namespace imports
13076 for (const module of modules)
13077 module.includeAllInBundle();
13078 }
13079 }
13080 warn(warning) {
13081 warning.toString = () => {
13082 let str = '';
13083 if (warning.plugin)
13084 str += `(${warning.plugin} plugin) `;
13085 if (warning.loc)
13086 str += `${index.relativeId(warning.loc.file)} (${warning.loc.line}:${warning.loc.column}) `;
13087 str += warning.message;
13088 return str;
13089 };
13090 this.onwarn(warning);
13091 }
13092 warnDeprecation(deprecation, activeDeprecation) {
13093 if (activeDeprecation || this.strictDeprecations) {
13094 const warning = errDeprecation(deprecation);
13095 if (this.strictDeprecations) {
13096 return error(warning);
13097 }
13098 this.warn(warning);
13099 }
13100 }
13101 link(entryModules) {
13102 for (const module of this.modules) {
13103 module.linkDependencies();
13104 }
13105 const { orderedModules, cyclePaths } = analyseModuleExecution(entryModules);
13106 for (const cyclePath of cyclePaths) {
13107 this.warn({
13108 code: 'CIRCULAR_DEPENDENCY',
13109 importer: cyclePath[0],
13110 message: `Circular dependency: ${cyclePath.join(' -> ')}`
13111 });
13112 }
13113 this.modules = orderedModules;
13114 for (const module of this.modules) {
13115 module.bindReferences();
13116 }
13117 this.warnForMissingExports();
13118 }
13119 warnForMissingExports() {
13120 for (const module of this.modules) {
13121 for (const importName of Object.keys(module.importDescriptions)) {
13122 const importDescription = module.importDescriptions[importName];
13123 if (importDescription.name !== '*' &&
13124 !importDescription.module.getVariableForExportName(importDescription.name)) {
13125 module.warn({
13126 code: 'NON_EXISTENT_EXPORT',
13127 message: `Non-existent export '${importDescription.name}' is imported from ${index.relativeId(importDescription.module.id)}`,
13128 name: importDescription.name,
13129 source: importDescription.module.id
13130 }, importDescription.start);
13131 }
13132 }
13133 }
13134 }
13135}
13136
13137function evalIfFn(strOrFn) {
13138 switch (typeof strOrFn) {
13139 case 'function':
13140 return strOrFn();
13141 case 'string':
13142 return strOrFn;
13143 default:
13144 return '';
13145 }
13146}
13147const concatSep = (out, next) => (next ? `${out}\n${next}` : out);
13148const concatDblSep = (out, next) => (next ? `${out}\n\n${next}` : out);
13149function createAddons(graph, options) {
13150 const pluginDriver = graph.pluginDriver;
13151 return Promise.all([
13152 pluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep),
13153 pluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep),
13154 pluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep),
13155 pluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep)
13156 ])
13157 .then(([banner, footer, intro, outro]) => {
13158 if (intro)
13159 intro += '\n\n';
13160 if (outro)
13161 outro = `\n\n${outro}`;
13162 if (banner.length)
13163 banner += '\n';
13164 if (footer.length)
13165 footer = '\n' + footer;
13166 return { intro, outro, banner, footer };
13167 })
13168 .catch((err) => {
13169 error({
13170 code: 'ADDON_ERROR',
13171 message: `Could not retrieve ${err.hook}. Check configuration of plugin ${err.plugin}.
13172\tError Message: ${err.message}`
13173 });
13174 });
13175}
13176
13177function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, bundle) {
13178 const entryChunks = [];
13179 const otherChunks = [];
13180 for (const chunk of chunks) {
13181 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
13182 ? entryChunks
13183 : otherChunks).push(chunk);
13184 }
13185 // make sure entry chunk names take precedence with regard to deconflicting
13186 const chunksForNaming = entryChunks.concat(otherChunks);
13187 for (const chunk of chunksForNaming) {
13188 if (outputOptions.file) {
13189 chunk.id = path.basename(outputOptions.file);
13190 }
13191 else if (inputOptions.preserveModules) {
13192 chunk.id = chunk.generateIdPreserveModules(inputBase, outputOptions, bundle);
13193 }
13194 else {
13195 chunk.id = chunk.generateId(addons, outputOptions, bundle, true);
13196 }
13197 bundle[chunk.id] = FILE_PLACEHOLDER;
13198 }
13199}
13200
13201// ported from https://github.com/substack/node-commondir
13202function commondir(files) {
13203 if (files.length === 0)
13204 return '/';
13205 if (files.length === 1)
13206 return path.dirname(files[0]);
13207 const commonSegments = files.slice(1).reduce((commonSegments, file) => {
13208 const pathSegements = file.split(/\/+|\\+/);
13209 let i;
13210 for (i = 0; commonSegments[i] === pathSegements[i] &&
13211 i < Math.min(commonSegments.length, pathSegements.length); i++)
13212 ;
13213 return commonSegments.slice(0, i);
13214 }, files[0].split(/\/+|\\+/));
13215 // Windows correctly handles paths with forward-slashes
13216 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
13217}
13218
13219function badExports(option, keys) {
13220 error({
13221 code: 'INVALID_EXPORT_OPTION',
13222 message: `'${option}' was specified for output.exports, but entry module has following exports: ${keys.join(', ')}`
13223 });
13224}
13225function getExportMode(chunk, { exports: exportMode, name, format }) {
13226 const exportKeys = chunk.getExportNames();
13227 if (exportMode === 'default') {
13228 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
13229 badExports('default', exportKeys);
13230 }
13231 }
13232 else if (exportMode === 'none' && exportKeys.length) {
13233 badExports('none', exportKeys);
13234 }
13235 if (!exportMode || exportMode === 'auto') {
13236 if (exportKeys.length === 0) {
13237 exportMode = 'none';
13238 }
13239 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
13240 exportMode = 'default';
13241 }
13242 else {
13243 if (chunk.facadeModule !== null &&
13244 chunk.facadeModule.isEntryPoint &&
13245 format !== 'es' &&
13246 exportKeys.indexOf('default') !== -1) {
13247 chunk.graph.warn({
13248 code: 'MIXED_EXPORTS',
13249 message: `Using named and default exports together. Consumers of your bundle will have to use ${name ||
13250 'bundle'}['default'] to access the default export, which may not be what you want. Use \`output.exports: 'named'\` to disable this warning`,
13251 url: `https://rollupjs.org/guide/en/#output-exports`
13252 });
13253 }
13254 exportMode = 'named';
13255 }
13256 }
13257 if (!/(?:default|named|none)/.test(exportMode)) {
13258 error({
13259 code: 'INVALID_EXPORT_OPTION',
13260 message: `output.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')`,
13261 url: `https://rollupjs.org/guide/en/#output-exports`
13262 });
13263 }
13264 return exportMode;
13265}
13266
13267function checkOutputOptions(options) {
13268 if (options.format === 'es6') {
13269 error(errDeprecation({
13270 message: 'The "es6" output format is deprecated – use "esm" instead',
13271 url: `https://rollupjs.org/guide/en/#output-format`
13272 }));
13273 }
13274 if (['amd', 'cjs', 'system', 'es', 'iife', 'umd'].indexOf(options.format) < 0) {
13275 error({
13276 message: `You must specify "output.format", which can be one of "amd", "cjs", "system", "esm", "iife" or "umd".`,
13277 url: `https://rollupjs.org/guide/en/#output-format`
13278 });
13279 }
13280}
13281function getAbsoluteEntryModulePaths(chunks) {
13282 const absoluteEntryModulePaths = [];
13283 for (const chunk of chunks) {
13284 for (const entryModule of chunk.entryModules) {
13285 if (index.isAbsolute(entryModule.id)) {
13286 absoluteEntryModulePaths.push(entryModule.id);
13287 }
13288 }
13289 }
13290 return absoluteEntryModulePaths;
13291}
13292const throwAsyncGenerateError = {
13293 get() {
13294 throw new Error(`bundle.generate(...) now returns a Promise instead of a { code, map } object`);
13295 }
13296};
13297function applyOptionHook(inputOptions, plugin) {
13298 if (plugin.options)
13299 return plugin.options.call({ meta: { rollupVersion: index.version } }, inputOptions) || inputOptions;
13300 return inputOptions;
13301}
13302function ensureArray(items) {
13303 if (Array.isArray(items)) {
13304 return items.filter(Boolean);
13305 }
13306 if (items) {
13307 return [items];
13308 }
13309 return [];
13310}
13311function getInputOptions(rawInputOptions) {
13312 if (!rawInputOptions) {
13313 throw new Error('You must supply an options object to rollup');
13314 }
13315 let { inputOptions, optionError } = index.mergeOptions({
13316 config: rawInputOptions
13317 });
13318 if (optionError)
13319 inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' });
13320 inputOptions = ensureArray(inputOptions.plugins).reduce(applyOptionHook, inputOptions);
13321 inputOptions.plugins = ensureArray(inputOptions.plugins);
13322 for (let pluginIndex = 0; pluginIndex < inputOptions.plugins.length; pluginIndex++) {
13323 const plugin = inputOptions.plugins[pluginIndex];
13324 if (!plugin.name) {
13325 plugin.name = `${ANONYMOUS_PLUGIN_PREFIX}${pluginIndex + 1}`;
13326 }
13327 }
13328 if (inputOptions.inlineDynamicImports) {
13329 if (inputOptions.preserveModules)
13330 error({
13331 code: 'INVALID_OPTION',
13332 message: `"preserveModules" does not support the "inlineDynamicImports" option.`
13333 });
13334 if (inputOptions.manualChunks)
13335 error({
13336 code: 'INVALID_OPTION',
13337 message: '"manualChunks" option is not supported for "inlineDynamicImports".'
13338 });
13339 if (inputOptions.experimentalOptimizeChunks)
13340 error({
13341 code: 'INVALID_OPTION',
13342 message: '"experimentalOptimizeChunks" option is not supported for "inlineDynamicImports".'
13343 });
13344 if ((inputOptions.input instanceof Array && inputOptions.input.length > 1) ||
13345 (typeof inputOptions.input === 'object' && Object.keys(inputOptions.input).length > 1))
13346 error({
13347 code: 'INVALID_OPTION',
13348 message: 'Multiple inputs are not supported for "inlineDynamicImports".'
13349 });
13350 }
13351 else if (inputOptions.preserveModules) {
13352 if (inputOptions.manualChunks)
13353 error({
13354 code: 'INVALID_OPTION',
13355 message: '"preserveModules" does not support the "manualChunks" option.'
13356 });
13357 if (inputOptions.experimentalOptimizeChunks)
13358 error({
13359 code: 'INVALID_OPTION',
13360 message: '"preserveModules" does not support the "experimentalOptimizeChunks" option.'
13361 });
13362 }
13363 return inputOptions;
13364}
13365let curWatcher;
13366function setWatcher(watcher) {
13367 curWatcher = watcher;
13368}
13369function assignChunksToBundle(chunks, outputBundle) {
13370 for (let i = 0; i < chunks.length; i++) {
13371 const chunk = chunks[i];
13372 const facadeModule = chunk.facadeModule;
13373 outputBundle[chunk.id] = {
13374 code: undefined,
13375 dynamicImports: chunk.getDynamicImportIds(),
13376 exports: chunk.getExportNames(),
13377 facadeModuleId: facadeModule && facadeModule.id,
13378 fileName: chunk.id,
13379 imports: chunk.getImportIds(),
13380 isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
13381 isEntry: facadeModule !== null && facadeModule.isEntryPoint,
13382 map: undefined,
13383 modules: chunk.renderedModules,
13384 get name() {
13385 return chunk.getChunkName();
13386 },
13387 type: 'chunk'
13388 };
13389 }
13390 return outputBundle;
13391}
13392function rollup(rawInputOptions) {
13393 return __awaiter(this, void 0, void 0, function* () {
13394 const inputOptions = getInputOptions(rawInputOptions);
13395 initialiseTimers(inputOptions);
13396 const graph = new Graph(inputOptions, curWatcher);
13397 curWatcher = undefined;
13398 // remove the cache option from the memory after graph creation (cache is not used anymore)
13399 const useCache = rawInputOptions.cache !== false;
13400 delete inputOptions.cache;
13401 delete rawInputOptions.cache;
13402 timeStart('BUILD', 1);
13403 let chunks;
13404 try {
13405 yield graph.pluginDriver.hookParallel('buildStart', [inputOptions]);
13406 chunks = yield graph.build(inputOptions.input, inputOptions.manualChunks, inputOptions.inlineDynamicImports);
13407 }
13408 catch (err) {
13409 yield graph.pluginDriver.hookParallel('buildEnd', [err]);
13410 throw err;
13411 }
13412 yield graph.pluginDriver.hookParallel('buildEnd', []);
13413 timeEnd('BUILD', 1);
13414 // ensure we only do one optimization pass per build
13415 let optimized = false;
13416 function getOutputOptions(rawOutputOptions) {
13417 return normalizeOutputOptions(inputOptions, rawOutputOptions, chunks.length > 1, graph.pluginDriver);
13418 }
13419 function generate(outputOptions, isWrite) {
13420 return __awaiter(this, void 0, void 0, function* () {
13421 timeStart('GENERATE', 1);
13422 const assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]';
13423 const outputBundleWithPlaceholders = Object.create(null);
13424 let outputBundle;
13425 const inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
13426 graph.pluginDriver.startOutput(outputBundleWithPlaceholders, assetFileNames);
13427 try {
13428 yield graph.pluginDriver.hookParallel('renderStart', []);
13429 const addons = yield createAddons(graph, outputOptions);
13430 for (const chunk of chunks) {
13431 if (!inputOptions.preserveModules)
13432 chunk.generateInternalExports(outputOptions);
13433 if (chunk.facadeModule && chunk.facadeModule.isEntryPoint)
13434 chunk.exportMode = getExportMode(chunk, outputOptions);
13435 }
13436 for (const chunk of chunks) {
13437 chunk.preRender(outputOptions, inputBase);
13438 }
13439 if (!optimized && inputOptions.experimentalOptimizeChunks) {
13440 optimizeChunks(chunks, outputOptions, inputOptions.chunkGroupingSize, inputBase);
13441 optimized = true;
13442 }
13443 assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons, outputBundleWithPlaceholders);
13444 outputBundle = assignChunksToBundle(chunks, outputBundleWithPlaceholders);
13445 yield Promise.all(chunks.map(chunk => {
13446 const outputChunk = outputBundleWithPlaceholders[chunk.id];
13447 return chunk.render(outputOptions, addons, outputChunk).then(rendered => {
13448 outputChunk.code = rendered.code;
13449 outputChunk.map = rendered.map;
13450 return graph.pluginDriver.hookParallel('ongenerate', [
13451 Object.assign({ bundle: outputChunk }, outputOptions),
13452 outputChunk
13453 ]);
13454 });
13455 }));
13456 }
13457 catch (error) {
13458 yield graph.pluginDriver.hookParallel('renderError', [error]);
13459 throw error;
13460 }
13461 yield graph.pluginDriver.hookSeq('generateBundle', [outputOptions, outputBundle, isWrite]);
13462 for (const key of Object.keys(outputBundle)) {
13463 const file = outputBundle[key];
13464 if (!file.type) {
13465 graph.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.', false);
13466 file.type = 'asset';
13467 }
13468 }
13469 graph.pluginDriver.finaliseAssets();
13470 timeEnd('GENERATE', 1);
13471 return outputBundle;
13472 });
13473 }
13474 const cache = useCache ? graph.getCache() : undefined;
13475 const result = {
13476 cache: cache,
13477 generate: ((rawOutputOptions) => {
13478 const promise = generate(getOutputOptions(rawOutputOptions), false).then(result => createOutput(result));
13479 Object.defineProperty(promise, 'code', throwAsyncGenerateError);
13480 Object.defineProperty(promise, 'map', throwAsyncGenerateError);
13481 return promise;
13482 }),
13483 watchFiles: Object.keys(graph.watchFiles),
13484 write: ((rawOutputOptions) => {
13485 const outputOptions = getOutputOptions(rawOutputOptions);
13486 if (!outputOptions.dir && !outputOptions.file) {
13487 error({
13488 code: 'MISSING_OPTION',
13489 message: 'You must specify "output.file" or "output.dir" for the build.'
13490 });
13491 }
13492 return generate(outputOptions, true).then((bundle) => __awaiter(this, void 0, void 0, function* () {
13493 let chunkCnt = 0;
13494 for (const fileName of Object.keys(bundle)) {
13495 const file = bundle[fileName];
13496 if (file.type === 'asset')
13497 continue;
13498 chunkCnt++;
13499 if (chunkCnt > 1)
13500 break;
13501 }
13502 if (chunkCnt > 1) {
13503 if (outputOptions.sourcemapFile)
13504 error({
13505 code: 'INVALID_OPTION',
13506 message: '"output.sourcemapFile" is only supported for single-file builds.'
13507 });
13508 if (typeof outputOptions.file === 'string')
13509 error({
13510 code: 'INVALID_OPTION',
13511 message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
13512 (typeof inputOptions.input !== 'string' ||
13513 inputOptions.inlineDynamicImports === true
13514 ? ''
13515 : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
13516 });
13517 }
13518 yield Promise.all(Object.keys(bundle).map(chunkId => writeOutputFile(graph, result, bundle[chunkId], outputOptions)));
13519 yield graph.pluginDriver.hookParallel('writeBundle', [bundle]);
13520 return createOutput(bundle);
13521 }));
13522 })
13523 };
13524 if (inputOptions.perf === true)
13525 result.getTimings = getTimings;
13526 return result;
13527 });
13528}
13529var SortingFileType;
13530(function (SortingFileType) {
13531 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
13532 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
13533 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
13534})(SortingFileType || (SortingFileType = {}));
13535function getSortingFileType(file) {
13536 if (file.type === 'asset') {
13537 return SortingFileType.ASSET;
13538 }
13539 if (file.isEntry) {
13540 return SortingFileType.ENTRY_CHUNK;
13541 }
13542 return SortingFileType.SECONDARY_CHUNK;
13543}
13544function createOutput(outputBundle) {
13545 return {
13546 output: Object.keys(outputBundle)
13547 .map(fileName => outputBundle[fileName])
13548 .filter(outputFile => Object.keys(outputFile).length > 0).sort((outputFileA, outputFileB) => {
13549 const fileTypeA = getSortingFileType(outputFileA);
13550 const fileTypeB = getSortingFileType(outputFileB);
13551 if (fileTypeA === fileTypeB)
13552 return 0;
13553 return fileTypeA < fileTypeB ? -1 : 1;
13554 })
13555 };
13556}
13557function writeOutputFile(graph, build, outputFile, outputOptions) {
13558 const fileName = path.resolve(outputOptions.dir || path.dirname(outputOptions.file), outputFile.fileName);
13559 let writeSourceMapPromise;
13560 let source;
13561 if (outputFile.type === 'asset') {
13562 source = outputFile.source;
13563 }
13564 else {
13565 source = outputFile.code;
13566 if (outputOptions.sourcemap && outputFile.map) {
13567 let url;
13568 if (outputOptions.sourcemap === 'inline') {
13569 url = outputFile.map.toUrl();
13570 }
13571 else {
13572 url = `${path.basename(outputFile.fileName)}.map`;
13573 writeSourceMapPromise = writeFile(`${fileName}.map`, outputFile.map.toString());
13574 }
13575 if (outputOptions.sourcemap !== 'hidden') {
13576 source += `//# ${SOURCEMAPPING_URL}=${url}\n`;
13577 }
13578 }
13579 }
13580 return writeFile(fileName, source)
13581 .then(() => writeSourceMapPromise)
13582 .then(() => outputFile.type === 'chunk' &&
13583 graph.pluginDriver.hookSeq('onwrite', [
13584 Object.assign({ bundle: build }, outputOptions),
13585 outputFile
13586 ]))
13587 .then(() => { });
13588}
13589function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, pluginDriver) {
13590 if (!rawOutputOptions) {
13591 throw new Error('You must supply an options object');
13592 }
13593 const mergedOptions = index.mergeOptions({
13594 config: {
13595 output: Object.assign(Object.assign(Object.assign({}, rawOutputOptions), rawOutputOptions.output), inputOptions.output)
13596 }
13597 });
13598 if (mergedOptions.optionError)
13599 throw new Error(mergedOptions.optionError);
13600 // now outputOptions is an array, but rollup.rollup API doesn't support arrays
13601 const mergedOutputOptions = mergedOptions.outputOptions[0];
13602 const outputOptionsReducer = (outputOptions, result) => result || outputOptions;
13603 const outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer, pluginContext => {
13604 const emitError = () => pluginContext.error(errCannotEmitFromOptionsHook());
13605 return Object.assign(Object.assign({}, pluginContext), { emitFile: emitError, setAssetSource: emitError });
13606 });
13607 checkOutputOptions(outputOptions);
13608 if (typeof outputOptions.file === 'string') {
13609 if (typeof outputOptions.dir === 'string')
13610 error({
13611 code: 'INVALID_OPTION',
13612 message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
13613 });
13614 if (inputOptions.preserveModules) {
13615 error({
13616 code: 'INVALID_OPTION',
13617 message: 'You must set "output.dir" instead of "output.file" when using the "preserveModules" option.'
13618 });
13619 }
13620 if (typeof inputOptions.input === 'object' && !Array.isArray(inputOptions.input))
13621 error({
13622 code: 'INVALID_OPTION',
13623 message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
13624 });
13625 }
13626 if (hasMultipleChunks) {
13627 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
13628 error({
13629 code: 'INVALID_OPTION',
13630 message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
13631 });
13632 if (typeof outputOptions.file === 'string')
13633 error({
13634 code: 'INVALID_OPTION',
13635 message: 'You must set "output.dir" instead of "output.file" when generating multiple chunks.'
13636 });
13637 }
13638 return outputOptions;
13639}
13640
13641var utils$1 = index.createCommonjsModule(function (module, exports) {
13642 exports.isInteger = num => {
13643 if (typeof num === 'number') {
13644 return Number.isInteger(num);
13645 }
13646 if (typeof num === 'string' && num.trim() !== '') {
13647 return Number.isInteger(Number(num));
13648 }
13649 return false;
13650 };
13651 /**
13652 * Find a node of the given type
13653 */
13654 exports.find = (node, type) => node.nodes.find(node => node.type === type);
13655 /**
13656 * Find a node of the given type
13657 */
13658 exports.exceedsLimit = (min, max, step = 1, limit) => {
13659 if (limit === false)
13660 return false;
13661 if (!exports.isInteger(min) || !exports.isInteger(max))
13662 return false;
13663 return ((Number(max) - Number(min)) / Number(step)) >= limit;
13664 };
13665 /**
13666 * Escape the given node with '\\' before node.value
13667 */
13668 exports.escapeNode = (block, n = 0, type) => {
13669 let node = block.nodes[n];
13670 if (!node)
13671 return;
13672 if ((type && node.type === type) || node.type === 'open' || node.type === 'close') {
13673 if (node.escaped !== true) {
13674 node.value = '\\' + node.value;
13675 node.escaped = true;
13676 }
13677 }
13678 };
13679 /**
13680 * Returns true if the given brace node should be enclosed in literal braces
13681 */
13682 exports.encloseBrace = node => {
13683 if (node.type !== 'brace')
13684 return false;
13685 if ((node.commas >> 0 + node.ranges >> 0) === 0) {
13686 node.invalid = true;
13687 return true;
13688 }
13689 return false;
13690 };
13691 /**
13692 * Returns true if a brace node is invalid.
13693 */
13694 exports.isInvalidBrace = block => {
13695 if (block.type !== 'brace')
13696 return false;
13697 if (block.invalid === true || block.dollar)
13698 return true;
13699 if ((block.commas >> 0 + block.ranges >> 0) === 0) {
13700 block.invalid = true;
13701 return true;
13702 }
13703 if (block.open !== true || block.close !== true) {
13704 block.invalid = true;
13705 return true;
13706 }
13707 return false;
13708 };
13709 /**
13710 * Returns true if a node is an open or close node
13711 */
13712 exports.isOpenOrClose = node => {
13713 if (node.type === 'open' || node.type === 'close') {
13714 return true;
13715 }
13716 return node.open === true || node.close === true;
13717 };
13718 /**
13719 * Reduce an array of text nodes.
13720 */
13721 exports.reduce = nodes => nodes.reduce((acc, node) => {
13722 if (node.type === 'text')
13723 acc.push(node.value);
13724 if (node.type === 'range')
13725 node.type = 'text';
13726 return acc;
13727 }, []);
13728 /**
13729 * Flatten an array
13730 */
13731 exports.flatten = (...args) => {
13732 const result = [];
13733 const flat = arr => {
13734 for (let i = 0; i < arr.length; i++) {
13735 let ele = arr[i];
13736 Array.isArray(ele) ? flat(ele) : ele !== void 0 && result.push(ele);
13737 }
13738 return result;
13739 };
13740 flat(args);
13741 return result;
13742 };
13743});
13744
13745var stringify = (ast, options = {}) => {
13746 let stringify = (node, parent = {}) => {
13747 let invalidBlock = options.escapeInvalid && utils$1.isInvalidBrace(parent);
13748 let invalidNode = node.invalid === true && options.escapeInvalid === true;
13749 let output = '';
13750 if (node.value) {
13751 if ((invalidBlock || invalidNode) && utils$1.isOpenOrClose(node)) {
13752 return '\\' + node.value;
13753 }
13754 return node.value;
13755 }
13756 if (node.value) {
13757 return node.value;
13758 }
13759 if (node.nodes) {
13760 for (let child of node.nodes) {
13761 output += stringify(child);
13762 }
13763 }
13764 return output;
13765 };
13766 return stringify(ast);
13767};
13768
13769/*!
13770 * is-number <https://github.com/jonschlinkert/is-number>
13771 *
13772 * Copyright (c) 2014-present, Jon Schlinkert.
13773 * Released under the MIT License.
13774 */
13775var isNumber = function (num) {
13776 if (typeof num === 'number') {
13777 return num - num === 0;
13778 }
13779 if (typeof num === 'string' && num.trim() !== '') {
13780 return Number.isFinite ? Number.isFinite(+num) : isFinite(+num);
13781 }
13782 return false;
13783};
13784
13785const toRegexRange = (min, max, options) => {
13786 if (isNumber(min) === false) {
13787 throw new TypeError('toRegexRange: expected the first argument to be a number');
13788 }
13789 if (max === void 0 || min === max) {
13790 return String(min);
13791 }
13792 if (isNumber(max) === false) {
13793 throw new TypeError('toRegexRange: expected the second argument to be a number.');
13794 }
13795 let opts = Object.assign({ relaxZeros: true }, options);
13796 if (typeof opts.strictZeros === 'boolean') {
13797 opts.relaxZeros = opts.strictZeros === false;
13798 }
13799 let relax = String(opts.relaxZeros);
13800 let shorthand = String(opts.shorthand);
13801 let capture = String(opts.capture);
13802 let wrap = String(opts.wrap);
13803 let cacheKey = min + ':' + max + '=' + relax + shorthand + capture + wrap;
13804 if (toRegexRange.cache.hasOwnProperty(cacheKey)) {
13805 return toRegexRange.cache[cacheKey].result;
13806 }
13807 let a = Math.min(min, max);
13808 let b = Math.max(min, max);
13809 if (Math.abs(a - b) === 1) {
13810 let result = min + '|' + max;
13811 if (opts.capture) {
13812 return `(${result})`;
13813 }
13814 if (opts.wrap === false) {
13815 return result;
13816 }
13817 return `(?:${result})`;
13818 }
13819 let isPadded = hasPadding(min) || hasPadding(max);
13820 let state = { min, max, a, b };
13821 let positives = [];
13822 let negatives = [];
13823 if (isPadded) {
13824 state.isPadded = isPadded;
13825 state.maxLen = String(state.max).length;
13826 }
13827 if (a < 0) {
13828 let newMin = b < 0 ? Math.abs(b) : 1;
13829 negatives = splitToPatterns(newMin, Math.abs(a), state, opts);
13830 a = state.a = 0;
13831 }
13832 if (b >= 0) {
13833 positives = splitToPatterns(a, b, state, opts);
13834 }
13835 state.negatives = negatives;
13836 state.positives = positives;
13837 state.result = collatePatterns(negatives, positives);
13838 if (opts.capture === true) {
13839 state.result = `(${state.result})`;
13840 }
13841 else if (opts.wrap !== false && (positives.length + negatives.length) > 1) {
13842 state.result = `(?:${state.result})`;
13843 }
13844 toRegexRange.cache[cacheKey] = state;
13845 return state.result;
13846};
13847function collatePatterns(neg, pos, options) {
13848 let onlyNegative = filterPatterns(neg, pos, '-', false) || [];
13849 let onlyPositive = filterPatterns(pos, neg, '', false) || [];
13850 let intersected = filterPatterns(neg, pos, '-?', true) || [];
13851 let subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
13852 return subpatterns.join('|');
13853}
13854function splitToRanges(min, max) {
13855 let nines = 1;
13856 let zeros = 1;
13857 let stop = countNines(min, nines);
13858 let stops = new Set([max]);
13859 while (min <= stop && stop <= max) {
13860 stops.add(stop);
13861 nines += 1;
13862 stop = countNines(min, nines);
13863 }
13864 stop = countZeros(max + 1, zeros) - 1;
13865 while (min < stop && stop <= max) {
13866 stops.add(stop);
13867 zeros += 1;
13868 stop = countZeros(max + 1, zeros) - 1;
13869 }
13870 stops = [...stops];
13871 stops.sort(compare);
13872 return stops;
13873}
13874/**
13875 * Convert a range to a regex pattern
13876 * @param {Number} `start`
13877 * @param {Number} `stop`
13878 * @return {String}
13879 */
13880function rangeToPattern(start, stop, options) {
13881 if (start === stop) {
13882 return { pattern: start, count: [], digits: 0 };
13883 }
13884 let zipped = zip(start, stop);
13885 let digits = zipped.length;
13886 let pattern = '';
13887 let count = 0;
13888 for (let i = 0; i < digits; i++) {
13889 let [startDigit, stopDigit] = zipped[i];
13890 if (startDigit === stopDigit) {
13891 pattern += startDigit;
13892 }
13893 else if (startDigit !== '0' || stopDigit !== '9') {
13894 pattern += toCharacterClass(startDigit, stopDigit);
13895 }
13896 else {
13897 count++;
13898 }
13899 }
13900 if (count) {
13901 pattern += options.shorthand === true ? '\\d' : '[0-9]';
13902 }
13903 return { pattern, count: [count], digits };
13904}
13905function splitToPatterns(min, max, tok, options) {
13906 let ranges = splitToRanges(min, max);
13907 let tokens = [];
13908 let start = min;
13909 let prev;
13910 for (let i = 0; i < ranges.length; i++) {
13911 let max = ranges[i];
13912 let obj = rangeToPattern(String(start), String(max), options);
13913 let zeros = '';
13914 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
13915 if (prev.count.length > 1) {
13916 prev.count.pop();
13917 }
13918 prev.count.push(obj.count[0]);
13919 prev.string = prev.pattern + toQuantifier(prev.count);
13920 start = max + 1;
13921 continue;
13922 }
13923 if (tok.isPadded) {
13924 zeros = padZeros(max, tok, options);
13925 }
13926 obj.string = zeros + obj.pattern + toQuantifier(obj.count);
13927 tokens.push(obj);
13928 start = max + 1;
13929 prev = obj;
13930 }
13931 return tokens;
13932}
13933function filterPatterns(arr, comparison, prefix, intersection, options) {
13934 let result = [];
13935 for (let ele of arr) {
13936 let { string } = ele;
13937 // only push if _both_ are negative...
13938 if (!intersection && !contains(comparison, 'string', string)) {
13939 result.push(prefix + string);
13940 }
13941 // or _both_ are positive
13942 if (intersection && contains(comparison, 'string', string)) {
13943 result.push(prefix + string);
13944 }
13945 }
13946 return result;
13947}
13948/**
13949 * Zip strings
13950 */
13951function zip(a, b) {
13952 let arr = [];
13953 for (let i = 0; i < a.length; i++)
13954 arr.push([a[i], b[i]]);
13955 return arr;
13956}
13957function compare(a, b) {
13958 return a > b ? 1 : b > a ? -1 : 0;
13959}
13960function contains(arr, key, val) {
13961 return arr.some(ele => ele[key] === val);
13962}
13963function countNines(min, len) {
13964 return Number(String(min).slice(0, -len) + '9'.repeat(len));
13965}
13966function countZeros(integer, zeros) {
13967 return integer - (integer % Math.pow(10, zeros));
13968}
13969function toQuantifier(digits) {
13970 let [start = 0, stop = ''] = digits;
13971 if (stop || start > 1) {
13972 return `{${start + (stop ? ',' + stop : '')}}`;
13973 }
13974 return '';
13975}
13976function toCharacterClass(a, b, options) {
13977 return `[${a}${(b - a === 1) ? '' : '-'}${b}]`;
13978}
13979function hasPadding(str) {
13980 return /^-?(0+)\d/.test(str);
13981}
13982function padZeros(value, tok, options) {
13983 if (!tok.isPadded) {
13984 return value;
13985 }
13986 let diff = Math.abs(tok.maxLen - String(value).length);
13987 let relax = options.relaxZeros !== false;
13988 switch (diff) {
13989 case 0:
13990 return '';
13991 case 1:
13992 return relax ? '0?' : '0';
13993 case 2:
13994 return relax ? '0{0,2}' : '00';
13995 default: {
13996 return relax ? `0{0,${diff}}` : `0{${diff}}`;
13997 }
13998 }
13999}
14000/**
14001 * Cache
14002 */
14003toRegexRange.cache = {};
14004toRegexRange.clearCache = () => (toRegexRange.cache = {});
14005/**
14006 * Expose `toRegexRange`
14007 */
14008var toRegexRange_1 = toRegexRange;
14009
14010const isObject$1 = val => val !== null && typeof val === 'object' && !Array.isArray(val);
14011const transform$1 = toNumber => {
14012 return value => toNumber === true ? Number(value) : String(value);
14013};
14014const isValidValue = value => {
14015 return typeof value === 'number' || (typeof value === 'string' && value !== '');
14016};
14017const isNumber$1 = num => Number.isInteger(+num);
14018const zeros = input => {
14019 let value = `${input}`;
14020 let index = -1;
14021 if (value[0] === '-')
14022 value = value.slice(1);
14023 if (value === '0')
14024 return false;
14025 while (value[++index] === '0')
14026 ;
14027 return index > 0;
14028};
14029const stringify$1 = (start, end, options) => {
14030 if (typeof start === 'string' || typeof end === 'string') {
14031 return true;
14032 }
14033 return options.stringify === true;
14034};
14035const pad = (input, maxLength, toNumber) => {
14036 if (maxLength > 0) {
14037 let dash = input[0] === '-' ? '-' : '';
14038 if (dash)
14039 input = input.slice(1);
14040 input = (dash + input.padStart(dash ? maxLength - 1 : maxLength, '0'));
14041 }
14042 if (toNumber === false) {
14043 return String(input);
14044 }
14045 return input;
14046};
14047const toMaxLen = (input, maxLength) => {
14048 let negative = input[0] === '-' ? '-' : '';
14049 if (negative) {
14050 input = input.slice(1);
14051 maxLength--;
14052 }
14053 while (input.length < maxLength)
14054 input = '0' + input;
14055 return negative ? ('-' + input) : input;
14056};
14057const toSequence = (parts, options) => {
14058 parts.negatives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
14059 parts.positives.sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
14060 let prefix = options.capture ? '' : '?:';
14061 let positives = '';
14062 let negatives = '';
14063 let result;
14064 if (parts.positives.length) {
14065 positives = parts.positives.join('|');
14066 }
14067 if (parts.negatives.length) {
14068 negatives = `-(${prefix}${parts.negatives.join('|')})`;
14069 }
14070 if (positives && negatives) {
14071 result = `${positives}|${negatives}`;
14072 }
14073 else {
14074 result = positives || negatives;
14075 }
14076 if (options.wrap) {
14077 return `(${prefix}${result})`;
14078 }
14079 return result;
14080};
14081const toRange = (a, b, isNumbers, options) => {
14082 if (isNumbers) {
14083 return toRegexRange_1(a, b, Object.assign({ wrap: false }, options));
14084 }
14085 let start = String.fromCharCode(a);
14086 if (a === b)
14087 return start;
14088 let stop = String.fromCharCode(b);
14089 return `[${start}-${stop}]`;
14090};
14091const toRegex = (start, end, options) => {
14092 if (Array.isArray(start)) {
14093 let wrap = options.wrap === true;
14094 let prefix = options.capture ? '' : '?:';
14095 return wrap ? `(${prefix}${start.join('|')})` : start.join('|');
14096 }
14097 return toRegexRange_1(start, end, options);
14098};
14099const rangeError = (...args) => {
14100 return new RangeError('Invalid range arguments: ' + util.inspect(...args));
14101};
14102const invalidRange = (start, end, options) => {
14103 if (options.strictRanges === true)
14104 throw rangeError([start, end]);
14105 return [];
14106};
14107const invalidStep = (step, options) => {
14108 if (options.strictRanges === true) {
14109 throw new TypeError(`Expected step "${step}" to be a number`);
14110 }
14111 return [];
14112};
14113const fillNumbers = (start, end, step = 1, options = {}) => {
14114 let a = Number(start);
14115 let b = Number(end);
14116 if (!Number.isInteger(a) || !Number.isInteger(b)) {
14117 if (options.strictRanges === true)
14118 throw rangeError([start, end]);
14119 return [];
14120 }
14121 // fix negative zero
14122 if (a === 0)
14123 a = 0;
14124 if (b === 0)
14125 b = 0;
14126 let descending = a > b;
14127 let startString = String(start);
14128 let endString = String(end);
14129 let stepString = String(step);
14130 step = Math.max(Math.abs(step), 1);
14131 let padded = zeros(startString) || zeros(endString) || zeros(stepString);
14132 let maxLen = padded ? Math.max(startString.length, endString.length, stepString.length) : 0;
14133 let toNumber = padded === false && stringify$1(start, end, options) === false;
14134 let format = options.transform || transform$1(toNumber);
14135 if (options.toRegex && step === 1) {
14136 return toRange(toMaxLen(start, maxLen), toMaxLen(end, maxLen), true, options);
14137 }
14138 let parts = { negatives: [], positives: [] };
14139 let push = num => parts[num < 0 ? 'negatives' : 'positives'].push(Math.abs(num));
14140 let range = [];
14141 let index = 0;
14142 while (descending ? a >= b : a <= b) {
14143 if (options.toRegex === true && step > 1) {
14144 push(a);
14145 }
14146 else {
14147 range.push(pad(format(a, index), maxLen, toNumber));
14148 }
14149 a = descending ? a - step : a + step;
14150 index++;
14151 }
14152 if (options.toRegex === true) {
14153 return step > 1
14154 ? toSequence(parts, options)
14155 : toRegex(range, null, Object.assign({ wrap: false }, options));
14156 }
14157 return range;
14158};
14159const fillLetters = (start, end, step = 1, options = {}) => {
14160 if ((!isNumber$1(start) && start.length > 1) || (!isNumber$1(end) && end.length > 1)) {
14161 return invalidRange(start, end, options);
14162 }
14163 let format = options.transform || (val => String.fromCharCode(val));
14164 let a = `${start}`.charCodeAt(0);
14165 let b = `${end}`.charCodeAt(0);
14166 let descending = a > b;
14167 let min = Math.min(a, b);
14168 let max = Math.max(a, b);
14169 if (options.toRegex && step === 1) {
14170 return toRange(min, max, false, options);
14171 }
14172 let range = [];
14173 let index = 0;
14174 while (descending ? a >= b : a <= b) {
14175 range.push(format(a, index));
14176 a = descending ? a - step : a + step;
14177 index++;
14178 }
14179 if (options.toRegex === true) {
14180 return toRegex(range, null, { wrap: false, options });
14181 }
14182 return range;
14183};
14184const fill = (start, end, step, options = {}) => {
14185 if (end == null && isValidValue(start)) {
14186 return [start];
14187 }
14188 if (!isValidValue(start) || !isValidValue(end)) {
14189 return invalidRange(start, end, options);
14190 }
14191 if (typeof step === 'function') {
14192 return fill(start, end, 1, { transform: step });
14193 }
14194 if (isObject$1(step)) {
14195 return fill(start, end, 0, step);
14196 }
14197 let opts = Object.assign({}, options);
14198 if (opts.capture === true)
14199 opts.wrap = true;
14200 step = step || opts.step || 1;
14201 if (!isNumber$1(step)) {
14202 if (step != null && !isObject$1(step))
14203 return invalidStep(step, opts);
14204 return fill(start, end, 1, step);
14205 }
14206 if (isNumber$1(start) && isNumber$1(end)) {
14207 return fillNumbers(start, end, step, opts);
14208 }
14209 return fillLetters(start, end, Math.max(Math.abs(step), 1), opts);
14210};
14211var fillRange = fill;
14212
14213const compile = (ast, options = {}) => {
14214 let walk = (node, parent = {}) => {
14215 let invalidBlock = utils$1.isInvalidBrace(parent);
14216 let invalidNode = node.invalid === true && options.escapeInvalid === true;
14217 let invalid = invalidBlock === true || invalidNode === true;
14218 let prefix = options.escapeInvalid === true ? '\\' : '';
14219 let output = '';
14220 if (node.isOpen === true) {
14221 return prefix + node.value;
14222 }
14223 if (node.isClose === true) {
14224 return prefix + node.value;
14225 }
14226 if (node.type === 'open') {
14227 return invalid ? (prefix + node.value) : '(';
14228 }
14229 if (node.type === 'close') {
14230 return invalid ? (prefix + node.value) : ')';
14231 }
14232 if (node.type === 'comma') {
14233 return node.prev.type === 'comma' ? '' : (invalid ? node.value : '|');
14234 }
14235 if (node.value) {
14236 return node.value;
14237 }
14238 if (node.nodes && node.ranges > 0) {
14239 let args = utils$1.reduce(node.nodes);
14240 let range = fillRange(...args, Object.assign(Object.assign({}, options), { wrap: false, toRegex: true }));
14241 if (range.length !== 0) {
14242 return args.length > 1 && range.length > 1 ? `(${range})` : range;
14243 }
14244 }
14245 if (node.nodes) {
14246 for (let child of node.nodes) {
14247 output += walk(child, node);
14248 }
14249 }
14250 return output;
14251 };
14252 return walk(ast);
14253};
14254var compile_1 = compile;
14255
14256const append = (queue = '', stash = '', enclose = false) => {
14257 let result = [];
14258 queue = [].concat(queue);
14259 stash = [].concat(stash);
14260 if (!stash.length)
14261 return queue;
14262 if (!queue.length) {
14263 return enclose ? utils$1.flatten(stash).map(ele => `{${ele}}`) : stash;
14264 }
14265 for (let item of queue) {
14266 if (Array.isArray(item)) {
14267 for (let value of item) {
14268 result.push(append(value, stash, enclose));
14269 }
14270 }
14271 else {
14272 for (let ele of stash) {
14273 if (enclose === true && typeof ele === 'string')
14274 ele = `{${ele}}`;
14275 result.push(Array.isArray(ele) ? append(item, ele, enclose) : (item + ele));
14276 }
14277 }
14278 }
14279 return utils$1.flatten(result);
14280};
14281const expand = (ast, options = {}) => {
14282 let rangeLimit = options.rangeLimit === void 0 ? 1000 : options.rangeLimit;
14283 let walk = (node, parent = {}) => {
14284 node.queue = [];
14285 let p = parent;
14286 let q = parent.queue;
14287 while (p.type !== 'brace' && p.type !== 'root' && p.parent) {
14288 p = p.parent;
14289 q = p.queue;
14290 }
14291 if (node.invalid || node.dollar) {
14292 q.push(append(q.pop(), stringify(node, options)));
14293 return;
14294 }
14295 if (node.type === 'brace' && node.invalid !== true && node.nodes.length === 2) {
14296 q.push(append(q.pop(), ['{}']));
14297 return;
14298 }
14299 if (node.nodes && node.ranges > 0) {
14300 let args = utils$1.reduce(node.nodes);
14301 if (utils$1.exceedsLimit(...args, options.step, rangeLimit)) {
14302 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
14303 }
14304 let range = fillRange(...args, options);
14305 if (range.length === 0) {
14306 range = stringify(node, options);
14307 }
14308 q.push(append(q.pop(), range));
14309 node.nodes = [];
14310 return;
14311 }
14312 let enclose = utils$1.encloseBrace(node);
14313 let queue = node.queue;
14314 let block = node;
14315 while (block.type !== 'brace' && block.type !== 'root' && block.parent) {
14316 block = block.parent;
14317 queue = block.queue;
14318 }
14319 for (let i = 0; i < node.nodes.length; i++) {
14320 let child = node.nodes[i];
14321 if (child.type === 'comma' && node.type === 'brace') {
14322 if (i === 1)
14323 queue.push('');
14324 queue.push('');
14325 continue;
14326 }
14327 if (child.type === 'close') {
14328 q.push(append(q.pop(), queue, enclose));
14329 continue;
14330 }
14331 if (child.value && child.type !== 'open') {
14332 queue.push(append(queue.pop(), child.value));
14333 continue;
14334 }
14335 if (child.nodes) {
14336 walk(child, node);
14337 }
14338 }
14339 return queue;
14340 };
14341 return utils$1.flatten(walk(ast));
14342};
14343var expand_1 = expand;
14344
14345var constants = {
14346 MAX_LENGTH: 1024 * 64,
14347 // Digits
14348 CHAR_0: '0',
14349 CHAR_9: '9',
14350 // Alphabet chars.
14351 CHAR_UPPERCASE_A: 'A',
14352 CHAR_LOWERCASE_A: 'a',
14353 CHAR_UPPERCASE_Z: 'Z',
14354 CHAR_LOWERCASE_Z: 'z',
14355 CHAR_LEFT_PARENTHESES: '(',
14356 CHAR_RIGHT_PARENTHESES: ')',
14357 CHAR_ASTERISK: '*',
14358 // Non-alphabetic chars.
14359 CHAR_AMPERSAND: '&',
14360 CHAR_AT: '@',
14361 CHAR_BACKSLASH: '\\',
14362 CHAR_BACKTICK: '`',
14363 CHAR_CARRIAGE_RETURN: '\r',
14364 CHAR_CIRCUMFLEX_ACCENT: '^',
14365 CHAR_COLON: ':',
14366 CHAR_COMMA: ',',
14367 CHAR_DOLLAR: '$',
14368 CHAR_DOT: '.',
14369 CHAR_DOUBLE_QUOTE: '"',
14370 CHAR_EQUAL: '=',
14371 CHAR_EXCLAMATION_MARK: '!',
14372 CHAR_FORM_FEED: '\f',
14373 CHAR_FORWARD_SLASH: '/',
14374 CHAR_HASH: '#',
14375 CHAR_HYPHEN_MINUS: '-',
14376 CHAR_LEFT_ANGLE_BRACKET: '<',
14377 CHAR_LEFT_CURLY_BRACE: '{',
14378 CHAR_LEFT_SQUARE_BRACKET: '[',
14379 CHAR_LINE_FEED: '\n',
14380 CHAR_NO_BREAK_SPACE: '\u00A0',
14381 CHAR_PERCENT: '%',
14382 CHAR_PLUS: '+',
14383 CHAR_QUESTION_MARK: '?',
14384 CHAR_RIGHT_ANGLE_BRACKET: '>',
14385 CHAR_RIGHT_CURLY_BRACE: '}',
14386 CHAR_RIGHT_SQUARE_BRACKET: ']',
14387 CHAR_SEMICOLON: ';',
14388 CHAR_SINGLE_QUOTE: '\'',
14389 CHAR_SPACE: ' ',
14390 CHAR_TAB: '\t',
14391 CHAR_UNDERSCORE: '_',
14392 CHAR_VERTICAL_LINE: '|',
14393 CHAR_ZERO_WIDTH_NOBREAK_SPACE: '\uFEFF' /* \uFEFF */
14394};
14395
14396/**
14397 * Constants
14398 */
14399const { MAX_LENGTH, CHAR_BACKSLASH, /* \ */ CHAR_BACKTICK, /* ` */ CHAR_COMMA, /* , */ CHAR_DOT, /* . */ CHAR_LEFT_PARENTHESES, /* ( */ CHAR_RIGHT_PARENTHESES, /* ) */ CHAR_LEFT_CURLY_BRACE, /* { */ CHAR_RIGHT_CURLY_BRACE, /* } */ CHAR_LEFT_SQUARE_BRACKET, /* [ */ CHAR_RIGHT_SQUARE_BRACKET, /* ] */ CHAR_DOUBLE_QUOTE, /* " */ CHAR_SINGLE_QUOTE, /* ' */ CHAR_NO_BREAK_SPACE, CHAR_ZERO_WIDTH_NOBREAK_SPACE } = constants;
14400/**
14401 * parse
14402 */
14403const parse = (input, options = {}) => {
14404 if (typeof input !== 'string') {
14405 throw new TypeError('Expected a string');
14406 }
14407 let opts = options || {};
14408 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH, opts.maxLength) : MAX_LENGTH;
14409 if (input.length > max) {
14410 throw new SyntaxError(`Input length (${input.length}), exceeds max characters (${max})`);
14411 }
14412 let ast = { type: 'root', input, nodes: [] };
14413 let stack = [ast];
14414 let block = ast;
14415 let prev = ast;
14416 let brackets = 0;
14417 let length = input.length;
14418 let index = 0;
14419 let depth = 0;
14420 let value;
14421 /**
14422 * Helpers
14423 */
14424 const advance = () => input[index++];
14425 const push = node => {
14426 if (node.type === 'text' && prev.type === 'dot') {
14427 prev.type = 'text';
14428 }
14429 if (prev && prev.type === 'text' && node.type === 'text') {
14430 prev.value += node.value;
14431 return;
14432 }
14433 block.nodes.push(node);
14434 node.parent = block;
14435 node.prev = prev;
14436 prev = node;
14437 return node;
14438 };
14439 push({ type: 'bos' });
14440 while (index < length) {
14441 block = stack[stack.length - 1];
14442 value = advance();
14443 /**
14444 * Invalid chars
14445 */
14446 if (value === CHAR_ZERO_WIDTH_NOBREAK_SPACE || value === CHAR_NO_BREAK_SPACE) {
14447 continue;
14448 }
14449 /**
14450 * Escaped chars
14451 */
14452 if (value === CHAR_BACKSLASH) {
14453 push({ type: 'text', value: (options.keepEscaping ? value : '') + advance() });
14454 continue;
14455 }
14456 /**
14457 * Right square bracket (literal): ']'
14458 */
14459 if (value === CHAR_RIGHT_SQUARE_BRACKET) {
14460 push({ type: 'text', value: '\\' + value });
14461 continue;
14462 }
14463 /**
14464 * Left square bracket: '['
14465 */
14466 if (value === CHAR_LEFT_SQUARE_BRACKET) {
14467 brackets++;
14468 let next;
14469 while (index < length && (next = advance())) {
14470 value += next;
14471 if (next === CHAR_LEFT_SQUARE_BRACKET) {
14472 brackets++;
14473 continue;
14474 }
14475 if (next === CHAR_BACKSLASH) {
14476 value += advance();
14477 continue;
14478 }
14479 if (next === CHAR_RIGHT_SQUARE_BRACKET) {
14480 brackets--;
14481 if (brackets === 0) {
14482 break;
14483 }
14484 }
14485 }
14486 push({ type: 'text', value });
14487 continue;
14488 }
14489 /**
14490 * Parentheses
14491 */
14492 if (value === CHAR_LEFT_PARENTHESES) {
14493 block = push({ type: 'paren', nodes: [] });
14494 stack.push(block);
14495 push({ type: 'text', value });
14496 continue;
14497 }
14498 if (value === CHAR_RIGHT_PARENTHESES) {
14499 if (block.type !== 'paren') {
14500 push({ type: 'text', value });
14501 continue;
14502 }
14503 block = stack.pop();
14504 push({ type: 'text', value });
14505 block = stack[stack.length - 1];
14506 continue;
14507 }
14508 /**
14509 * Quotes: '|"|`
14510 */
14511 if (value === CHAR_DOUBLE_QUOTE || value === CHAR_SINGLE_QUOTE || value === CHAR_BACKTICK) {
14512 let open = value;
14513 let next;
14514 if (options.keepQuotes !== true) {
14515 value = '';
14516 }
14517 while (index < length && (next = advance())) {
14518 if (next === CHAR_BACKSLASH) {
14519 value += next + advance();
14520 continue;
14521 }
14522 if (next === open) {
14523 if (options.keepQuotes === true)
14524 value += next;
14525 break;
14526 }
14527 value += next;
14528 }
14529 push({ type: 'text', value });
14530 continue;
14531 }
14532 /**
14533 * Left curly brace: '{'
14534 */
14535 if (value === CHAR_LEFT_CURLY_BRACE) {
14536 depth++;
14537 let dollar = prev.value && prev.value.slice(-1) === '$' || block.dollar === true;
14538 let brace = {
14539 type: 'brace',
14540 open: true,
14541 close: false,
14542 dollar,
14543 depth,
14544 commas: 0,
14545 ranges: 0,
14546 nodes: []
14547 };
14548 block = push(brace);
14549 stack.push(block);
14550 push({ type: 'open', value });
14551 continue;
14552 }
14553 /**
14554 * Right curly brace: '}'
14555 */
14556 if (value === CHAR_RIGHT_CURLY_BRACE) {
14557 if (block.type !== 'brace') {
14558 push({ type: 'text', value });
14559 continue;
14560 }
14561 let type = 'close';
14562 block = stack.pop();
14563 block.close = true;
14564 push({ type, value });
14565 depth--;
14566 block = stack[stack.length - 1];
14567 continue;
14568 }
14569 /**
14570 * Comma: ','
14571 */
14572 if (value === CHAR_COMMA && depth > 0) {
14573 if (block.ranges > 0) {
14574 block.ranges = 0;
14575 let open = block.nodes.shift();
14576 block.nodes = [open, { type: 'text', value: stringify(block) }];
14577 }
14578 push({ type: 'comma', value });
14579 block.commas++;
14580 continue;
14581 }
14582 /**
14583 * Dot: '.'
14584 */
14585 if (value === CHAR_DOT && depth > 0 && block.commas === 0) {
14586 let siblings = block.nodes;
14587 if (depth === 0 || siblings.length === 0) {
14588 push({ type: 'text', value });
14589 continue;
14590 }
14591 if (prev.type === 'dot') {
14592 block.range = [];
14593 prev.value += value;
14594 prev.type = 'range';
14595 if (block.nodes.length !== 3 && block.nodes.length !== 5) {
14596 block.invalid = true;
14597 block.ranges = 0;
14598 prev.type = 'text';
14599 continue;
14600 }
14601 block.ranges++;
14602 block.args = [];
14603 continue;
14604 }
14605 if (prev.type === 'range') {
14606 siblings.pop();
14607 let before = siblings[siblings.length - 1];
14608 before.value += prev.value + value;
14609 prev = before;
14610 block.ranges--;
14611 continue;
14612 }
14613 push({ type: 'dot', value });
14614 continue;
14615 }
14616 /**
14617 * Text
14618 */
14619 push({ type: 'text', value });
14620 }
14621 // Mark imbalanced braces and brackets as invalid
14622 do {
14623 block = stack.pop();
14624 if (block.type !== 'root') {
14625 block.nodes.forEach(node => {
14626 if (!node.nodes) {
14627 if (node.type === 'open')
14628 node.isOpen = true;
14629 if (node.type === 'close')
14630 node.isClose = true;
14631 if (!node.nodes)
14632 node.type = 'text';
14633 node.invalid = true;
14634 }
14635 });
14636 // get the location of the block on parent.nodes (block's siblings)
14637 let parent = stack[stack.length - 1];
14638 let index = parent.nodes.indexOf(block);
14639 // replace the (invalid) block with it's nodes
14640 parent.nodes.splice(index, 1, ...block.nodes);
14641 }
14642 } while (stack.length > 0);
14643 push({ type: 'eos' });
14644 return ast;
14645};
14646var parse_1 = parse;
14647
14648/**
14649 * Expand the given pattern or create a regex-compatible string.
14650 *
14651 * ```js
14652 * const braces = require('braces');
14653 * console.log(braces('{a,b,c}', { compile: true })); //=> ['(a|b|c)']
14654 * console.log(braces('{a,b,c}')); //=> ['a', 'b', 'c']
14655 * ```
14656 * @param {String} `str`
14657 * @param {Object} `options`
14658 * @return {String}
14659 * @api public
14660 */
14661const braces = (input, options = {}) => {
14662 let output = [];
14663 if (Array.isArray(input)) {
14664 for (let pattern of input) {
14665 let result = braces.create(pattern, options);
14666 if (Array.isArray(result)) {
14667 output.push(...result);
14668 }
14669 else {
14670 output.push(result);
14671 }
14672 }
14673 }
14674 else {
14675 output = [].concat(braces.create(input, options));
14676 }
14677 if (options && options.expand === true && options.nodupes === true) {
14678 output = [...new Set(output)];
14679 }
14680 return output;
14681};
14682/**
14683 * Parse the given `str` with the given `options`.
14684 *
14685 * ```js
14686 * // braces.parse(pattern, [, options]);
14687 * const ast = braces.parse('a/{b,c}/d');
14688 * console.log(ast);
14689 * ```
14690 * @param {String} pattern Brace pattern to parse
14691 * @param {Object} options
14692 * @return {Object} Returns an AST
14693 * @api public
14694 */
14695braces.parse = (input, options = {}) => parse_1(input, options);
14696/**
14697 * Creates a braces string from an AST, or an AST node.
14698 *
14699 * ```js
14700 * const braces = require('braces');
14701 * let ast = braces.parse('foo/{a,b}/bar');
14702 * console.log(stringify(ast.nodes[2])); //=> '{a,b}'
14703 * ```
14704 * @param {String} `input` Brace pattern or AST.
14705 * @param {Object} `options`
14706 * @return {Array} Returns an array of expanded values.
14707 * @api public
14708 */
14709braces.stringify = (input, options = {}) => {
14710 if (typeof input === 'string') {
14711 return stringify(braces.parse(input, options), options);
14712 }
14713 return stringify(input, options);
14714};
14715/**
14716 * Compiles a brace pattern into a regex-compatible, optimized string.
14717 * This method is called by the main [braces](#braces) function by default.
14718 *
14719 * ```js
14720 * const braces = require('braces');
14721 * console.log(braces.compile('a/{b,c}/d'));
14722 * //=> ['a/(b|c)/d']
14723 * ```
14724 * @param {String} `input` Brace pattern or AST.
14725 * @param {Object} `options`
14726 * @return {Array} Returns an array of expanded values.
14727 * @api public
14728 */
14729braces.compile = (input, options = {}) => {
14730 if (typeof input === 'string') {
14731 input = braces.parse(input, options);
14732 }
14733 return compile_1(input, options);
14734};
14735/**
14736 * Expands a brace pattern into an array. This method is called by the
14737 * main [braces](#braces) function when `options.expand` is true. Before
14738 * using this method it's recommended that you read the [performance notes](#performance))
14739 * and advantages of using [.compile](#compile) instead.
14740 *
14741 * ```js
14742 * const braces = require('braces');
14743 * console.log(braces.expand('a/{b,c}/d'));
14744 * //=> ['a/b/d', 'a/c/d'];
14745 * ```
14746 * @param {String} `pattern` Brace pattern
14747 * @param {Object} `options`
14748 * @return {Array} Returns an array of expanded values.
14749 * @api public
14750 */
14751braces.expand = (input, options = {}) => {
14752 if (typeof input === 'string') {
14753 input = braces.parse(input, options);
14754 }
14755 let result = expand_1(input, options);
14756 // filter out empty strings if specified
14757 if (options.noempty === true) {
14758 result = result.filter(Boolean);
14759 }
14760 // filter out duplicates if specified
14761 if (options.nodupes === true) {
14762 result = [...new Set(result)];
14763 }
14764 return result;
14765};
14766/**
14767 * Processes a brace pattern and returns either an expanded array
14768 * (if `options.expand` is true), a highly optimized regex-compatible string.
14769 * This method is called by the main [braces](#braces) function.
14770 *
14771 * ```js
14772 * const braces = require('braces');
14773 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
14774 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
14775 * ```
14776 * @param {String} `pattern` Brace pattern
14777 * @param {Object} `options`
14778 * @return {Array} Returns an array of expanded values.
14779 * @api public
14780 */
14781braces.create = (input, options = {}) => {
14782 if (input === '' || input.length < 3) {
14783 return [input];
14784 }
14785 return options.expand !== true
14786 ? braces.compile(input, options)
14787 : braces.expand(input, options);
14788};
14789/**
14790 * Expose "braces"
14791 */
14792var braces_1 = braces;
14793
14794const WIN_SLASH = '\\\\/';
14795const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
14796/**
14797 * Posix glob regex
14798 */
14799const DOT_LITERAL = '\\.';
14800const PLUS_LITERAL = '\\+';
14801const QMARK_LITERAL = '\\?';
14802const SLASH_LITERAL = '\\/';
14803const ONE_CHAR = '(?=.)';
14804const QMARK = '[^/]';
14805const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
14806const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
14807const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
14808const NO_DOT = `(?!${DOT_LITERAL})`;
14809const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
14810const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
14811const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
14812const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
14813const STAR = `${QMARK}*?`;
14814const POSIX_CHARS = {
14815 DOT_LITERAL,
14816 PLUS_LITERAL,
14817 QMARK_LITERAL,
14818 SLASH_LITERAL,
14819 ONE_CHAR,
14820 QMARK,
14821 END_ANCHOR,
14822 DOTS_SLASH,
14823 NO_DOT,
14824 NO_DOTS,
14825 NO_DOT_SLASH,
14826 NO_DOTS_SLASH,
14827 QMARK_NO_DOT,
14828 STAR,
14829 START_ANCHOR
14830};
14831/**
14832 * Windows glob regex
14833 */
14834const WINDOWS_CHARS = Object.assign(Object.assign({}, POSIX_CHARS), { SLASH_LITERAL: `[${WIN_SLASH}]`, QMARK: WIN_NO_SLASH, STAR: `${WIN_NO_SLASH}*?`, DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`, NO_DOT: `(?!${DOT_LITERAL})`, NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`, NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`, QMARK_NO_DOT: `[^.${WIN_SLASH}]`, START_ANCHOR: `(?:^|[${WIN_SLASH}])`, END_ANCHOR: `(?:[${WIN_SLASH}]|$)` });
14835/**
14836 * POSIX Bracket Regex
14837 */
14838const POSIX_REGEX_SOURCE = {
14839 alnum: 'a-zA-Z0-9',
14840 alpha: 'a-zA-Z',
14841 ascii: '\\x00-\\x7F',
14842 blank: ' \\t',
14843 cntrl: '\\x00-\\x1F\\x7F',
14844 digit: '0-9',
14845 graph: '\\x21-\\x7E',
14846 lower: 'a-z',
14847 print: '\\x20-\\x7E ',
14848 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
14849 space: ' \\t\\r\\n\\v\\f',
14850 upper: 'A-Z',
14851 word: 'A-Za-z0-9_',
14852 xdigit: 'A-Fa-f0-9'
14853};
14854var constants$1 = {
14855 MAX_LENGTH: 1024 * 64,
14856 POSIX_REGEX_SOURCE,
14857 // regular expressions
14858 REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
14859 REGEX_NON_SPECIAL_CHAR: /^[^@![\].,$*+?^{}()|\\/]+/,
14860 REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
14861 REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
14862 REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
14863 REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
14864 // Replace globs with equivalent patterns to reduce parsing time.
14865 REPLACEMENTS: {
14866 '***': '*',
14867 '**/**': '**',
14868 '**/**/**': '**'
14869 },
14870 // Digits
14871 CHAR_0: 48,
14872 CHAR_9: 57,
14873 // Alphabet chars.
14874 CHAR_UPPERCASE_A: 65,
14875 CHAR_LOWERCASE_A: 97,
14876 CHAR_UPPERCASE_Z: 90,
14877 CHAR_LOWERCASE_Z: 122,
14878 CHAR_LEFT_PARENTHESES: 40,
14879 CHAR_RIGHT_PARENTHESES: 41,
14880 CHAR_ASTERISK: 42,
14881 // Non-alphabetic chars.
14882 CHAR_AMPERSAND: 38,
14883 CHAR_AT: 64,
14884 CHAR_BACKWARD_SLASH: 92,
14885 CHAR_CARRIAGE_RETURN: 13,
14886 CHAR_CIRCUMFLEX_ACCENT: 94,
14887 CHAR_COLON: 58,
14888 CHAR_COMMA: 44,
14889 CHAR_DOT: 46,
14890 CHAR_DOUBLE_QUOTE: 34,
14891 CHAR_EQUAL: 61,
14892 CHAR_EXCLAMATION_MARK: 33,
14893 CHAR_FORM_FEED: 12,
14894 CHAR_FORWARD_SLASH: 47,
14895 CHAR_GRAVE_ACCENT: 96,
14896 CHAR_HASH: 35,
14897 CHAR_HYPHEN_MINUS: 45,
14898 CHAR_LEFT_ANGLE_BRACKET: 60,
14899 CHAR_LEFT_CURLY_BRACE: 123,
14900 CHAR_LEFT_SQUARE_BRACKET: 91,
14901 CHAR_LINE_FEED: 10,
14902 CHAR_NO_BREAK_SPACE: 160,
14903 CHAR_PERCENT: 37,
14904 CHAR_PLUS: 43,
14905 CHAR_QUESTION_MARK: 63,
14906 CHAR_RIGHT_ANGLE_BRACKET: 62,
14907 CHAR_RIGHT_CURLY_BRACE: 125,
14908 CHAR_RIGHT_SQUARE_BRACKET: 93,
14909 CHAR_SEMICOLON: 59,
14910 CHAR_SINGLE_QUOTE: 39,
14911 CHAR_SPACE: 32,
14912 CHAR_TAB: 9,
14913 CHAR_UNDERSCORE: 95,
14914 CHAR_VERTICAL_LINE: 124,
14915 CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279,
14916 SEP: path.sep,
14917 /**
14918 * Create EXTGLOB_CHARS
14919 */
14920 extglobChars(chars) {
14921 return {
14922 '!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
14923 '?': { type: 'qmark', open: '(?:', close: ')?' },
14924 '+': { type: 'plus', open: '(?:', close: ')+' },
14925 '*': { type: 'star', open: '(?:', close: ')*' },
14926 '@': { type: 'at', open: '(?:', close: ')' }
14927 };
14928 },
14929 /**
14930 * Create GLOB_CHARS
14931 */
14932 globChars(win32) {
14933 return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
14934 }
14935};
14936
14937var utils$2 = index.createCommonjsModule(function (module, exports) {
14938 const win32 = process.platform === 'win32';
14939 const { REGEX_SPECIAL_CHARS, REGEX_SPECIAL_CHARS_GLOBAL, REGEX_REMOVE_BACKSLASH } = constants$1;
14940 exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
14941 exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
14942 exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
14943 exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
14944 exports.toPosixSlashes = str => str.replace(/\\/g, '/');
14945 exports.removeBackslashes = str => {
14946 return str.replace(REGEX_REMOVE_BACKSLASH, match => {
14947 return match === '\\' ? '' : match;
14948 });
14949 };
14950 exports.supportsLookbehinds = () => {
14951 let segs = process.version.slice(1).split('.');
14952 if (segs.length === 3 && +segs[0] >= 9 || (+segs[0] === 8 && +segs[1] >= 10)) {
14953 return true;
14954 }
14955 return false;
14956 };
14957 exports.isWindows = options => {
14958 if (options && typeof options.windows === 'boolean') {
14959 return options.windows;
14960 }
14961 return win32 === true || path.sep === '\\';
14962 };
14963 exports.escapeLast = (input, char, lastIdx) => {
14964 let idx = input.lastIndexOf(char, lastIdx);
14965 if (idx === -1)
14966 return input;
14967 if (input[idx - 1] === '\\')
14968 return exports.escapeLast(input, char, idx - 1);
14969 return input.slice(0, idx) + '\\' + input.slice(idx);
14970 };
14971});
14972
14973const { CHAR_ASTERISK, /* * */ CHAR_AT, /* @ */ CHAR_BACKWARD_SLASH, /* \ */ CHAR_COMMA: CHAR_COMMA$1, /* , */ CHAR_DOT: CHAR_DOT$1, /* . */ CHAR_EXCLAMATION_MARK, /* ! */ CHAR_FORWARD_SLASH, /* / */ CHAR_LEFT_CURLY_BRACE: CHAR_LEFT_CURLY_BRACE$1, /* { */ CHAR_LEFT_PARENTHESES: CHAR_LEFT_PARENTHESES$1, /* ( */ CHAR_LEFT_SQUARE_BRACKET: CHAR_LEFT_SQUARE_BRACKET$1, /* [ */ CHAR_PLUS, /* + */ CHAR_QUESTION_MARK, /* ? */ CHAR_RIGHT_CURLY_BRACE: CHAR_RIGHT_CURLY_BRACE$1, /* } */ CHAR_RIGHT_PARENTHESES: CHAR_RIGHT_PARENTHESES$1, /* ) */ CHAR_RIGHT_SQUARE_BRACKET: CHAR_RIGHT_SQUARE_BRACKET$1 /* ] */ } = constants$1;
14974const isPathSeparator = code => {
14975 return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
14976};
14977/**
14978 * Quickly scans a glob pattern and returns an object with a handful of
14979 * useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
14980 * `glob` (the actual pattern), and `negated` (true if the path starts with `!`).
14981 *
14982 * ```js
14983 * const pm = require('picomatch');
14984 * console.log(pm.scan('foo/bar/*.js'));
14985 * { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
14986 * ```
14987 * @param {String} `str`
14988 * @param {Object} `options`
14989 * @return {Object} Returns an object with tokens and regex source string.
14990 * @api public
14991 */
14992var scan = (input, options) => {
14993 let opts = options || {};
14994 let length = input.length - 1;
14995 let index = -1;
14996 let start = 0;
14997 let lastIndex = 0;
14998 let isGlob = false;
14999 let backslashes = false;
15000 let negated = false;
15001 let braces = 0;
15002 let prev;
15003 let code;
15004 let braceEscaped = false;
15005 let eos = () => index >= length;
15006 let advance = () => {
15007 prev = code;
15008 return input.charCodeAt(++index);
15009 };
15010 while (index < length) {
15011 code = advance();
15012 let next;
15013 if (code === CHAR_BACKWARD_SLASH) {
15014 backslashes = true;
15015 next = advance();
15016 if (next === CHAR_LEFT_CURLY_BRACE$1) {
15017 braceEscaped = true;
15018 }
15019 continue;
15020 }
15021 if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE$1) {
15022 braces++;
15023 while (!eos() && (next = advance())) {
15024 if (next === CHAR_BACKWARD_SLASH) {
15025 backslashes = true;
15026 next = advance();
15027 continue;
15028 }
15029 if (next === CHAR_LEFT_CURLY_BRACE$1) {
15030 braces++;
15031 continue;
15032 }
15033 if (!braceEscaped && next === CHAR_DOT$1 && (next = advance()) === CHAR_DOT$1) {
15034 isGlob = true;
15035 break;
15036 }
15037 if (!braceEscaped && next === CHAR_COMMA$1) {
15038 isGlob = true;
15039 break;
15040 }
15041 if (next === CHAR_RIGHT_CURLY_BRACE$1) {
15042 braces--;
15043 if (braces === 0) {
15044 braceEscaped = false;
15045 break;
15046 }
15047 }
15048 }
15049 }
15050 if (code === CHAR_FORWARD_SLASH) {
15051 if (prev === CHAR_DOT$1 && index === (start + 1)) {
15052 start += 2;
15053 continue;
15054 }
15055 lastIndex = index + 1;
15056 continue;
15057 }
15058 if (code === CHAR_ASTERISK) {
15059 isGlob = true;
15060 break;
15061 }
15062 if (code === CHAR_ASTERISK || code === CHAR_QUESTION_MARK) {
15063 isGlob = true;
15064 break;
15065 }
15066 if (code === CHAR_LEFT_SQUARE_BRACKET$1) {
15067 while (!eos() && (next = advance())) {
15068 if (next === CHAR_BACKWARD_SLASH) {
15069 backslashes = true;
15070 next = advance();
15071 continue;
15072 }
15073 if (next === CHAR_RIGHT_SQUARE_BRACKET$1) {
15074 isGlob = true;
15075 break;
15076 }
15077 }
15078 }
15079 let isExtglobChar = code === CHAR_PLUS
15080 || code === CHAR_AT
15081 || code === CHAR_EXCLAMATION_MARK;
15082 if (isExtglobChar && input.charCodeAt(index + 1) === CHAR_LEFT_PARENTHESES$1) {
15083 isGlob = true;
15084 break;
15085 }
15086 if (code === CHAR_EXCLAMATION_MARK && index === start) {
15087 negated = true;
15088 start++;
15089 continue;
15090 }
15091 if (code === CHAR_LEFT_PARENTHESES$1) {
15092 while (!eos() && (next = advance())) {
15093 if (next === CHAR_BACKWARD_SLASH) {
15094 backslashes = true;
15095 next = advance();
15096 continue;
15097 }
15098 if (next === CHAR_RIGHT_PARENTHESES$1) {
15099 isGlob = true;
15100 break;
15101 }
15102 }
15103 }
15104 if (isGlob) {
15105 break;
15106 }
15107 }
15108 let prefix = '';
15109 let orig = input;
15110 let base = input;
15111 let glob = '';
15112 if (start > 0) {
15113 prefix = input.slice(0, start);
15114 input = input.slice(start);
15115 lastIndex -= start;
15116 }
15117 if (base && isGlob === true && lastIndex > 0) {
15118 base = input.slice(0, lastIndex);
15119 glob = input.slice(lastIndex);
15120 }
15121 else if (isGlob === true) {
15122 base = '';
15123 glob = input;
15124 }
15125 else {
15126 base = input;
15127 }
15128 if (base && base !== '' && base !== '/' && base !== input) {
15129 if (isPathSeparator(base.charCodeAt(base.length - 1))) {
15130 base = base.slice(0, -1);
15131 }
15132 }
15133 if (opts.unescape === true) {
15134 if (glob)
15135 glob = utils$2.removeBackslashes(glob);
15136 if (base && backslashes === true) {
15137 base = utils$2.removeBackslashes(base);
15138 }
15139 }
15140 return { prefix, input: orig, base, glob, negated, isGlob };
15141};
15142
15143/**
15144 * Constants
15145 */
15146const { MAX_LENGTH: MAX_LENGTH$1, POSIX_REGEX_SOURCE: POSIX_REGEX_SOURCE$1, REGEX_NON_SPECIAL_CHAR, REGEX_SPECIAL_CHARS_BACKREF, REPLACEMENTS } = constants$1;
15147/**
15148 * Helpers
15149 */
15150const expandRange = (args, options) => {
15151 if (typeof options.expandRange === 'function') {
15152 return options.expandRange(...args, options);
15153 }
15154 args.sort();
15155 let value = `[${args.join('-')}]`;
15156 return value;
15157};
15158const negate = state => {
15159 let count = 1;
15160 while (state.peek() === '!' && (state.peek(2) !== '(' || state.peek(3) === '?')) {
15161 state.advance();
15162 state.start++;
15163 count++;
15164 }
15165 if (count % 2 === 0) {
15166 return false;
15167 }
15168 state.negated = true;
15169 state.start++;
15170 return true;
15171};
15172/**
15173 * Create the message for a syntax error
15174 */
15175const syntaxError = (type, char) => {
15176 return `Missing ${type}: "${char}" - use "\\\\${char}" to match literal characters`;
15177};
15178/**
15179 * Parse the given input string.
15180 * @param {String} input
15181 * @param {Object} options
15182 * @return {Object}
15183 */
15184const parse$1 = (input, options) => {
15185 if (typeof input !== 'string') {
15186 throw new TypeError('Expected a string');
15187 }
15188 input = REPLACEMENTS[input] || input;
15189 let opts = Object.assign({}, options);
15190 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
15191 let len = input.length;
15192 if (len > max) {
15193 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
15194 }
15195 let bos = { type: 'bos', value: '', output: opts.prepend || '' };
15196 let tokens = [bos];
15197 let capture = opts.capture ? '' : '?:';
15198 let win32 = utils$2.isWindows(options);
15199 // create constants based on platform, for windows or posix
15200 const PLATFORM_CHARS = constants$1.globChars(win32);
15201 const EXTGLOB_CHARS = constants$1.extglobChars(PLATFORM_CHARS);
15202 const { DOT_LITERAL, PLUS_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOT_SLASH, NO_DOTS_SLASH, QMARK, QMARK_NO_DOT, STAR, START_ANCHOR } = PLATFORM_CHARS;
15203 const globstar = (opts) => {
15204 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
15205 };
15206 let nodot = opts.dot ? '' : NO_DOT;
15207 let star = opts.bash === true ? globstar(opts) : STAR;
15208 let qmarkNoDot = opts.dot ? QMARK : QMARK_NO_DOT;
15209 if (opts.capture) {
15210 star = `(${star})`;
15211 }
15212 // minimatch options support
15213 if (typeof opts.noext === 'boolean') {
15214 opts.noextglob = opts.noext;
15215 }
15216 let state = {
15217 index: -1,
15218 start: 0,
15219 consumed: '',
15220 output: '',
15221 backtrack: false,
15222 brackets: 0,
15223 braces: 0,
15224 parens: 0,
15225 quotes: 0,
15226 tokens
15227 };
15228 let extglobs = [];
15229 let stack = [];
15230 let prev = bos;
15231 let value;
15232 /**
15233 * Tokenizing helpers
15234 */
15235 const eos = () => state.index === len - 1;
15236 const peek = state.peek = (n = 1) => input[state.index + n];
15237 const advance = state.advance = () => input[++state.index];
15238 const append = token => {
15239 state.output += token.output != null ? token.output : token.value;
15240 state.consumed += token.value || '';
15241 };
15242 const increment = type => {
15243 state[type]++;
15244 stack.push(type);
15245 };
15246 const decrement = type => {
15247 state[type]--;
15248 stack.pop();
15249 };
15250 /**
15251 * Push tokens onto the tokens array. This helper speeds up
15252 * tokenizing by 1) helping us avoid backtracking as much as possible,
15253 * and 2) helping us avoid creating extra tokens when consecutive
15254 * characters are plain text. This improves performance and simplifies
15255 * lookbehinds.
15256 */
15257 const push = tok => {
15258 if (prev.type === 'globstar') {
15259 let isBrace = state.braces > 0 && (tok.type === 'comma' || tok.type === 'brace');
15260 let isExtglob = extglobs.length && (tok.type === 'pipe' || tok.type === 'paren');
15261 if (tok.type !== 'slash' && tok.type !== 'paren' && !isBrace && !isExtglob) {
15262 state.output = state.output.slice(0, -prev.output.length);
15263 prev.type = 'star';
15264 prev.value = '*';
15265 prev.output = star;
15266 state.output += prev.output;
15267 }
15268 }
15269 if (extglobs.length && tok.type !== 'paren' && !EXTGLOB_CHARS[tok.value]) {
15270 extglobs[extglobs.length - 1].inner += tok.value;
15271 }
15272 if (tok.value || tok.output)
15273 append(tok);
15274 if (prev && prev.type === 'text' && tok.type === 'text') {
15275 prev.value += tok.value;
15276 return;
15277 }
15278 tok.prev = prev;
15279 tokens.push(tok);
15280 prev = tok;
15281 };
15282 const extglobOpen = (type, value) => {
15283 let token = Object.assign(Object.assign({}, EXTGLOB_CHARS[value]), { conditions: 1, inner: '' });
15284 token.prev = prev;
15285 token.parens = state.parens;
15286 token.output = state.output;
15287 let output = (opts.capture ? '(' : '') + token.open;
15288 push({ type, value, output: state.output ? '' : ONE_CHAR });
15289 push({ type: 'paren', extglob: true, value: advance(), output });
15290 increment('parens');
15291 extglobs.push(token);
15292 };
15293 const extglobClose = token => {
15294 let output = token.close + (opts.capture ? ')' : '');
15295 if (token.type === 'negate') {
15296 let extglobStar = star;
15297 if (token.inner && token.inner.length > 1 && token.inner.includes('/')) {
15298 extglobStar = globstar(opts);
15299 }
15300 if (extglobStar !== star || eos() || /^\)+$/.test(input.slice(state.index + 1))) {
15301 output = token.close = ')$))' + extglobStar;
15302 }
15303 if (token.prev.type === 'bos' && eos()) {
15304 state.negatedExtglob = true;
15305 }
15306 }
15307 push({ type: 'paren', extglob: true, value, output });
15308 decrement('parens');
15309 };
15310 if (opts.fastpaths !== false && !/(^[*!]|[/{[()\]}"])/.test(input)) {
15311 let backslashes = false;
15312 let output = input.replace(REGEX_SPECIAL_CHARS_BACKREF, (m, esc, chars, first, rest, index) => {
15313 if (first === '\\') {
15314 backslashes = true;
15315 return m;
15316 }
15317 if (first === '?') {
15318 if (esc) {
15319 return esc + first + (rest ? QMARK.repeat(rest.length) : '');
15320 }
15321 if (index === 0) {
15322 return qmarkNoDot + (rest ? QMARK.repeat(rest.length) : '');
15323 }
15324 return QMARK.repeat(chars.length);
15325 }
15326 if (first === '.') {
15327 return DOT_LITERAL.repeat(chars.length);
15328 }
15329 if (first === '*') {
15330 if (esc) {
15331 return esc + first + (rest ? star : '');
15332 }
15333 return star;
15334 }
15335 return esc ? m : '\\' + m;
15336 });
15337 if (backslashes === true) {
15338 if (opts.unescape === true) {
15339 output = output.replace(/\\/g, '');
15340 }
15341 else {
15342 output = output.replace(/\\+/g, m => {
15343 return m.length % 2 === 0 ? '\\\\' : (m ? '\\' : '');
15344 });
15345 }
15346 }
15347 state.output = output;
15348 return state;
15349 }
15350 /**
15351 * Tokenize input until we reach end-of-string
15352 */
15353 while (!eos()) {
15354 value = advance();
15355 if (value === '\u0000') {
15356 continue;
15357 }
15358 /**
15359 * Escaped characters
15360 */
15361 if (value === '\\') {
15362 let next = peek();
15363 if (next === '/' && opts.bash !== true) {
15364 continue;
15365 }
15366 if (next === '.' || next === ';') {
15367 continue;
15368 }
15369 if (!next) {
15370 value += '\\';
15371 push({ type: 'text', value });
15372 continue;
15373 }
15374 // collapse slashes to reduce potential for exploits
15375 let match = /^\\+/.exec(input.slice(state.index + 1));
15376 let slashes = 0;
15377 if (match && match[0].length > 2) {
15378 slashes = match[0].length;
15379 state.index += slashes;
15380 if (slashes % 2 !== 0) {
15381 value += '\\';
15382 }
15383 }
15384 if (opts.unescape === true) {
15385 value = advance() || '';
15386 }
15387 else {
15388 value += advance() || '';
15389 }
15390 if (state.brackets === 0) {
15391 push({ type: 'text', value });
15392 continue;
15393 }
15394 }
15395 /**
15396 * If we're inside a regex character class, continue
15397 * until we reach the closing bracket.
15398 */
15399 if (state.brackets > 0 && (value !== ']' || prev.value === '[' || prev.value === '[^')) {
15400 if (opts.posix !== false && value === ':') {
15401 let inner = prev.value.slice(1);
15402 if (inner.includes('[')) {
15403 prev.posix = true;
15404 if (inner.includes(':')) {
15405 let idx = prev.value.lastIndexOf('[');
15406 let pre = prev.value.slice(0, idx);
15407 let rest = prev.value.slice(idx + 2);
15408 let posix = POSIX_REGEX_SOURCE$1[rest];
15409 if (posix) {
15410 prev.value = pre + posix;
15411 state.backtrack = true;
15412 advance();
15413 if (!bos.output && tokens.indexOf(prev) === 1) {
15414 bos.output = ONE_CHAR;
15415 }
15416 continue;
15417 }
15418 }
15419 }
15420 }
15421 if ((value === '[' && peek() !== ':') || (value === '-' && peek() === ']')) {
15422 value = '\\' + value;
15423 }
15424 if (value === ']' && (prev.value === '[' || prev.value === '[^')) {
15425 value = '\\' + value;
15426 }
15427 if (opts.posix === true && value === '!' && prev.value === '[') {
15428 value = '^';
15429 }
15430 prev.value += value;
15431 append({ value });
15432 continue;
15433 }
15434 /**
15435 * If we're inside a quoted string, continue
15436 * until we reach the closing double quote.
15437 */
15438 if (state.quotes === 1 && value !== '"') {
15439 value = utils$2.escapeRegex(value);
15440 prev.value += value;
15441 append({ value });
15442 continue;
15443 }
15444 /**
15445 * Double quotes
15446 */
15447 if (value === '"') {
15448 state.quotes = state.quotes === 1 ? 0 : 1;
15449 if (opts.keepQuotes === true) {
15450 push({ type: 'text', value });
15451 }
15452 continue;
15453 }
15454 /**
15455 * Parentheses
15456 */
15457 if (value === '(') {
15458 push({ type: 'paren', value });
15459 increment('parens');
15460 continue;
15461 }
15462 if (value === ')') {
15463 if (state.parens === 0 && opts.strictBrackets === true) {
15464 throw new SyntaxError(syntaxError('opening', '('));
15465 }
15466 let extglob = extglobs[extglobs.length - 1];
15467 if (extglob && state.parens === extglob.parens + 1) {
15468 extglobClose(extglobs.pop());
15469 continue;
15470 }
15471 push({ type: 'paren', value, output: state.parens ? ')' : '\\)' });
15472 decrement('parens');
15473 continue;
15474 }
15475 /**
15476 * Brackets
15477 */
15478 if (value === '[') {
15479 if (opts.nobracket === true || !input.slice(state.index + 1).includes(']')) {
15480 if (opts.nobracket !== true && opts.strictBrackets === true) {
15481 throw new SyntaxError(syntaxError('closing', ']'));
15482 }
15483 value = '\\' + value;
15484 }
15485 else {
15486 increment('brackets');
15487 }
15488 push({ type: 'bracket', value });
15489 continue;
15490 }
15491 if (value === ']') {
15492 if (opts.nobracket === true || (prev && prev.type === 'bracket' && prev.value.length === 1)) {
15493 push({ type: 'text', value, output: '\\' + value });
15494 continue;
15495 }
15496 if (state.brackets === 0) {
15497 if (opts.strictBrackets === true) {
15498 throw new SyntaxError(syntaxError('opening', '['));
15499 }
15500 push({ type: 'text', value, output: '\\' + value });
15501 continue;
15502 }
15503 decrement('brackets');
15504 let prevValue = prev.value.slice(1);
15505 if (prev.posix !== true && prevValue[0] === '^' && !prevValue.includes('/')) {
15506 value = '/' + value;
15507 }
15508 prev.value += value;
15509 append({ value });
15510 // when literal brackets are explicitly disabled
15511 // assume we should match with a regex character class
15512 if (opts.literalBrackets === false || utils$2.hasRegexChars(prevValue)) {
15513 continue;
15514 }
15515 let escaped = utils$2.escapeRegex(prev.value);
15516 state.output = state.output.slice(0, -prev.value.length);
15517 // when literal brackets are explicitly enabled
15518 // assume we should escape the brackets to match literal characters
15519 if (opts.literalBrackets === true) {
15520 state.output += escaped;
15521 prev.value = escaped;
15522 continue;
15523 }
15524 // when the user specifies nothing, try to match both
15525 prev.value = `(${capture}${escaped}|${prev.value})`;
15526 state.output += prev.value;
15527 continue;
15528 }
15529 /**
15530 * Braces
15531 */
15532 if (value === '{' && opts.nobrace !== true) {
15533 push({ type: 'brace', value, output: '(' });
15534 increment('braces');
15535 continue;
15536 }
15537 if (value === '}') {
15538 if (opts.nobrace === true || state.braces === 0) {
15539 push({ type: 'text', value, output: '\\' + value });
15540 continue;
15541 }
15542 let output = ')';
15543 if (state.dots === true) {
15544 let arr = tokens.slice();
15545 let range = [];
15546 for (let i = arr.length - 1; i >= 0; i--) {
15547 tokens.pop();
15548 if (arr[i].type === 'brace') {
15549 break;
15550 }
15551 if (arr[i].type !== 'dots') {
15552 range.unshift(arr[i].value);
15553 }
15554 }
15555 output = expandRange(range, opts);
15556 state.backtrack = true;
15557 }
15558 push({ type: 'brace', value, output });
15559 decrement('braces');
15560 continue;
15561 }
15562 /**
15563 * Pipes
15564 */
15565 if (value === '|') {
15566 if (extglobs.length > 0) {
15567 extglobs[extglobs.length - 1].conditions++;
15568 }
15569 push({ type: 'text', value });
15570 continue;
15571 }
15572 /**
15573 * Commas
15574 */
15575 if (value === ',') {
15576 let output = value;
15577 if (state.braces > 0 && stack[stack.length - 1] === 'braces') {
15578 output = '|';
15579 }
15580 push({ type: 'comma', value, output });
15581 continue;
15582 }
15583 /**
15584 * Slashes
15585 */
15586 if (value === '/') {
15587 // if the beginning of the glob is "./", advance the start
15588 // to the current index, and don't add the "./" characters
15589 // to the state. This greatly simplifies lookbehinds when
15590 // checking for BOS characters like "!" and "." (not "./")
15591 if (prev.type === 'dot' && state.index === 1) {
15592 state.start = state.index + 1;
15593 state.consumed = '';
15594 state.output = '';
15595 tokens.pop();
15596 prev = bos; // reset "prev" to the first token
15597 continue;
15598 }
15599 push({ type: 'slash', value, output: SLASH_LITERAL });
15600 continue;
15601 }
15602 /**
15603 * Dots
15604 */
15605 if (value === '.') {
15606 if (state.braces > 0 && prev.type === 'dot') {
15607 if (prev.value === '.')
15608 prev.output = DOT_LITERAL;
15609 prev.type = 'dots';
15610 prev.output += value;
15611 prev.value += value;
15612 state.dots = true;
15613 continue;
15614 }
15615 push({ type: 'dot', value, output: DOT_LITERAL });
15616 continue;
15617 }
15618 /**
15619 * Question marks
15620 */
15621 if (value === '?') {
15622 if (prev && prev.type === 'paren') {
15623 let next = peek();
15624 let output = value;
15625 if (next === '<' && !utils$2.supportsLookbehinds()) {
15626 throw new Error('Node.js v10 or higher is required for regex lookbehinds');
15627 }
15628 if (prev.value === '(' && !/[!=<:]/.test(next) || (next === '<' && !/[!=]/.test(peek(2)))) {
15629 output = '\\' + value;
15630 }
15631 push({ type: 'text', value, output });
15632 continue;
15633 }
15634 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
15635 extglobOpen('qmark', value);
15636 continue;
15637 }
15638 if (opts.dot !== true && (prev.type === 'slash' || prev.type === 'bos')) {
15639 push({ type: 'qmark', value, output: QMARK_NO_DOT });
15640 continue;
15641 }
15642 push({ type: 'qmark', value, output: QMARK });
15643 continue;
15644 }
15645 /**
15646 * Exclamation
15647 */
15648 if (value === '!') {
15649 if (opts.noextglob !== true && peek() === '(') {
15650 if (peek(2) !== '?' || !/[!=<:]/.test(peek(3))) {
15651 extglobOpen('negate', value);
15652 continue;
15653 }
15654 }
15655 if (opts.nonegate !== true && state.index === 0) {
15656 negate(state);
15657 continue;
15658 }
15659 }
15660 /**
15661 * Plus
15662 */
15663 if (value === '+') {
15664 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
15665 extglobOpen('plus', value);
15666 continue;
15667 }
15668 if (prev && (prev.type === 'bracket' || prev.type === 'paren' || prev.type === 'brace')) {
15669 let output = prev.extglob === true ? '\\' + value : value;
15670 push({ type: 'plus', value, output });
15671 continue;
15672 }
15673 // use regex behavior inside parens
15674 if (state.parens > 0 && opts.regex !== false) {
15675 push({ type: 'plus', value });
15676 continue;
15677 }
15678 push({ type: 'plus', value: PLUS_LITERAL });
15679 continue;
15680 }
15681 /**
15682 * Plain text
15683 */
15684 if (value === '@') {
15685 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
15686 push({ type: 'at', value, output: '' });
15687 continue;
15688 }
15689 push({ type: 'text', value });
15690 continue;
15691 }
15692 /**
15693 * Plain text
15694 */
15695 if (value !== '*') {
15696 if (value === '$' || value === '^') {
15697 value = '\\' + value;
15698 }
15699 let match = REGEX_NON_SPECIAL_CHAR.exec(input.slice(state.index + 1));
15700 if (match) {
15701 value += match[0];
15702 state.index += match[0].length;
15703 }
15704 push({ type: 'text', value });
15705 continue;
15706 }
15707 /**
15708 * Stars
15709 */
15710 if (prev && (prev.type === 'globstar' || prev.star === true)) {
15711 prev.type = 'star';
15712 prev.star = true;
15713 prev.value += value;
15714 prev.output = star;
15715 state.backtrack = true;
15716 state.consumed += value;
15717 continue;
15718 }
15719 if (opts.noextglob !== true && peek() === '(' && peek(2) !== '?') {
15720 extglobOpen('star', value);
15721 continue;
15722 }
15723 if (prev.type === 'star') {
15724 if (opts.noglobstar === true) {
15725 state.consumed += value;
15726 continue;
15727 }
15728 let prior = prev.prev;
15729 let before = prior.prev;
15730 let isStart = prior.type === 'slash' || prior.type === 'bos';
15731 let afterStar = before && (before.type === 'star' || before.type === 'globstar');
15732 if (opts.bash === true && (!isStart || (!eos() && peek() !== '/'))) {
15733 push({ type: 'star', value, output: '' });
15734 continue;
15735 }
15736 let isBrace = state.braces > 0 && (prior.type === 'comma' || prior.type === 'brace');
15737 let isExtglob = extglobs.length && (prior.type === 'pipe' || prior.type === 'paren');
15738 if (!isStart && prior.type !== 'paren' && !isBrace && !isExtglob) {
15739 push({ type: 'star', value, output: '' });
15740 continue;
15741 }
15742 // strip consecutive `/**/`
15743 while (input.slice(state.index + 1, state.index + 4) === '/**') {
15744 let after = input[state.index + 4];
15745 if (after && after !== '/') {
15746 break;
15747 }
15748 state.consumed += '/**';
15749 state.index += 3;
15750 }
15751 if (prior.type === 'bos' && eos()) {
15752 prev.type = 'globstar';
15753 prev.value += value;
15754 prev.output = globstar(opts);
15755 state.output = prev.output;
15756 state.consumed += value;
15757 continue;
15758 }
15759 if (prior.type === 'slash' && prior.prev.type !== 'bos' && !afterStar && eos()) {
15760 state.output = state.output.slice(0, -(prior.output + prev.output).length);
15761 prior.output = '(?:' + prior.output;
15762 prev.type = 'globstar';
15763 prev.output = globstar(opts) + '|$)';
15764 prev.value += value;
15765 state.output += prior.output + prev.output;
15766 state.consumed += value;
15767 continue;
15768 }
15769 let next = peek();
15770 if (prior.type === 'slash' && prior.prev.type !== 'bos' && next === '/') {
15771 let end = peek(2) !== void 0 ? '|$' : '';
15772 state.output = state.output.slice(0, -(prior.output + prev.output).length);
15773 prior.output = '(?:' + prior.output;
15774 prev.type = 'globstar';
15775 prev.output = `${globstar(opts)}${SLASH_LITERAL}|${SLASH_LITERAL}${end})`;
15776 prev.value += value;
15777 state.output += prior.output + prev.output;
15778 state.consumed += value + advance();
15779 push({ type: 'slash', value, output: '' });
15780 continue;
15781 }
15782 if (prior.type === 'bos' && next === '/') {
15783 prev.type = 'globstar';
15784 prev.value += value;
15785 prev.output = `(?:^|${SLASH_LITERAL}|${globstar(opts)}${SLASH_LITERAL})`;
15786 state.output = prev.output;
15787 state.consumed += value + advance();
15788 push({ type: 'slash', value, output: '' });
15789 continue;
15790 }
15791 // remove single star from output
15792 state.output = state.output.slice(0, -prev.output.length);
15793 // reset previous token to globstar
15794 prev.type = 'globstar';
15795 prev.output = globstar(opts);
15796 prev.value += value;
15797 // reset output with globstar
15798 state.output += prev.output;
15799 state.consumed += value;
15800 continue;
15801 }
15802 let token = { type: 'star', value, output: star };
15803 if (opts.bash === true) {
15804 token.output = '.*?';
15805 if (prev.type === 'bos' || prev.type === 'slash') {
15806 token.output = nodot + token.output;
15807 }
15808 push(token);
15809 continue;
15810 }
15811 if (prev && (prev.type === 'bracket' || prev.type === 'paren') && opts.regex === true) {
15812 token.output = value;
15813 push(token);
15814 continue;
15815 }
15816 if (state.index === state.start || prev.type === 'slash' || prev.type === 'dot') {
15817 if (prev.type === 'dot') {
15818 state.output += NO_DOT_SLASH;
15819 prev.output += NO_DOT_SLASH;
15820 }
15821 else if (opts.dot === true) {
15822 state.output += NO_DOTS_SLASH;
15823 prev.output += NO_DOTS_SLASH;
15824 }
15825 else {
15826 state.output += nodot;
15827 prev.output += nodot;
15828 }
15829 if (peek() !== '*') {
15830 state.output += ONE_CHAR;
15831 prev.output += ONE_CHAR;
15832 }
15833 }
15834 push(token);
15835 }
15836 while (state.brackets > 0) {
15837 if (opts.strictBrackets === true)
15838 throw new SyntaxError(syntaxError('closing', ']'));
15839 state.output = utils$2.escapeLast(state.output, '[');
15840 decrement('brackets');
15841 }
15842 while (state.parens > 0) {
15843 if (opts.strictBrackets === true)
15844 throw new SyntaxError(syntaxError('closing', ')'));
15845 state.output = utils$2.escapeLast(state.output, '(');
15846 decrement('parens');
15847 }
15848 while (state.braces > 0) {
15849 if (opts.strictBrackets === true)
15850 throw new SyntaxError(syntaxError('closing', '}'));
15851 state.output = utils$2.escapeLast(state.output, '{');
15852 decrement('braces');
15853 }
15854 if (opts.strictSlashes !== true && (prev.type === 'star' || prev.type === 'bracket')) {
15855 push({ type: 'maybe_slash', value: '', output: `${SLASH_LITERAL}?` });
15856 }
15857 // rebuild the output if we had to backtrack at any point
15858 if (state.backtrack === true) {
15859 state.output = '';
15860 for (let token of state.tokens) {
15861 state.output += token.output != null ? token.output : token.value;
15862 if (token.suffix) {
15863 state.output += token.suffix;
15864 }
15865 }
15866 }
15867 return state;
15868};
15869/**
15870 * Fast paths for creating regular expressions for common glob patterns.
15871 * This can significantly speed up processing and has very little downside
15872 * impact when none of the fast paths match.
15873 */
15874parse$1.fastpaths = (input, options) => {
15875 let opts = Object.assign({}, options);
15876 let max = typeof opts.maxLength === 'number' ? Math.min(MAX_LENGTH$1, opts.maxLength) : MAX_LENGTH$1;
15877 let len = input.length;
15878 if (len > max) {
15879 throw new SyntaxError(`Input length: ${len}, exceeds maximum allowed length: ${max}`);
15880 }
15881 input = REPLACEMENTS[input] || input;
15882 let win32 = utils$2.isWindows(options);
15883 // create constants based on platform, for windows or posix
15884 const { DOT_LITERAL, SLASH_LITERAL, ONE_CHAR, DOTS_SLASH, NO_DOT, NO_DOTS, NO_DOTS_SLASH, STAR, START_ANCHOR } = constants$1.globChars(win32);
15885 let capture = opts.capture ? '' : '?:';
15886 let star = opts.bash === true ? '.*?' : STAR;
15887 let nodot = opts.dot ? NO_DOTS : NO_DOT;
15888 let slashDot = opts.dot ? NO_DOTS_SLASH : NO_DOT;
15889 if (opts.capture) {
15890 star = `(${star})`;
15891 }
15892 const globstar = (opts) => {
15893 return `(${capture}(?:(?!${START_ANCHOR}${opts.dot ? DOTS_SLASH : DOT_LITERAL}).)*?)`;
15894 };
15895 const create = str => {
15896 switch (str) {
15897 case '*':
15898 return `${nodot}${ONE_CHAR}${star}`;
15899 case '.*':
15900 return `${DOT_LITERAL}${ONE_CHAR}${star}`;
15901 case '*.*':
15902 return `${nodot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
15903 case '*/*':
15904 return `${nodot}${star}${SLASH_LITERAL}${ONE_CHAR}${slashDot}${star}`;
15905 case '**':
15906 return nodot + globstar(opts);
15907 case '**/*':
15908 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${ONE_CHAR}${star}`;
15909 case '**/*.*':
15910 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${slashDot}${star}${DOT_LITERAL}${ONE_CHAR}${star}`;
15911 case '**/.*':
15912 return `(?:${nodot}${globstar(opts)}${SLASH_LITERAL})?${DOT_LITERAL}${ONE_CHAR}${star}`;
15913 default: {
15914 let match = /^(.*?)\.(\w+)$/.exec(str);
15915 if (!match)
15916 return;
15917 let source = create(match[1]);
15918 if (!source)
15919 return;
15920 return source + DOT_LITERAL + match[2];
15921 }
15922 }
15923 };
15924 let output = create(input);
15925 if (output && opts.strictSlashes !== true) {
15926 output += `${SLASH_LITERAL}?`;
15927 }
15928 return output;
15929};
15930var parse_1$1 = parse$1;
15931
15932/**
15933 * Creates a matcher function from one or more glob patterns. The
15934 * returned function takes a string to match as its first argument,
15935 * and returns true if the string is a match. The returned matcher
15936 * function also takes a boolean as the second argument that, when true,
15937 * returns an object with additional information.
15938 *
15939 * ```js
15940 * const picomatch = require('picomatch');
15941 * // picomatch(glob[, options]);
15942 *
15943 * const isMatch = picomatch('*.!(*a)');
15944 * console.log(isMatch('a.a')); //=> false
15945 * console.log(isMatch('a.b')); //=> true
15946 * ```
15947 * @name picomatch
15948 * @param {String|Array} `globs` One or more glob patterns.
15949 * @param {Object=} `options`
15950 * @return {Function=} Returns a matcher function.
15951 * @api public
15952 */
15953const picomatch = (glob, options, returnState = false) => {
15954 if (Array.isArray(glob)) {
15955 let fns = glob.map(input => picomatch(input, options, returnState));
15956 return str => {
15957 for (let isMatch of fns) {
15958 let state = isMatch(str);
15959 if (state)
15960 return state;
15961 }
15962 return false;
15963 };
15964 }
15965 if (typeof glob !== 'string' || glob === '') {
15966 throw new TypeError('Expected pattern to be a non-empty string');
15967 }
15968 let opts = options || {};
15969 let posix = utils$2.isWindows(options);
15970 let regex = picomatch.makeRe(glob, options, false, true);
15971 let state = regex.state;
15972 delete regex.state;
15973 let isIgnored = () => false;
15974 if (opts.ignore) {
15975 let ignoreOpts = Object.assign(Object.assign({}, options), { ignore: null, onMatch: null, onResult: null });
15976 isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
15977 }
15978 const matcher = (input, returnObject = false) => {
15979 let { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
15980 let result = { glob, state, regex, posix, input, output, match, isMatch };
15981 if (typeof opts.onResult === 'function') {
15982 opts.onResult(result);
15983 }
15984 if (isMatch === false) {
15985 result.isMatch = false;
15986 return returnObject ? result : false;
15987 }
15988 if (isIgnored(input)) {
15989 if (typeof opts.onIgnore === 'function') {
15990 opts.onIgnore(result);
15991 }
15992 result.isMatch = false;
15993 return returnObject ? result : false;
15994 }
15995 if (typeof opts.onMatch === 'function') {
15996 opts.onMatch(result);
15997 }
15998 return returnObject ? result : true;
15999 };
16000 if (returnState) {
16001 matcher.state = state;
16002 }
16003 return matcher;
16004};
16005/**
16006 * Test `input` with the given `regex`. This is used by the main
16007 * `picomatch()` function to test the input string.
16008 *
16009 * ```js
16010 * const picomatch = require('picomatch');
16011 * // picomatch.test(input, regex[, options]);
16012 *
16013 * console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
16014 * // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
16015 * ```
16016 * @param {String} `input` String to test.
16017 * @param {RegExp} `regex`
16018 * @return {Object} Returns an object with matching info.
16019 * @api public
16020 */
16021picomatch.test = (input, regex, options, { glob, posix } = {}) => {
16022 if (typeof input !== 'string') {
16023 throw new TypeError('Expected input to be a string');
16024 }
16025 if (input === '') {
16026 return { isMatch: false, output: '' };
16027 }
16028 let opts = options || {};
16029 let format = opts.format || (posix ? utils$2.toPosixSlashes : null);
16030 let match = input === glob;
16031 let output = (match && format) ? format(input) : input;
16032 if (match === false) {
16033 output = format ? format(input) : input;
16034 match = output === glob;
16035 }
16036 if (match === false || opts.capture === true) {
16037 if (opts.matchBase === true || opts.basename === true) {
16038 match = picomatch.matchBase(input, regex, options, posix);
16039 }
16040 else {
16041 match = regex.exec(output);
16042 }
16043 }
16044 return { isMatch: !!match, match, output };
16045};
16046/**
16047 * Match the basename of a filepath.
16048 *
16049 * ```js
16050 * const picomatch = require('picomatch');
16051 * // picomatch.matchBase(input, glob[, options]);
16052 * console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
16053 * ```
16054 * @param {String} `input` String to test.
16055 * @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
16056 * @return {Boolean}
16057 * @api public
16058 */
16059picomatch.matchBase = (input, glob, options, posix = utils$2.isWindows(options)) => {
16060 let regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
16061 return regex.test(path.basename(input));
16062};
16063/**
16064 * Returns true if **any** of the given glob `patterns` match the specified `string`.
16065 *
16066 * ```js
16067 * const picomatch = require('picomatch');
16068 * // picomatch.isMatch(string, patterns[, options]);
16069 *
16070 * console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
16071 * console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
16072 * ```
16073 * @param {String|Array} str The string to test.
16074 * @param {String|Array} patterns One or more glob patterns to use for matching.
16075 * @param {Object} [options] See available [options](#options).
16076 * @return {Boolean} Returns true if any patterns match `str`
16077 * @api public
16078 */
16079picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
16080/**
16081 * Parse a glob pattern to create the source string for a regular
16082 * expression.
16083 *
16084 * ```js
16085 * const picomatch = require('picomatch');
16086 * const result = picomatch.parse(glob[, options]);
16087 * ```
16088 * @param {String} `glob`
16089 * @param {Object} `options`
16090 * @return {Object} Returns an object with useful properties and output to be used as a regex source string.
16091 * @api public
16092 */
16093picomatch.parse = (glob, options) => parse_1$1(glob, options);
16094/**
16095 * Scan a glob pattern to separate the pattern into segments.
16096 *
16097 * ```js
16098 * const picomatch = require('picomatch');
16099 * // picomatch.scan(input[, options]);
16100 *
16101 * const result = picomatch.scan('!./foo/*.js');
16102 * console.log(result);
16103 * // { prefix: '!./',
16104 * // input: '!./foo/*.js',
16105 * // base: 'foo',
16106 * // glob: '*.js',
16107 * // negated: true,
16108 * // isGlob: true }
16109 * ```
16110 * @param {String} `input` Glob pattern to scan.
16111 * @param {Object} `options`
16112 * @return {Object} Returns an object with
16113 * @api public
16114 */
16115picomatch.scan = (input, options) => scan(input, options);
16116/**
16117 * Create a regular expression from a glob pattern.
16118 *
16119 * ```js
16120 * const picomatch = require('picomatch');
16121 * // picomatch.makeRe(input[, options]);
16122 *
16123 * console.log(picomatch.makeRe('*.js'));
16124 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
16125 * ```
16126 * @param {String} `input` A glob pattern to convert to regex.
16127 * @param {Object} `options`
16128 * @return {RegExp} Returns a regex created from the given pattern.
16129 * @api public
16130 */
16131picomatch.makeRe = (input, options, returnOutput = false, returnState = false) => {
16132 if (!input || typeof input !== 'string') {
16133 throw new TypeError('Expected a non-empty string');
16134 }
16135 let opts = options || {};
16136 let prepend = opts.contains ? '' : '^';
16137 let append = opts.contains ? '' : '$';
16138 let state = { negated: false, fastpaths: true };
16139 let prefix = '';
16140 let output;
16141 if (input.startsWith('./')) {
16142 input = input.slice(2);
16143 prefix = state.prefix = './';
16144 }
16145 if (opts.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
16146 output = parse_1$1.fastpaths(input, options);
16147 }
16148 if (output === void 0) {
16149 state = picomatch.parse(input, options);
16150 state.prefix = prefix + (state.prefix || '');
16151 output = state.output;
16152 }
16153 if (returnOutput === true) {
16154 return output;
16155 }
16156 let source = `${prepend}(?:${output})${append}`;
16157 if (state && state.negated === true) {
16158 source = `^(?!${source}).*$`;
16159 }
16160 let regex = picomatch.toRegex(source, options);
16161 if (returnState === true) {
16162 regex.state = state;
16163 }
16164 return regex;
16165};
16166/**
16167 * Create a regular expression from the given regex source string.
16168 *
16169 * ```js
16170 * const picomatch = require('picomatch');
16171 * // picomatch.toRegex(source[, options]);
16172 *
16173 * const { output } = picomatch.parse('*.js');
16174 * console.log(picomatch.toRegex(output));
16175 * //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
16176 * ```
16177 * @param {String} `source` Regular expression source string.
16178 * @param {Object} `options`
16179 * @return {RegExp}
16180 * @api public
16181 */
16182picomatch.toRegex = (source, options) => {
16183 try {
16184 let opts = options || {};
16185 return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
16186 }
16187 catch (err) {
16188 if (options && options.debug === true)
16189 throw err;
16190 return /$^/;
16191 }
16192};
16193/**
16194 * Picomatch constants.
16195 * @return {Object}
16196 */
16197picomatch.constants = constants$1;
16198/**
16199 * Expose "picomatch"
16200 */
16201var picomatch_1 = picomatch;
16202
16203var picomatch$1 = picomatch_1;
16204
16205const isEmptyString = val => typeof val === 'string' && (val === '' || val === './');
16206/**
16207 * Returns an array of strings that match one or more glob patterns.
16208 *
16209 * ```js
16210 * const mm = require('micromatch');
16211 * // mm(list, patterns[, options]);
16212 *
16213 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
16214 * //=> [ 'a.js' ]
16215 * ```
16216 * @param {String|Array<string>} list List of strings to match.
16217 * @param {String|Array<string>} patterns One or more glob patterns to use for matching.
16218 * @param {Object} options See available [options](#options)
16219 * @return {Array} Returns an array of matches
16220 * @summary false
16221 * @api public
16222 */
16223const micromatch = (list, patterns, options) => {
16224 patterns = [].concat(patterns);
16225 list = [].concat(list);
16226 let omit = new Set();
16227 let keep = new Set();
16228 let items = new Set();
16229 let negatives = 0;
16230 let onResult = state => {
16231 items.add(state.output);
16232 if (options && options.onResult) {
16233 options.onResult(state);
16234 }
16235 };
16236 for (let i = 0; i < patterns.length; i++) {
16237 let isMatch = picomatch$1(String(patterns[i]), Object.assign(Object.assign({}, options), { onResult }), true);
16238 let negated = isMatch.state.negated || isMatch.state.negatedExtglob;
16239 if (negated)
16240 negatives++;
16241 for (let item of list) {
16242 let matched = isMatch(item, true);
16243 let match = negated ? !matched.isMatch : matched.isMatch;
16244 if (!match)
16245 continue;
16246 if (negated) {
16247 omit.add(matched.output);
16248 }
16249 else {
16250 omit.delete(matched.output);
16251 keep.add(matched.output);
16252 }
16253 }
16254 }
16255 let result = negatives === patterns.length ? [...items] : [...keep];
16256 let matches = result.filter(item => !omit.has(item));
16257 if (options && matches.length === 0) {
16258 if (options.failglob === true) {
16259 throw new Error(`No matches found for "${patterns.join(', ')}"`);
16260 }
16261 if (options.nonull === true || options.nullglob === true) {
16262 return options.unescape ? patterns.map(p => p.replace(/\\/g, '')) : patterns;
16263 }
16264 }
16265 return matches;
16266};
16267/**
16268 * Backwards compatibility
16269 */
16270micromatch.match = micromatch;
16271/**
16272 * Returns a matcher function from the given glob `pattern` and `options`.
16273 * The returned function takes a string to match as its only argument and returns
16274 * true if the string is a match.
16275 *
16276 * ```js
16277 * const mm = require('micromatch');
16278 * // mm.matcher(pattern[, options]);
16279 *
16280 * const isMatch = mm.matcher('*.!(*a)');
16281 * console.log(isMatch('a.a')); //=> false
16282 * console.log(isMatch('a.b')); //=> true
16283 * ```
16284 * @param {String} `pattern` Glob pattern
16285 * @param {Object} `options`
16286 * @return {Function} Returns a matcher function.
16287 * @api public
16288 */
16289micromatch.matcher = (pattern, options) => picomatch$1(pattern, options);
16290/**
16291 * Returns true if **any** of the given glob `patterns` match the specified `string`.
16292 *
16293 * ```js
16294 * const mm = require('micromatch');
16295 * // mm.isMatch(string, patterns[, options]);
16296 *
16297 * console.log(mm.isMatch('a.a', ['b.*', '*.a'])); //=> true
16298 * console.log(mm.isMatch('a.a', 'b.*')); //=> false
16299 * ```
16300 * @param {String} str The string to test.
16301 * @param {String|Array} patterns One or more glob patterns to use for matching.
16302 * @param {Object} [options] See available [options](#options).
16303 * @return {Boolean} Returns true if any patterns match `str`
16304 * @api public
16305 */
16306micromatch.isMatch = (str, patterns, options) => picomatch$1(patterns, options)(str);
16307/**
16308 * Backwards compatibility
16309 */
16310micromatch.any = micromatch.isMatch;
16311/**
16312 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
16313 *
16314 * ```js
16315 * const mm = require('micromatch');
16316 * // mm.not(list, patterns[, options]);
16317 *
16318 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
16319 * //=> ['b.b', 'c.c']
16320 * ```
16321 * @param {Array} `list` Array of strings to match.
16322 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
16323 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16324 * @return {Array} Returns an array of strings that **do not match** the given patterns.
16325 * @api public
16326 */
16327micromatch.not = (list, patterns, options = {}) => {
16328 patterns = [].concat(patterns).map(String);
16329 let result = new Set();
16330 let items = [];
16331 let onResult = state => {
16332 if (options.onResult)
16333 options.onResult(state);
16334 items.push(state.output);
16335 };
16336 let matches = micromatch(list, patterns, Object.assign(Object.assign({}, options), { onResult }));
16337 for (let item of items) {
16338 if (!matches.includes(item)) {
16339 result.add(item);
16340 }
16341 }
16342 return [...result];
16343};
16344/**
16345 * Returns true if the given `string` contains the given pattern. Similar
16346 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
16347 *
16348 * ```js
16349 * var mm = require('micromatch');
16350 * // mm.contains(string, pattern[, options]);
16351 *
16352 * console.log(mm.contains('aa/bb/cc', '*b'));
16353 * //=> true
16354 * console.log(mm.contains('aa/bb/cc', '*d'));
16355 * //=> false
16356 * ```
16357 * @param {String} `str` The string to match.
16358 * @param {String|Array} `patterns` Glob pattern to use for matching.
16359 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16360 * @return {Boolean} Returns true if the patter matches any part of `str`.
16361 * @api public
16362 */
16363micromatch.contains = (str, pattern, options) => {
16364 if (typeof str !== 'string') {
16365 throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
16366 }
16367 if (Array.isArray(pattern)) {
16368 return pattern.some(p => micromatch.contains(str, p, options));
16369 }
16370 if (typeof pattern === 'string') {
16371 if (isEmptyString(str) || isEmptyString(pattern)) {
16372 return false;
16373 }
16374 if (str.includes(pattern) || (str.startsWith('./') && str.slice(2).includes(pattern))) {
16375 return true;
16376 }
16377 }
16378 return micromatch.isMatch(str, pattern, Object.assign(Object.assign({}, options), { contains: true }));
16379};
16380/**
16381 * Filter the keys of the given object with the given `glob` pattern
16382 * and `options`. Does not attempt to match nested keys. If you need this feature,
16383 * use [glob-object][] instead.
16384 *
16385 * ```js
16386 * const mm = require('micromatch');
16387 * // mm.matchKeys(object, patterns[, options]);
16388 *
16389 * const obj = { aa: 'a', ab: 'b', ac: 'c' };
16390 * console.log(mm.matchKeys(obj, '*b'));
16391 * //=> { ab: 'b' }
16392 * ```
16393 * @param {Object} `object` The object with keys to filter.
16394 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
16395 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16396 * @return {Object} Returns an object with only keys that match the given patterns.
16397 * @api public
16398 */
16399micromatch.matchKeys = (obj, patterns, options) => {
16400 if (!utils$2.isObject(obj)) {
16401 throw new TypeError('Expected the first argument to be an object');
16402 }
16403 let keys = micromatch(Object.keys(obj), patterns, options);
16404 let res = {};
16405 for (let key of keys)
16406 res[key] = obj[key];
16407 return res;
16408};
16409/**
16410 * Returns true if some of the strings in the given `list` match any of the given glob `patterns`.
16411 *
16412 * ```js
16413 * const mm = require('micromatch');
16414 * // mm.some(list, patterns[, options]);
16415 *
16416 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
16417 * // true
16418 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
16419 * // false
16420 * ```
16421 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
16422 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
16423 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16424 * @return {Boolean} Returns true if any patterns match `str`
16425 * @api public
16426 */
16427micromatch.some = (list, patterns, options) => {
16428 let items = [].concat(list);
16429 for (let pattern of [].concat(patterns)) {
16430 let isMatch = picomatch$1(String(pattern), options);
16431 if (items.some(item => isMatch(item))) {
16432 return true;
16433 }
16434 }
16435 return false;
16436};
16437/**
16438 * Returns true if every string in the given `list` matches
16439 * any of the given glob `patterns`.
16440 *
16441 * ```js
16442 * const mm = require('micromatch');
16443 * // mm.every(list, patterns[, options]);
16444 *
16445 * console.log(mm.every('foo.js', ['foo.js']));
16446 * // true
16447 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
16448 * // true
16449 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
16450 * // false
16451 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
16452 * // false
16453 * ```
16454 * @param {String|Array} `list` The string or array of strings to test.
16455 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
16456 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16457 * @return {Boolean} Returns true if any patterns match `str`
16458 * @api public
16459 */
16460micromatch.every = (list, patterns, options) => {
16461 let items = [].concat(list);
16462 for (let pattern of [].concat(patterns)) {
16463 let isMatch = picomatch$1(String(pattern), options);
16464 if (!items.every(item => isMatch(item))) {
16465 return false;
16466 }
16467 }
16468 return true;
16469};
16470/**
16471 * Returns true if **all** of the given `patterns` match
16472 * the specified string.
16473 *
16474 * ```js
16475 * const mm = require('micromatch');
16476 * // mm.all(string, patterns[, options]);
16477 *
16478 * console.log(mm.all('foo.js', ['foo.js']));
16479 * // true
16480 *
16481 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
16482 * // false
16483 *
16484 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
16485 * // true
16486 *
16487 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
16488 * // true
16489 * ```
16490 * @param {String|Array} `str` The string to test.
16491 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
16492 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16493 * @return {Boolean} Returns true if any patterns match `str`
16494 * @api public
16495 */
16496micromatch.all = (str, patterns, options) => {
16497 if (typeof str !== 'string') {
16498 throw new TypeError(`Expected a string: "${util.inspect(str)}"`);
16499 }
16500 return [].concat(patterns).every(p => picomatch$1(p, options)(str));
16501};
16502/**
16503 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
16504 *
16505 * ```js
16506 * const mm = require('micromatch');
16507 * // mm.capture(pattern, string[, options]);
16508 *
16509 * console.log(mm.capture('test/*.js', 'test/foo.js'));
16510 * //=> ['foo']
16511 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
16512 * //=> null
16513 * ```
16514 * @param {String} `glob` Glob pattern to use for matching.
16515 * @param {String} `input` String to match
16516 * @param {Object} `options` See available [options](#options) for changing how matches are performed
16517 * @return {Boolean} Returns an array of captures if the input matches the glob pattern, otherwise `null`.
16518 * @api public
16519 */
16520micromatch.capture = (glob, input, options) => {
16521 let posix = utils$2.isWindows(options);
16522 let regex = picomatch$1.makeRe(String(glob), Object.assign(Object.assign({}, options), { capture: true }));
16523 let match = regex.exec(posix ? utils$2.toPosixSlashes(input) : input);
16524 if (match) {
16525 return match.slice(1).map(v => v === void 0 ? '' : v);
16526 }
16527};
16528/**
16529 * Create a regular expression from the given glob `pattern`.
16530 *
16531 * ```js
16532 * const mm = require('micromatch');
16533 * // mm.makeRe(pattern[, options]);
16534 *
16535 * console.log(mm.makeRe('*.js'));
16536 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
16537 * ```
16538 * @param {String} `pattern` A glob pattern to convert to regex.
16539 * @param {Object} `options`
16540 * @return {RegExp} Returns a regex created from the given pattern.
16541 * @api public
16542 */
16543micromatch.makeRe = (...args) => picomatch$1.makeRe(...args);
16544/**
16545 * Scan a glob pattern to separate the pattern into segments. Used
16546 * by the [split](#split) method.
16547 *
16548 * ```js
16549 * const mm = require('micromatch');
16550 * const state = mm.scan(pattern[, options]);
16551 * ```
16552 * @param {String} `pattern`
16553 * @param {Object} `options`
16554 * @return {Object} Returns an object with
16555 * @api public
16556 */
16557micromatch.scan = (...args) => picomatch$1.scan(...args);
16558/**
16559 * Parse a glob pattern to create the source string for a regular
16560 * expression.
16561 *
16562 * ```js
16563 * const mm = require('micromatch');
16564 * const state = mm(pattern[, options]);
16565 * ```
16566 * @param {String} `glob`
16567 * @param {Object} `options`
16568 * @return {Object} Returns an object with useful properties and output to be used as regex source string.
16569 * @api public
16570 */
16571micromatch.parse = (patterns, options) => {
16572 let res = [];
16573 for (let pattern of [].concat(patterns || [])) {
16574 for (let str of braces_1(String(pattern), options)) {
16575 res.push(picomatch$1.parse(str, options));
16576 }
16577 }
16578 return res;
16579};
16580/**
16581 * Process the given brace `pattern`.
16582 *
16583 * ```js
16584 * const { braces } = require('micromatch');
16585 * console.log(braces('foo/{a,b,c}/bar'));
16586 * //=> [ 'foo/(a|b|c)/bar' ]
16587 *
16588 * console.log(braces('foo/{a,b,c}/bar', { expand: true }));
16589 * //=> [ 'foo/a/bar', 'foo/b/bar', 'foo/c/bar' ]
16590 * ```
16591 * @param {String} `pattern` String with brace pattern to process.
16592 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
16593 * @return {Array}
16594 * @api public
16595 */
16596micromatch.braces = (pattern, options) => {
16597 if (typeof pattern !== 'string')
16598 throw new TypeError('Expected a string');
16599 if ((options && options.nobrace === true) || !/\{.*\}/.test(pattern)) {
16600 return [pattern];
16601 }
16602 return braces_1(pattern, options);
16603};
16604/**
16605 * Expand braces
16606 */
16607micromatch.braceExpand = (pattern, options) => {
16608 if (typeof pattern !== 'string')
16609 throw new TypeError('Expected a string');
16610 return micromatch.braces(pattern, Object.assign(Object.assign({}, options), { expand: true }));
16611};
16612/**
16613 * Expose micromatch
16614 */
16615var micromatch_1 = micromatch;
16616
16617function ensureArray$1(thing) {
16618 if (Array.isArray(thing))
16619 return thing;
16620 if (thing == undefined)
16621 return [];
16622 return [thing];
16623}
16624
16625function getMatcherString(id, resolutionBase) {
16626 if (resolutionBase === false) {
16627 return id;
16628 }
16629 return path.resolve(...(typeof resolutionBase === 'string' ? [resolutionBase, id] : [id]));
16630}
16631const createFilter = function createFilter(include, exclude, options) {
16632 const resolutionBase = options && options.resolve;
16633 const getMatcher = (id) => {
16634 return id instanceof RegExp
16635 ? id
16636 : {
16637 test: micromatch_1.matcher(getMatcherString(id, resolutionBase)
16638 .split(path.sep)
16639 .join('/'), { dot: true })
16640 };
16641 };
16642 const includeMatchers = ensureArray$1(include).map(getMatcher);
16643 const excludeMatchers = ensureArray$1(exclude).map(getMatcher);
16644 return function (id) {
16645 if (typeof id !== 'string')
16646 return false;
16647 if (/\0/.test(id))
16648 return false;
16649 id = id.split(path.sep).join('/');
16650 for (let i = 0; i < excludeMatchers.length; ++i) {
16651 const matcher = excludeMatchers[i];
16652 if (matcher.test(id))
16653 return false;
16654 }
16655 for (let i = 0; i < includeMatchers.length; ++i) {
16656 const matcher = includeMatchers[i];
16657 if (matcher.test(id))
16658 return true;
16659 }
16660 return !includeMatchers.length;
16661 };
16662};
16663
16664let chokidar;
16665try {
16666 chokidar = index.relative('chokidar', process.cwd());
16667}
16668catch (err) {
16669 chokidar = null;
16670}
16671var chokidar$1 = chokidar;
16672
16673const opts = { encoding: 'utf-8', persistent: true };
16674const watchers = new Map();
16675function addTask(id, task, chokidarOptions, chokidarOptionsHash, isTransformDependency) {
16676 if (!watchers.has(chokidarOptionsHash))
16677 watchers.set(chokidarOptionsHash, new Map());
16678 const group = watchers.get(chokidarOptionsHash);
16679 const watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group);
16680 if (!watcher.fsWatcher) {
16681 if (isTransformDependency)
16682 throw new Error(`Transform dependency ${id} does not exist.`);
16683 }
16684 else {
16685 watcher.addTask(task, isTransformDependency);
16686 }
16687}
16688function deleteTask(id, target, chokidarOptionsHash) {
16689 const group = watchers.get(chokidarOptionsHash);
16690 const watcher = group.get(id);
16691 if (watcher)
16692 watcher.deleteTask(target, group);
16693}
16694class FileWatcher {
16695 constructor(id, chokidarOptions, group) {
16696 this.id = id;
16697 this.tasks = new Set();
16698 this.transformDependencyTasks = new Set();
16699 let modifiedTime;
16700 try {
16701 const stats = fs.statSync(id);
16702 modifiedTime = +stats.mtime;
16703 }
16704 catch (err) {
16705 if (err.code === 'ENOENT') {
16706 // can't watch files that don't exist (e.g. injected
16707 // by plugins somehow)
16708 return;
16709 }
16710 throw err;
16711 }
16712 const handleWatchEvent = (event) => {
16713 if (event === 'rename' || event === 'unlink') {
16714 this.close();
16715 group.delete(id);
16716 this.trigger(id);
16717 return;
16718 }
16719 else {
16720 let stats;
16721 try {
16722 stats = fs.statSync(id);
16723 }
16724 catch (err) {
16725 if (err.code === 'ENOENT') {
16726 modifiedTime = -1;
16727 this.trigger(id);
16728 return;
16729 }
16730 throw err;
16731 }
16732 // debounce
16733 if (+stats.mtime - modifiedTime > 15)
16734 this.trigger(id);
16735 }
16736 };
16737 this.fsWatcher = chokidarOptions
16738 ? chokidar$1.watch(id, chokidarOptions).on('all', handleWatchEvent)
16739 : fs.watch(id, opts, handleWatchEvent);
16740 group.set(id, this);
16741 }
16742 addTask(task, isTransformDependency) {
16743 if (isTransformDependency)
16744 this.transformDependencyTasks.add(task);
16745 else
16746 this.tasks.add(task);
16747 }
16748 close() {
16749 if (this.fsWatcher)
16750 this.fsWatcher.close();
16751 }
16752 deleteTask(task, group) {
16753 let deleted = this.tasks.delete(task);
16754 deleted = this.transformDependencyTasks.delete(task) || deleted;
16755 if (deleted && this.tasks.size === 0 && this.transformDependencyTasks.size === 0) {
16756 group.delete(this.id);
16757 this.close();
16758 }
16759 }
16760 trigger(id) {
16761 this.tasks.forEach(task => {
16762 task.invalidate(id, false);
16763 });
16764 this.transformDependencyTasks.forEach(task => {
16765 task.invalidate(id, true);
16766 });
16767 }
16768}
16769
16770const DELAY = 200;
16771class Watcher {
16772 constructor(configs) {
16773 this.buildTimeout = null;
16774 this.invalidatedIds = new Set();
16775 this.rerun = false;
16776 this.emitter = new (class extends events.EventEmitter {
16777 constructor(close) {
16778 super();
16779 this.close = close;
16780 // Allows more than 10 bundles to be watched without
16781 // showing the `MaxListenersExceededWarning` to the user.
16782 this.setMaxListeners(Infinity);
16783 }
16784 })(this.close.bind(this));
16785 this.tasks = (Array.isArray(configs) ? configs : configs ? [configs] : []).map(config => new Task(this, config));
16786 this.running = true;
16787 process.nextTick(() => this.run());
16788 }
16789 close() {
16790 if (this.buildTimeout)
16791 clearTimeout(this.buildTimeout);
16792 for (const task of this.tasks) {
16793 task.close();
16794 }
16795 this.emitter.removeAllListeners();
16796 }
16797 emit(event, value) {
16798 this.emitter.emit(event, value);
16799 }
16800 invalidate(id) {
16801 if (id) {
16802 this.invalidatedIds.add(id);
16803 }
16804 if (this.running) {
16805 this.rerun = true;
16806 return;
16807 }
16808 if (this.buildTimeout)
16809 clearTimeout(this.buildTimeout);
16810 this.buildTimeout = setTimeout(() => {
16811 this.buildTimeout = null;
16812 for (const id of this.invalidatedIds) {
16813 this.emit('change', id);
16814 }
16815 this.invalidatedIds.clear();
16816 this.emit('restart');
16817 this.run();
16818 }, DELAY);
16819 }
16820 run() {
16821 this.running = true;
16822 this.emit('event', {
16823 code: 'START'
16824 });
16825 let taskPromise = Promise.resolve();
16826 for (const task of this.tasks)
16827 taskPromise = taskPromise.then(() => task.run());
16828 return taskPromise
16829 .then(() => {
16830 this.running = false;
16831 this.emit('event', {
16832 code: 'END'
16833 });
16834 })
16835 .catch(error => {
16836 this.running = false;
16837 this.emit('event', {
16838 code: 'ERROR',
16839 error
16840 });
16841 })
16842 .then(() => {
16843 if (this.rerun) {
16844 this.rerun = false;
16845 this.invalidate();
16846 }
16847 });
16848 }
16849}
16850class Task {
16851 constructor(watcher, config) {
16852 this.cache = { modules: [] };
16853 this.watchFiles = [];
16854 this.invalidated = true;
16855 this.watcher = watcher;
16856 this.closed = false;
16857 this.watched = new Set();
16858 const { inputOptions, outputOptions } = index.mergeOptions({
16859 config
16860 });
16861 this.inputOptions = inputOptions;
16862 this.outputs = outputOptions;
16863 this.outputFiles = this.outputs.map(output => {
16864 if (output.file || output.dir)
16865 return path.resolve(output.file || output.dir);
16866 return undefined;
16867 });
16868 const watchOptions = inputOptions.watch || {};
16869 if ('useChokidar' in watchOptions)
16870 watchOptions.chokidar = watchOptions.useChokidar;
16871 let chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
16872 if (chokidarOptions) {
16873 chokidarOptions = Object.assign(Object.assign({}, (chokidarOptions === true ? {} : chokidarOptions)), { disableGlobbing: true, ignoreInitial: true });
16874 }
16875 if (chokidarOptions && !chokidar$1) {
16876 throw new Error(`watch.chokidar was provided, but chokidar could not be found. Have you installed it?`);
16877 }
16878 this.chokidarOptions = chokidarOptions;
16879 this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
16880 this.filter = createFilter(watchOptions.include, watchOptions.exclude);
16881 }
16882 close() {
16883 this.closed = true;
16884 for (const id of this.watched) {
16885 deleteTask(id, this, this.chokidarOptionsHash);
16886 }
16887 }
16888 invalidate(id, isTransformDependency) {
16889 this.invalidated = true;
16890 if (isTransformDependency) {
16891 for (const module of this.cache.modules) {
16892 if (module.transformDependencies.indexOf(id) === -1)
16893 continue;
16894 // effective invalidation
16895 module.originalCode = null;
16896 }
16897 }
16898 this.watcher.invalidate(id);
16899 }
16900 run() {
16901 if (!this.invalidated)
16902 return;
16903 this.invalidated = false;
16904 const options = Object.assign(Object.assign({}, this.inputOptions), { cache: this.cache });
16905 const start = Date.now();
16906 this.watcher.emit('event', {
16907 code: 'BUNDLE_START',
16908 input: this.inputOptions.input,
16909 output: this.outputFiles
16910 });
16911 setWatcher(this.watcher.emitter);
16912 return rollup(options)
16913 .then(result => {
16914 if (this.closed)
16915 return undefined;
16916 this.updateWatchedFiles(result);
16917 return Promise.all(this.outputs.map(output => result.write(output))).then(() => result);
16918 })
16919 .then((result) => {
16920 this.watcher.emit('event', {
16921 code: 'BUNDLE_END',
16922 duration: Date.now() - start,
16923 input: this.inputOptions.input,
16924 output: this.outputFiles,
16925 result
16926 });
16927 })
16928 .catch((error) => {
16929 if (this.closed)
16930 return;
16931 if (Array.isArray(error.watchFiles)) {
16932 for (const id of error.watchFiles) {
16933 this.watchFile(id);
16934 }
16935 }
16936 throw error;
16937 });
16938 }
16939 updateWatchedFiles(result) {
16940 const previouslyWatched = this.watched;
16941 this.watched = new Set();
16942 this.watchFiles = result.watchFiles;
16943 this.cache = result.cache;
16944 for (const id of this.watchFiles) {
16945 this.watchFile(id);
16946 }
16947 for (const module of this.cache.modules) {
16948 for (const depId of module.transformDependencies) {
16949 this.watchFile(depId, true);
16950 }
16951 }
16952 for (const id of previouslyWatched) {
16953 if (!this.watched.has(id))
16954 deleteTask(id, this, this.chokidarOptionsHash);
16955 }
16956 }
16957 watchFile(id, isTransformDependency = false) {
16958 if (!this.filter(id))
16959 return;
16960 this.watched.add(id);
16961 if (this.outputFiles.some(file => file === id)) {
16962 throw new Error('Cannot import the generated bundle');
16963 }
16964 // this is necessary to ensure that any 'renamed' files
16965 // continue to be watched following an error
16966 addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash, isTransformDependency);
16967 }
16968}
16969function watch(configs) {
16970 return new Watcher(configs).emitter;
16971}
16972
16973exports.VERSION = index.version;
16974exports.rollup = rollup;
16975exports.watch = watch;
16976//# sourceMappingURL=rollup.js.map