UNPKG

1.17 MBJavaScriptView Raw
1/*
2 @license
3 Rollup.js v1.11.1
4 Sat, 04 May 2019 06:20:24 GMT - commit 67a717bd5b0b85523c202895483f76a4185e0a3b
5
6
7 https://github.com/rollup/rollup
8
9 Released under the MIT License.
10*/
11import util$2 from 'util';
12import path, { relative, extname, basename, dirname, resolve as resolve$1, sep } from 'path';
13import * as acorn__default from 'acorn';
14import { tokTypes, Parser as Parser$1 } from 'acorn';
15import fs__default, { writeFile as writeFile$1, readdirSync, mkdirSync, readFileSync, lstatSync, realpathSync, statSync, watch as watch$1 } from 'fs';
16import { EventEmitter } from 'events';
17import tty from 'tty';
18import net from 'net';
19import url from 'url';
20import module$1 from 'module';
21
22/*! *****************************************************************************
23Copyright (c) Microsoft Corporation. All rights reserved.
24Licensed under the Apache License, Version 2.0 (the "License"); you may not use
25this file except in compliance with the License. You may obtain a copy of the
26License at http://www.apache.org/licenses/LICENSE-2.0
27
28THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
29KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
30WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
31MERCHANTABLITY OR NON-INFRINGEMENT.
32
33See the Apache Version 2.0 License for specific language governing permissions
34and limitations under the License.
35***************************************************************************** */
36/* global Reflect, Promise */
37
38var extendStatics = function(d, b) {
39 extendStatics = Object.setPrototypeOf ||
40 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
41 function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
42 return extendStatics(d, b);
43};
44
45function __extends(d, b) {
46 extendStatics(d, b);
47 function __() { this.constructor = d; }
48 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
49}
50
51var __assign = function() {
52 __assign = Object.assign || function __assign(t) {
53 for (var s, i = 1, n = arguments.length; i < n; i++) {
54 s = arguments[i];
55 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
56 }
57 return t;
58 };
59 return __assign.apply(this, arguments);
60};
61
62function __rest(s, e) {
63 var t = {};
64 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
65 t[p] = s[p];
66 if (s != null && typeof Object.getOwnPropertySymbols === "function")
67 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
68 t[p[i]] = s[p[i]];
69 return t;
70}
71
72function __decorate(decorators, target, key, desc) {
73 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
74 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
75 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
76 return c > 3 && r && Object.defineProperty(target, key, r), r;
77}
78
79function __param(paramIndex, decorator) {
80 return function (target, key) { decorator(target, key, paramIndex); }
81}
82
83function __metadata(metadataKey, metadataValue) {
84 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
85}
86
87function __awaiter(thisArg, _arguments, P, generator) {
88 return new (P || (P = Promise))(function (resolve, reject) {
89 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
90 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
91 function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
92 step((generator = generator.apply(thisArg, _arguments || [])).next());
93 });
94}
95
96function __generator(thisArg, body) {
97 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
98 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
99 function verb(n) { return function (v) { return step([n, v]); }; }
100 function step(op) {
101 if (f) throw new TypeError("Generator is already executing.");
102 while (_) try {
103 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
104 if (y = 0, t) op = [op[0] & 2, t.value];
105 switch (op[0]) {
106 case 0: case 1: t = op; break;
107 case 4: _.label++; return { value: op[1], done: false };
108 case 5: _.label++; y = op[1]; op = [0]; continue;
109 case 7: op = _.ops.pop(); _.trys.pop(); continue;
110 default:
111 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
112 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
113 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
114 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
115 if (t[2]) _.ops.pop();
116 _.trys.pop(); continue;
117 }
118 op = body.call(thisArg, _);
119 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
120 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
121 }
122}
123
124function __exportStar(m, exports) {
125 for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
126}
127
128function __values(o) {
129 var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
130 if (m) return m.call(o);
131 return {
132 next: function () {
133 if (o && i >= o.length) o = void 0;
134 return { value: o && o[i++], done: !o };
135 }
136 };
137}
138
139function __read(o, n) {
140 var m = typeof Symbol === "function" && o[Symbol.iterator];
141 if (!m) return o;
142 var i = m.call(o), r, ar = [], e;
143 try {
144 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
145 }
146 catch (error) { e = { error: error }; }
147 finally {
148 try {
149 if (r && !r.done && (m = i["return"])) m.call(i);
150 }
151 finally { if (e) throw e.error; }
152 }
153 return ar;
154}
155
156function __spread() {
157 for (var ar = [], i = 0; i < arguments.length; i++)
158 ar = ar.concat(__read(arguments[i]));
159 return ar;
160}
161
162function __await(v) {
163 return this instanceof __await ? (this.v = v, this) : new __await(v);
164}
165
166function __asyncGenerator(thisArg, _arguments, generator) {
167 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
168 var g = generator.apply(thisArg, _arguments || []), i, q = [];
169 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
170 function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
171 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
172 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
173 function fulfill(value) { resume("next", value); }
174 function reject(value) { resume("throw", value); }
175 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
176}
177
178function __asyncDelegator(o) {
179 var i, p;
180 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
181 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
182}
183
184function __asyncValues(o) {
185 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
186 var m = o[Symbol.asyncIterator], i;
187 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
188 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
189 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
190}
191
192function __makeTemplateObject(cooked, raw) {
193 if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
194 return cooked;
195}
196function __importStar(mod) {
197 if (mod && mod.__esModule) return mod;
198 var result = {};
199 if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
200 result.default = mod;
201 return result;
202}
203
204function __importDefault(mod) {
205 return (mod && mod.__esModule) ? mod : { default: mod };
206}
207
208var tslib_1 = /*#__PURE__*/Object.freeze({
209 __extends: __extends,
210 get __assign () { return __assign; },
211 __rest: __rest,
212 __decorate: __decorate,
213 __param: __param,
214 __metadata: __metadata,
215 __awaiter: __awaiter,
216 __generator: __generator,
217 __exportStar: __exportStar,
218 __values: __values,
219 __read: __read,
220 __spread: __spread,
221 __await: __await,
222 __asyncGenerator: __asyncGenerator,
223 __asyncDelegator: __asyncDelegator,
224 __asyncValues: __asyncValues,
225 __makeTemplateObject: __makeTemplateObject,
226 __importStar: __importStar,
227 __importDefault: __importDefault
228});
229
230var version = "1.11.1";
231
232var minimalisticAssert = assert;
233
234function assert(val, msg) {
235 if (!val)
236 throw new Error(msg || 'Assertion failed');
237}
238
239assert.equal = function assertEqual(l, r, msg) {
240 if (l != r)
241 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
242};
243
244var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
245
246function createCommonjsModule(fn, module) {
247 return module = { exports: {} }, fn(module, module.exports), module.exports;
248}
249
250var inherits_browser = createCommonjsModule(function (module) {
251if (typeof Object.create === 'function') {
252 // implementation from standard node.js 'util' module
253 module.exports = function inherits(ctor, superCtor) {
254 ctor.super_ = superCtor;
255 ctor.prototype = Object.create(superCtor.prototype, {
256 constructor: {
257 value: ctor,
258 enumerable: false,
259 writable: true,
260 configurable: true
261 }
262 });
263 };
264} else {
265 // old school shim for old browsers
266 module.exports = function inherits(ctor, superCtor) {
267 ctor.super_ = superCtor;
268 var TempCtor = function () {};
269 TempCtor.prototype = superCtor.prototype;
270 ctor.prototype = new TempCtor();
271 ctor.prototype.constructor = ctor;
272 };
273}
274});
275
276var inherits = createCommonjsModule(function (module) {
277try {
278 var util = util$2;
279 if (typeof util.inherits !== 'function') throw '';
280 module.exports = util.inherits;
281} catch (e) {
282 module.exports = inherits_browser;
283}
284});
285
286var inherits_1 = inherits;
287
288function isSurrogatePair(msg, i) {
289 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
290 return false;
291 }
292 if (i < 0 || i + 1 >= msg.length) {
293 return false;
294 }
295 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
296}
297
298function toArray(msg, enc) {
299 if (Array.isArray(msg))
300 return msg.slice();
301 if (!msg)
302 return [];
303 var res = [];
304 if (typeof msg === 'string') {
305 if (!enc) {
306 // Inspired by stringToUtf8ByteArray() in closure-library by Google
307 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
308 // Apache License 2.0
309 // https://github.com/google/closure-library/blob/master/LICENSE
310 var p = 0;
311 for (var i = 0; i < msg.length; i++) {
312 var c = msg.charCodeAt(i);
313 if (c < 128) {
314 res[p++] = c;
315 } else if (c < 2048) {
316 res[p++] = (c >> 6) | 192;
317 res[p++] = (c & 63) | 128;
318 } else if (isSurrogatePair(msg, i)) {
319 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
320 res[p++] = (c >> 18) | 240;
321 res[p++] = ((c >> 12) & 63) | 128;
322 res[p++] = ((c >> 6) & 63) | 128;
323 res[p++] = (c & 63) | 128;
324 } else {
325 res[p++] = (c >> 12) | 224;
326 res[p++] = ((c >> 6) & 63) | 128;
327 res[p++] = (c & 63) | 128;
328 }
329 }
330 } else if (enc === 'hex') {
331 msg = msg.replace(/[^a-z0-9]+/ig, '');
332 if (msg.length % 2 !== 0)
333 msg = '0' + msg;
334 for (i = 0; i < msg.length; i += 2)
335 res.push(parseInt(msg[i] + msg[i + 1], 16));
336 }
337 } else {
338 for (i = 0; i < msg.length; i++)
339 res[i] = msg[i] | 0;
340 }
341 return res;
342}
343var toArray_1 = toArray;
344
345function toHex(msg) {
346 var res = '';
347 for (var i = 0; i < msg.length; i++)
348 res += zero2(msg[i].toString(16));
349 return res;
350}
351var toHex_1 = toHex;
352
353function htonl(w) {
354 var res = (w >>> 24) |
355 ((w >>> 8) & 0xff00) |
356 ((w << 8) & 0xff0000) |
357 ((w & 0xff) << 24);
358 return res >>> 0;
359}
360var htonl_1 = htonl;
361
362function toHex32(msg, endian) {
363 var res = '';
364 for (var i = 0; i < msg.length; i++) {
365 var w = msg[i];
366 if (endian === 'little')
367 w = htonl(w);
368 res += zero8(w.toString(16));
369 }
370 return res;
371}
372var toHex32_1 = toHex32;
373
374function zero2(word) {
375 if (word.length === 1)
376 return '0' + word;
377 else
378 return word;
379}
380var zero2_1 = zero2;
381
382function zero8(word) {
383 if (word.length === 7)
384 return '0' + word;
385 else if (word.length === 6)
386 return '00' + word;
387 else if (word.length === 5)
388 return '000' + word;
389 else if (word.length === 4)
390 return '0000' + word;
391 else if (word.length === 3)
392 return '00000' + word;
393 else if (word.length === 2)
394 return '000000' + word;
395 else if (word.length === 1)
396 return '0000000' + word;
397 else
398 return word;
399}
400var zero8_1 = zero8;
401
402function join32(msg, start, end, endian) {
403 var len = end - start;
404 minimalisticAssert(len % 4 === 0);
405 var res = new Array(len / 4);
406 for (var i = 0, k = start; i < res.length; i++, k += 4) {
407 var w;
408 if (endian === 'big')
409 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
410 else
411 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
412 res[i] = w >>> 0;
413 }
414 return res;
415}
416var join32_1 = join32;
417
418function split32(msg, endian) {
419 var res = new Array(msg.length * 4);
420 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
421 var m = msg[i];
422 if (endian === 'big') {
423 res[k] = m >>> 24;
424 res[k + 1] = (m >>> 16) & 0xff;
425 res[k + 2] = (m >>> 8) & 0xff;
426 res[k + 3] = m & 0xff;
427 } else {
428 res[k + 3] = m >>> 24;
429 res[k + 2] = (m >>> 16) & 0xff;
430 res[k + 1] = (m >>> 8) & 0xff;
431 res[k] = m & 0xff;
432 }
433 }
434 return res;
435}
436var split32_1 = split32;
437
438function rotr32(w, b) {
439 return (w >>> b) | (w << (32 - b));
440}
441var rotr32_1 = rotr32;
442
443function rotl32(w, b) {
444 return (w << b) | (w >>> (32 - b));
445}
446var rotl32_1 = rotl32;
447
448function sum32(a, b) {
449 return (a + b) >>> 0;
450}
451var sum32_1 = sum32;
452
453function sum32_3(a, b, c) {
454 return (a + b + c) >>> 0;
455}
456var sum32_3_1 = sum32_3;
457
458function sum32_4(a, b, c, d) {
459 return (a + b + c + d) >>> 0;
460}
461var sum32_4_1 = sum32_4;
462
463function sum32_5(a, b, c, d, e) {
464 return (a + b + c + d + e) >>> 0;
465}
466var sum32_5_1 = sum32_5;
467
468function sum64(buf, pos, ah, al) {
469 var bh = buf[pos];
470 var bl = buf[pos + 1];
471
472 var lo = (al + bl) >>> 0;
473 var hi = (lo < al ? 1 : 0) + ah + bh;
474 buf[pos] = hi >>> 0;
475 buf[pos + 1] = lo;
476}
477var sum64_1 = sum64;
478
479function sum64_hi(ah, al, bh, bl) {
480 var lo = (al + bl) >>> 0;
481 var hi = (lo < al ? 1 : 0) + ah + bh;
482 return hi >>> 0;
483}
484var sum64_hi_1 = sum64_hi;
485
486function sum64_lo(ah, al, bh, bl) {
487 var lo = al + bl;
488 return lo >>> 0;
489}
490var sum64_lo_1 = sum64_lo;
491
492function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
493 var carry = 0;
494 var lo = al;
495 lo = (lo + bl) >>> 0;
496 carry += lo < al ? 1 : 0;
497 lo = (lo + cl) >>> 0;
498 carry += lo < cl ? 1 : 0;
499 lo = (lo + dl) >>> 0;
500 carry += lo < dl ? 1 : 0;
501
502 var hi = ah + bh + ch + dh + carry;
503 return hi >>> 0;
504}
505var sum64_4_hi_1 = sum64_4_hi;
506
507function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
508 var lo = al + bl + cl + dl;
509 return lo >>> 0;
510}
511var sum64_4_lo_1 = sum64_4_lo;
512
513function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
514 var carry = 0;
515 var lo = al;
516 lo = (lo + bl) >>> 0;
517 carry += lo < al ? 1 : 0;
518 lo = (lo + cl) >>> 0;
519 carry += lo < cl ? 1 : 0;
520 lo = (lo + dl) >>> 0;
521 carry += lo < dl ? 1 : 0;
522 lo = (lo + el) >>> 0;
523 carry += lo < el ? 1 : 0;
524
525 var hi = ah + bh + ch + dh + eh + carry;
526 return hi >>> 0;
527}
528var sum64_5_hi_1 = sum64_5_hi;
529
530function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
531 var lo = al + bl + cl + dl + el;
532
533 return lo >>> 0;
534}
535var sum64_5_lo_1 = sum64_5_lo;
536
537function rotr64_hi(ah, al, num) {
538 var r = (al << (32 - num)) | (ah >>> num);
539 return r >>> 0;
540}
541var rotr64_hi_1 = rotr64_hi;
542
543function rotr64_lo(ah, al, num) {
544 var r = (ah << (32 - num)) | (al >>> num);
545 return r >>> 0;
546}
547var rotr64_lo_1 = rotr64_lo;
548
549function shr64_hi(ah, al, num) {
550 return ah >>> num;
551}
552var shr64_hi_1 = shr64_hi;
553
554function shr64_lo(ah, al, num) {
555 var r = (ah << (32 - num)) | (al >>> num);
556 return r >>> 0;
557}
558var shr64_lo_1 = shr64_lo;
559
560var utils = {
561 inherits: inherits_1,
562 toArray: toArray_1,
563 toHex: toHex_1,
564 htonl: htonl_1,
565 toHex32: toHex32_1,
566 zero2: zero2_1,
567 zero8: zero8_1,
568 join32: join32_1,
569 split32: split32_1,
570 rotr32: rotr32_1,
571 rotl32: rotl32_1,
572 sum32: sum32_1,
573 sum32_3: sum32_3_1,
574 sum32_4: sum32_4_1,
575 sum32_5: sum32_5_1,
576 sum64: sum64_1,
577 sum64_hi: sum64_hi_1,
578 sum64_lo: sum64_lo_1,
579 sum64_4_hi: sum64_4_hi_1,
580 sum64_4_lo: sum64_4_lo_1,
581 sum64_5_hi: sum64_5_hi_1,
582 sum64_5_lo: sum64_5_lo_1,
583 rotr64_hi: rotr64_hi_1,
584 rotr64_lo: rotr64_lo_1,
585 shr64_hi: shr64_hi_1,
586 shr64_lo: shr64_lo_1
587};
588
589function BlockHash() {
590 this.pending = null;
591 this.pendingTotal = 0;
592 this.blockSize = this.constructor.blockSize;
593 this.outSize = this.constructor.outSize;
594 this.hmacStrength = this.constructor.hmacStrength;
595 this.padLength = this.constructor.padLength / 8;
596 this.endian = 'big';
597
598 this._delta8 = this.blockSize / 8;
599 this._delta32 = this.blockSize / 32;
600}
601var BlockHash_1 = BlockHash;
602
603BlockHash.prototype.update = function update(msg, enc) {
604 // Convert message to array, pad it, and join into 32bit blocks
605 msg = utils.toArray(msg, enc);
606 if (!this.pending)
607 this.pending = msg;
608 else
609 this.pending = this.pending.concat(msg);
610 this.pendingTotal += msg.length;
611
612 // Enough data, try updating
613 if (this.pending.length >= this._delta8) {
614 msg = this.pending;
615
616 // Process pending data in blocks
617 var r = msg.length % this._delta8;
618 this.pending = msg.slice(msg.length - r, msg.length);
619 if (this.pending.length === 0)
620 this.pending = null;
621
622 msg = utils.join32(msg, 0, msg.length - r, this.endian);
623 for (var i = 0; i < msg.length; i += this._delta32)
624 this._update(msg, i, i + this._delta32);
625 }
626
627 return this;
628};
629
630BlockHash.prototype.digest = function digest(enc) {
631 this.update(this._pad());
632 minimalisticAssert(this.pending === null);
633
634 return this._digest(enc);
635};
636
637BlockHash.prototype._pad = function pad() {
638 var len = this.pendingTotal;
639 var bytes = this._delta8;
640 var k = bytes - ((len + this.padLength) % bytes);
641 var res = new Array(k + this.padLength);
642 res[0] = 0x80;
643 for (var i = 1; i < k; i++)
644 res[i] = 0;
645
646 // Append length
647 len <<= 3;
648 if (this.endian === 'big') {
649 for (var t = 8; t < this.padLength; t++)
650 res[i++] = 0;
651
652 res[i++] = 0;
653 res[i++] = 0;
654 res[i++] = 0;
655 res[i++] = 0;
656 res[i++] = (len >>> 24) & 0xff;
657 res[i++] = (len >>> 16) & 0xff;
658 res[i++] = (len >>> 8) & 0xff;
659 res[i++] = len & 0xff;
660 } else {
661 res[i++] = len & 0xff;
662 res[i++] = (len >>> 8) & 0xff;
663 res[i++] = (len >>> 16) & 0xff;
664 res[i++] = (len >>> 24) & 0xff;
665 res[i++] = 0;
666 res[i++] = 0;
667 res[i++] = 0;
668 res[i++] = 0;
669
670 for (t = 8; t < this.padLength; t++)
671 res[i++] = 0;
672 }
673
674 return res;
675};
676
677var common = {
678 BlockHash: BlockHash_1
679};
680
681var rotr32$1 = utils.rotr32;
682
683function ft_1(s, x, y, z) {
684 if (s === 0)
685 return ch32(x, y, z);
686 if (s === 1 || s === 3)
687 return p32(x, y, z);
688 if (s === 2)
689 return maj32(x, y, z);
690}
691var ft_1_1 = ft_1;
692
693function ch32(x, y, z) {
694 return (x & y) ^ ((~x) & z);
695}
696var ch32_1 = ch32;
697
698function maj32(x, y, z) {
699 return (x & y) ^ (x & z) ^ (y & z);
700}
701var maj32_1 = maj32;
702
703function p32(x, y, z) {
704 return x ^ y ^ z;
705}
706var p32_1 = p32;
707
708function s0_256(x) {
709 return rotr32$1(x, 2) ^ rotr32$1(x, 13) ^ rotr32$1(x, 22);
710}
711var s0_256_1 = s0_256;
712
713function s1_256(x) {
714 return rotr32$1(x, 6) ^ rotr32$1(x, 11) ^ rotr32$1(x, 25);
715}
716var s1_256_1 = s1_256;
717
718function g0_256(x) {
719 return rotr32$1(x, 7) ^ rotr32$1(x, 18) ^ (x >>> 3);
720}
721var g0_256_1 = g0_256;
722
723function g1_256(x) {
724 return rotr32$1(x, 17) ^ rotr32$1(x, 19) ^ (x >>> 10);
725}
726var g1_256_1 = g1_256;
727
728var common$1 = {
729 ft_1: ft_1_1,
730 ch32: ch32_1,
731 maj32: maj32_1,
732 p32: p32_1,
733 s0_256: s0_256_1,
734 s1_256: s1_256_1,
735 g0_256: g0_256_1,
736 g1_256: g1_256_1
737};
738
739var sum32$1 = utils.sum32;
740var sum32_4$1 = utils.sum32_4;
741var sum32_5$1 = utils.sum32_5;
742var ch32$1 = common$1.ch32;
743var maj32$1 = common$1.maj32;
744var s0_256$1 = common$1.s0_256;
745var s1_256$1 = common$1.s1_256;
746var g0_256$1 = common$1.g0_256;
747var g1_256$1 = common$1.g1_256;
748
749var BlockHash$1 = common.BlockHash;
750
751var sha256_K = [
752 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
753 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
754 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
755 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
756 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
757 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
758 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
759 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
760 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
761 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
762 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
763 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
764 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
765 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
766 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
767 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
768];
769
770function SHA256() {
771 if (!(this instanceof SHA256))
772 return new SHA256();
773
774 BlockHash$1.call(this);
775 this.h = [
776 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
777 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
778 ];
779 this.k = sha256_K;
780 this.W = new Array(64);
781}
782utils.inherits(SHA256, BlockHash$1);
783var _256 = SHA256;
784
785SHA256.blockSize = 512;
786SHA256.outSize = 256;
787SHA256.hmacStrength = 192;
788SHA256.padLength = 64;
789
790SHA256.prototype._update = function _update(msg, start) {
791 var W = this.W;
792
793 for (var i = 0; i < 16; i++)
794 W[i] = msg[start + i];
795 for (; i < W.length; i++)
796 W[i] = sum32_4$1(g1_256$1(W[i - 2]), W[i - 7], g0_256$1(W[i - 15]), W[i - 16]);
797
798 var a = this.h[0];
799 var b = this.h[1];
800 var c = this.h[2];
801 var d = this.h[3];
802 var e = this.h[4];
803 var f = this.h[5];
804 var g = this.h[6];
805 var h = this.h[7];
806
807 minimalisticAssert(this.k.length === W.length);
808 for (i = 0; i < W.length; i++) {
809 var T1 = sum32_5$1(h, s1_256$1(e), ch32$1(e, f, g), this.k[i], W[i]);
810 var T2 = sum32$1(s0_256$1(a), maj32$1(a, b, c));
811 h = g;
812 g = f;
813 f = e;
814 e = sum32$1(d, T1);
815 d = c;
816 c = b;
817 b = a;
818 a = sum32$1(T1, T2);
819 }
820
821 this.h[0] = sum32$1(this.h[0], a);
822 this.h[1] = sum32$1(this.h[1], b);
823 this.h[2] = sum32$1(this.h[2], c);
824 this.h[3] = sum32$1(this.h[3], d);
825 this.h[4] = sum32$1(this.h[4], e);
826 this.h[5] = sum32$1(this.h[5], f);
827 this.h[6] = sum32$1(this.h[6], g);
828 this.h[7] = sum32$1(this.h[7], h);
829};
830
831SHA256.prototype._digest = function digest(enc) {
832 if (enc === 'hex')
833 return utils.toHex32(this.h, 'big');
834 else
835 return utils.split32(this.h, 'big');
836};
837
838var charToInteger = {};
839var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
840for (var i = 0; i < chars.length; i++) {
841 charToInteger[chars.charCodeAt(i)] = i;
842}
843function decode(mappings) {
844 var generatedCodeColumn = 0; // first field
845 var sourceFileIndex = 0; // second field
846 var sourceCodeLine = 0; // third field
847 var sourceCodeColumn = 0; // fourth field
848 var nameIndex = 0; // fifth field
849 var decoded = [];
850 var line = [];
851 var segment = [];
852 for (var i = 0, j = 0, shift = 0, value = 0, len = mappings.length; i < len; i++) {
853 var c = mappings.charCodeAt(i);
854 if (c === 44) { // ","
855 if (segment.length)
856 line.push(new Int32Array(segment));
857 segment = [];
858 j = 0;
859 }
860 else if (c === 59) { // ";"
861 if (segment.length)
862 line.push(new Int32Array(segment));
863 segment = [];
864 j = 0;
865 decoded.push(line);
866 line = [];
867 generatedCodeColumn = 0;
868 }
869 else {
870 var integer = charToInteger[c];
871 if (integer === undefined) {
872 throw new Error('Invalid character (' + String.fromCharCode(c) + ')');
873 }
874 var hasContinuationBit = integer & 32;
875 integer &= 31;
876 value += integer << shift;
877 if (hasContinuationBit) {
878 shift += 5;
879 }
880 else {
881 var shouldNegate = value & 1;
882 value >>= 1;
883 var num = shouldNegate ? -value : value;
884 if (j == 0) {
885 generatedCodeColumn += num;
886 segment.push(generatedCodeColumn);
887 }
888 else if (j === 1) {
889 sourceFileIndex += num;
890 segment.push(sourceFileIndex);
891 }
892 else if (j === 2) {
893 sourceCodeLine += num;
894 segment.push(sourceCodeLine);
895 }
896 else if (j === 3) {
897 sourceCodeColumn += num;
898 segment.push(sourceCodeColumn);
899 }
900 else if (j === 4) {
901 nameIndex += num;
902 segment.push(nameIndex);
903 }
904 j++;
905 value = shift = 0; // reset
906 }
907 }
908 }
909 if (segment.length)
910 line.push(new Int32Array(segment));
911 decoded.push(line);
912 return decoded;
913}
914function encode(decoded) {
915 var sourceFileIndex = 0; // second field
916 var sourceCodeLine = 0; // third field
917 var sourceCodeColumn = 0; // fourth field
918 var nameIndex = 0; // fifth field
919 var mappings = '';
920 for (var i = 0; i < decoded.length; i++) {
921 var line = decoded[i];
922 if (i > 0)
923 mappings += ';';
924 if (line.length === 0)
925 continue;
926 var generatedCodeColumn = 0; // first field
927 var lineMappings = [];
928 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
929 var segment = line_1[_i];
930 var segmentMappings = encodeInteger(segment[0] - generatedCodeColumn);
931 generatedCodeColumn = segment[0];
932 if (segment.length > 1) {
933 segmentMappings +=
934 encodeInteger(segment[1] - sourceFileIndex) +
935 encodeInteger(segment[2] - sourceCodeLine) +
936 encodeInteger(segment[3] - sourceCodeColumn);
937 sourceFileIndex = segment[1];
938 sourceCodeLine = segment[2];
939 sourceCodeColumn = segment[3];
940 }
941 if (segment.length === 5) {
942 segmentMappings += encodeInteger(segment[4] - nameIndex);
943 nameIndex = segment[4];
944 }
945 lineMappings.push(segmentMappings);
946 }
947 mappings += lineMappings.join(',');
948 }
949 return mappings;
950}
951function encodeInteger(num) {
952 var result = '';
953 num = num < 0 ? (-num << 1) | 1 : num << 1;
954 do {
955 var clamped = num & 31;
956 num >>= 5;
957 if (num > 0) {
958 clamped |= 32;
959 }
960 result += chars[clamped];
961 } while (num > 0);
962 return result;
963}
964
965var Chunk = function Chunk(start, end, content) {
966 this.start = start;
967 this.end = end;
968 this.original = content;
969
970 this.intro = '';
971 this.outro = '';
972
973 this.content = content;
974 this.storeName = false;
975 this.edited = false;
976
977 // we make these non-enumerable, for sanity while debugging
978 Object.defineProperties(this, {
979 previous: { writable: true, value: null },
980 next: { writable: true, value: null }
981 });
982};
983
984Chunk.prototype.appendLeft = function appendLeft (content) {
985 this.outro += content;
986};
987
988Chunk.prototype.appendRight = function appendRight (content) {
989 this.intro = this.intro + content;
990};
991
992Chunk.prototype.clone = function clone () {
993 var chunk = new Chunk(this.start, this.end, this.original);
994
995 chunk.intro = this.intro;
996 chunk.outro = this.outro;
997 chunk.content = this.content;
998 chunk.storeName = this.storeName;
999 chunk.edited = this.edited;
1000
1001 return chunk;
1002};
1003
1004Chunk.prototype.contains = function contains (index) {
1005 return this.start < index && index < this.end;
1006};
1007
1008Chunk.prototype.eachNext = function eachNext (fn) {
1009 var chunk = this;
1010 while (chunk) {
1011 fn(chunk);
1012 chunk = chunk.next;
1013 }
1014};
1015
1016Chunk.prototype.eachPrevious = function eachPrevious (fn) {
1017 var chunk = this;
1018 while (chunk) {
1019 fn(chunk);
1020 chunk = chunk.previous;
1021 }
1022};
1023
1024Chunk.prototype.edit = function edit (content, storeName, contentOnly) {
1025 this.content = content;
1026 if (!contentOnly) {
1027 this.intro = '';
1028 this.outro = '';
1029 }
1030 this.storeName = storeName;
1031
1032 this.edited = true;
1033
1034 return this;
1035};
1036
1037Chunk.prototype.prependLeft = function prependLeft (content) {
1038 this.outro = content + this.outro;
1039};
1040
1041Chunk.prototype.prependRight = function prependRight (content) {
1042 this.intro = content + this.intro;
1043};
1044
1045Chunk.prototype.split = function split (index) {
1046 var sliceIndex = index - this.start;
1047
1048 var originalBefore = this.original.slice(0, sliceIndex);
1049 var originalAfter = this.original.slice(sliceIndex);
1050
1051 this.original = originalBefore;
1052
1053 var newChunk = new Chunk(index, this.end, originalAfter);
1054 newChunk.outro = this.outro;
1055 this.outro = '';
1056
1057 this.end = index;
1058
1059 if (this.edited) {
1060 // TODO is this block necessary?...
1061 newChunk.edit('', false);
1062 this.content = '';
1063 } else {
1064 this.content = originalBefore;
1065 }
1066
1067 newChunk.next = this.next;
1068 if (newChunk.next) { newChunk.next.previous = newChunk; }
1069 newChunk.previous = this;
1070 this.next = newChunk;
1071
1072 return newChunk;
1073};
1074
1075Chunk.prototype.toString = function toString () {
1076 return this.intro + this.content + this.outro;
1077};
1078
1079Chunk.prototype.trimEnd = function trimEnd (rx) {
1080 this.outro = this.outro.replace(rx, '');
1081 if (this.outro.length) { return true; }
1082
1083 var trimmed = this.content.replace(rx, '');
1084
1085 if (trimmed.length) {
1086 if (trimmed !== this.content) {
1087 this.split(this.start + trimmed.length).edit('', undefined, true);
1088 }
1089 return true;
1090
1091 } else {
1092 this.edit('', undefined, true);
1093
1094 this.intro = this.intro.replace(rx, '');
1095 if (this.intro.length) { return true; }
1096 }
1097};
1098
1099Chunk.prototype.trimStart = function trimStart (rx) {
1100 this.intro = this.intro.replace(rx, '');
1101 if (this.intro.length) { return true; }
1102
1103 var trimmed = this.content.replace(rx, '');
1104
1105 if (trimmed.length) {
1106 if (trimmed !== this.content) {
1107 this.split(this.end - trimmed.length);
1108 this.edit('', undefined, true);
1109 }
1110 return true;
1111
1112 } else {
1113 this.edit('', undefined, true);
1114
1115 this.outro = this.outro.replace(rx, '');
1116 if (this.outro.length) { return true; }
1117 }
1118};
1119
1120var btoa = function () {
1121 throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
1122};
1123if (typeof window !== 'undefined' && typeof window.btoa === 'function') {
1124 btoa = function (str) { return window.btoa(unescape(encodeURIComponent(str))); };
1125} else if (typeof Buffer === 'function') {
1126 btoa = function (str) { return Buffer.from(str, 'utf-8').toString('base64'); };
1127}
1128
1129var SourceMap = function SourceMap(properties) {
1130 this.version = 3;
1131 this.file = properties.file;
1132 this.sources = properties.sources;
1133 this.sourcesContent = properties.sourcesContent;
1134 this.names = properties.names;
1135 this.mappings = encode(properties.mappings);
1136};
1137
1138SourceMap.prototype.toString = function toString () {
1139 return JSON.stringify(this);
1140};
1141
1142SourceMap.prototype.toUrl = function toUrl () {
1143 return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
1144};
1145
1146function guessIndent(code) {
1147 var lines = code.split('\n');
1148
1149 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
1150 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
1151
1152 if (tabbed.length === 0 && spaced.length === 0) {
1153 return null;
1154 }
1155
1156 // More lines tabbed than spaced? Assume tabs, and
1157 // default to tabs in the case of a tie (or nothing
1158 // to go on)
1159 if (tabbed.length >= spaced.length) {
1160 return '\t';
1161 }
1162
1163 // Otherwise, we need to guess the multiple
1164 var min = spaced.reduce(function (previous, current) {
1165 var numSpaces = /^ +/.exec(current)[0].length;
1166 return Math.min(numSpaces, previous);
1167 }, Infinity);
1168
1169 return new Array(min + 1).join(' ');
1170}
1171
1172function getRelativePath(from, to) {
1173 var fromParts = from.split(/[/\\]/);
1174 var toParts = to.split(/[/\\]/);
1175
1176 fromParts.pop(); // get dirname
1177
1178 while (fromParts[0] === toParts[0]) {
1179 fromParts.shift();
1180 toParts.shift();
1181 }
1182
1183 if (fromParts.length) {
1184 var i = fromParts.length;
1185 while (i--) { fromParts[i] = '..'; }
1186 }
1187
1188 return fromParts.concat(toParts).join('/');
1189}
1190
1191var toString = Object.prototype.toString;
1192
1193function isObject(thing) {
1194 return toString.call(thing) === '[object Object]';
1195}
1196
1197function getLocator(source) {
1198 var originalLines = source.split('\n');
1199 var lineOffsets = [];
1200
1201 for (var i = 0, pos = 0; i < originalLines.length; i++) {
1202 lineOffsets.push(pos);
1203 pos += originalLines[i].length + 1;
1204 }
1205
1206 return function locate(index) {
1207 var i = 0;
1208 var j = lineOffsets.length;
1209 while (i < j) {
1210 var m = (i + j) >> 1;
1211 if (index < lineOffsets[m]) {
1212 j = m;
1213 } else {
1214 i = m + 1;
1215 }
1216 }
1217 var line = i - 1;
1218 var column = index - lineOffsets[line];
1219 return { line: line, column: column };
1220 };
1221}
1222
1223var Mappings = function Mappings(hires) {
1224 this.hires = hires;
1225 this.generatedCodeLine = 0;
1226 this.generatedCodeColumn = 0;
1227 this.raw = [];
1228 this.rawSegments = this.raw[this.generatedCodeLine] = [];
1229 this.pending = null;
1230};
1231
1232Mappings.prototype.addEdit = function addEdit (sourceIndex, content, loc, nameIndex) {
1233 if (content.length) {
1234 var segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
1235 if (nameIndex >= 0) {
1236 segment.push(nameIndex);
1237 }
1238 this.rawSegments.push(segment);
1239 } else if (this.pending) {
1240 this.rawSegments.push(this.pending);
1241 }
1242
1243 this.advance(content);
1244 this.pending = null;
1245};
1246
1247Mappings.prototype.addUneditedChunk = function addUneditedChunk (sourceIndex, chunk, original, loc, sourcemapLocations) {
1248 var originalCharIndex = chunk.start;
1249 var first = true;
1250
1251 while (originalCharIndex < chunk.end) {
1252 if (this.hires || first || sourcemapLocations[originalCharIndex]) {
1253 this.rawSegments.push([this.generatedCodeColumn, sourceIndex, loc.line, loc.column]);
1254 }
1255
1256 if (original[originalCharIndex] === '\n') {
1257 loc.line += 1;
1258 loc.column = 0;
1259 this.generatedCodeLine += 1;
1260 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1261 this.generatedCodeColumn = 0;
1262 } else {
1263 loc.column += 1;
1264 this.generatedCodeColumn += 1;
1265 }
1266
1267 originalCharIndex += 1;
1268 first = false;
1269 }
1270
1271 this.pending = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
1272};
1273
1274Mappings.prototype.advance = function advance (str) {
1275 if (!str) { return; }
1276
1277 var lines = str.split('\n');
1278
1279 if (lines.length > 1) {
1280 for (var i = 0; i < lines.length - 1; i++) {
1281 this.generatedCodeLine++;
1282 this.raw[this.generatedCodeLine] = this.rawSegments = [];
1283 }
1284 this.generatedCodeColumn = 0;
1285 }
1286
1287 this.generatedCodeColumn += lines[lines.length - 1].length;
1288};
1289
1290var n = '\n';
1291
1292var warned = {
1293 insertLeft: false,
1294 insertRight: false,
1295 storeName: false
1296};
1297
1298var MagicString = function MagicString(string, options) {
1299 if ( options === void 0 ) options = {};
1300
1301 var chunk = new Chunk(0, string.length, string);
1302
1303 Object.defineProperties(this, {
1304 original: { writable: true, value: string },
1305 outro: { writable: true, value: '' },
1306 intro: { writable: true, value: '' },
1307 firstChunk: { writable: true, value: chunk },
1308 lastChunk: { writable: true, value: chunk },
1309 lastSearchedChunk: { writable: true, value: chunk },
1310 byStart: { writable: true, value: {} },
1311 byEnd: { writable: true, value: {} },
1312 filename: { writable: true, value: options.filename },
1313 indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
1314 sourcemapLocations: { writable: true, value: {} },
1315 storedNames: { writable: true, value: {} },
1316 indentStr: { writable: true, value: guessIndent(string) }
1317 });
1318
1319 this.byStart[0] = chunk;
1320 this.byEnd[string.length] = chunk;
1321};
1322
1323MagicString.prototype.addSourcemapLocation = function addSourcemapLocation (char) {
1324 this.sourcemapLocations[char] = true;
1325};
1326
1327MagicString.prototype.append = function append (content) {
1328 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
1329
1330 this.outro += content;
1331 return this;
1332};
1333
1334MagicString.prototype.appendLeft = function appendLeft (index, content) {
1335 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1336
1337 this._split(index);
1338
1339 var chunk = this.byEnd[index];
1340
1341 if (chunk) {
1342 chunk.appendLeft(content);
1343 } else {
1344 this.intro += content;
1345 }
1346 return this;
1347};
1348
1349MagicString.prototype.appendRight = function appendRight (index, content) {
1350 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1351
1352 this._split(index);
1353
1354 var chunk = this.byStart[index];
1355
1356 if (chunk) {
1357 chunk.appendRight(content);
1358 } else {
1359 this.outro += content;
1360 }
1361 return this;
1362};
1363
1364MagicString.prototype.clone = function clone () {
1365 var cloned = new MagicString(this.original, { filename: this.filename });
1366
1367 var originalChunk = this.firstChunk;
1368 var clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1369
1370 while (originalChunk) {
1371 cloned.byStart[clonedChunk.start] = clonedChunk;
1372 cloned.byEnd[clonedChunk.end] = clonedChunk;
1373
1374 var nextOriginalChunk = originalChunk.next;
1375 var nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1376
1377 if (nextClonedChunk) {
1378 clonedChunk.next = nextClonedChunk;
1379 nextClonedChunk.previous = clonedChunk;
1380
1381 clonedChunk = nextClonedChunk;
1382 }
1383
1384 originalChunk = nextOriginalChunk;
1385 }
1386
1387 cloned.lastChunk = clonedChunk;
1388
1389 if (this.indentExclusionRanges) {
1390 cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1391 }
1392
1393 Object.keys(this.sourcemapLocations).forEach(function (loc) {
1394 cloned.sourcemapLocations[loc] = true;
1395 });
1396
1397 return cloned;
1398};
1399
1400MagicString.prototype.generateDecodedMap = function generateDecodedMap (options) {
1401 var this$1 = this;
1402
1403 options = options || {};
1404
1405 var sourceIndex = 0;
1406 var names = Object.keys(this.storedNames);
1407 var mappings = new Mappings(options.hires);
1408
1409 var locate = getLocator(this.original);
1410
1411 if (this.intro) {
1412 mappings.advance(this.intro);
1413 }
1414
1415 this.firstChunk.eachNext(function (chunk) {
1416 var loc = locate(chunk.start);
1417
1418 if (chunk.intro.length) { mappings.advance(chunk.intro); }
1419
1420 if (chunk.edited) {
1421 mappings.addEdit(
1422 sourceIndex,
1423 chunk.content,
1424 loc,
1425 chunk.storeName ? names.indexOf(chunk.original) : -1
1426 );
1427 } else {
1428 mappings.addUneditedChunk(sourceIndex, chunk, this$1.original, loc, this$1.sourcemapLocations);
1429 }
1430
1431 if (chunk.outro.length) { mappings.advance(chunk.outro); }
1432 });
1433
1434 return {
1435 file: options.file ? options.file.split(/[/\\]/).pop() : null,
1436 sources: [options.source ? getRelativePath(options.file || '', options.source) : null],
1437 sourcesContent: options.includeContent ? [this.original] : [null],
1438 names: names,
1439 mappings: mappings.raw
1440 };
1441};
1442
1443MagicString.prototype.generateMap = function generateMap (options) {
1444 return new SourceMap(this.generateDecodedMap(options));
1445};
1446
1447MagicString.prototype.getIndentString = function getIndentString () {
1448 return this.indentStr === null ? '\t' : this.indentStr;
1449};
1450
1451MagicString.prototype.indent = function indent (indentStr, options) {
1452 var pattern = /^[^\r\n]/gm;
1453
1454 if (isObject(indentStr)) {
1455 options = indentStr;
1456 indentStr = undefined;
1457 }
1458
1459 indentStr = indentStr !== undefined ? indentStr : this.indentStr || '\t';
1460
1461 if (indentStr === '') { return this; } // noop
1462
1463 options = options || {};
1464
1465 // Process exclusion ranges
1466 var isExcluded = {};
1467
1468 if (options.exclude) {
1469 var exclusions =
1470 typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1471 exclusions.forEach(function (exclusion) {
1472 for (var i = exclusion[0]; i < exclusion[1]; i += 1) {
1473 isExcluded[i] = true;
1474 }
1475 });
1476 }
1477
1478 var shouldIndentNextCharacter = options.indentStart !== false;
1479 var replacer = function (match) {
1480 if (shouldIndentNextCharacter) { return ("" + indentStr + match); }
1481 shouldIndentNextCharacter = true;
1482 return match;
1483 };
1484
1485 this.intro = this.intro.replace(pattern, replacer);
1486
1487 var charIndex = 0;
1488 var chunk = this.firstChunk;
1489
1490 while (chunk) {
1491 var end = chunk.end;
1492
1493 if (chunk.edited) {
1494 if (!isExcluded[charIndex]) {
1495 chunk.content = chunk.content.replace(pattern, replacer);
1496
1497 if (chunk.content.length) {
1498 shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1499 }
1500 }
1501 } else {
1502 charIndex = chunk.start;
1503
1504 while (charIndex < end) {
1505 if (!isExcluded[charIndex]) {
1506 var char = this.original[charIndex];
1507
1508 if (char === '\n') {
1509 shouldIndentNextCharacter = true;
1510 } else if (char !== '\r' && shouldIndentNextCharacter) {
1511 shouldIndentNextCharacter = false;
1512
1513 if (charIndex === chunk.start) {
1514 chunk.prependRight(indentStr);
1515 } else {
1516 this._splitChunk(chunk, charIndex);
1517 chunk = chunk.next;
1518 chunk.prependRight(indentStr);
1519 }
1520 }
1521 }
1522
1523 charIndex += 1;
1524 }
1525 }
1526
1527 charIndex = chunk.end;
1528 chunk = chunk.next;
1529 }
1530
1531 this.outro = this.outro.replace(pattern, replacer);
1532
1533 return this;
1534};
1535
1536MagicString.prototype.insert = function insert () {
1537 throw new Error('magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)');
1538};
1539
1540MagicString.prototype.insertLeft = function insertLeft (index, content) {
1541 if (!warned.insertLeft) {
1542 console.warn('magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead'); // eslint-disable-line no-console
1543 warned.insertLeft = true;
1544 }
1545
1546 return this.appendLeft(index, content);
1547};
1548
1549MagicString.prototype.insertRight = function insertRight (index, content) {
1550 if (!warned.insertRight) {
1551 console.warn('magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead'); // eslint-disable-line no-console
1552 warned.insertRight = true;
1553 }
1554
1555 return this.prependRight(index, content);
1556};
1557
1558MagicString.prototype.move = function move (start, end, index) {
1559 if (index >= start && index <= end) { throw new Error('Cannot move a selection inside itself'); }
1560
1561 this._split(start);
1562 this._split(end);
1563 this._split(index);
1564
1565 var first = this.byStart[start];
1566 var last = this.byEnd[end];
1567
1568 var oldLeft = first.previous;
1569 var oldRight = last.next;
1570
1571 var newRight = this.byStart[index];
1572 if (!newRight && last === this.lastChunk) { return this; }
1573 var newLeft = newRight ? newRight.previous : this.lastChunk;
1574
1575 if (oldLeft) { oldLeft.next = oldRight; }
1576 if (oldRight) { oldRight.previous = oldLeft; }
1577
1578 if (newLeft) { newLeft.next = first; }
1579 if (newRight) { newRight.previous = last; }
1580
1581 if (!first.previous) { this.firstChunk = last.next; }
1582 if (!last.next) {
1583 this.lastChunk = first.previous;
1584 this.lastChunk.next = null;
1585 }
1586
1587 first.previous = newLeft;
1588 last.next = newRight || null;
1589
1590 if (!newLeft) { this.firstChunk = first; }
1591 if (!newRight) { this.lastChunk = last; }
1592 return this;
1593};
1594
1595MagicString.prototype.overwrite = function overwrite (start, end, content, options) {
1596 if (typeof content !== 'string') { throw new TypeError('replacement content must be a string'); }
1597
1598 while (start < 0) { start += this.original.length; }
1599 while (end < 0) { end += this.original.length; }
1600
1601 if (end > this.original.length) { throw new Error('end is out of bounds'); }
1602 if (start === end)
1603 { throw new Error('Cannot overwrite a zero-length range – use appendLeft or prependRight instead'); }
1604
1605 this._split(start);
1606 this._split(end);
1607
1608 if (options === true) {
1609 if (!warned.storeName) {
1610 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
1611 warned.storeName = true;
1612 }
1613
1614 options = { storeName: true };
1615 }
1616 var storeName = options !== undefined ? options.storeName : false;
1617 var contentOnly = options !== undefined ? options.contentOnly : false;
1618
1619 if (storeName) {
1620 var original = this.original.slice(start, end);
1621 this.storedNames[original] = true;
1622 }
1623
1624 var first = this.byStart[start];
1625 var last = this.byEnd[end];
1626
1627 if (first) {
1628 if (end > first.end && first.next !== this.byStart[first.end]) {
1629 throw new Error('Cannot overwrite across a split point');
1630 }
1631
1632 first.edit(content, storeName, contentOnly);
1633
1634 if (first !== last) {
1635 var chunk = first.next;
1636 while (chunk !== last) {
1637 chunk.edit('', false);
1638 chunk = chunk.next;
1639 }
1640
1641 chunk.edit('', false);
1642 }
1643 } else {
1644 // must be inserting at the end
1645 var newChunk = new Chunk(start, end, '').edit(content, storeName);
1646
1647 // TODO last chunk in the array may not be the last chunk, if it's moved...
1648 last.next = newChunk;
1649 newChunk.previous = last;
1650 }
1651 return this;
1652};
1653
1654MagicString.prototype.prepend = function prepend (content) {
1655 if (typeof content !== 'string') { throw new TypeError('outro content must be a string'); }
1656
1657 this.intro = content + this.intro;
1658 return this;
1659};
1660
1661MagicString.prototype.prependLeft = function prependLeft (index, content) {
1662 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1663
1664 this._split(index);
1665
1666 var chunk = this.byEnd[index];
1667
1668 if (chunk) {
1669 chunk.prependLeft(content);
1670 } else {
1671 this.intro = content + this.intro;
1672 }
1673 return this;
1674};
1675
1676MagicString.prototype.prependRight = function prependRight (index, content) {
1677 if (typeof content !== 'string') { throw new TypeError('inserted content must be a string'); }
1678
1679 this._split(index);
1680
1681 var chunk = this.byStart[index];
1682
1683 if (chunk) {
1684 chunk.prependRight(content);
1685 } else {
1686 this.outro = content + this.outro;
1687 }
1688 return this;
1689};
1690
1691MagicString.prototype.remove = function remove (start, end) {
1692 while (start < 0) { start += this.original.length; }
1693 while (end < 0) { end += this.original.length; }
1694
1695 if (start === end) { return this; }
1696
1697 if (start < 0 || end > this.original.length) { throw new Error('Character is out of bounds'); }
1698 if (start > end) { throw new Error('end must be greater than start'); }
1699
1700 this._split(start);
1701 this._split(end);
1702
1703 var chunk = this.byStart[start];
1704
1705 while (chunk) {
1706 chunk.intro = '';
1707 chunk.outro = '';
1708 chunk.edit('');
1709
1710 chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1711 }
1712 return this;
1713};
1714
1715MagicString.prototype.lastChar = function lastChar () {
1716 if (this.outro.length)
1717 { return this.outro[this.outro.length - 1]; }
1718 var chunk = this.lastChunk;
1719 do {
1720 if (chunk.outro.length)
1721 { return chunk.outro[chunk.outro.length - 1]; }
1722 if (chunk.content.length)
1723 { return chunk.content[chunk.content.length - 1]; }
1724 if (chunk.intro.length)
1725 { return chunk.intro[chunk.intro.length - 1]; }
1726 } while (chunk = chunk.previous);
1727 if (this.intro.length)
1728 { return this.intro[this.intro.length - 1]; }
1729 return '';
1730};
1731
1732MagicString.prototype.lastLine = function lastLine () {
1733 var lineIndex = this.outro.lastIndexOf(n);
1734 if (lineIndex !== -1)
1735 { return this.outro.substr(lineIndex + 1); }
1736 var lineStr = this.outro;
1737 var chunk = this.lastChunk;
1738 do {
1739 if (chunk.outro.length > 0) {
1740 lineIndex = chunk.outro.lastIndexOf(n);
1741 if (lineIndex !== -1)
1742 { return chunk.outro.substr(lineIndex + 1) + lineStr; }
1743 lineStr = chunk.outro + lineStr;
1744 }
1745
1746 if (chunk.content.length > 0) {
1747 lineIndex = chunk.content.lastIndexOf(n);
1748 if (lineIndex !== -1)
1749 { return chunk.content.substr(lineIndex + 1) + lineStr; }
1750 lineStr = chunk.content + lineStr;
1751 }
1752
1753 if (chunk.intro.length > 0) {
1754 lineIndex = chunk.intro.lastIndexOf(n);
1755 if (lineIndex !== -1)
1756 { return chunk.intro.substr(lineIndex + 1) + lineStr; }
1757 lineStr = chunk.intro + lineStr;
1758 }
1759 } while (chunk = chunk.previous);
1760 lineIndex = this.intro.lastIndexOf(n);
1761 if (lineIndex !== -1)
1762 { return this.intro.substr(lineIndex + 1) + lineStr; }
1763 return this.intro + lineStr;
1764};
1765
1766MagicString.prototype.slice = function slice (start, end) {
1767 if ( start === void 0 ) start = 0;
1768 if ( end === void 0 ) end = this.original.length;
1769
1770 while (start < 0) { start += this.original.length; }
1771 while (end < 0) { end += this.original.length; }
1772
1773 var result = '';
1774
1775 // find start chunk
1776 var chunk = this.firstChunk;
1777 while (chunk && (chunk.start > start || chunk.end <= start)) {
1778 // found end chunk before start
1779 if (chunk.start < end && chunk.end >= end) {
1780 return result;
1781 }
1782
1783 chunk = chunk.next;
1784 }
1785
1786 if (chunk && chunk.edited && chunk.start !== start)
1787 { throw new Error(("Cannot use replaced character " + start + " as slice start anchor.")); }
1788
1789 var startChunk = chunk;
1790 while (chunk) {
1791 if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1792 result += chunk.intro;
1793 }
1794
1795 var containsEnd = chunk.start < end && chunk.end >= end;
1796 if (containsEnd && chunk.edited && chunk.end !== end)
1797 { throw new Error(("Cannot use replaced character " + end + " as slice end anchor.")); }
1798
1799 var sliceStart = startChunk === chunk ? start - chunk.start : 0;
1800 var sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1801
1802 result += chunk.content.slice(sliceStart, sliceEnd);
1803
1804 if (chunk.outro && (!containsEnd || chunk.end === end)) {
1805 result += chunk.outro;
1806 }
1807
1808 if (containsEnd) {
1809 break;
1810 }
1811
1812 chunk = chunk.next;
1813 }
1814
1815 return result;
1816};
1817
1818// TODO deprecate this? not really very useful
1819MagicString.prototype.snip = function snip (start, end) {
1820 var clone = this.clone();
1821 clone.remove(0, start);
1822 clone.remove(end, clone.original.length);
1823
1824 return clone;
1825};
1826
1827MagicString.prototype._split = function _split (index) {
1828 if (this.byStart[index] || this.byEnd[index]) { return; }
1829
1830 var chunk = this.lastSearchedChunk;
1831 var searchForward = index > chunk.end;
1832
1833 while (chunk) {
1834 if (chunk.contains(index)) { return this._splitChunk(chunk, index); }
1835
1836 chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1837 }
1838};
1839
1840MagicString.prototype._splitChunk = function _splitChunk (chunk, index) {
1841 if (chunk.edited && chunk.content.length) {
1842 // zero-length edited chunks are a special case (overlapping replacements)
1843 var loc = getLocator(this.original)(index);
1844 throw new Error(
1845 ("Cannot split a chunk that has already been edited (" + (loc.line) + ":" + (loc.column) + " – \"" + (chunk.original) + "\")")
1846 );
1847 }
1848
1849 var newChunk = chunk.split(index);
1850
1851 this.byEnd[index] = chunk;
1852 this.byStart[index] = newChunk;
1853 this.byEnd[newChunk.end] = newChunk;
1854
1855 if (chunk === this.lastChunk) { this.lastChunk = newChunk; }
1856
1857 this.lastSearchedChunk = chunk;
1858 return true;
1859};
1860
1861MagicString.prototype.toString = function toString () {
1862 var str = this.intro;
1863
1864 var chunk = this.firstChunk;
1865 while (chunk) {
1866 str += chunk.toString();
1867 chunk = chunk.next;
1868 }
1869
1870 return str + this.outro;
1871};
1872
1873MagicString.prototype.isEmpty = function isEmpty () {
1874 var chunk = this.firstChunk;
1875 do {
1876 if (chunk.intro.length && chunk.intro.trim() ||
1877 chunk.content.length && chunk.content.trim() ||
1878 chunk.outro.length && chunk.outro.trim())
1879 { return false; }
1880 } while (chunk = chunk.next);
1881 return true;
1882};
1883
1884MagicString.prototype.length = function length () {
1885 var chunk = this.firstChunk;
1886 var length = 0;
1887 do {
1888 length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1889 } while (chunk = chunk.next);
1890 return length;
1891};
1892
1893MagicString.prototype.trimLines = function trimLines () {
1894 return this.trim('[\\r\\n]');
1895};
1896
1897MagicString.prototype.trim = function trim (charType) {
1898 return this.trimStart(charType).trimEnd(charType);
1899};
1900
1901MagicString.prototype.trimEndAborted = function trimEndAborted (charType) {
1902 var rx = new RegExp((charType || '\\s') + '+$');
1903
1904 this.outro = this.outro.replace(rx, '');
1905 if (this.outro.length) { return true; }
1906
1907 var chunk = this.lastChunk;
1908
1909 do {
1910 var end = chunk.end;
1911 var aborted = chunk.trimEnd(rx);
1912
1913 // if chunk was trimmed, we have a new lastChunk
1914 if (chunk.end !== end) {
1915 if (this.lastChunk === chunk) {
1916 this.lastChunk = chunk.next;
1917 }
1918
1919 this.byEnd[chunk.end] = chunk;
1920 this.byStart[chunk.next.start] = chunk.next;
1921 this.byEnd[chunk.next.end] = chunk.next;
1922 }
1923
1924 if (aborted) { return true; }
1925 chunk = chunk.previous;
1926 } while (chunk);
1927
1928 return false;
1929};
1930
1931MagicString.prototype.trimEnd = function trimEnd (charType) {
1932 this.trimEndAborted(charType);
1933 return this;
1934};
1935MagicString.prototype.trimStartAborted = function trimStartAborted (charType) {
1936 var rx = new RegExp('^' + (charType || '\\s') + '+');
1937
1938 this.intro = this.intro.replace(rx, '');
1939 if (this.intro.length) { return true; }
1940
1941 var chunk = this.firstChunk;
1942
1943 do {
1944 var end = chunk.end;
1945 var aborted = chunk.trimStart(rx);
1946
1947 if (chunk.end !== end) {
1948 // special case...
1949 if (chunk === this.lastChunk) { this.lastChunk = chunk.next; }
1950
1951 this.byEnd[chunk.end] = chunk;
1952 this.byStart[chunk.next.start] = chunk.next;
1953 this.byEnd[chunk.next.end] = chunk.next;
1954 }
1955
1956 if (aborted) { return true; }
1957 chunk = chunk.next;
1958 } while (chunk);
1959
1960 return false;
1961};
1962
1963MagicString.prototype.trimStart = function trimStart (charType) {
1964 this.trimStartAborted(charType);
1965 return this;
1966};
1967
1968var hasOwnProp = Object.prototype.hasOwnProperty;
1969
1970var Bundle = function Bundle(options) {
1971 if ( options === void 0 ) options = {};
1972
1973 this.intro = options.intro || '';
1974 this.separator = options.separator !== undefined ? options.separator : '\n';
1975 this.sources = [];
1976 this.uniqueSources = [];
1977 this.uniqueSourceIndexByFilename = {};
1978};
1979
1980Bundle.prototype.addSource = function addSource (source) {
1981 if (source instanceof MagicString) {
1982 return this.addSource({
1983 content: source,
1984 filename: source.filename,
1985 separator: this.separator
1986 });
1987 }
1988
1989 if (!isObject(source) || !source.content) {
1990 throw new Error('bundle.addSource() takes an object with a `content` property, which should be an instance of MagicString, and an optional `filename`');
1991 }
1992
1993 ['filename', 'indentExclusionRanges', 'separator'].forEach(function (option) {
1994 if (!hasOwnProp.call(source, option)) { source[option] = source.content[option]; }
1995 });
1996
1997 if (source.separator === undefined) {
1998 // TODO there's a bunch of this sort of thing, needs cleaning up
1999 source.separator = this.separator;
2000 }
2001
2002 if (source.filename) {
2003 if (!hasOwnProp.call(this.uniqueSourceIndexByFilename, source.filename)) {
2004 this.uniqueSourceIndexByFilename[source.filename] = this.uniqueSources.length;
2005 this.uniqueSources.push({ filename: source.filename, content: source.content.original });
2006 } else {
2007 var uniqueSource = this.uniqueSources[this.uniqueSourceIndexByFilename[source.filename]];
2008 if (source.content.original !== uniqueSource.content) {
2009 throw new Error(("Illegal source: same filename (" + (source.filename) + "), different contents"));
2010 }
2011 }
2012 }
2013
2014 this.sources.push(source);
2015 return this;
2016};
2017
2018Bundle.prototype.append = function append (str, options) {
2019 this.addSource({
2020 content: new MagicString(str),
2021 separator: (options && options.separator) || ''
2022 });
2023
2024 return this;
2025};
2026
2027Bundle.prototype.clone = function clone () {
2028 var bundle = new Bundle({
2029 intro: this.intro,
2030 separator: this.separator
2031 });
2032
2033 this.sources.forEach(function (source) {
2034 bundle.addSource({
2035 filename: source.filename,
2036 content: source.content.clone(),
2037 separator: source.separator
2038 });
2039 });
2040
2041 return bundle;
2042};
2043
2044Bundle.prototype.generateDecodedMap = function generateDecodedMap (options) {
2045 var this$1 = this;
2046 if ( options === void 0 ) options = {};
2047
2048 var names = [];
2049 this.sources.forEach(function (source) {
2050 Object.keys(source.content.storedNames).forEach(function (name) {
2051 if (!~names.indexOf(name)) { names.push(name); }
2052 });
2053 });
2054
2055 var mappings = new Mappings(options.hires);
2056
2057 if (this.intro) {
2058 mappings.advance(this.intro);
2059 }
2060
2061 this.sources.forEach(function (source, i) {
2062 if (i > 0) {
2063 mappings.advance(this$1.separator);
2064 }
2065
2066 var sourceIndex = source.filename ? this$1.uniqueSourceIndexByFilename[source.filename] : -1;
2067 var magicString = source.content;
2068 var locate = getLocator(magicString.original);
2069
2070 if (magicString.intro) {
2071 mappings.advance(magicString.intro);
2072 }
2073
2074 magicString.firstChunk.eachNext(function (chunk) {
2075 var loc = locate(chunk.start);
2076
2077 if (chunk.intro.length) { mappings.advance(chunk.intro); }
2078
2079 if (source.filename) {
2080 if (chunk.edited) {
2081 mappings.addEdit(
2082 sourceIndex,
2083 chunk.content,
2084 loc,
2085 chunk.storeName ? names.indexOf(chunk.original) : -1
2086 );
2087 } else {
2088 mappings.addUneditedChunk(
2089 sourceIndex,
2090 chunk,
2091 magicString.original,
2092 loc,
2093 magicString.sourcemapLocations
2094 );
2095 }
2096 } else {
2097 mappings.advance(chunk.content);
2098 }
2099
2100 if (chunk.outro.length) { mappings.advance(chunk.outro); }
2101 });
2102
2103 if (magicString.outro) {
2104 mappings.advance(magicString.outro);
2105 }
2106 });
2107
2108 return {
2109 file: options.file ? options.file.split(/[/\\]/).pop() : null,
2110 sources: this.uniqueSources.map(function (source) {
2111 return options.file ? getRelativePath(options.file, source.filename) : source.filename;
2112 }),
2113 sourcesContent: this.uniqueSources.map(function (source) {
2114 return options.includeContent ? source.content : null;
2115 }),
2116 names: names,
2117 mappings: mappings.raw
2118 };
2119};
2120
2121Bundle.prototype.generateMap = function generateMap (options) {
2122 return new SourceMap(this.generateDecodedMap(options));
2123};
2124
2125Bundle.prototype.getIndentString = function getIndentString () {
2126 var indentStringCounts = {};
2127
2128 this.sources.forEach(function (source) {
2129 var indentStr = source.content.indentStr;
2130
2131 if (indentStr === null) { return; }
2132
2133 if (!indentStringCounts[indentStr]) { indentStringCounts[indentStr] = 0; }
2134 indentStringCounts[indentStr] += 1;
2135 });
2136
2137 return (
2138 Object.keys(indentStringCounts).sort(function (a, b) {
2139 return indentStringCounts[a] - indentStringCounts[b];
2140 })[0] || '\t'
2141 );
2142};
2143
2144Bundle.prototype.indent = function indent (indentStr) {
2145 var this$1 = this;
2146
2147 if (!arguments.length) {
2148 indentStr = this.getIndentString();
2149 }
2150
2151 if (indentStr === '') { return this; } // noop
2152
2153 var trailingNewline = !this.intro || this.intro.slice(-1) === '\n';
2154
2155 this.sources.forEach(function (source, i) {
2156 var separator = source.separator !== undefined ? source.separator : this$1.separator;
2157 var indentStart = trailingNewline || (i > 0 && /\r?\n$/.test(separator));
2158
2159 source.content.indent(indentStr, {
2160 exclude: source.indentExclusionRanges,
2161 indentStart: indentStart //: trailingNewline || /\r?\n$/.test( separator ) //true///\r?\n/.test( separator )
2162 });
2163
2164 trailingNewline = source.content.lastChar() === '\n';
2165 });
2166
2167 if (this.intro) {
2168 this.intro =
2169 indentStr +
2170 this.intro.replace(/^[^\n]/gm, function (match, index) {
2171 return index > 0 ? indentStr + match : match;
2172 });
2173 }
2174
2175 return this;
2176};
2177
2178Bundle.prototype.prepend = function prepend (str) {
2179 this.intro = str + this.intro;
2180 return this;
2181};
2182
2183Bundle.prototype.toString = function toString () {
2184 var this$1 = this;
2185
2186 var body = this.sources
2187 .map(function (source, i) {
2188 var separator = source.separator !== undefined ? source.separator : this$1.separator;
2189 var str = (i > 0 ? separator : '') + source.content.toString();
2190
2191 return str;
2192 })
2193 .join('');
2194
2195 return this.intro + body;
2196};
2197
2198Bundle.prototype.isEmpty = function isEmpty () {
2199 if (this.intro.length && this.intro.trim())
2200 { return false; }
2201 if (this.sources.some(function (source) { return !source.content.isEmpty(); }))
2202 { return false; }
2203 return true;
2204};
2205
2206Bundle.prototype.length = function length () {
2207 return this.sources.reduce(function (length, source) { return length + source.content.length(); }, this.intro.length);
2208};
2209
2210Bundle.prototype.trimLines = function trimLines () {
2211 return this.trim('[\\r\\n]');
2212};
2213
2214Bundle.prototype.trim = function trim (charType) {
2215 return this.trimStart(charType).trimEnd(charType);
2216};
2217
2218Bundle.prototype.trimStart = function trimStart (charType) {
2219 var rx = new RegExp('^' + (charType || '\\s') + '+');
2220 this.intro = this.intro.replace(rx, '');
2221
2222 if (!this.intro) {
2223 var source;
2224 var i = 0;
2225
2226 do {
2227 source = this.sources[i++];
2228 if (!source) {
2229 break;
2230 }
2231 } while (!source.content.trimStartAborted(charType));
2232 }
2233
2234 return this;
2235};
2236
2237Bundle.prototype.trimEnd = function trimEnd (charType) {
2238 var rx = new RegExp((charType || '\\s') + '+$');
2239
2240 var source;
2241 var i = this.sources.length - 1;
2242
2243 do {
2244 source = this.sources[i--];
2245 if (!source) {
2246 this.intro = this.intro.replace(rx, '');
2247 break;
2248 }
2249 } while (!source.content.trimEndAborted(charType));
2250
2251 return this;
2252};
2253
2254var BlockStatement = 'BlockStatement';
2255var CallExpression = 'CallExpression';
2256var ClassDeclaration = 'ClassDeclaration';
2257var ExportAllDeclaration = 'ExportAllDeclaration';
2258var ExportDefaultDeclaration = 'ExportDefaultDeclaration';
2259var ExpressionStatement = 'ExpressionStatement';
2260var FunctionDeclaration = 'FunctionDeclaration';
2261var FunctionExpression = 'FunctionExpression';
2262var Identifier = 'Identifier';
2263var ImportDefaultSpecifier = 'ImportDefaultSpecifier';
2264var ImportNamespaceSpecifier = 'ImportNamespaceSpecifier';
2265var Literal = 'Literal';
2266var MemberExpression = 'MemberExpression';
2267var Program = 'Program';
2268var Property = 'Property';
2269var ReturnStatement = 'ReturnStatement';
2270var TemplateLiteral = 'TemplateLiteral';
2271var VariableDeclaration = 'VariableDeclaration';
2272
2273var CallOptions = /** @class */ (function () {
2274 function CallOptions(_a) {
2275 var _b = _a === void 0 ? {} : _a, _c = _b.withNew, withNew = _c === void 0 ? false : _c, _d = _b.args, args = _d === void 0 ? [] : _d, _e = _b.callIdentifier, callIdentifier = _e === void 0 ? undefined : _e;
2276 this.withNew = withNew;
2277 this.args = args;
2278 this.callIdentifier = callIdentifier;
2279 }
2280 CallOptions.create = function (callOptions) {
2281 return new this(callOptions);
2282 };
2283 CallOptions.prototype.equals = function (callOptions) {
2284 return callOptions && this.callIdentifier === callOptions.callIdentifier;
2285 };
2286 return CallOptions;
2287}());
2288
2289var UNKNOWN_KEY = { UNKNOWN_KEY: true };
2290var EMPTY_PATH = [];
2291var UNKNOWN_PATH = [UNKNOWN_KEY];
2292function assembleMemberDescriptions(memberDescriptions, inheritedDescriptions) {
2293 if (inheritedDescriptions === void 0) { inheritedDescriptions = null; }
2294 return Object.create(inheritedDescriptions, memberDescriptions);
2295}
2296var UNKNOWN_VALUE = { UNKNOWN_VALUE: true };
2297var UNKNOWN_EXPRESSION = {
2298 deoptimizePath: function () { },
2299 getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
2300 getReturnExpressionWhenCalledAtPath: function () { return UNKNOWN_EXPRESSION; },
2301 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 0; },
2302 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2303 hasEffectsWhenCalledAtPath: function () { return true; },
2304 include: function () { },
2305 included: true,
2306 toString: function () { return '[[UNKNOWN]]'; }
2307};
2308var UNDEFINED_EXPRESSION = {
2309 deoptimizePath: function () { },
2310 getLiteralValueAtPath: function () { return undefined; },
2311 getReturnExpressionWhenCalledAtPath: function () { return UNKNOWN_EXPRESSION; },
2312 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 0; },
2313 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2314 hasEffectsWhenCalledAtPath: function () { return true; },
2315 include: function () { },
2316 included: true,
2317 toString: function () { return 'undefined'; }
2318};
2319var returnsUnknown = {
2320 value: {
2321 callsArgs: null,
2322 mutatesSelf: false,
2323 returns: null,
2324 returnsPrimitive: UNKNOWN_EXPRESSION
2325 }
2326};
2327var mutatesSelfReturnsUnknown = {
2328 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: null, mutatesSelf: true }
2329};
2330var callsArgReturnsUnknown = {
2331 value: { returns: null, returnsPrimitive: UNKNOWN_EXPRESSION, callsArgs: [0], mutatesSelf: false }
2332};
2333var UnknownArrayExpression = /** @class */ (function () {
2334 function UnknownArrayExpression() {
2335 this.included = false;
2336 }
2337 UnknownArrayExpression.prototype.deoptimizePath = function () { };
2338 UnknownArrayExpression.prototype.getLiteralValueAtPath = function () {
2339 return UNKNOWN_VALUE;
2340 };
2341 UnknownArrayExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
2342 if (path.length === 1) {
2343 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
2344 }
2345 return UNKNOWN_EXPRESSION;
2346 };
2347 UnknownArrayExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
2348 return path.length > 1;
2349 };
2350 UnknownArrayExpression.prototype.hasEffectsWhenAssignedAtPath = function (path) {
2351 return path.length > 1;
2352 };
2353 UnknownArrayExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
2354 if (path.length === 1) {
2355 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options);
2356 }
2357 return true;
2358 };
2359 UnknownArrayExpression.prototype.include = function () {
2360 this.included = true;
2361 };
2362 UnknownArrayExpression.prototype.toString = function () {
2363 return '[[UNKNOWN ARRAY]]';
2364 };
2365 return UnknownArrayExpression;
2366}());
2367var returnsArray = {
2368 value: {
2369 callsArgs: null,
2370 mutatesSelf: false,
2371 returns: UnknownArrayExpression,
2372 returnsPrimitive: null
2373 }
2374};
2375var mutatesSelfReturnsArray = {
2376 value: {
2377 callsArgs: null,
2378 mutatesSelf: true,
2379 returns: UnknownArrayExpression,
2380 returnsPrimitive: null
2381 }
2382};
2383var callsArgReturnsArray = {
2384 value: {
2385 callsArgs: [0],
2386 mutatesSelf: false,
2387 returns: UnknownArrayExpression,
2388 returnsPrimitive: null
2389 }
2390};
2391var callsArgMutatesSelfReturnsArray = {
2392 value: {
2393 callsArgs: [0],
2394 mutatesSelf: true,
2395 returns: UnknownArrayExpression,
2396 returnsPrimitive: null
2397 }
2398};
2399var UNKNOWN_LITERAL_BOOLEAN = {
2400 deoptimizePath: function () { },
2401 getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
2402 getReturnExpressionWhenCalledAtPath: function (path) {
2403 if (path.length === 1) {
2404 return getMemberReturnExpressionWhenCalled(literalBooleanMembers, path[0]);
2405 }
2406 return UNKNOWN_EXPRESSION;
2407 },
2408 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
2409 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2410 hasEffectsWhenCalledAtPath: function (path) {
2411 if (path.length === 1) {
2412 var subPath = path[0];
2413 return typeof subPath !== 'string' || !literalBooleanMembers[subPath];
2414 }
2415 return true;
2416 },
2417 include: function () { },
2418 included: true,
2419 toString: function () { return '[[UNKNOWN BOOLEAN]]'; }
2420};
2421var returnsBoolean = {
2422 value: {
2423 callsArgs: null,
2424 mutatesSelf: false,
2425 returns: null,
2426 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2427 }
2428};
2429var callsArgReturnsBoolean = {
2430 value: {
2431 callsArgs: [0],
2432 mutatesSelf: false,
2433 returns: null,
2434 returnsPrimitive: UNKNOWN_LITERAL_BOOLEAN
2435 }
2436};
2437var UNKNOWN_LITERAL_NUMBER = {
2438 deoptimizePath: function () { },
2439 getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
2440 getReturnExpressionWhenCalledAtPath: function (path) {
2441 if (path.length === 1) {
2442 return getMemberReturnExpressionWhenCalled(literalNumberMembers, path[0]);
2443 }
2444 return UNKNOWN_EXPRESSION;
2445 },
2446 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
2447 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2448 hasEffectsWhenCalledAtPath: function (path) {
2449 if (path.length === 1) {
2450 var subPath = path[0];
2451 return typeof subPath !== 'string' || !literalNumberMembers[subPath];
2452 }
2453 return true;
2454 },
2455 include: function () { },
2456 included: true,
2457 toString: function () { return '[[UNKNOWN NUMBER]]'; }
2458};
2459var returnsNumber = {
2460 value: {
2461 callsArgs: null,
2462 mutatesSelf: false,
2463 returns: null,
2464 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2465 }
2466};
2467var mutatesSelfReturnsNumber = {
2468 value: {
2469 callsArgs: null,
2470 mutatesSelf: true,
2471 returns: null,
2472 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2473 }
2474};
2475var callsArgReturnsNumber = {
2476 value: {
2477 callsArgs: [0],
2478 mutatesSelf: false,
2479 returns: null,
2480 returnsPrimitive: UNKNOWN_LITERAL_NUMBER
2481 }
2482};
2483var UNKNOWN_LITERAL_STRING = {
2484 deoptimizePath: function () { },
2485 getLiteralValueAtPath: function () { return UNKNOWN_VALUE; },
2486 getReturnExpressionWhenCalledAtPath: function (path) {
2487 if (path.length === 1) {
2488 return getMemberReturnExpressionWhenCalled(literalStringMembers, path[0]);
2489 }
2490 return UNKNOWN_EXPRESSION;
2491 },
2492 hasEffectsWhenAccessedAtPath: function (path) { return path.length > 1; },
2493 hasEffectsWhenAssignedAtPath: function (path) { return path.length > 0; },
2494 hasEffectsWhenCalledAtPath: function (path, callOptions, options) {
2495 if (path.length === 1) {
2496 return hasMemberEffectWhenCalled(literalStringMembers, path[0], true, callOptions, options);
2497 }
2498 return true;
2499 },
2500 include: function () { },
2501 included: true,
2502 toString: function () { return '[[UNKNOWN STRING]]'; }
2503};
2504var returnsString = {
2505 value: {
2506 callsArgs: null,
2507 mutatesSelf: false,
2508 returns: null,
2509 returnsPrimitive: UNKNOWN_LITERAL_STRING
2510 }
2511};
2512var UnknownObjectExpression = /** @class */ (function () {
2513 function UnknownObjectExpression() {
2514 this.included = false;
2515 }
2516 UnknownObjectExpression.prototype.deoptimizePath = function () { };
2517 UnknownObjectExpression.prototype.getLiteralValueAtPath = function () {
2518 return UNKNOWN_VALUE;
2519 };
2520 UnknownObjectExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
2521 if (path.length === 1) {
2522 return getMemberReturnExpressionWhenCalled(objectMembers, path[0]);
2523 }
2524 return UNKNOWN_EXPRESSION;
2525 };
2526 UnknownObjectExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
2527 return path.length > 1;
2528 };
2529 UnknownObjectExpression.prototype.hasEffectsWhenAssignedAtPath = function (path) {
2530 return path.length > 1;
2531 };
2532 UnknownObjectExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
2533 if (path.length === 1) {
2534 return hasMemberEffectWhenCalled(objectMembers, path[0], this.included, callOptions, options);
2535 }
2536 return true;
2537 };
2538 UnknownObjectExpression.prototype.include = function () {
2539 this.included = true;
2540 };
2541 UnknownObjectExpression.prototype.toString = function () {
2542 return '[[UNKNOWN OBJECT]]';
2543 };
2544 return UnknownObjectExpression;
2545}());
2546var objectMembers = assembleMemberDescriptions({
2547 hasOwnProperty: returnsBoolean,
2548 isPrototypeOf: returnsBoolean,
2549 propertyIsEnumerable: returnsBoolean,
2550 toLocaleString: returnsString,
2551 toString: returnsString,
2552 valueOf: returnsUnknown
2553});
2554var arrayMembers = assembleMemberDescriptions({
2555 concat: returnsArray,
2556 copyWithin: mutatesSelfReturnsArray,
2557 every: callsArgReturnsBoolean,
2558 fill: mutatesSelfReturnsArray,
2559 filter: callsArgReturnsArray,
2560 find: callsArgReturnsUnknown,
2561 findIndex: callsArgReturnsNumber,
2562 forEach: callsArgReturnsUnknown,
2563 includes: returnsBoolean,
2564 indexOf: returnsNumber,
2565 join: returnsString,
2566 lastIndexOf: returnsNumber,
2567 map: callsArgReturnsArray,
2568 pop: mutatesSelfReturnsUnknown,
2569 push: mutatesSelfReturnsNumber,
2570 reduce: callsArgReturnsUnknown,
2571 reduceRight: callsArgReturnsUnknown,
2572 reverse: mutatesSelfReturnsArray,
2573 shift: mutatesSelfReturnsUnknown,
2574 slice: returnsArray,
2575 some: callsArgReturnsBoolean,
2576 sort: callsArgMutatesSelfReturnsArray,
2577 splice: mutatesSelfReturnsArray,
2578 unshift: mutatesSelfReturnsNumber
2579}, objectMembers);
2580var literalBooleanMembers = assembleMemberDescriptions({
2581 valueOf: returnsBoolean
2582}, objectMembers);
2583var literalNumberMembers = assembleMemberDescriptions({
2584 toExponential: returnsString,
2585 toFixed: returnsString,
2586 toLocaleString: returnsString,
2587 toPrecision: returnsString,
2588 valueOf: returnsNumber
2589}, objectMembers);
2590var literalStringMembers = assembleMemberDescriptions({
2591 charAt: returnsString,
2592 charCodeAt: returnsNumber,
2593 codePointAt: returnsNumber,
2594 concat: returnsString,
2595 endsWith: returnsBoolean,
2596 includes: returnsBoolean,
2597 indexOf: returnsNumber,
2598 lastIndexOf: returnsNumber,
2599 localeCompare: returnsNumber,
2600 match: returnsBoolean,
2601 normalize: returnsString,
2602 padEnd: returnsString,
2603 padStart: returnsString,
2604 repeat: returnsString,
2605 replace: {
2606 value: {
2607 callsArgs: [1],
2608 mutatesSelf: false,
2609 returns: null,
2610 returnsPrimitive: UNKNOWN_LITERAL_STRING
2611 }
2612 },
2613 search: returnsNumber,
2614 slice: returnsString,
2615 split: returnsArray,
2616 startsWith: returnsBoolean,
2617 substr: returnsString,
2618 substring: returnsString,
2619 toLocaleLowerCase: returnsString,
2620 toLocaleUpperCase: returnsString,
2621 toLowerCase: returnsString,
2622 toUpperCase: returnsString,
2623 trim: returnsString,
2624 valueOf: returnsString
2625}, objectMembers);
2626function getLiteralMembersForValue(value) {
2627 switch (typeof value) {
2628 case 'boolean':
2629 return literalBooleanMembers;
2630 case 'number':
2631 return literalNumberMembers;
2632 case 'string':
2633 return literalStringMembers;
2634 default:
2635 return Object.create(null);
2636 }
2637}
2638function hasMemberEffectWhenCalled(members, memberName, parentIncluded, callOptions, options) {
2639 if (typeof memberName !== 'string' || !members[memberName])
2640 return true;
2641 if (members[memberName].mutatesSelf && parentIncluded)
2642 return true;
2643 if (!members[memberName].callsArgs)
2644 return false;
2645 for (var _i = 0, _a = members[memberName].callsArgs; _i < _a.length; _i++) {
2646 var argIndex = _a[_i];
2647 if (callOptions.args[argIndex] &&
2648 callOptions.args[argIndex].hasEffectsWhenCalledAtPath(EMPTY_PATH, CallOptions.create({
2649 args: [],
2650 callIdentifier: {},
2651 withNew: false
2652 }), options.getHasEffectsWhenCalledOptions()))
2653 return true;
2654 }
2655 return false;
2656}
2657function getMemberReturnExpressionWhenCalled(members, memberName) {
2658 if (typeof memberName !== 'string' || !members[memberName])
2659 return UNKNOWN_EXPRESSION;
2660 return members[memberName].returnsPrimitive !== null
2661 ? members[memberName].returnsPrimitive
2662 : new members[memberName].returns();
2663}
2664
2665var Variable = /** @class */ (function () {
2666 function Variable(name) {
2667 this.exportName = null;
2668 this.included = false;
2669 this.isId = false;
2670 this.isReassigned = false;
2671 this.reexported = false;
2672 this.renderBaseName = null;
2673 this.renderName = null;
2674 this.safeExportName = null;
2675 this.name = name;
2676 }
2677 /**
2678 * Binds identifiers that reference this variable to this variable.
2679 * Necessary to be able to change variable names.
2680 */
2681 Variable.prototype.addReference = function (_identifier) { };
2682 Variable.prototype.deoptimizePath = function (_path) { };
2683 Variable.prototype.getBaseVariableName = function () {
2684 return this.renderBaseName || this.renderName || this.name;
2685 };
2686 Variable.prototype.getLiteralValueAtPath = function (_path, _recursionTracker, _origin) {
2687 return UNKNOWN_VALUE;
2688 };
2689 Variable.prototype.getName = function () {
2690 var name = this.renderName || this.name;
2691 return this.renderBaseName ? this.renderBaseName + "." + name : name;
2692 };
2693 Variable.prototype.getReturnExpressionWhenCalledAtPath = function (_path, _recursionTracker, _origin) {
2694 return UNKNOWN_EXPRESSION;
2695 };
2696 Variable.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
2697 return path.length > 0;
2698 };
2699 Variable.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
2700 return true;
2701 };
2702 Variable.prototype.hasEffectsWhenCalledAtPath = function (_path, _callOptions, _options) {
2703 return true;
2704 };
2705 /**
2706 * Marks this variable as being part of the bundle, which is usually the case when one of
2707 * its identifiers becomes part of the bundle. Returns true if it has not been included
2708 * previously.
2709 * Once a variable is included, it should take care all its declarations are included.
2710 */
2711 Variable.prototype.include = function () {
2712 this.included = true;
2713 };
2714 Variable.prototype.setRenderNames = function (baseName, name) {
2715 this.renderBaseName = baseName;
2716 this.renderName = name;
2717 };
2718 Variable.prototype.setSafeName = function (name) {
2719 this.renderName = name;
2720 };
2721 Variable.prototype.toString = function () {
2722 return this.name;
2723 };
2724 return Variable;
2725}());
2726
2727// To avoid infinite recursions
2728var MAX_PATH_DEPTH = 7;
2729var LocalVariable = /** @class */ (function (_super) {
2730 __extends(LocalVariable, _super);
2731 function LocalVariable(name, declarator, init, context) {
2732 var _this = _super.call(this, name) || this;
2733 _this.additionalInitializers = null;
2734 _this.expressionsToBeDeoptimized = [];
2735 _this.declarations = declarator ? [declarator] : [];
2736 _this.init = init;
2737 _this.deoptimizationTracker = context.deoptimizationTracker;
2738 _this.module = context.module;
2739 return _this;
2740 }
2741 LocalVariable.prototype.addDeclaration = function (identifier, init) {
2742 this.declarations.push(identifier);
2743 if (this.additionalInitializers === null) {
2744 this.additionalInitializers = this.init === null ? [] : [this.init];
2745 this.init = UNKNOWN_EXPRESSION;
2746 this.isReassigned = true;
2747 }
2748 if (init !== null) {
2749 this.additionalInitializers.push(init);
2750 }
2751 };
2752 LocalVariable.prototype.consolidateInitializers = function () {
2753 if (this.additionalInitializers !== null) {
2754 for (var _i = 0, _a = this.additionalInitializers; _i < _a.length; _i++) {
2755 var initializer = _a[_i];
2756 initializer.deoptimizePath(UNKNOWN_PATH);
2757 }
2758 this.additionalInitializers = null;
2759 }
2760 };
2761 LocalVariable.prototype.deoptimizePath = function (path) {
2762 if (path.length > MAX_PATH_DEPTH)
2763 return;
2764 if (!(this.isReassigned || this.deoptimizationTracker.track(this, path))) {
2765 if (path.length === 0) {
2766 if (!this.isReassigned) {
2767 this.isReassigned = true;
2768 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
2769 var expression = _a[_i];
2770 expression.deoptimizeCache();
2771 }
2772 if (this.init) {
2773 this.init.deoptimizePath(UNKNOWN_PATH);
2774 }
2775 }
2776 }
2777 else if (this.init) {
2778 this.init.deoptimizePath(path);
2779 }
2780 }
2781 };
2782 LocalVariable.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
2783 if (this.isReassigned ||
2784 !this.init ||
2785 path.length > MAX_PATH_DEPTH ||
2786 recursionTracker.isTracked(this.init, path)) {
2787 return UNKNOWN_VALUE;
2788 }
2789 this.expressionsToBeDeoptimized.push(origin);
2790 return this.init.getLiteralValueAtPath(path, recursionTracker.track(this.init, path), origin);
2791 };
2792 LocalVariable.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
2793 if (this.isReassigned ||
2794 !this.init ||
2795 path.length > MAX_PATH_DEPTH ||
2796 recursionTracker.isTracked(this.init, path)) {
2797 return UNKNOWN_EXPRESSION;
2798 }
2799 this.expressionsToBeDeoptimized.push(origin);
2800 return this.init.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.init, path), origin);
2801 };
2802 LocalVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
2803 if (path.length === 0)
2804 return false;
2805 return (this.isReassigned ||
2806 path.length > MAX_PATH_DEPTH ||
2807 (this.init &&
2808 !options.hasNodeBeenAccessedAtPath(path, this.init) &&
2809 this.init.hasEffectsWhenAccessedAtPath(path, options.addAccessedNodeAtPath(path, this.init))));
2810 };
2811 LocalVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
2812 if (this.included || path.length > MAX_PATH_DEPTH)
2813 return true;
2814 if (path.length === 0)
2815 return false;
2816 return (this.isReassigned ||
2817 (this.init &&
2818 !options.hasNodeBeenAssignedAtPath(path, this.init) &&
2819 this.init.hasEffectsWhenAssignedAtPath(path, options.addAssignedNodeAtPath(path, this.init))));
2820 };
2821 LocalVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
2822 if (path.length > MAX_PATH_DEPTH)
2823 return true;
2824 return (this.isReassigned ||
2825 (this.init &&
2826 !options.hasNodeBeenCalledAtPathWithOptions(path, this.init, callOptions) &&
2827 this.init.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledNodeAtPathWithOptions(path, this.init, callOptions))));
2828 };
2829 LocalVariable.prototype.include = function () {
2830 if (!this.included) {
2831 this.included = true;
2832 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
2833 var declaration = _a[_i];
2834 // If node is a default export, it can save a tree-shaking run to include the full declaration now
2835 if (!declaration.included)
2836 declaration.include(false);
2837 var node = declaration.parent;
2838 while (!node.included) {
2839 // We do not want to properly include parents in case they are part of a dead branch
2840 // in which case .include() might pull in more dead code
2841 node.included = true;
2842 if (node.type === Program)
2843 break;
2844 node = node.parent;
2845 }
2846 }
2847 }
2848 };
2849 return LocalVariable;
2850}(Variable));
2851LocalVariable.prototype.isLocal = true;
2852
2853function isExportDefaultVariable(variable) {
2854 return variable.isDefault;
2855}
2856var ExportDefaultVariable = /** @class */ (function (_super) {
2857 __extends(ExportDefaultVariable, _super);
2858 function ExportDefaultVariable(name, exportDefaultDeclaration, context) {
2859 var _this = _super.call(this, name, exportDefaultDeclaration, exportDefaultDeclaration.declaration, context) || this;
2860 // Not initialised during construction
2861 _this.originalId = null;
2862 var declaration = exportDefaultDeclaration.declaration;
2863 if ((declaration.type === FunctionDeclaration ||
2864 declaration.type === ClassDeclaration) &&
2865 declaration.id) {
2866 _this.hasId = true;
2867 _this.originalId = declaration.id;
2868 }
2869 else if (declaration.type === Identifier) {
2870 _this.originalId = declaration;
2871 }
2872 return _this;
2873 }
2874 ExportDefaultVariable.prototype.addReference = function (identifier) {
2875 if (!this.hasId) {
2876 this.name = identifier.name;
2877 }
2878 };
2879 ExportDefaultVariable.prototype.getName = function () {
2880 return this.referencesOriginal() ? this.originalId.variable.getName() : _super.prototype.getName.call(this);
2881 };
2882 ExportDefaultVariable.prototype.getOriginalVariable = function () {
2883 return (this.originalId && this.originalId.variable) || null;
2884 };
2885 ExportDefaultVariable.prototype.getOriginalVariableName = function () {
2886 return (this.originalId && this.originalId.name) || null;
2887 };
2888 ExportDefaultVariable.prototype.referencesOriginal = function () {
2889 return this.originalId && (this.hasId || !this.originalId.variable.isReassigned);
2890 };
2891 ExportDefaultVariable.prototype.setRenderNames = function (baseName, name) {
2892 if (this.referencesOriginal()) {
2893 this.originalId.variable.setRenderNames(baseName, name);
2894 }
2895 else {
2896 _super.prototype.setRenderNames.call(this, baseName, name);
2897 }
2898 };
2899 ExportDefaultVariable.prototype.setSafeName = function (name) {
2900 if (this.referencesOriginal()) {
2901 this.originalId.variable.setSafeName(name);
2902 }
2903 else {
2904 _super.prototype.setSafeName.call(this, name);
2905 }
2906 };
2907 return ExportDefaultVariable;
2908}(LocalVariable));
2909ExportDefaultVariable.prototype.getBaseVariableName = ExportDefaultVariable.prototype.getName;
2910ExportDefaultVariable.prototype.isDefault = true;
2911
2912var MISSING_EXPORT_SHIM_VARIABLE = '_missingExportShim';
2913var INTEROP_DEFAULT_VARIABLE = '_interopDefault';
2914
2915var ExportShimVariable = /** @class */ (function (_super) {
2916 __extends(ExportShimVariable, _super);
2917 function ExportShimVariable(module) {
2918 var _this = _super.call(this, MISSING_EXPORT_SHIM_VARIABLE) || this;
2919 _this.module = module;
2920 return _this;
2921 }
2922 return ExportShimVariable;
2923}(Variable));
2924
2925var pureFunctions = {};
2926var arrayTypes = 'Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array'.split(' ');
2927var simdTypes = 'Int8x16 Int16x8 Int32x4 Float32x4 Float64x2'.split(' ');
2928var simdMethods = 'abs add and bool check div equal extractLane fromFloat32x4 fromFloat32x4Bits fromFloat64x2 fromFloat64x2Bits fromInt16x8Bits fromInt32x4 fromInt32x4Bits fromInt8x16Bits greaterThan greaterThanOrEqual lessThan lessThanOrEqual load max maxNum min minNum mul neg not notEqual or reciprocalApproximation reciprocalSqrtApproximation replaceLane select selectBits shiftLeftByScalar shiftRightArithmeticByScalar shiftRightLogicalByScalar shuffle splat sqrt store sub swizzle xor'.split(' ');
2929var allSimdMethods = [];
2930simdTypes.forEach(function (t) {
2931 simdMethods.forEach(function (m) {
2932 allSimdMethods.push("SIMD." + t + "." + m);
2933 });
2934});
2935[
2936 'Array.isArray',
2937 'Error',
2938 'EvalError',
2939 'InternalError',
2940 'RangeError',
2941 'ReferenceError',
2942 'SyntaxError',
2943 'TypeError',
2944 'URIError',
2945 'isFinite',
2946 'isNaN',
2947 'parseFloat',
2948 'parseInt',
2949 'decodeURI',
2950 'decodeURIComponent',
2951 'encodeURI',
2952 'encodeURIComponent',
2953 'escape',
2954 'unescape',
2955 'Object',
2956 'Object.create',
2957 'Object.getNotifier',
2958 'Object.getOwn',
2959 'Object.getOwnPropertyDescriptor',
2960 'Object.getOwnPropertyNames',
2961 'Object.getOwnPropertySymbols',
2962 'Object.getPrototypeOf',
2963 'Object.is',
2964 'Object.isExtensible',
2965 'Object.isFrozen',
2966 'Object.isSealed',
2967 'Object.keys',
2968 'Boolean',
2969 'Number',
2970 'Number.isFinite',
2971 'Number.isInteger',
2972 'Number.isNaN',
2973 'Number.isSafeInteger',
2974 'Number.parseFloat',
2975 'Number.parseInt',
2976 'Symbol',
2977 'Symbol.for',
2978 'Symbol.keyFor',
2979 'Math.abs',
2980 'Math.acos',
2981 'Math.acosh',
2982 'Math.asin',
2983 'Math.asinh',
2984 'Math.atan',
2985 'Math.atan2',
2986 'Math.atanh',
2987 'Math.cbrt',
2988 'Math.ceil',
2989 'Math.clz32',
2990 'Math.cos',
2991 'Math.cosh',
2992 'Math.exp',
2993 'Math.expm1',
2994 'Math.floor',
2995 'Math.fround',
2996 'Math.hypot',
2997 'Math.imul',
2998 'Math.log',
2999 'Math.log10',
3000 'Math.log1p',
3001 'Math.log2',
3002 'Math.max',
3003 'Math.min',
3004 'Math.pow',
3005 'Math.random',
3006 'Math.round',
3007 'Math.sign',
3008 'Math.sin',
3009 'Math.sinh',
3010 'Math.sqrt',
3011 'Math.tan',
3012 'Math.tanh',
3013 'Math.trunc',
3014 'Date',
3015 'Date.UTC',
3016 'Date.now',
3017 'Date.parse',
3018 'String',
3019 'String.fromCharCode',
3020 'String.fromCodePoint',
3021 'String.raw',
3022 'RegExp',
3023 'Map',
3024 'Set',
3025 'WeakMap',
3026 'WeakSet',
3027 'ArrayBuffer',
3028 'ArrayBuffer.isView',
3029 'DataView',
3030 'Promise.all',
3031 'Promise.race',
3032 'Promise.resolve',
3033 'Intl.Collator',
3034 'Intl.Collator.supportedLocalesOf',
3035 'Intl.DateTimeFormat',
3036 'Intl.DateTimeFormat.supportedLocalesOf',
3037 'Intl.NumberFormat',
3038 'Intl.NumberFormat.supportedLocalesOf'
3039 // TODO properties of e.g. window...
3040]
3041 .concat(arrayTypes, arrayTypes.map(function (t) { return t + ".from"; }), arrayTypes.map(function (t) { return t + ".of"; }), simdTypes.map(function (t) { return "SIMD." + t; }), allSimdMethods)
3042 .forEach(function (name) { return (pureFunctions[name] = true); });
3043
3044var GlobalVariable = /** @class */ (function (_super) {
3045 __extends(GlobalVariable, _super);
3046 function GlobalVariable() {
3047 return _super !== null && _super.apply(this, arguments) || this;
3048 }
3049 GlobalVariable.prototype.hasEffectsWhenAccessedAtPath = function (path) {
3050 // path.length == 0 can also have an effect but we postpone this for now
3051 return (path.length > 0 &&
3052 !this.isPureFunctionMember(path) &&
3053 !(this.name === 'Reflect' && path.length === 1));
3054 };
3055 GlobalVariable.prototype.hasEffectsWhenCalledAtPath = function (path) {
3056 return !pureFunctions[[this.name].concat(path).join('.')];
3057 };
3058 GlobalVariable.prototype.isPureFunctionMember = function (path) {
3059 return (pureFunctions[[this.name].concat(path).join('.')] ||
3060 (path.length >= 1 && pureFunctions[[this.name].concat(path.slice(0, -1)).join('.')]) ||
3061 (path.length >= 2 &&
3062 pureFunctions[[this.name].concat(path.slice(0, -2)).join('.')] &&
3063 path[path.length - 2] === 'prototype'));
3064 };
3065 return GlobalVariable;
3066}(Variable));
3067
3068var NamespaceVariable = /** @class */ (function (_super) {
3069 __extends(NamespaceVariable, _super);
3070 function NamespaceVariable(context) {
3071 var _this = _super.call(this, context.getModuleName()) || this;
3072 _this.memberVariables = Object.create(null);
3073 _this.containsExternalNamespace = false;
3074 _this.referencedEarly = false;
3075 _this.references = [];
3076 _this.context = context;
3077 _this.module = context.module;
3078 for (var _i = 0, _a = _this.context.getExports().concat(_this.context.getReexports()); _i < _a.length; _i++) {
3079 var name = _a[_i];
3080 if (name[0] === '*' && name.length > 1)
3081 _this.containsExternalNamespace = true;
3082 _this.memberVariables[name] = _this.context.traceExport(name);
3083 }
3084 return _this;
3085 }
3086 NamespaceVariable.prototype.addReference = function (identifier) {
3087 this.references.push(identifier);
3088 this.name = identifier.name;
3089 };
3090 // This is only called if "UNKNOWN_PATH" is reassigned as in all other situations, either the
3091 // build fails due to an illegal namespace reassignment or MemberExpression already forwards
3092 // the reassignment to the right variable. This means we lost track of this variable and thus
3093 // need to reassign all exports.
3094 NamespaceVariable.prototype.deoptimizePath = function () {
3095 for (var key in this.memberVariables) {
3096 this.memberVariables[key].deoptimizePath(UNKNOWN_PATH);
3097 }
3098 };
3099 NamespaceVariable.prototype.include = function () {
3100 if (!this.included) {
3101 if (this.containsExternalNamespace) {
3102 this.context.error({
3103 code: 'NAMESPACE_CANNOT_CONTAIN_EXTERNAL',
3104 id: this.module.id,
3105 message: "Cannot create an explicit namespace object for module \"" + this.context.getModuleName() + "\" because it contains a reexported external namespace"
3106 }, undefined);
3107 }
3108 this.included = true;
3109 for (var _i = 0, _a = this.references; _i < _a.length; _i++) {
3110 var identifier = _a[_i];
3111 if (identifier.context.getModuleExecIndex() <= this.context.getModuleExecIndex()) {
3112 this.referencedEarly = true;
3113 break;
3114 }
3115 }
3116 if (this.context.preserveModules) {
3117 for (var _b = 0, _c = Object.keys(this.memberVariables); _b < _c.length; _b++) {
3118 var memberName = _c[_b];
3119 this.memberVariables[memberName].include();
3120 }
3121 }
3122 else {
3123 for (var _d = 0, _e = Object.keys(this.memberVariables); _d < _e.length; _d++) {
3124 var memberName = _e[_d];
3125 this.context.includeVariable(this.memberVariables[memberName]);
3126 }
3127 }
3128 }
3129 };
3130 NamespaceVariable.prototype.renderBlock = function (options) {
3131 var _this = this;
3132 var _ = options.compact ? '' : ' ';
3133 var n = options.compact ? '' : '\n';
3134 var t = options.indent;
3135 var members = Object.keys(this.memberVariables).map(function (name) {
3136 var original = _this.memberVariables[name];
3137 if (_this.referencedEarly || original.isReassigned) {
3138 return t + "get " + name + _ + "()" + _ + "{" + _ + "return " + original.getName() + (options.compact ? '' : ';') + _ + "}";
3139 }
3140 return "" + t + name + ": " + original.getName();
3141 });
3142 var name = this.getName();
3143 var callee = options.freeze ? "/*#__PURE__*/Object.freeze" : '';
3144 var output = options.varOrConst + " " + name + " = " + (options.namespaceToStringTag
3145 ? "{" + n + members.join("," + n) + n + "};"
3146 : callee + "({" + n + members.join("," + n) + n + "});");
3147 if (options.namespaceToStringTag) {
3148 output += n + "if" + _ + "(typeof Symbol" + _ + "!==" + _ + "'undefined'" + _ + "&&" + _ + "Symbol.toStringTag)" + n;
3149 output += t + "Object.defineProperty(" + name + "," + _ + "Symbol.toStringTag," + _ + "{" + _ + "value:" + _ + "'Module'" + _ + "});" + n;
3150 output += "else" + (n || ' ');
3151 output += t + "Object.defineProperty(" + name + "," + _ + "'toString'," + _ + "{" + _ + "value:" + _ + "function" + _ + "()" + _ + "{" + _ + "return" + _ + "'[object Module]'" + (options.compact ? ';' : '') + _ + "}" + _ + "});" + n;
3152 output += callee + "(" + name + ");";
3153 }
3154 if (options.format === 'system' && this.exportName) {
3155 output += n + "exports('" + this.exportName + "'," + _ + name + ");";
3156 }
3157 return output;
3158 };
3159 NamespaceVariable.prototype.renderFirst = function () {
3160 return this.referencedEarly;
3161 };
3162 return NamespaceVariable;
3163}(Variable));
3164NamespaceVariable.prototype.isNamespace = true;
3165
3166var ExternalVariable = /** @class */ (function (_super) {
3167 __extends(ExternalVariable, _super);
3168 function ExternalVariable(module, name) {
3169 var _this = _super.call(this, name) || this;
3170 _this.module = module;
3171 _this.isNamespace = name === '*';
3172 _this.referenced = false;
3173 return _this;
3174 }
3175 ExternalVariable.prototype.addReference = function (identifier) {
3176 this.referenced = true;
3177 if (this.name === 'default' || this.name === '*') {
3178 this.module.suggestName(identifier.name);
3179 }
3180 };
3181 ExternalVariable.prototype.include = function () {
3182 if (!this.included) {
3183 this.included = true;
3184 this.module.used = true;
3185 }
3186 };
3187 return ExternalVariable;
3188}(Variable));
3189ExternalVariable.prototype.isExternal = true;
3190
3191var 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(' ');
3192var 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(' ');
3193var blacklisted = Object.create(null);
3194reservedWords.concat(builtins).forEach(function (word) { return (blacklisted[word] = true); });
3195var illegalCharacters = /[^$_a-zA-Z0-9]/g;
3196var startsWithDigit = function (str) { return /\d/.test(str[0]); };
3197function isLegal(str) {
3198 if (startsWithDigit(str) || blacklisted[str]) {
3199 return false;
3200 }
3201 return !illegalCharacters.test(str);
3202}
3203function makeLegal(str) {
3204 str = str.replace(/-(\w)/g, function (_, letter) { return letter.toUpperCase(); }).replace(illegalCharacters, '_');
3205 if (startsWithDigit(str) || blacklisted[str])
3206 str = "_" + str;
3207 return str;
3208}
3209
3210var absolutePath = /^(?:\/|(?:[A-Za-z]:)?[\\|/])/;
3211var relativePath = /^\.?\.\//;
3212function isAbsolute(path) {
3213 return absolutePath.test(path);
3214}
3215function isRelative(path) {
3216 return relativePath.test(path);
3217}
3218function normalize(path) {
3219 if (path.indexOf('\\') == -1)
3220 return path;
3221 return path.replace(/\\/g, '/');
3222}
3223
3224var ExternalModule = /** @class */ (function () {
3225 function ExternalModule(_a) {
3226 var graph = _a.graph, id = _a.id;
3227 this.exportsNames = false;
3228 this.exportsNamespace = false;
3229 this.isEntryPoint = false;
3230 this.isExternal = true;
3231 this.mostCommonSuggestion = 0;
3232 this.reexported = false;
3233 this.renderPath = undefined;
3234 this.renormalizeRenderPath = false;
3235 this.used = false;
3236 this.graph = graph;
3237 this.id = id;
3238 this.execIndex = Infinity;
3239 var parts = id.split(/[\\/]/);
3240 this.variableName = makeLegal(parts.pop());
3241 this.nameSuggestions = Object.create(null);
3242 this.declarations = Object.create(null);
3243 this.exportedVariables = new Map();
3244 }
3245 ExternalModule.prototype.getVariableForExportName = function (name, _isExportAllSearch) {
3246 if (name !== 'default' && name !== '*')
3247 this.exportsNames = true;
3248 if (name === '*')
3249 this.exportsNamespace = true;
3250 var declaration = this.declarations[name];
3251 if (declaration)
3252 return declaration;
3253 this.declarations[name] = declaration = new ExternalVariable(this, name);
3254 this.exportedVariables.set(declaration, name);
3255 return declaration;
3256 };
3257 ExternalModule.prototype.setRenderPath = function (options, inputBase) {
3258 this.renderPath = '';
3259 if (options.paths) {
3260 this.renderPath =
3261 typeof options.paths === 'function' ? options.paths(this.id) : options.paths[this.id];
3262 }
3263 if (!this.renderPath) {
3264 if (!isAbsolute(this.id)) {
3265 this.renderPath = this.id;
3266 }
3267 else {
3268 this.renderPath = normalize(relative(inputBase, this.id));
3269 this.renormalizeRenderPath = true;
3270 }
3271 }
3272 return this.renderPath;
3273 };
3274 ExternalModule.prototype.suggestName = function (name) {
3275 if (!this.nameSuggestions[name])
3276 this.nameSuggestions[name] = 0;
3277 this.nameSuggestions[name] += 1;
3278 if (this.nameSuggestions[name] > this.mostCommonSuggestion) {
3279 this.mostCommonSuggestion = this.nameSuggestions[name];
3280 this.variableName = name;
3281 }
3282 };
3283 ExternalModule.prototype.warnUnusedImports = function () {
3284 var _this = this;
3285 var unused = Object.keys(this.declarations).filter(function (name) {
3286 if (name === '*')
3287 return false;
3288 var declaration = _this.declarations[name];
3289 return !declaration.included && !_this.reexported && !declaration.referenced;
3290 });
3291 if (unused.length === 0)
3292 return;
3293 var names = unused.length === 1
3294 ? "'" + unused[0] + "' is"
3295 : unused
3296 .slice(0, -1)
3297 .map(function (name) { return "'" + name + "'"; })
3298 .join(', ') + " and '" + unused.slice(-1) + "' are";
3299 this.graph.warn({
3300 code: 'UNUSED_EXTERNAL_IMPORT',
3301 message: names + " imported from external module '" + this.id + "' but never used",
3302 names: unused,
3303 source: this.id
3304 });
3305 };
3306 return ExternalModule;
3307}());
3308
3309var esModuleExport = "Object.defineProperty(exports, '__esModule', { value: true });";
3310var compactEsModuleExport = "Object.defineProperty(exports,'__esModule',{value:true});";
3311
3312function getExportBlock(exports, dependencies, namedExportsMode, interop, compact, t, mechanism) {
3313 if (mechanism === void 0) { mechanism = 'return '; }
3314 var _ = compact ? '' : ' ';
3315 var n = compact ? '' : '\n';
3316 if (!namedExportsMode) {
3317 var local_1;
3318 exports.some(function (expt) {
3319 if (expt.exported === 'default') {
3320 local_1 = expt.local;
3321 return true;
3322 }
3323 return false;
3324 });
3325 // search for reexported default otherwise
3326 if (!local_1) {
3327 dependencies.some(function (dep) {
3328 if (!dep.reexports)
3329 return false;
3330 return dep.reexports.some(function (expt) {
3331 if (expt.reexported === 'default') {
3332 local_1 = dep.namedExportsMode ? dep.name + "." + expt.imported : dep.name;
3333 return true;
3334 }
3335 return false;
3336 });
3337 });
3338 }
3339 return "" + mechanism + local_1 + ";";
3340 }
3341 var exportBlock = '';
3342 // star exports must always output first for precedence
3343 dependencies.forEach(function (_a) {
3344 var name = _a.name, reexports = _a.reexports;
3345 if (reexports && namedExportsMode) {
3346 reexports.forEach(function (specifier) {
3347 if (specifier.reexported === '*') {
3348 if (!compact && exportBlock)
3349 exportBlock += '\n';
3350 exportBlock +=
3351 "Object.keys(" + name + ").forEach(function" + _ + "(key)" + _ + "{" + n +
3352 (t + "Object.defineProperty(exports," + _ + "key," + _ + "{" + n) +
3353 ("" + t + t + "enumerable:" + _ + "true," + n) +
3354 ("" + t + t + "get:" + _ + "function" + _ + "()" + _ + "{" + n) +
3355 ("" + t + t + t + "return " + name + "[key];" + n) +
3356 ("" + t + t + "}" + n + t + "});" + n + "});");
3357 }
3358 });
3359 }
3360 });
3361 dependencies.forEach(function (_a) {
3362 var name = _a.name, imports = _a.imports, reexports = _a.reexports, isChunk = _a.isChunk, depNamedExportsMode = _a.namedExportsMode;
3363 if (reexports && namedExportsMode) {
3364 reexports.forEach(function (specifier) {
3365 if (specifier.imported === 'default' && !isChunk) {
3366 var exportsNamesOrNamespace = (imports && imports.some(function (specifier) { return specifier.imported !== 'default'; })) ||
3367 (reexports &&
3368 reexports.some(function (specifier) { return specifier.imported !== 'default' && specifier.imported !== '*'; }));
3369 var reexportsDefaultAsDefault = reexports &&
3370 reexports.some(function (specifier) { return specifier.imported === 'default' && specifier.reexported === 'default'; });
3371 if (exportBlock && !compact)
3372 exportBlock += '\n';
3373 if (exportsNamesOrNamespace || reexportsDefaultAsDefault)
3374 exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + (interop !== false ? '__default' : '.default') + ";";
3375 else
3376 exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + ";";
3377 }
3378 else if (specifier.imported !== '*') {
3379 if (exportBlock && !compact)
3380 exportBlock += '\n';
3381 var importName = specifier.imported === 'default' && !depNamedExportsMode
3382 ? name
3383 : name + "." + specifier.imported;
3384 exportBlock += specifier.needsLiveBinding
3385 ? "Object.defineProperty(exports," + _ + "'" + specifier.reexported + "'," + _ + "{" + n +
3386 (t + "enumerable:" + _ + "true," + n) +
3387 (t + "get:" + _ + "function" + _ + "()" + _ + "{" + n) +
3388 ("" + t + t + "return " + importName + ";" + n + t + "}" + n + "});")
3389 : "exports." + specifier.reexported + _ + "=" + _ + importName + ";";
3390 }
3391 else if (specifier.reexported !== '*') {
3392 if (exportBlock && !compact)
3393 exportBlock += '\n';
3394 exportBlock += "exports." + specifier.reexported + _ + "=" + _ + name + ";";
3395 }
3396 });
3397 }
3398 });
3399 exports.forEach(function (expt) {
3400 var lhs = "exports." + expt.exported;
3401 var rhs = expt.local;
3402 if (lhs === rhs) {
3403 return;
3404 }
3405 if (exportBlock && !compact)
3406 exportBlock += '\n';
3407 exportBlock += "" + lhs + _ + "=" + _ + rhs + ";";
3408 });
3409 return exportBlock;
3410}
3411
3412function getInteropBlock(dependencies, options, varOrConst) {
3413 return dependencies
3414 .map(function (_a) {
3415 var name = _a.name, exportsNames = _a.exportsNames, exportsDefault = _a.exportsDefault, namedExportsMode = _a.namedExportsMode;
3416 if (!namedExportsMode)
3417 return;
3418 if (!exportsDefault || options.interop === false)
3419 return null;
3420 if (exportsNames) {
3421 if (options.compact)
3422 return varOrConst + " " + name + "__default='default'in " + name + "?" + name + "['default']:" + name + ";";
3423 return varOrConst + " " + name + "__default = 'default' in " + name + " ? " + name + "['default'] : " + name + ";";
3424 }
3425 if (options.compact)
3426 return name + "=" + name + "&&" + name + ".hasOwnProperty('default')?" + name + "['default']:" + name + ";";
3427 return name + " = " + name + " && " + name + ".hasOwnProperty('default') ? " + name + "['default'] : " + name + ";";
3428 })
3429 .filter(Boolean)
3430 .join(options.compact ? '' : '\n');
3431}
3432
3433var builtins$1 = {
3434 assert: true,
3435 buffer: true,
3436 console: true,
3437 constants: true,
3438 domain: true,
3439 events: true,
3440 http: true,
3441 https: true,
3442 os: true,
3443 path: true,
3444 process: true,
3445 punycode: true,
3446 querystring: true,
3447 stream: true,
3448 string_decoder: true,
3449 timers: true,
3450 tty: true,
3451 url: true,
3452 util: true,
3453 vm: true,
3454 zlib: true
3455};
3456// 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
3457function warnOnBuiltins(warn, dependencies) {
3458 var externalBuiltins = dependencies.map(function (_a) {
3459 var id = _a.id;
3460 return id;
3461 }).filter(function (id) { return id in builtins$1; });
3462 if (!externalBuiltins.length)
3463 return;
3464 var detail = externalBuiltins.length === 1
3465 ? "module ('" + externalBuiltins[0] + "')"
3466 : "modules (" + externalBuiltins
3467 .slice(0, -1)
3468 .map(function (name) { return "'" + name + "'"; })
3469 .join(', ') + " and '" + externalBuiltins.slice(-1) + "')";
3470 warn({
3471 code: 'MISSING_NODE_BUILTINS',
3472 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",
3473 modules: externalBuiltins
3474 });
3475}
3476
3477// TODO consider using improved AMD relative imports:
3478// https://requirejs.org/docs/api.html#modulenotes-urls
3479// AMD resolution will only respect the AMD baseUrl if the .js extension is omitted.
3480// The assumption is that this makes sense for all relative ids:
3481// https://requirejs.org/docs/api.html#jsfiles
3482function removeExtensionFromRelativeAmdId(id) {
3483 if (id[0] === '.' && id.endsWith('.js')) {
3484 return id.slice(0, -3);
3485 }
3486 return id;
3487}
3488function amd(magicString, _a, options) {
3489 var dependencies = _a.dependencies, dynamicImport = _a.dynamicImport, exports = _a.exports, hasExports = _a.hasExports, t = _a.indentString, intro = _a.intro, isEntryModuleFacade = _a.isEntryModuleFacade, namedExportsMode = _a.namedExportsMode, needsAmdModule = _a.needsAmdModule, outro = _a.outro, varOrConst = _a.varOrConst, warn = _a.warn;
3490 warnOnBuiltins(warn, dependencies);
3491 var deps = dependencies.map(function (m) { return "'" + removeExtensionFromRelativeAmdId(m.id) + "'"; });
3492 var args = dependencies.map(function (m) { return m.name; });
3493 var n = options.compact ? '' : '\n';
3494 var _ = options.compact ? '' : ' ';
3495 if (namedExportsMode && hasExports) {
3496 args.unshift("exports");
3497 deps.unshift("'exports'");
3498 }
3499 if (dynamicImport) {
3500 args.unshift('require');
3501 deps.unshift("'require'");
3502 }
3503 if (needsAmdModule) {
3504 args.unshift('module');
3505 deps.unshift("'module'");
3506 }
3507 var amdOptions = options.amd || {};
3508 var params = (amdOptions.id ? "'" + amdOptions.id + "'," + _ : "") +
3509 (deps.length ? "[" + deps.join("," + _) + "]," + _ : "");
3510 var useStrict = options.strict !== false ? _ + "'use strict';" : "";
3511 var define = amdOptions.define || 'define';
3512 var wrapperStart = define + "(" + params + "function" + _ + "(" + args.join("," + _) + ")" + _ + "{" + useStrict + n + n;
3513 // var foo__default = 'default' in foo ? foo['default'] : foo;
3514 var interopBlock = getInteropBlock(dependencies, options, varOrConst);
3515 if (interopBlock)
3516 magicString.prepend(interopBlock + n + n);
3517 if (intro)
3518 magicString.prepend(intro);
3519 var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
3520 if (exportBlock)
3521 magicString.append(n + n + exportBlock);
3522 if (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule)
3523 magicString.append("" + n + n + (options.compact ? compactEsModuleExport : esModuleExport));
3524 if (outro)
3525 magicString.append(outro);
3526 return magicString
3527 .indent(t)
3528 .append(n + n + '});')
3529 .prepend(wrapperStart);
3530}
3531
3532function cjs(magicString, _a, options) {
3533 var dependencies = _a.dependencies, exports = _a.exports, hasExports = _a.hasExports, t = _a.indentString, intro = _a.intro, isEntryModuleFacade = _a.isEntryModuleFacade, namedExportsMode = _a.namedExportsMode, outro = _a.outro, varOrConst = _a.varOrConst;
3534 var n = options.compact ? '' : '\n';
3535 var _ = options.compact ? '' : ' ';
3536 intro =
3537 (options.strict === false ? intro : "'use strict';" + n + n + intro) +
3538 (namedExportsMode && hasExports && isEntryModuleFacade && options.esModule
3539 ? "" + (options.compact ? compactEsModuleExport : esModuleExport) + n + n
3540 : '');
3541 var needsInterop = false;
3542 var interop = options.interop !== false;
3543 var importBlock;
3544 var definingVariable = false;
3545 importBlock = '';
3546 for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) {
3547 var _b = dependencies_1[_i], id = _b.id, namedExportsMode_1 = _b.namedExportsMode, isChunk = _b.isChunk, name = _b.name, reexports = _b.reexports, imports = _b.imports, exportsNames = _b.exportsNames, exportsDefault = _b.exportsDefault;
3548 if (!reexports && !imports) {
3549 if (importBlock) {
3550 importBlock += !options.compact || definingVariable ? ";" + n : ',';
3551 }
3552 definingVariable = false;
3553 importBlock += "require('" + id + "')";
3554 }
3555 else {
3556 importBlock +=
3557 options.compact && definingVariable ? ',' : "" + (importBlock ? ";" + n : '') + varOrConst + " ";
3558 definingVariable = true;
3559 if (!interop || isChunk || !exportsDefault || !namedExportsMode_1) {
3560 importBlock += "" + name + _ + "=" + _ + "require('" + id + "')";
3561 }
3562 else {
3563 needsInterop = true;
3564 if (exportsNames)
3565 importBlock += "" + name + _ + "=" + _ + "require('" + id + "')" + (options.compact ? ',' : ";\n" + varOrConst + " ") + name + "__default" + _ + "=" + _ + INTEROP_DEFAULT_VARIABLE + "(" + name + ")";
3566 else
3567 importBlock += "" + name + _ + "=" + _ + INTEROP_DEFAULT_VARIABLE + "(require('" + id + "'))";
3568 }
3569 }
3570 }
3571 if (importBlock)
3572 importBlock += ';';
3573 if (needsInterop) {
3574 var ex = options.compact ? 'e' : 'ex';
3575 intro +=
3576 "function " + INTEROP_DEFAULT_VARIABLE + _ + "(" + ex + ")" + _ + "{" + _ + "return" + _ +
3577 ("(" + ex + _ + "&&" + _ + "(typeof " + ex + _ + "===" + _ + "'object')" + _ + "&&" + _ + "'default'" + _ + "in " + ex + ")" + _) +
3578 ("?" + _ + ex + "['default']" + _ + ":" + _ + ex + (options.compact ? '' : '; ') + "}" + n + n);
3579 }
3580 if (importBlock)
3581 intro += importBlock + n + n;
3582 var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t, "module.exports" + _ + "=" + _);
3583 magicString.prepend(intro);
3584 if (exportBlock)
3585 magicString.append(n + n + exportBlock);
3586 if (outro)
3587 magicString.append(outro);
3588 return magicString;
3589}
3590
3591function esm(magicString, _a, options) {
3592 var intro = _a.intro, outro = _a.outro, dependencies = _a.dependencies, exports = _a.exports;
3593 var _ = options.compact ? '' : ' ';
3594 var n = options.compact ? '' : '\n';
3595 var importBlock = dependencies
3596 .map(function (_a) {
3597 var id = _a.id, reexports = _a.reexports, imports = _a.imports, name = _a.name;
3598 if (!reexports && !imports) {
3599 return "import" + _ + "'" + id + "';";
3600 }
3601 var output = '';
3602 if (imports) {
3603 var defaultImport_1 = imports.find(function (specifier) { return specifier.imported === 'default'; });
3604 var starImport_1 = imports.find(function (specifier) { return specifier.imported === '*'; });
3605 if (starImport_1) {
3606 output += "import" + _ + "*" + _ + "as " + starImport_1.local + " from" + _ + "'" + id + "';";
3607 if (imports.length > 1)
3608 output += n;
3609 }
3610 if (defaultImport_1 && imports.length === 1) {
3611 output += "import " + defaultImport_1.local + " from" + _ + "'" + id + "';";
3612 }
3613 else if (!starImport_1 || imports.length > 1) {
3614 output += "import " + (defaultImport_1 ? defaultImport_1.local + "," + _ : '') + "{" + _ + imports
3615 .filter(function (specifier) { return specifier !== defaultImport_1 && specifier !== starImport_1; })
3616 .map(function (specifier) {
3617 if (specifier.imported === specifier.local) {
3618 return specifier.imported;
3619 }
3620 else {
3621 return specifier.imported + " as " + specifier.local;
3622 }
3623 })
3624 .join("," + _) + _ + "}" + _ + "from" + _ + "'" + id + "';";
3625 }
3626 }
3627 if (reexports) {
3628 if (imports)
3629 output += n;
3630 var starExport_1 = reexports.find(function (specifier) { return specifier.reexported === '*'; });
3631 var namespaceReexport_1 = reexports.find(function (specifier) { return specifier.imported === '*' && specifier.reexported !== '*'; });
3632 if (starExport_1) {
3633 output += "export" + _ + "*" + _ + "from" + _ + "'" + id + "';";
3634 if (reexports.length === 1) {
3635 return output;
3636 }
3637 output += n;
3638 }
3639 if (namespaceReexport_1) {
3640 if (!imports ||
3641 !imports.some(function (specifier) { return specifier.imported === '*' && specifier.local === name; }))
3642 output += "import" + _ + "*" + _ + "as " + name + " from" + _ + "'" + id + "';" + n;
3643 output += "export" + _ + "{" + _ + (name === namespaceReexport_1.reexported
3644 ? name
3645 : name + " as " + namespaceReexport_1.reexported) + " };";
3646 if (reexports.length === (starExport_1 ? 2 : 1)) {
3647 return output;
3648 }
3649 output += n;
3650 }
3651 output += "export" + _ + "{" + _ + reexports
3652 .filter(function (specifier) { return specifier !== starExport_1 && specifier !== namespaceReexport_1; })
3653 .map(function (specifier) {
3654 if (specifier.imported === specifier.reexported) {
3655 return specifier.imported;
3656 }
3657 else {
3658 return specifier.imported + " as " + specifier.reexported;
3659 }
3660 })
3661 .join("," + _) + _ + "}" + _ + "from" + _ + "'" + id + "';";
3662 }
3663 return output;
3664 })
3665 .join(n);
3666 if (importBlock)
3667 intro += importBlock + n + n;
3668 if (intro)
3669 magicString.prepend(intro);
3670 var exportBlock = [];
3671 var exportDeclaration = [];
3672 exports.forEach(function (specifier) {
3673 if (specifier.exported === 'default') {
3674 exportBlock.push("export default " + specifier.local + ";");
3675 }
3676 else {
3677 exportDeclaration.push(specifier.exported === specifier.local
3678 ? specifier.local
3679 : specifier.local + " as " + specifier.exported);
3680 }
3681 });
3682 if (exportDeclaration.length) {
3683 exportBlock.push("export" + _ + "{" + _ + exportDeclaration.join("," + _) + _ + "};");
3684 }
3685 if (exportBlock.length)
3686 magicString.append(n + n + exportBlock.join(n).trim());
3687 if (outro)
3688 magicString.append(outro);
3689 return magicString.trim();
3690}
3691
3692function getLocator$1(source, options) {
3693 if (options === void 0) { options = {}; }
3694 var offsetLine = options.offsetLine || 0;
3695 var offsetColumn = options.offsetColumn || 0;
3696 var originalLines = source.split('\n');
3697 var start = 0;
3698 var lineRanges = originalLines.map(function (line, i) {
3699 var end = start + line.length + 1;
3700 var range = { start: start, end: end, line: i };
3701 start = end;
3702 return range;
3703 });
3704 var i = 0;
3705 function rangeContains(range, index) {
3706 return range.start <= index && index < range.end;
3707 }
3708 function getLocation(range, index) {
3709 return { line: offsetLine + range.line, column: offsetColumn + index - range.start, character: index };
3710 }
3711 function locate(search, startIndex) {
3712 if (typeof search === 'string') {
3713 search = source.indexOf(search, startIndex || 0);
3714 }
3715 var range = lineRanges[i];
3716 var d = search >= range.end ? 1 : -1;
3717 while (range) {
3718 if (rangeContains(range, search))
3719 return getLocation(range, search);
3720 i += d;
3721 range = lineRanges[i];
3722 }
3723 }
3724 return locate;
3725}
3726function locate(source, search, options) {
3727 if (typeof options === 'number') {
3728 throw new Error('locate takes a { startIndex, offsetLine, offsetColumn } object as the third argument');
3729 }
3730 return getLocator$1(source, options)(search, options && options.startIndex);
3731}
3732
3733function spaces(i) {
3734 var result = '';
3735 while (i--)
3736 result += ' ';
3737 return result;
3738}
3739function tabsToSpaces(str) {
3740 return str.replace(/^\t+/, function (match) { return match.split('\t').join(' '); });
3741}
3742function getCodeFrame(source, line, column) {
3743 var lines = source.split('\n');
3744 var frameStart = Math.max(0, line - 3);
3745 var frameEnd = Math.min(line + 2, lines.length);
3746 lines = lines.slice(frameStart, frameEnd);
3747 while (!/\S/.test(lines[lines.length - 1])) {
3748 lines.pop();
3749 frameEnd -= 1;
3750 }
3751 var digits = String(frameEnd).length;
3752 return lines
3753 .map(function (str, i) {
3754 var isErrorLine = frameStart + i + 1 === line;
3755 var lineNum = String(i + frameStart + 1);
3756 while (lineNum.length < digits)
3757 lineNum = " " + lineNum;
3758 if (isErrorLine) {
3759 var indicator = spaces(digits + 2 + tabsToSpaces(str.slice(0, column)).length) + '^';
3760 return lineNum + ": " + tabsToSpaces(str) + "\n" + indicator;
3761 }
3762 return lineNum + ": " + tabsToSpaces(str);
3763 })
3764 .join('\n');
3765}
3766
3767function getAliasName(id) {
3768 var base = basename(id);
3769 return base.substr(0, base.length - extname(id).length);
3770}
3771function relativeId(id) {
3772 if (typeof process === 'undefined' || !isAbsolute(id))
3773 return id;
3774 return relative(process.cwd(), id);
3775}
3776function isPlainName(name) {
3777 // not starting with "./", "/". "../"
3778 return !(name[0] === '/' ||
3779 (name[1] === '.' && (name[2] === '/' || (name[2] === '.' && name[3] === '/'))));
3780}
3781
3782function error(base, props) {
3783 if (base instanceof Error === false)
3784 base = Object.assign(new Error(base.message), base);
3785 if (props)
3786 Object.assign(base, props);
3787 throw base;
3788}
3789function augmentCodeLocation(object, pos, source, id) {
3790 if (pos.line !== undefined && pos.column !== undefined) {
3791 var line = pos.line, column = pos.column;
3792 object.loc = { file: id, line: line, column: column };
3793 }
3794 else {
3795 object.pos = pos;
3796 var _a = locate(source, pos, { offsetLine: 1 }), line = _a.line, column = _a.column;
3797 object.loc = { file: id, line: line, column: column };
3798 }
3799 if (object.frame === undefined) {
3800 var _b = object.loc, line = _b.line, column = _b.column;
3801 object.frame = getCodeFrame(source, line, column);
3802 }
3803}
3804var Errors;
3805(function (Errors) {
3806 Errors["ASSET_NOT_FINALISED"] = "ASSET_NOT_FINALISED";
3807 Errors["ASSET_NOT_FOUND"] = "ASSET_NOT_FOUND";
3808 Errors["ASSET_SOURCE_ALREADY_SET"] = "ASSET_SOURCE_ALREADY_SET";
3809 Errors["ASSET_SOURCE_MISSING"] = "ASSET_SOURCE_MISSING";
3810 Errors["BAD_LOADER"] = "BAD_LOADER";
3811 Errors["CHUNK_NOT_FOUND"] = "CHUNK_NOT_FOUND";
3812 Errors["CHUNK_NOT_GENERATED"] = "CHUNK_NOT_GENERATED";
3813 Errors["INVALID_ASSET_NAME"] = "INVALID_ASSET_NAME";
3814 Errors["INVALID_CHUNK"] = "INVALID_CHUNK";
3815 Errors["INVALID_EXTERNAL_ID"] = "INVALID_EXTERNAL_ID";
3816 Errors["INVALID_PLUGIN_HOOK"] = "INVALID_PLUGIN_HOOK";
3817 Errors["INVALID_ROLLUP_PHASE"] = "INVALID_ROLLUP_PHASE";
3818 Errors["NAMESPACE_CONFLICT"] = "NAMESPACE_CONFLICT";
3819 Errors["UNRESOLVED_ENTRY"] = "UNRESOLVED_ENTRY";
3820 Errors["UNRESOLVED_IMPORT"] = "UNRESOLVED_IMPORT";
3821})(Errors || (Errors = {}));
3822function errAssetNotFinalisedForFileName(asset) {
3823 return {
3824 code: Errors.ASSET_NOT_FINALISED,
3825 message: "Plugin error - Unable to get file name for asset \"" + asset.name + "\". Ensure that the source is set and that generate is called first."
3826 };
3827}
3828function errChunkNotGeneratedForFileName(entry) {
3829 return {
3830 code: Errors.CHUNK_NOT_GENERATED,
3831 message: "Plugin error - Unable to get file name for chunk \"" + entry.name + "\". Ensure that generate is called first."
3832 };
3833}
3834function errAssetReferenceIdNotFoundForFilename(assetReferenceId) {
3835 return {
3836 code: Errors.ASSET_NOT_FOUND,
3837 message: "Plugin error - Unable to get file name for unknown asset \"" + assetReferenceId + "\"."
3838 };
3839}
3840function errAssetReferenceIdNotFoundForSetSource(assetReferenceId) {
3841 return {
3842 code: Errors.ASSET_NOT_FOUND,
3843 message: "Plugin error - Unable to set the source for unknown asset \"" + assetReferenceId + "\"."
3844 };
3845}
3846function errAssetSourceAlreadySet(asset) {
3847 return {
3848 code: Errors.ASSET_SOURCE_ALREADY_SET,
3849 message: "Plugin error - Unable to set the source for asset \"" + asset.name + "\", source already set."
3850 };
3851}
3852function errAssetSourceMissingForSetSource(asset) {
3853 return {
3854 code: Errors.ASSET_SOURCE_MISSING,
3855 message: "Plugin error creating asset \"" + asset.name + "\", setAssetSource call without a source."
3856 };
3857}
3858function errNoAssetSourceSet(asset) {
3859 return {
3860 code: Errors.ASSET_SOURCE_MISSING,
3861 message: "Plugin error creating asset \"" + asset.name + "\" - no asset source set."
3862 };
3863}
3864function errBadLoader(id) {
3865 return {
3866 code: Errors.BAD_LOADER,
3867 message: "Error loading " + relativeId(id) + ": plugin load hook should return a string, a { code, map } object, or nothing/null"
3868 };
3869}
3870function errChunkReferenceIdNotFoundForFilename(chunkReferenceId) {
3871 return {
3872 code: Errors.CHUNK_NOT_FOUND,
3873 message: "Plugin error - Unable to get file name for unknown chunk \"" + chunkReferenceId + "\"."
3874 };
3875}
3876function errInvalidAssetName(name) {
3877 return {
3878 code: Errors.INVALID_ASSET_NAME,
3879 message: "Plugin error creating asset, name \"" + name + "\" is not a plain (non relative or absolute URL) string name."
3880 };
3881}
3882function errCannotAssignModuleToChunk(moduleId, assignToAlias, currentAlias) {
3883 return {
3884 code: Errors.INVALID_CHUNK,
3885 message: "Cannot assign " + relativeId(moduleId) + " to the \"" + assignToAlias + "\" chunk as it is already in the \"" + currentAlias + "\" chunk."
3886 };
3887}
3888function errInternalIdCannotBeExternal(source, importer) {
3889 return {
3890 code: Errors.INVALID_EXTERNAL_ID,
3891 message: "'" + source + "' is imported as an external by " + relativeId(importer) + ", but is already an existing non-external module id."
3892 };
3893}
3894function errInvalidRollupPhaseForAddWatchFile() {
3895 return {
3896 code: Errors.INVALID_ROLLUP_PHASE,
3897 message: "Cannot call addWatchFile after the build has finished."
3898 };
3899}
3900function errInvalidRollupPhaseForEmitChunk() {
3901 return {
3902 code: Errors.INVALID_ROLLUP_PHASE,
3903 message: "Cannot call emitChunk after module loading has finished."
3904 };
3905}
3906function errNamespaceConflict(name, reexportingModule, additionalExportAllModule) {
3907 return {
3908 code: Errors.NAMESPACE_CONFLICT,
3909 message: "Conflicting namespaces: " + relativeId(reexportingModule.id) + " re-exports '" + name + "' from both " + relativeId(reexportingModule.exportsAll[name]) + " and " + relativeId(additionalExportAllModule.exportsAll[name]) + " (will be ignored)",
3910 name: name,
3911 reexporter: reexportingModule.id,
3912 sources: [reexportingModule.exportsAll[name], additionalExportAllModule.exportsAll[name]]
3913 };
3914}
3915function errEntryCannotBeExternal(unresolvedId) {
3916 return {
3917 code: Errors.UNRESOLVED_ENTRY,
3918 message: "Entry module cannot be external (" + relativeId(unresolvedId) + ")."
3919 };
3920}
3921function errUnresolvedEntry(unresolvedId) {
3922 return {
3923 code: Errors.UNRESOLVED_ENTRY,
3924 message: "Could not resolve entry module (" + relativeId(unresolvedId) + ")."
3925 };
3926}
3927function errUnresolvedImport(source, importer) {
3928 return {
3929 code: Errors.UNRESOLVED_IMPORT,
3930 message: "Could not resolve '" + source + "' from " + relativeId(importer)
3931 };
3932}
3933function errUnresolvedImportTreatedAsExternal(source, importer) {
3934 return {
3935 code: Errors.UNRESOLVED_IMPORT,
3936 importer: relativeId(importer),
3937 message: "'" + source + "' is imported by " + relativeId(importer) + ", but could not be resolved \u2013 treating it as an external dependency",
3938 source: source,
3939 url: 'https://rollupjs.org/guide/en#warning-treating-module-as-external-dependency'
3940 };
3941}
3942
3943// Generate strings which dereference dotted properties, but use array notation `['prop-deref']`
3944// if the property name isn't trivial
3945var shouldUseDot = /^[a-zA-Z$_][a-zA-Z0-9$_]*$/;
3946function property(prop) {
3947 return shouldUseDot.test(prop) ? "." + prop : "['" + prop + "']";
3948}
3949function keypath(keypath) {
3950 return keypath
3951 .split('.')
3952 .map(property)
3953 .join('');
3954}
3955
3956function setupNamespace(name, root, globals, compact) {
3957 var parts = name.split('.');
3958 if (globals) {
3959 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
3960 }
3961 var _ = compact ? '' : ' ';
3962 parts.pop();
3963 var acc = root;
3964 return (parts
3965 .map(function (part) { return ((acc += property(part)), "" + acc + _ + "=" + _ + acc + _ + "||" + _ + "{}" + (compact ? '' : ';')); })
3966 .join(compact ? ',' : '\n') + (compact && parts.length ? ';' : '\n'));
3967}
3968function assignToDeepVariable(deepName, root, globals, compact, assignment) {
3969 var _ = compact ? '' : ' ';
3970 var parts = deepName.split('.');
3971 if (globals) {
3972 parts[0] = (typeof globals === 'function' ? globals(parts[0]) : globals[parts[0]]) || parts[0];
3973 }
3974 var last = parts.pop();
3975 var acc = root;
3976 var deepAssignment = parts
3977 .map(function (part) { return ((acc += property(part)), "" + acc + _ + "=" + _ + acc + _ + "||" + _ + "{}"); })
3978 .concat("" + acc + property(last))
3979 .join("," + _)
3980 .concat(_ + "=" + _ + assignment);
3981 if (parts.length > 0) {
3982 deepAssignment = "(" + deepAssignment + ")";
3983 }
3984 return deepAssignment;
3985}
3986
3987function trimEmptyImports(dependencies) {
3988 var i = dependencies.length;
3989 while (i--) {
3990 var dependency = dependencies[i];
3991 if (dependency.exportsDefault || dependency.exportsNames) {
3992 return dependencies.slice(0, i + 1);
3993 }
3994 }
3995 return [];
3996}
3997
3998var thisProp = function (name) { return "this" + keypath(name); };
3999function iife(magicString, _a, options) {
4000 var dependencies = _a.dependencies, exports = _a.exports, hasExports = _a.hasExports, t = _a.indentString, intro = _a.intro, namedExportsMode = _a.namedExportsMode, outro = _a.outro, varOrConst = _a.varOrConst, warn = _a.warn;
4001 var _ = options.compact ? '' : ' ';
4002 var n = options.compact ? '' : '\n';
4003 var extend = options.extend, name = options.name;
4004 var isNamespaced = name && name.indexOf('.') !== -1;
4005 var useVariableAssignment = !extend && !isNamespaced;
4006 if (name && useVariableAssignment && !isLegal(name)) {
4007 error({
4008 code: 'ILLEGAL_IDENTIFIER_AS_NAME',
4009 message: "Given name (" + name + ") is not legal JS identifier. If you need this you can try --extend option"
4010 });
4011 }
4012 warnOnBuiltins(warn, dependencies);
4013 var external = trimEmptyImports(dependencies);
4014 var deps = external.map(function (dep) { return dep.globalName || 'null'; });
4015 var args = external.map(function (m) { return m.name; });
4016 if (hasExports && !name) {
4017 error({
4018 code: 'INVALID_OPTION',
4019 message: "You must supply \"output.name\" for IIFE bundles."
4020 });
4021 }
4022 if (namedExportsMode && hasExports) {
4023 if (extend) {
4024 deps.unshift("" + thisProp(name) + _ + "=" + _ + thisProp(name) + _ + "||" + _ + "{}");
4025 args.unshift('exports');
4026 }
4027 else {
4028 deps.unshift('{}');
4029 args.unshift('exports');
4030 }
4031 }
4032 var useStrict = options.strict !== false ? t + "'use strict';" + n + n : "";
4033 var wrapperIntro = "(function" + _ + "(" + args.join("," + _) + ")" + _ + "{" + n + useStrict;
4034 if (hasExports && (!extend || !namedExportsMode)) {
4035 wrapperIntro =
4036 (useVariableAssignment ? varOrConst + " " + name : thisProp(name)) +
4037 (_ + "=" + _ + wrapperIntro);
4038 }
4039 if (isNamespaced && hasExports) {
4040 wrapperIntro = setupNamespace(name, 'this', options.globals, options.compact) + wrapperIntro;
4041 }
4042 var wrapperOutro = "" + n + n + "}(" + deps.join("," + _) + "));";
4043 if (!extend && namedExportsMode && hasExports) {
4044 wrapperOutro = "" + n + n + t + "return exports;" + wrapperOutro;
4045 }
4046 // var foo__default = 'default' in foo ? foo['default'] : foo;
4047 var interopBlock = getInteropBlock(dependencies, options, varOrConst);
4048 if (interopBlock)
4049 magicString.prepend(interopBlock + n + n);
4050 if (intro)
4051 magicString.prepend(intro);
4052 var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
4053 if (exportBlock)
4054 magicString.append(n + n + exportBlock);
4055 if (outro)
4056 magicString.append(outro);
4057 return magicString
4058 .indent(t)
4059 .prepend(wrapperIntro)
4060 .append(wrapperOutro);
4061}
4062
4063function getStarExcludes(_a) {
4064 var dependencies = _a.dependencies, exports = _a.exports;
4065 var starExcludes = new Set(exports.map(function (expt) { return expt.exported; }));
4066 if (!starExcludes.has('default'))
4067 starExcludes.add('default');
4068 // also include reexport names
4069 dependencies.forEach(function (_a) {
4070 var reexports = _a.reexports;
4071 if (reexports)
4072 reexports.forEach(function (reexport) {
4073 if (reexport.imported !== '*' && !starExcludes.has(reexport.reexported))
4074 starExcludes.add(reexport.reexported);
4075 });
4076 });
4077 return starExcludes;
4078}
4079var getStarExcludesBlock = function (starExcludes, varOrConst, _, t, n) {
4080 return starExcludes
4081 ? "" + n + t + varOrConst + " _starExcludes" + _ + "=" + _ + "{" + _ + Array.from(starExcludes).join(":" + _ + "1," + _) + (starExcludes.size ? ":" + _ + "1" : '') + _ + "};"
4082 : '';
4083};
4084var getImportBindingsBlock = function (importBindings, _, t, n) { return (importBindings.length ? "" + n + t + "var " + importBindings.join("," + _) + ";" : ''); };
4085function getExportsBlock(exports, _, t, n) {
4086 if (exports.length === 0) {
4087 return '';
4088 }
4089 if (exports.length === 1) {
4090 return "" + t + t + t + "exports('" + exports[0].name + "'," + _ + exports[0].value + ");" + n + n;
4091 }
4092 return ("" + t + t + t + "exports({" + n +
4093 exports.map(function (_a) {
4094 var name = _a.name, value = _a.value;
4095 return "" + t + t + t + t + name + ":" + _ + value;
4096 }).join("," + n) +
4097 ("" + n + t + t + t + "});" + n + n));
4098}
4099var getHoistedExportsBlock = function (exports, _, t, n) {
4100 return getExportsBlock(exports
4101 .filter(function (expt) { return expt.hoisted || expt.uninitialized; })
4102 .map(function (expt) { return ({ name: expt.exported, value: expt.uninitialized ? 'void 0' : expt.local }); }), _, t, n);
4103};
4104var getMissingExportsBlock = function (exports, _, t, n) {
4105 return getExportsBlock(exports
4106 .filter(function (expt) { return expt.local === MISSING_EXPORT_SHIM_VARIABLE; })
4107 .map(function (expt) { return ({ name: expt.exported, value: MISSING_EXPORT_SHIM_VARIABLE }); }), _, t, n);
4108};
4109function system(magicString, _a, options) {
4110 var dependencies = _a.dependencies, exports = _a.exports, t = _a.indentString, intro = _a.intro, outro = _a.outro, usesTopLevelAwait = _a.usesTopLevelAwait, varOrConst = _a.varOrConst;
4111 var n = options.compact ? '' : '\n';
4112 var _ = options.compact ? '' : ' ';
4113 var dependencyIds = dependencies.map(function (m) { return "'" + m.id + "'"; });
4114 var importBindings = [];
4115 var starExcludes;
4116 var setters = [];
4117 dependencies.forEach(function (_a) {
4118 var imports = _a.imports, reexports = _a.reexports;
4119 var setter = [];
4120 if (imports) {
4121 imports.forEach(function (specifier) {
4122 importBindings.push(specifier.local);
4123 if (specifier.imported === '*') {
4124 setter.push("" + specifier.local + _ + "=" + _ + "module;");
4125 }
4126 else {
4127 setter.push("" + specifier.local + _ + "=" + _ + "module." + specifier.imported + ";");
4128 }
4129 });
4130 }
4131 if (reexports) {
4132 var createdSetter_1 = false;
4133 // bulk-reexport form
4134 if (reexports.length > 1 ||
4135 (reexports.length === 1 &&
4136 (reexports[0].reexported === '*' || reexports[0].imported === '*'))) {
4137 // star reexports
4138 reexports.forEach(function (specifier) {
4139 if (specifier.reexported !== '*')
4140 return;
4141 // need own exports list for deduping in star export case
4142 if (!starExcludes) {
4143 starExcludes = getStarExcludes({ dependencies: dependencies, exports: exports });
4144 }
4145 if (!createdSetter_1) {
4146 setter.push(varOrConst + " _setter" + _ + "=" + _ + "{};");
4147 createdSetter_1 = true;
4148 }
4149 setter.push("for" + _ + "(var _$p" + _ + "in" + _ + "module)" + _ + "{");
4150 setter.push(t + "if" + _ + "(!_starExcludes[_$p])" + _ + "_setter[_$p]" + _ + "=" + _ + "module[_$p];");
4151 setter.push('}');
4152 });
4153 // star import reexport
4154 reexports.forEach(function (specifier) {
4155 if (specifier.imported !== '*' || specifier.reexported === '*')
4156 return;
4157 setter.push("exports('" + specifier.reexported + "'," + _ + "module);");
4158 });
4159 // reexports
4160 reexports.forEach(function (specifier) {
4161 if (specifier.reexported === '*' || specifier.imported === '*')
4162 return;
4163 if (!createdSetter_1) {
4164 setter.push(varOrConst + " _setter" + _ + "=" + _ + "{};");
4165 createdSetter_1 = true;
4166 }
4167 setter.push("_setter." + specifier.reexported + _ + "=" + _ + "module." + specifier.imported + ";");
4168 });
4169 if (createdSetter_1) {
4170 setter.push('exports(_setter);');
4171 }
4172 }
4173 else {
4174 // single reexport
4175 reexports.forEach(function (specifier) {
4176 setter.push("exports('" + specifier.reexported + "'," + _ + "module." + specifier.imported + ");");
4177 });
4178 }
4179 }
4180 setters.push(setter.join("" + n + t + t + t));
4181 });
4182 var registeredName = options.name ? "'" + options.name + "'," + _ : '';
4183 var wrapperStart = "System.register(" + registeredName + "[" +
4184 dependencyIds.join("," + _) +
4185 ("]," + _ + "function" + _ + "(exports," + _ + "module)" + _ + "{" + n + t + "'use strict';") +
4186 getStarExcludesBlock(starExcludes, varOrConst, _, t, n) +
4187 getImportBindingsBlock(importBindings, _, t, n) +
4188 ("" + n + t + "return" + _ + "{" + (setters.length
4189 ? "" + n + t + t + "setters:" + _ + "[" + setters
4190 .map(function (s) {
4191 return s
4192 ? "function" + _ + "(module)" + _ + "{" + n + t + t + t + s + n + t + t + "}"
4193 : "function" + _ + "()" + _ + "{}";
4194 })
4195 .join("," + _) + "],"
4196 : '') + n);
4197 wrapperStart +=
4198 "" + t + t + "execute:" + _ + (usesTopLevelAwait ? "async" + _ : '') + "function" + _ + "()" + _ + "{" + n + n +
4199 getHoistedExportsBlock(exports, _, t, n);
4200 var wrapperEnd = "" + n + n +
4201 getMissingExportsBlock(exports, _, t, n) +
4202 ("" + t + t + "}" + n + t + "}" + (options.compact ? '' : ';') + n + "});");
4203 if (intro)
4204 magicString.prepend(intro);
4205 if (outro)
4206 magicString.append(outro);
4207 return magicString
4208 .indent("" + t + t + t)
4209 .append(wrapperEnd)
4210 .prepend(wrapperStart);
4211}
4212
4213function globalProp(name, globalVar) {
4214 if (!name)
4215 return 'null';
4216 return "" + globalVar + keypath(name);
4217}
4218function safeAccess(name, globalVar, _) {
4219 var parts = name.split('.');
4220 var acc = globalVar;
4221 return parts.map(function (part) { return ((acc += property(part)), acc); }).join(_ + "&&" + _);
4222}
4223function umd(magicString, _a, options) {
4224 var dependencies = _a.dependencies, exports = _a.exports, hasExports = _a.hasExports, t = _a.indentString, intro = _a.intro, namedExportsMode = _a.namedExportsMode, outro = _a.outro, varOrConst = _a.varOrConst, warn = _a.warn;
4225 var _ = options.compact ? '' : ' ';
4226 var n = options.compact ? '' : '\n';
4227 var factoryVar = options.compact ? 'f' : 'factory';
4228 var globalVar = options.compact ? 'g' : 'global';
4229 if (hasExports && !options.name) {
4230 error({
4231 code: 'INVALID_OPTION',
4232 message: 'You must supply "output.name" for UMD bundles.'
4233 });
4234 }
4235 warnOnBuiltins(warn, dependencies);
4236 var amdDeps = dependencies.map(function (m) { return "'" + m.id + "'"; });
4237 var cjsDeps = dependencies.map(function (m) { return "require('" + m.id + "')"; });
4238 var trimmedImports = trimEmptyImports(dependencies);
4239 var globalDeps = trimmedImports.map(function (module) { return globalProp(module.globalName, globalVar); });
4240 var factoryArgs = trimmedImports.map(function (m) { return m.name; });
4241 if (namedExportsMode && (hasExports || options.noConflict === true)) {
4242 amdDeps.unshift("'exports'");
4243 cjsDeps.unshift("exports");
4244 globalDeps.unshift(assignToDeepVariable(options.name, globalVar, options.globals, options.compact, (options.extend ? "" + globalProp(options.name, globalVar) + _ + "||" + _ : '') + "{}"));
4245 factoryArgs.unshift('exports');
4246 }
4247 var amdOptions = options.amd || {};
4248 var amdParams = (amdOptions.id ? "'" + amdOptions.id + "'," + _ : "") +
4249 (amdDeps.length ? "[" + amdDeps.join("," + _) + "]," + _ : "");
4250 var define = amdOptions.define || 'define';
4251 var cjsExport = !namedExportsMode && hasExports ? "module.exports" + _ + "=" + _ : "";
4252 var useStrict = options.strict !== false ? _ + "'use strict';" + n : "";
4253 var iifeExport;
4254 if (options.noConflict === true) {
4255 var noConflictExportsVar = options.compact ? 'e' : 'exports';
4256 var factory = void 0;
4257 if (!namedExportsMode && hasExports) {
4258 factory = "var " + noConflictExportsVar + _ + "=" + _ + assignToDeepVariable(options.name, globalVar, options.globals, options.compact, factoryVar + "(" + globalDeps.join("," + _) + ")") + ";";
4259 }
4260 else if (namedExportsMode) {
4261 var module = globalDeps.shift();
4262 factory =
4263 "var " + noConflictExportsVar + _ + "=" + _ + module + ";" + n +
4264 ("" + t + t + factoryVar + "(" + [noConflictExportsVar].concat(globalDeps).join("," + _) + ");");
4265 }
4266 iifeExport =
4267 "(function" + _ + "()" + _ + "{" + n +
4268 ("" + t + t + "var current" + _ + "=" + _ + safeAccess(options.name, globalVar, _) + ";" + n) +
4269 ("" + t + t + factory + n) +
4270 ("" + t + t + noConflictExportsVar + ".noConflict" + _ + "=" + _ + "function" + _ + "()" + _ + "{" + _) +
4271 ("" + globalProp(options.name, globalVar) + _ + "=" + _ + "current;" + _ + "return " + noConflictExportsVar + (options.compact ? '' : '; ') + "};" + n) +
4272 (t + "}())");
4273 }
4274 else {
4275 iifeExport = factoryVar + "(" + globalDeps.join("," + _) + ")";
4276 if (!namedExportsMode && hasExports) {
4277 iifeExport = assignToDeepVariable(options.name, globalVar, options.globals, options.compact, iifeExport);
4278 }
4279 }
4280 var iifeNeedsGlobal = hasExports || (options.noConflict === true && namedExportsMode) || globalDeps.length > 0;
4281 var globalParam = iifeNeedsGlobal ? globalVar + "," + _ : '';
4282 var globalArg = iifeNeedsGlobal ? "this," + _ : '';
4283 var iifeStart = iifeNeedsGlobal ? "(" + globalVar + _ + "=" + _ + globalVar + _ + "||" + _ + "self," + _ : '';
4284 var iifeEnd = iifeNeedsGlobal ? ')' : '';
4285 var cjsIntro = iifeNeedsGlobal
4286 ? t + "typeof exports" + _ + "===" + _ + "'object'" + _ + "&&" + _ + "typeof module" + _ + "!==" + _ + "'undefined'" + _ + "?" +
4287 ("" + _ + cjsExport + factoryVar + "(" + cjsDeps.join("," + _) + ")" + _ + ":" + n)
4288 : '';
4289 var wrapperIntro = "(function" + _ + "(" + globalParam + factoryVar + ")" + _ + "{" + n +
4290 cjsIntro +
4291 (t + "typeof " + define + _ + "===" + _ + "'function'" + _ + "&&" + _ + define + ".amd" + _ + "?" + _ + define + "(" + amdParams + factoryVar + ")" + _ + ":" + n) +
4292 ("" + t + iifeStart + iifeExport + iifeEnd + ";" + n) +
4293 ("}(" + globalArg + "function" + _ + "(" + factoryArgs.join(', ') + ")" + _ + "{" + useStrict + n);
4294 var wrapperOutro = n + n + '}));';
4295 // var foo__default = 'default' in foo ? foo['default'] : foo;
4296 var interopBlock = getInteropBlock(dependencies, options, varOrConst);
4297 if (interopBlock)
4298 magicString.prepend(interopBlock + n + n);
4299 if (intro)
4300 magicString.prepend(intro);
4301 var exportBlock = getExportBlock(exports, dependencies, namedExportsMode, options.interop, options.compact, t);
4302 if (exportBlock)
4303 magicString.append(n + n + exportBlock);
4304 if (namedExportsMode && hasExports && options.esModule)
4305 magicString.append(n + n + (options.compact ? compactEsModuleExport : esModuleExport));
4306 if (outro)
4307 magicString.append(outro);
4308 return magicString
4309 .trim()
4310 .indent(t)
4311 .append(wrapperOutro)
4312 .prepend(wrapperIntro);
4313}
4314
4315var finalisers = { system: system, amd: amd, cjs: cjs, es: esm, iife: iife, umd: umd };
4316
4317var extractors = {
4318 ArrayPattern: function (names, param) {
4319 for (var _i = 0, _a = param.elements; _i < _a.length; _i++) {
4320 var element = _a[_i];
4321 if (element)
4322 extractors[element.type](names, element);
4323 }
4324 },
4325 AssignmentPattern: function (names, param) {
4326 extractors[param.left.type](names, param.left);
4327 },
4328 Identifier: function (names, param) {
4329 names.push(param.name);
4330 },
4331 MemberExpression: function () { },
4332 ObjectPattern: function (names, param) {
4333 for (var _i = 0, _a = param.properties; _i < _a.length; _i++) {
4334 var prop = _a[_i];
4335 if (prop.type === 'RestElement') {
4336 extractors.RestElement(names, prop);
4337 }
4338 else {
4339 extractors[prop.value.type](names, prop.value);
4340 }
4341 }
4342 },
4343 RestElement: function (names, param) {
4344 extractors[param.argument.type](names, param.argument);
4345 }
4346};
4347var extractAssignedNames = function extractAssignedNames(param) {
4348 var names = [];
4349 extractors[param.type](names, param);
4350 return names;
4351};
4352
4353var BLANK = Object.create(null);
4354
4355function treeshakeNode(node, code, start, end) {
4356 code.remove(start, end);
4357 if (node.annotations) {
4358 for (var _i = 0, _a = node.annotations; _i < _a.length; _i++) {
4359 var annotation = _a[_i];
4360 if (annotation.start < start) {
4361 code.remove(annotation.start, annotation.end);
4362 }
4363 else {
4364 return;
4365 }
4366 }
4367 }
4368}
4369function removeAnnotations(node, code) {
4370 if (!node.annotations && node.parent.type === ExpressionStatement) {
4371 node = node.parent;
4372 }
4373 if (node.annotations) {
4374 for (var _i = 0, _a = node.annotations; _i < _a.length; _i++) {
4375 var annotation = _a[_i];
4376 code.remove(annotation.start, annotation.end);
4377 }
4378 }
4379}
4380
4381var NO_SEMICOLON = { isNoStatement: true };
4382function findFirstOccurrenceOutsideComment(code, searchString, start) {
4383 if (start === void 0) { start = 0; }
4384 var searchPos, charCodeAfterSlash;
4385 searchPos = code.indexOf(searchString, start);
4386 while (true) {
4387 start = code.indexOf('/', start);
4388 if (start === -1 || start > searchPos)
4389 return searchPos;
4390 charCodeAfterSlash = code.charCodeAt(++start);
4391 ++start;
4392 if (charCodeAfterSlash === 47 /*"/"*/) {
4393 start = code.indexOf('\n', start) + 1;
4394 if (start === 0)
4395 return -1;
4396 if (start > searchPos) {
4397 searchPos = code.indexOf(searchString, start);
4398 }
4399 }
4400 else if (charCodeAfterSlash === 42 /*"*"*/) {
4401 start = code.indexOf('*/', start) + 2;
4402 if (start > searchPos) {
4403 searchPos = code.indexOf(searchString, start);
4404 }
4405 }
4406 }
4407}
4408function findFirstLineBreakOutsideComment(code, start) {
4409 if (start === void 0) { start = 0; }
4410 var lineBreakPos, charCodeAfterSlash;
4411 lineBreakPos = code.indexOf('\n', start);
4412 while (true) {
4413 start = code.indexOf('/', start);
4414 if (start === -1 || start > lineBreakPos)
4415 return lineBreakPos;
4416 charCodeAfterSlash = code.charCodeAt(++start);
4417 if (charCodeAfterSlash === 47 /*"/"*/)
4418 return lineBreakPos;
4419 ++start;
4420 if (charCodeAfterSlash === 42 /*"*"*/) {
4421 start = code.indexOf('*/', start) + 2;
4422 if (start > lineBreakPos) {
4423 lineBreakPos = code.indexOf('\n', start);
4424 }
4425 }
4426 }
4427}
4428function renderStatementList(statements, code, start, end, options) {
4429 if (statements.length === 0)
4430 return;
4431 var currentNode, currentNodeStart, currentNodeNeedsBoundaries, nextNodeStart;
4432 var nextNode = statements[0];
4433 var nextNodeNeedsBoundaries = !nextNode.included || nextNode.needsBoundaries;
4434 if (nextNodeNeedsBoundaries) {
4435 nextNodeStart =
4436 start + findFirstLineBreakOutsideComment(code.original.slice(start, nextNode.start)) + 1;
4437 }
4438 for (var nextIndex = 1; nextIndex <= statements.length; nextIndex++) {
4439 currentNode = nextNode;
4440 currentNodeStart = nextNodeStart;
4441 currentNodeNeedsBoundaries = nextNodeNeedsBoundaries;
4442 nextNode = statements[nextIndex];
4443 nextNodeNeedsBoundaries =
4444 nextNode === undefined ? false : !nextNode.included || nextNode.needsBoundaries;
4445 if (currentNodeNeedsBoundaries || nextNodeNeedsBoundaries) {
4446 nextNodeStart =
4447 currentNode.end +
4448 findFirstLineBreakOutsideComment(code.original.slice(currentNode.end, nextNode === undefined ? end : nextNode.start)) +
4449 1;
4450 if (currentNode.included) {
4451 currentNodeNeedsBoundaries
4452 ? currentNode.render(code, options, {
4453 end: nextNodeStart,
4454 start: currentNodeStart
4455 })
4456 : currentNode.render(code, options);
4457 }
4458 else {
4459 treeshakeNode(currentNode, code, currentNodeStart, nextNodeStart);
4460 }
4461 }
4462 else {
4463 currentNode.render(code, options);
4464 }
4465 }
4466}
4467// This assumes that the first character is not part of the first node
4468function getCommaSeparatedNodesWithBoundaries(nodes, code, start, end) {
4469 var splitUpNodes = [];
4470 var node, nextNode, nextNodeStart, contentEnd, char;
4471 var separator = start - 1;
4472 for (var nextIndex = 0; nextIndex < nodes.length; nextIndex++) {
4473 nextNode = nodes[nextIndex];
4474 if (node !== undefined) {
4475 separator =
4476 node.end +
4477 findFirstOccurrenceOutsideComment(code.original.slice(node.end, nextNode.start), ',');
4478 }
4479 nextNodeStart = contentEnd =
4480 separator +
4481 2 +
4482 findFirstLineBreakOutsideComment(code.original.slice(separator + 1, nextNode.start));
4483 while (((char = code.original.charCodeAt(nextNodeStart)),
4484 char === 32 /*" "*/ || char === 9 /*"\t"*/ || char === 10 /*"\n"*/ || char === 13) /*"\r"*/)
4485 nextNodeStart++;
4486 if (node !== undefined) {
4487 splitUpNodes.push({
4488 contentEnd: contentEnd,
4489 end: nextNodeStart,
4490 node: node,
4491 separator: separator,
4492 start: start
4493 });
4494 }
4495 node = nextNode;
4496 start = nextNodeStart;
4497 }
4498 splitUpNodes.push({
4499 contentEnd: end,
4500 end: end,
4501 node: node,
4502 separator: null,
4503 start: start
4504 });
4505 return splitUpNodes;
4506}
4507
4508var chars$1 = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$';
4509var base = 64;
4510function toBase64(num) {
4511 var outStr = '';
4512 do {
4513 var curDigit = num % base;
4514 num = Math.floor(num / base);
4515 outStr = chars$1[curDigit] + outStr;
4516 } while (num !== 0);
4517 return outStr;
4518}
4519
4520function getSafeName(baseName, usedNames) {
4521 var safeName = baseName;
4522 var count = 1;
4523 while (usedNames[safeName]) {
4524 safeName = baseName + "$" + toBase64(count++);
4525 }
4526 usedNames[safeName] = true;
4527 return safeName;
4528}
4529
4530var Scope = /** @class */ (function () {
4531 function Scope() {
4532 this.children = [];
4533 this.variables = Object.create(null);
4534 }
4535 Scope.prototype.addDeclaration = function (identifier, context, init, _isHoisted) {
4536 if (init === void 0) { init = null; }
4537 var name = identifier.name;
4538 if (this.variables[name]) {
4539 this.variables[name].addDeclaration(identifier, init);
4540 }
4541 else {
4542 this.variables[name] = new LocalVariable(identifier.name, identifier, init || UNDEFINED_EXPRESSION, context);
4543 }
4544 return this.variables[name];
4545 };
4546 Scope.prototype.contains = function (name) {
4547 return name in this.variables;
4548 };
4549 Scope.prototype.findVariable = function (_name) {
4550 throw new Error('Internal Error: findVariable needs to be implemented by a subclass');
4551 };
4552 return Scope;
4553}());
4554
4555var ChildScope = /** @class */ (function (_super) {
4556 __extends(ChildScope, _super);
4557 function ChildScope(parent) {
4558 var _this = _super.call(this) || this;
4559 _this.accessedOutsideVariables = Object.create(null);
4560 _this.parent = parent;
4561 parent.children.push(_this);
4562 return _this;
4563 }
4564 ChildScope.prototype.addNamespaceMemberAccess = function (name, variable) {
4565 this.accessedOutsideVariables[name] = variable;
4566 if (this.parent instanceof ChildScope) {
4567 this.parent.addNamespaceMemberAccess(name, variable);
4568 }
4569 };
4570 ChildScope.prototype.addReturnExpression = function (expression) {
4571 this.parent instanceof ChildScope && this.parent.addReturnExpression(expression);
4572 };
4573 ChildScope.prototype.contains = function (name) {
4574 return name in this.variables || this.parent.contains(name);
4575 };
4576 ChildScope.prototype.deconflict = function (forbiddenNames) {
4577 var usedNames = Object.assign(Object.create(null), forbiddenNames);
4578 for (var _i = 0, _a = Object.keys(this.accessedOutsideVariables); _i < _a.length; _i++) {
4579 var name = _a[_i];
4580 var variable = this.accessedOutsideVariables[name];
4581 if (variable.included) {
4582 usedNames[variable.getBaseVariableName()] = true;
4583 }
4584 }
4585 for (var _b = 0, _c = Object.keys(this.variables); _b < _c.length; _b++) {
4586 var name = _c[_b];
4587 var variable = this.variables[name];
4588 if (variable.included) {
4589 variable.setSafeName(getSafeName(name, usedNames));
4590 }
4591 }
4592 for (var _d = 0, _e = this.children; _d < _e.length; _d++) {
4593 var scope = _e[_d];
4594 scope.deconflict(forbiddenNames);
4595 }
4596 };
4597 ChildScope.prototype.findLexicalBoundary = function () {
4598 return this.parent instanceof ChildScope ? this.parent.findLexicalBoundary() : this;
4599 };
4600 ChildScope.prototype.findVariable = function (name) {
4601 var knownVariable = this.variables[name] || this.accessedOutsideVariables[name];
4602 if (knownVariable) {
4603 return knownVariable;
4604 }
4605 return (this.accessedOutsideVariables[name] = this.parent.findVariable(name));
4606 };
4607 return ChildScope;
4608}(Scope));
4609
4610/**
4611 * Copyright (c) 2014-present, Facebook, Inc.
4612 *
4613 * This source code is licensed under the MIT license found in the
4614 * LICENSE file in the root directory of this source tree.
4615 */
4616
4617// Used for setting prototype methods that IE8 chokes on.
4618var DELETE = 'delete';
4619
4620// Constants describing the size of trie nodes.
4621var SHIFT = 5; // Resulted in best performance after ______?
4622var SIZE = 1 << SHIFT;
4623var MASK = SIZE - 1;
4624
4625// A consistent shared value representing "not set" which equals nothing other
4626// than itself, and nothing that could be provided externally.
4627var NOT_SET = {};
4628
4629// Boolean references, Rough equivalent of `bool &`.
4630function MakeRef() {
4631 return { value: false };
4632}
4633
4634function SetRef(ref) {
4635 if (ref) {
4636 ref.value = true;
4637 }
4638}
4639
4640// A function which returns a value representing an "owner" for transient writes
4641// to tries. The return value will only ever equal itself, and will not equal
4642// the return of any subsequent call of this function.
4643function OwnerID() {}
4644
4645function ensureSize(iter) {
4646 if (iter.size === undefined) {
4647 iter.size = iter.__iterate(returnTrue);
4648 }
4649 return iter.size;
4650}
4651
4652function wrapIndex(iter, index) {
4653 // This implements "is array index" which the ECMAString spec defines as:
4654 //
4655 // A String property name P is an array index if and only if
4656 // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
4657 // to 2^32−1.
4658 //
4659 // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
4660 if (typeof index !== 'number') {
4661 var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
4662 if ('' + uint32Index !== index || uint32Index === 4294967295) {
4663 return NaN;
4664 }
4665 index = uint32Index;
4666 }
4667 return index < 0 ? ensureSize(iter) + index : index;
4668}
4669
4670function returnTrue() {
4671 return true;
4672}
4673
4674function wholeSlice(begin, end, size) {
4675 return (
4676 ((begin === 0 && !isNeg(begin)) ||
4677 (size !== undefined && begin <= -size)) &&
4678 (end === undefined || (size !== undefined && end >= size))
4679 );
4680}
4681
4682function resolveBegin(begin, size) {
4683 return resolveIndex(begin, size, 0);
4684}
4685
4686function resolveEnd(end, size) {
4687 return resolveIndex(end, size, size);
4688}
4689
4690function resolveIndex(index, size, defaultIndex) {
4691 // Sanitize indices using this shorthand for ToInt32(argument)
4692 // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
4693 return index === undefined
4694 ? defaultIndex
4695 : isNeg(index)
4696 ? size === Infinity
4697 ? size
4698 : Math.max(0, size + index) | 0
4699 : size === undefined || size === index
4700 ? index
4701 : Math.min(size, index) | 0;
4702}
4703
4704function isNeg(value) {
4705 // Account for -0 which is negative, but not less than 0.
4706 return value < 0 || (value === 0 && 1 / value === -Infinity);
4707}
4708
4709// Note: value is unchanged to not break immutable-devtools.
4710var IS_COLLECTION_SYMBOL = '@@__IMMUTABLE_ITERABLE__@@';
4711
4712function isCollection(maybeCollection) {
4713 return Boolean(maybeCollection && maybeCollection[IS_COLLECTION_SYMBOL]);
4714}
4715
4716var IS_KEYED_SYMBOL = '@@__IMMUTABLE_KEYED__@@';
4717
4718function isKeyed(maybeKeyed) {
4719 return Boolean(maybeKeyed && maybeKeyed[IS_KEYED_SYMBOL]);
4720}
4721
4722var IS_INDEXED_SYMBOL = '@@__IMMUTABLE_INDEXED__@@';
4723
4724function isIndexed(maybeIndexed) {
4725 return Boolean(maybeIndexed && maybeIndexed[IS_INDEXED_SYMBOL]);
4726}
4727
4728function isAssociative(maybeAssociative) {
4729 return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
4730}
4731
4732var Collection = function Collection(value) {
4733 return isCollection(value) ? value : Seq(value);
4734};
4735
4736var KeyedCollection = /*@__PURE__*/(function (Collection) {
4737 function KeyedCollection(value) {
4738 return isKeyed(value) ? value : KeyedSeq(value);
4739 }
4740
4741 if ( Collection ) KeyedCollection.__proto__ = Collection;
4742 KeyedCollection.prototype = Object.create( Collection && Collection.prototype );
4743 KeyedCollection.prototype.constructor = KeyedCollection;
4744
4745 return KeyedCollection;
4746}(Collection));
4747
4748var IndexedCollection = /*@__PURE__*/(function (Collection) {
4749 function IndexedCollection(value) {
4750 return isIndexed(value) ? value : IndexedSeq(value);
4751 }
4752
4753 if ( Collection ) IndexedCollection.__proto__ = Collection;
4754 IndexedCollection.prototype = Object.create( Collection && Collection.prototype );
4755 IndexedCollection.prototype.constructor = IndexedCollection;
4756
4757 return IndexedCollection;
4758}(Collection));
4759
4760var SetCollection = /*@__PURE__*/(function (Collection) {
4761 function SetCollection(value) {
4762 return isCollection(value) && !isAssociative(value) ? value : SetSeq(value);
4763 }
4764
4765 if ( Collection ) SetCollection.__proto__ = Collection;
4766 SetCollection.prototype = Object.create( Collection && Collection.prototype );
4767 SetCollection.prototype.constructor = SetCollection;
4768
4769 return SetCollection;
4770}(Collection));
4771
4772Collection.Keyed = KeyedCollection;
4773Collection.Indexed = IndexedCollection;
4774Collection.Set = SetCollection;
4775
4776var IS_SEQ_SYMBOL = '@@__IMMUTABLE_SEQ__@@';
4777
4778function isSeq(maybeSeq) {
4779 return Boolean(maybeSeq && maybeSeq[IS_SEQ_SYMBOL]);
4780}
4781
4782var IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@';
4783
4784function isRecord(maybeRecord) {
4785 return Boolean(maybeRecord && maybeRecord[IS_RECORD_SYMBOL]);
4786}
4787
4788function isImmutable(maybeImmutable) {
4789 return isCollection(maybeImmutable) || isRecord(maybeImmutable);
4790}
4791
4792var IS_ORDERED_SYMBOL = '@@__IMMUTABLE_ORDERED__@@';
4793
4794function isOrdered(maybeOrdered) {
4795 return Boolean(maybeOrdered && maybeOrdered[IS_ORDERED_SYMBOL]);
4796}
4797
4798var ITERATE_KEYS = 0;
4799var ITERATE_VALUES = 1;
4800var ITERATE_ENTRIES = 2;
4801
4802var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
4803var FAUX_ITERATOR_SYMBOL = '@@iterator';
4804
4805var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;
4806
4807var Iterator = function Iterator(next) {
4808 this.next = next;
4809};
4810
4811Iterator.prototype.toString = function toString () {
4812 return '[Iterator]';
4813};
4814
4815Iterator.KEYS = ITERATE_KEYS;
4816Iterator.VALUES = ITERATE_VALUES;
4817Iterator.ENTRIES = ITERATE_ENTRIES;
4818
4819Iterator.prototype.inspect = Iterator.prototype.toSource = function() {
4820 return this.toString();
4821};
4822Iterator.prototype[ITERATOR_SYMBOL] = function() {
4823 return this;
4824};
4825
4826function iteratorValue(type, k, v, iteratorResult) {
4827 var value = type === 0 ? k : type === 1 ? v : [k, v];
4828 iteratorResult
4829 ? (iteratorResult.value = value)
4830 : (iteratorResult = {
4831 value: value,
4832 done: false,
4833 });
4834 return iteratorResult;
4835}
4836
4837function iteratorDone() {
4838 return { value: undefined, done: true };
4839}
4840
4841function hasIterator(maybeIterable) {
4842 return !!getIteratorFn(maybeIterable);
4843}
4844
4845function isIterator(maybeIterator) {
4846 return maybeIterator && typeof maybeIterator.next === 'function';
4847}
4848
4849function getIterator(iterable) {
4850 var iteratorFn = getIteratorFn(iterable);
4851 return iteratorFn && iteratorFn.call(iterable);
4852}
4853
4854function getIteratorFn(iterable) {
4855 var iteratorFn =
4856 iterable &&
4857 ((REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
4858 iterable[FAUX_ITERATOR_SYMBOL]);
4859 if (typeof iteratorFn === 'function') {
4860 return iteratorFn;
4861 }
4862}
4863
4864var hasOwnProperty = Object.prototype.hasOwnProperty;
4865
4866function isArrayLike(value) {
4867 if (Array.isArray(value) || typeof value === 'string') {
4868 return true;
4869 }
4870
4871 return (
4872 value &&
4873 typeof value === 'object' &&
4874 Number.isInteger(value.length) &&
4875 value.length >= 0 &&
4876 (value.length === 0
4877 ? // Only {length: 0} is considered Array-like.
4878 Object.keys(value).length === 1
4879 : // An object is only Array-like if it has a property where the last value
4880 // in the array-like may be found (which could be undefined).
4881 value.hasOwnProperty(value.length - 1))
4882 );
4883}
4884
4885var Seq = /*@__PURE__*/(function (Collection$$1) {
4886 function Seq(value) {
4887 return value === null || value === undefined
4888 ? emptySequence()
4889 : isImmutable(value)
4890 ? value.toSeq()
4891 : seqFromValue(value);
4892 }
4893
4894 if ( Collection$$1 ) Seq.__proto__ = Collection$$1;
4895 Seq.prototype = Object.create( Collection$$1 && Collection$$1.prototype );
4896 Seq.prototype.constructor = Seq;
4897
4898 Seq.prototype.toSeq = function toSeq () {
4899 return this;
4900 };
4901
4902 Seq.prototype.toString = function toString () {
4903 return this.__toString('Seq {', '}');
4904 };
4905
4906 Seq.prototype.cacheResult = function cacheResult () {
4907 if (!this._cache && this.__iterateUncached) {
4908 this._cache = this.entrySeq().toArray();
4909 this.size = this._cache.length;
4910 }
4911 return this;
4912 };
4913
4914 // abstract __iterateUncached(fn, reverse)
4915
4916 Seq.prototype.__iterate = function __iterate (fn, reverse) {
4917 var cache = this._cache;
4918 if (cache) {
4919 var size = cache.length;
4920 var i = 0;
4921 while (i !== size) {
4922 var entry = cache[reverse ? size - ++i : i++];
4923 if (fn(entry[1], entry[0], this) === false) {
4924 break;
4925 }
4926 }
4927 return i;
4928 }
4929 return this.__iterateUncached(fn, reverse);
4930 };
4931
4932 // abstract __iteratorUncached(type, reverse)
4933
4934 Seq.prototype.__iterator = function __iterator (type, reverse) {
4935 var cache = this._cache;
4936 if (cache) {
4937 var size = cache.length;
4938 var i = 0;
4939 return new Iterator(function () {
4940 if (i === size) {
4941 return iteratorDone();
4942 }
4943 var entry = cache[reverse ? size - ++i : i++];
4944 return iteratorValue(type, entry[0], entry[1]);
4945 });
4946 }
4947 return this.__iteratorUncached(type, reverse);
4948 };
4949
4950 return Seq;
4951}(Collection));
4952
4953var KeyedSeq = /*@__PURE__*/(function (Seq) {
4954 function KeyedSeq(value) {
4955 return value === null || value === undefined
4956 ? emptySequence().toKeyedSeq()
4957 : isCollection(value)
4958 ? isKeyed(value)
4959 ? value.toSeq()
4960 : value.fromEntrySeq()
4961 : isRecord(value)
4962 ? value.toSeq()
4963 : keyedSeqFromValue(value);
4964 }
4965
4966 if ( Seq ) KeyedSeq.__proto__ = Seq;
4967 KeyedSeq.prototype = Object.create( Seq && Seq.prototype );
4968 KeyedSeq.prototype.constructor = KeyedSeq;
4969
4970 KeyedSeq.prototype.toKeyedSeq = function toKeyedSeq () {
4971 return this;
4972 };
4973
4974 return KeyedSeq;
4975}(Seq));
4976
4977var IndexedSeq = /*@__PURE__*/(function (Seq) {
4978 function IndexedSeq(value) {
4979 return value === null || value === undefined
4980 ? emptySequence()
4981 : isCollection(value)
4982 ? isKeyed(value)
4983 ? value.entrySeq()
4984 : value.toIndexedSeq()
4985 : isRecord(value)
4986 ? value.toSeq().entrySeq()
4987 : indexedSeqFromValue(value);
4988 }
4989
4990 if ( Seq ) IndexedSeq.__proto__ = Seq;
4991 IndexedSeq.prototype = Object.create( Seq && Seq.prototype );
4992 IndexedSeq.prototype.constructor = IndexedSeq;
4993
4994 IndexedSeq.of = function of (/*...values*/) {
4995 return IndexedSeq(arguments);
4996 };
4997
4998 IndexedSeq.prototype.toIndexedSeq = function toIndexedSeq () {
4999 return this;
5000 };
5001
5002 IndexedSeq.prototype.toString = function toString () {
5003 return this.__toString('Seq [', ']');
5004 };
5005
5006 return IndexedSeq;
5007}(Seq));
5008
5009var SetSeq = /*@__PURE__*/(function (Seq) {
5010 function SetSeq(value) {
5011 return (isCollection(value) && !isAssociative(value)
5012 ? value
5013 : IndexedSeq(value)
5014 ).toSetSeq();
5015 }
5016
5017 if ( Seq ) SetSeq.__proto__ = Seq;
5018 SetSeq.prototype = Object.create( Seq && Seq.prototype );
5019 SetSeq.prototype.constructor = SetSeq;
5020
5021 SetSeq.of = function of (/*...values*/) {
5022 return SetSeq(arguments);
5023 };
5024
5025 SetSeq.prototype.toSetSeq = function toSetSeq () {
5026 return this;
5027 };
5028
5029 return SetSeq;
5030}(Seq));
5031
5032Seq.isSeq = isSeq;
5033Seq.Keyed = KeyedSeq;
5034Seq.Set = SetSeq;
5035Seq.Indexed = IndexedSeq;
5036
5037Seq.prototype[IS_SEQ_SYMBOL] = true;
5038
5039// #pragma Root Sequences
5040
5041var ArraySeq = /*@__PURE__*/(function (IndexedSeq) {
5042 function ArraySeq(array) {
5043 this._array = array;
5044 this.size = array.length;
5045 }
5046
5047 if ( IndexedSeq ) ArraySeq.__proto__ = IndexedSeq;
5048 ArraySeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
5049 ArraySeq.prototype.constructor = ArraySeq;
5050
5051 ArraySeq.prototype.get = function get (index, notSetValue) {
5052 return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
5053 };
5054
5055 ArraySeq.prototype.__iterate = function __iterate (fn, reverse) {
5056 var array = this._array;
5057 var size = array.length;
5058 var i = 0;
5059 while (i !== size) {
5060 var ii = reverse ? size - ++i : i++;
5061 if (fn(array[ii], ii, this) === false) {
5062 break;
5063 }
5064 }
5065 return i;
5066 };
5067
5068 ArraySeq.prototype.__iterator = function __iterator (type, reverse) {
5069 var array = this._array;
5070 var size = array.length;
5071 var i = 0;
5072 return new Iterator(function () {
5073 if (i === size) {
5074 return iteratorDone();
5075 }
5076 var ii = reverse ? size - ++i : i++;
5077 return iteratorValue(type, ii, array[ii]);
5078 });
5079 };
5080
5081 return ArraySeq;
5082}(IndexedSeq));
5083
5084var ObjectSeq = /*@__PURE__*/(function (KeyedSeq) {
5085 function ObjectSeq(object) {
5086 var keys = Object.keys(object);
5087 this._object = object;
5088 this._keys = keys;
5089 this.size = keys.length;
5090 }
5091
5092 if ( KeyedSeq ) ObjectSeq.__proto__ = KeyedSeq;
5093 ObjectSeq.prototype = Object.create( KeyedSeq && KeyedSeq.prototype );
5094 ObjectSeq.prototype.constructor = ObjectSeq;
5095
5096 ObjectSeq.prototype.get = function get (key, notSetValue) {
5097 if (notSetValue !== undefined && !this.has(key)) {
5098 return notSetValue;
5099 }
5100 return this._object[key];
5101 };
5102
5103 ObjectSeq.prototype.has = function has (key) {
5104 return hasOwnProperty.call(this._object, key);
5105 };
5106
5107 ObjectSeq.prototype.__iterate = function __iterate (fn, reverse) {
5108 var object = this._object;
5109 var keys = this._keys;
5110 var size = keys.length;
5111 var i = 0;
5112 while (i !== size) {
5113 var key = keys[reverse ? size - ++i : i++];
5114 if (fn(object[key], key, this) === false) {
5115 break;
5116 }
5117 }
5118 return i;
5119 };
5120
5121 ObjectSeq.prototype.__iterator = function __iterator (type, reverse) {
5122 var object = this._object;
5123 var keys = this._keys;
5124 var size = keys.length;
5125 var i = 0;
5126 return new Iterator(function () {
5127 if (i === size) {
5128 return iteratorDone();
5129 }
5130 var key = keys[reverse ? size - ++i : i++];
5131 return iteratorValue(type, key, object[key]);
5132 });
5133 };
5134
5135 return ObjectSeq;
5136}(KeyedSeq));
5137ObjectSeq.prototype[IS_ORDERED_SYMBOL] = true;
5138
5139var CollectionSeq = /*@__PURE__*/(function (IndexedSeq) {
5140 function CollectionSeq(collection) {
5141 this._collection = collection;
5142 this.size = collection.length || collection.size;
5143 }
5144
5145 if ( IndexedSeq ) CollectionSeq.__proto__ = IndexedSeq;
5146 CollectionSeq.prototype = Object.create( IndexedSeq && IndexedSeq.prototype );
5147 CollectionSeq.prototype.constructor = CollectionSeq;
5148
5149 CollectionSeq.prototype.__iterateUncached = function __iterateUncached (fn, reverse) {
5150 if (reverse) {
5151 return this.cacheResult().__iterate(fn, reverse);
5152 }
5153 var collection = this._collection;
5154 var iterator = getIterator(collection);
5155 var iterations = 0;
5156 if (isIterator(iterator)) {
5157 var step;
5158 while (!(step = iterator.next()).done) {
5159 if (fn(step.value, iterations++, this) === false) {
5160 break;
5161 }
5162 }
5163 }
5164 return iterations;
5165 };
5166
5167 CollectionSeq.prototype.__iteratorUncached = function __iteratorUncached (type, reverse) {
5168 if (reverse) {
5169 return this.cacheResult().__iterator(type, reverse);
5170 }
5171 var collection = this._collection;
5172 var iterator = getIterator(collection);
5173 if (!isIterator(iterator)) {
5174 return new Iterator(iteratorDone);
5175 }
5176 var iterations = 0;
5177 return new Iterator(function () {
5178 var step = iterator.next();
5179 return step.done ? step : iteratorValue(type, iterations++, step.value);
5180 });
5181 };
5182
5183 return CollectionSeq;
5184}(IndexedSeq));
5185
5186// # pragma Helper functions
5187
5188var EMPTY_SEQ;
5189
5190function emptySequence() {
5191 return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
5192}
5193
5194function keyedSeqFromValue(value) {
5195 var seq = Array.isArray(value)
5196 ? new ArraySeq(value)
5197 : hasIterator(value)
5198 ? new CollectionSeq(value)
5199 : undefined;
5200 if (seq) {
5201 return seq.fromEntrySeq();
5202 }
5203 if (typeof value === 'object') {
5204 return new ObjectSeq(value);
5205 }
5206 throw new TypeError(
5207 'Expected Array or collection object of [k, v] entries, or keyed object: ' +
5208 value
5209 );
5210}
5211
5212function indexedSeqFromValue(value) {
5213 var seq = maybeIndexedSeqFromValue(value);
5214 if (seq) {
5215 return seq;
5216 }
5217 throw new TypeError(
5218 'Expected Array or collection object of values: ' + value
5219 );
5220}
5221
5222function seqFromValue(value) {
5223 var seq = maybeIndexedSeqFromValue(value);
5224 if (seq) {
5225 return seq;
5226 }
5227 if (typeof value === 'object') {
5228 return new ObjectSeq(value);
5229 }
5230 throw new TypeError(
5231 'Expected Array or collection object of values, or keyed object: ' + value
5232 );
5233}
5234
5235function maybeIndexedSeqFromValue(value) {
5236 return isArrayLike(value)
5237 ? new ArraySeq(value)
5238 : hasIterator(value)
5239 ? new CollectionSeq(value)
5240 : undefined;
5241}
5242
5243var IS_MAP_SYMBOL = '@@__IMMUTABLE_MAP__@@';
5244
5245function isMap(maybeMap) {
5246 return Boolean(maybeMap && maybeMap[IS_MAP_SYMBOL]);
5247}
5248
5249function isOrderedMap(maybeOrderedMap) {
5250 return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
5251}
5252
5253function isValueObject(maybeValue) {
5254 return Boolean(
5255 maybeValue &&
5256 typeof maybeValue.equals === 'function' &&
5257 typeof maybeValue.hashCode === 'function'
5258 );
5259}
5260
5261/**
5262 * An extension of the "same-value" algorithm as [described for use by ES6 Map
5263 * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
5264 *
5265 * NaN is considered the same as NaN, however -0 and 0 are considered the same
5266 * value, which is different from the algorithm described by
5267 * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
5268 *
5269 * This is extended further to allow Objects to describe the values they
5270 * represent, by way of `valueOf` or `equals` (and `hashCode`).
5271 *
5272 * Note: because of this extension, the key equality of Immutable.Map and the
5273 * value equality of Immutable.Set will differ from ES6 Map and Set.
5274 *
5275 * ### Defining custom values
5276 *
5277 * The easiest way to describe the value an object represents is by implementing
5278 * `valueOf`. For example, `Date` represents a value by returning a unix
5279 * timestamp for `valueOf`:
5280 *
5281 * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
5282 * var date2 = new Date(1234567890000);
5283 * date1.valueOf(); // 1234567890000
5284 * assert( date1 !== date2 );
5285 * assert( Immutable.is( date1, date2 ) );
5286 *
5287 * Note: overriding `valueOf` may have other implications if you use this object
5288 * where JavaScript expects a primitive, such as implicit string coercion.
5289 *
5290 * For more complex types, especially collections, implementing `valueOf` may
5291 * not be performant. An alternative is to implement `equals` and `hashCode`.
5292 *
5293 * `equals` takes another object, presumably of similar type, and returns true
5294 * if it is equal. Equality is symmetrical, so the same result should be
5295 * returned if this and the argument are flipped.
5296 *
5297 * assert( a.equals(b) === b.equals(a) );
5298 *
5299 * `hashCode` returns a 32bit integer number representing the object which will
5300 * be used to determine how to store the value object in a Map or Set. You must
5301 * provide both or neither methods, one must not exist without the other.
5302 *
5303 * Also, an important relationship between these methods must be upheld: if two
5304 * values are equal, they *must* return the same hashCode. If the values are not
5305 * equal, they might have the same hashCode; this is called a hash collision,
5306 * and while undesirable for performance reasons, it is acceptable.
5307 *
5308 * if (a.equals(b)) {
5309 * assert( a.hashCode() === b.hashCode() );
5310 * }
5311 *
5312 * All Immutable collections are Value Objects: they implement `equals()`
5313 * and `hashCode()`.
5314 */
5315function is(valueA, valueB) {
5316 if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
5317 return true;
5318 }
5319 if (!valueA || !valueB) {
5320 return false;
5321 }
5322 if (
5323 typeof valueA.valueOf === 'function' &&
5324 typeof valueB.valueOf === 'function'
5325 ) {
5326 valueA = valueA.valueOf();
5327 valueB = valueB.valueOf();
5328 if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
5329 return true;
5330 }
5331 if (!valueA || !valueB) {
5332 return false;
5333 }
5334 }
5335 return !!(
5336 isValueObject(valueA) &&
5337 isValueObject(valueB) &&
5338 valueA.equals(valueB)
5339 );
5340}
5341
5342var imul =
5343 typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2
5344 ? Math.imul
5345 : function imul(a, b) {
5346 a |= 0; // int
5347 b |= 0; // int
5348 var c = a & 0xffff;
5349 var d = b & 0xffff;
5350 // Shift by 0 fixes the sign on the high part.
5351 return (c * d + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0)) | 0; // int
5352 };
5353
5354// v8 has an optimization for storing 31-bit signed numbers.
5355// Values which have either 00 or 11 as the high order bits qualify.
5356// This function drops the highest order bit in a signed number, maintaining
5357// the sign bit.
5358function smi(i32) {
5359 return ((i32 >>> 1) & 0x40000000) | (i32 & 0xbfffffff);
5360}
5361
5362var defaultValueOf = Object.prototype.valueOf;
5363
5364function hash(o) {
5365 switch (typeof o) {
5366 case 'boolean':
5367 // The hash values for built-in constants are a 1 value for each 5-byte
5368 // shift region expect for the first, which encodes the value. This
5369 // reduces the odds of a hash collision for these common values.
5370 return o ? 0x42108421 : 0x42108420;
5371 case 'number':
5372 return hashNumber(o);
5373 case 'string':
5374 return o.length > STRING_HASH_CACHE_MIN_STRLEN
5375 ? cachedHashString(o)
5376 : hashString(o);
5377 case 'object':
5378 case 'function':
5379 if (o === null) {
5380 return 0x42108422;
5381 }
5382 if (typeof o.hashCode === 'function') {
5383 // Drop any high bits from accidentally long hash codes.
5384 return smi(o.hashCode(o));
5385 }
5386 if (o.valueOf !== defaultValueOf && typeof o.valueOf === 'function') {
5387 o = o.valueOf(o);
5388 }
5389 return hashJSObj(o);
5390 case 'undefined':
5391 return 0x42108423;
5392 default:
5393 if (typeof o.toString === 'function') {
5394 return hashString(o.toString());
5395 }
5396 throw new Error('Value type ' + typeof o + ' cannot be hashed.');
5397 }
5398}
5399
5400// Compress arbitrarily large numbers into smi hashes.
5401function hashNumber(n) {
5402 if (n !== n || n === Infinity) {
5403 return 0;
5404 }
5405 var hash = n | 0;
5406 if (hash !== n) {
5407 hash ^= n * 0xffffffff;
5408 }
5409 while (n > 0xffffffff) {
5410 n /= 0xffffffff;
5411 hash ^= n;
5412 }
5413 return smi(hash);
5414}
5415
5416function cachedHashString(string) {
5417 var hashed = stringHashCache[string];
5418 if (hashed === undefined) {
5419 hashed = hashString(string);
5420 if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
5421 STRING_HASH_CACHE_SIZE = 0;
5422 stringHashCache = {};
5423 }
5424 STRING_HASH_CACHE_SIZE++;
5425 stringHashCache[string] = hashed;
5426 }
5427 return hashed;
5428}
5429
5430// http://jsperf.com/hashing-strings
5431function hashString(string) {
5432 // This is the hash from JVM
5433 // The hash code for a string is computed as
5434 // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
5435 // where s[i] is the ith character of the string and n is the length of
5436 // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
5437 // (exclusive) by dropping high bits.
5438 var hashed = 0;
5439 for (var ii = 0; ii < string.length; ii++) {
5440 hashed = (31 * hashed + string.charCodeAt(ii)) | 0;
5441 }
5442 return smi(hashed);
5443}
5444
5445function hashJSObj(obj) {
5446 var hashed;
5447 if (usingWeakMap) {
5448 hashed = weakMap.get(obj);
5449 if (hashed !== undefined) {
5450 return hashed;
5451 }
5452 }
5453
5454 hashed = obj[UID_HASH_KEY];
5455 if (hashed !== undefined) {
5456 return hashed;
5457 }
5458
5459 if (!canDefineProperty) {
5460 hashed = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
5461 if (hashed !== undefined) {
5462 return hashed;
5463 }
5464
5465 hashed = getIENodeHash(obj);
5466 if (hashed !== undefined) {
5467 return hashed;
5468 }
5469 }
5470
5471 hashed = ++objHashUID;
5472 if (objHashUID & 0x40000000) {
5473 objHashUID = 0;
5474 }
5475
5476 if (usingWeakMap) {
5477 weakMap.set(obj, hashed);
5478 } else if (isExtensible !== undefined && isExtensible(obj) === false) {
5479 throw new Error('Non-extensible objects are not allowed as keys.');
5480 } else if (canDefineProperty) {
5481 Object.defineProperty(obj, UID_HASH_KEY, {
5482 enumerable: false,
5483 configurable: false,
5484 writable: false,
5485 value: hashed,
5486 });
5487 } else if (
5488 obj.propertyIsEnumerable !== undefined &&
5489 obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable
5490 ) {
5491 // Since we can't define a non-enumerable property on the object
5492 // we'll hijack one of the less-used non-enumerable properties to
5493 // save our hash on it. Since this is a function it will not show up in
5494 // `JSON.stringify` which is what we want.
5495 obj.propertyIsEnumerable = function() {
5496 return this.constructor.prototype.propertyIsEnumerable.apply(
5497 this,
5498 arguments
5499 );
5500 };
5501 obj.propertyIsEnumerable[UID_HASH_KEY] = hashed;
5502 } else if (obj.nodeType !== undefined) {
5503 // At this point we couldn't get the IE `uniqueID` to use as a hash
5504 // and we couldn't use a non-enumerable property to exploit the
5505 // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
5506 // itself.
5507 obj[UID_HASH_KEY] = hashed;
5508 } else {
5509 throw new Error('Unable to set a non-enumerable property on object.');
5510 }
5511
5512 return hashed;
5513}
5514
5515// Get references to ES5 object methods.
5516var isExtensible = Object.isExtensible;
5517
5518// True if Object.defineProperty works as expected. IE8 fails this test.
5519var canDefineProperty = (function() {
5520 try {
5521 Object.defineProperty({}, '@', {});
5522 return true;
5523 } catch (e) {
5524 return false;
5525 }
5526})();
5527
5528// IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
5529// and avoid memory leaks from the IE cloneNode bug.
5530function getIENodeHash(node) {
5531 if (node && node.nodeType > 0) {
5532 switch (node.nodeType) {
5533 case 1: // Element
5534 return node.uniqueID;
5535 case 9: // Document
5536 return node.documentElement && node.documentElement.uniqueID;
5537 }
5538 }
5539}
5540
5541// If possible, use a WeakMap.
5542var usingWeakMap = typeof WeakMap === 'function';
5543var weakMap;
5544if (usingWeakMap) {
5545 weakMap = new WeakMap();
5546}
5547
5548var objHashUID = 0;
5549
5550var UID_HASH_KEY = '__immutablehash__';
5551if (typeof Symbol === 'function') {
5552 UID_HASH_KEY = Symbol(UID_HASH_KEY);
5553}
5554
5555var STRING_HASH_CACHE_MIN_STRLEN = 16;
5556var STRING_HASH_CACHE_MAX_SIZE = 255;
5557var STRING_HASH_CACHE_SIZE = 0;
5558var stringHashCache = {};
5559
5560var ToKeyedSequence = /*@__PURE__*/(function (KeyedSeq$$1) {
5561 function ToKeyedSequence(indexed, useKeys) {
5562 this._iter = indexed;
5563 this._useKeys = useKeys;
5564 this.size = indexed.size;
5565 }
5566
5567 if ( KeyedSeq$$1 ) ToKeyedSequence.__proto__ = KeyedSeq$$1;
5568 ToKeyedSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype );
5569 ToKeyedSequence.prototype.constructor = ToKeyedSequence;
5570
5571 ToKeyedSequence.prototype.get = function get (key, notSetValue) {
5572 return this._iter.get(key, notSetValue);
5573 };
5574
5575 ToKeyedSequence.prototype.has = function has (key) {
5576 return this._iter.has(key);
5577 };
5578
5579 ToKeyedSequence.prototype.valueSeq = function valueSeq () {
5580 return this._iter.valueSeq();
5581 };
5582
5583 ToKeyedSequence.prototype.reverse = function reverse () {
5584 var this$1 = this;
5585
5586 var reversedSequence = reverseFactory(this, true);
5587 if (!this._useKeys) {
5588 reversedSequence.valueSeq = function () { return this$1._iter.toSeq().reverse(); };
5589 }
5590 return reversedSequence;
5591 };
5592
5593 ToKeyedSequence.prototype.map = function map (mapper, context) {
5594 var this$1 = this;
5595
5596 var mappedSequence = mapFactory(this, mapper, context);
5597 if (!this._useKeys) {
5598 mappedSequence.valueSeq = function () { return this$1._iter.toSeq().map(mapper, context); };
5599 }
5600 return mappedSequence;
5601 };
5602
5603 ToKeyedSequence.prototype.__iterate = function __iterate (fn, reverse) {
5604 var this$1 = this;
5605
5606 return this._iter.__iterate(function (v, k) { return fn(v, k, this$1); }, reverse);
5607 };
5608
5609 ToKeyedSequence.prototype.__iterator = function __iterator (type, reverse) {
5610 return this._iter.__iterator(type, reverse);
5611 };
5612
5613 return ToKeyedSequence;
5614}(KeyedSeq));
5615ToKeyedSequence.prototype[IS_ORDERED_SYMBOL] = true;
5616
5617var ToIndexedSequence = /*@__PURE__*/(function (IndexedSeq$$1) {
5618 function ToIndexedSequence(iter) {
5619 this._iter = iter;
5620 this.size = iter.size;
5621 }
5622
5623 if ( IndexedSeq$$1 ) ToIndexedSequence.__proto__ = IndexedSeq$$1;
5624 ToIndexedSequence.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
5625 ToIndexedSequence.prototype.constructor = ToIndexedSequence;
5626
5627 ToIndexedSequence.prototype.includes = function includes (value) {
5628 return this._iter.includes(value);
5629 };
5630
5631 ToIndexedSequence.prototype.__iterate = function __iterate (fn, reverse) {
5632 var this$1 = this;
5633
5634 var i = 0;
5635 reverse && ensureSize(this);
5636 return this._iter.__iterate(
5637 function (v) { return fn(v, reverse ? this$1.size - ++i : i++, this$1); },
5638 reverse
5639 );
5640 };
5641
5642 ToIndexedSequence.prototype.__iterator = function __iterator (type, reverse) {
5643 var this$1 = this;
5644
5645 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
5646 var i = 0;
5647 reverse && ensureSize(this);
5648 return new Iterator(function () {
5649 var step = iterator.next();
5650 return step.done
5651 ? step
5652 : iteratorValue(
5653 type,
5654 reverse ? this$1.size - ++i : i++,
5655 step.value,
5656 step
5657 );
5658 });
5659 };
5660
5661 return ToIndexedSequence;
5662}(IndexedSeq));
5663
5664var ToSetSequence = /*@__PURE__*/(function (SetSeq$$1) {
5665 function ToSetSequence(iter) {
5666 this._iter = iter;
5667 this.size = iter.size;
5668 }
5669
5670 if ( SetSeq$$1 ) ToSetSequence.__proto__ = SetSeq$$1;
5671 ToSetSequence.prototype = Object.create( SetSeq$$1 && SetSeq$$1.prototype );
5672 ToSetSequence.prototype.constructor = ToSetSequence;
5673
5674 ToSetSequence.prototype.has = function has (key) {
5675 return this._iter.includes(key);
5676 };
5677
5678 ToSetSequence.prototype.__iterate = function __iterate (fn, reverse) {
5679 var this$1 = this;
5680
5681 return this._iter.__iterate(function (v) { return fn(v, v, this$1); }, reverse);
5682 };
5683
5684 ToSetSequence.prototype.__iterator = function __iterator (type, reverse) {
5685 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
5686 return new Iterator(function () {
5687 var step = iterator.next();
5688 return step.done
5689 ? step
5690 : iteratorValue(type, step.value, step.value, step);
5691 });
5692 };
5693
5694 return ToSetSequence;
5695}(SetSeq));
5696
5697var FromEntriesSequence = /*@__PURE__*/(function (KeyedSeq$$1) {
5698 function FromEntriesSequence(entries) {
5699 this._iter = entries;
5700 this.size = entries.size;
5701 }
5702
5703 if ( KeyedSeq$$1 ) FromEntriesSequence.__proto__ = KeyedSeq$$1;
5704 FromEntriesSequence.prototype = Object.create( KeyedSeq$$1 && KeyedSeq$$1.prototype );
5705 FromEntriesSequence.prototype.constructor = FromEntriesSequence;
5706
5707 FromEntriesSequence.prototype.entrySeq = function entrySeq () {
5708 return this._iter.toSeq();
5709 };
5710
5711 FromEntriesSequence.prototype.__iterate = function __iterate (fn, reverse) {
5712 var this$1 = this;
5713
5714 return this._iter.__iterate(function (entry) {
5715 // Check if entry exists first so array access doesn't throw for holes
5716 // in the parent iteration.
5717 if (entry) {
5718 validateEntry(entry);
5719 var indexedCollection = isCollection(entry);
5720 return fn(
5721 indexedCollection ? entry.get(1) : entry[1],
5722 indexedCollection ? entry.get(0) : entry[0],
5723 this$1
5724 );
5725 }
5726 }, reverse);
5727 };
5728
5729 FromEntriesSequence.prototype.__iterator = function __iterator (type, reverse) {
5730 var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
5731 return new Iterator(function () {
5732 while (true) {
5733 var step = iterator.next();
5734 if (step.done) {
5735 return step;
5736 }
5737 var entry = step.value;
5738 // Check if entry exists first so array access doesn't throw for holes
5739 // in the parent iteration.
5740 if (entry) {
5741 validateEntry(entry);
5742 var indexedCollection = isCollection(entry);
5743 return iteratorValue(
5744 type,
5745 indexedCollection ? entry.get(0) : entry[0],
5746 indexedCollection ? entry.get(1) : entry[1],
5747 step
5748 );
5749 }
5750 }
5751 });
5752 };
5753
5754 return FromEntriesSequence;
5755}(KeyedSeq));
5756
5757ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough;
5758
5759function flipFactory(collection) {
5760 var flipSequence = makeSequence(collection);
5761 flipSequence._iter = collection;
5762 flipSequence.size = collection.size;
5763 flipSequence.flip = function () { return collection; };
5764 flipSequence.reverse = function() {
5765 var reversedSequence = collection.reverse.apply(this); // super.reverse()
5766 reversedSequence.flip = function () { return collection.reverse(); };
5767 return reversedSequence;
5768 };
5769 flipSequence.has = function (key) { return collection.includes(key); };
5770 flipSequence.includes = function (key) { return collection.has(key); };
5771 flipSequence.cacheResult = cacheResultThrough;
5772 flipSequence.__iterateUncached = function(fn, reverse) {
5773 var this$1 = this;
5774
5775 return collection.__iterate(function (v, k) { return fn(k, v, this$1) !== false; }, reverse);
5776 };
5777 flipSequence.__iteratorUncached = function(type, reverse) {
5778 if (type === ITERATE_ENTRIES) {
5779 var iterator = collection.__iterator(type, reverse);
5780 return new Iterator(function () {
5781 var step = iterator.next();
5782 if (!step.done) {
5783 var k = step.value[0];
5784 step.value[0] = step.value[1];
5785 step.value[1] = k;
5786 }
5787 return step;
5788 });
5789 }
5790 return collection.__iterator(
5791 type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
5792 reverse
5793 );
5794 };
5795 return flipSequence;
5796}
5797
5798function mapFactory(collection, mapper, context) {
5799 var mappedSequence = makeSequence(collection);
5800 mappedSequence.size = collection.size;
5801 mappedSequence.has = function (key) { return collection.has(key); };
5802 mappedSequence.get = function (key, notSetValue) {
5803 var v = collection.get(key, NOT_SET);
5804 return v === NOT_SET
5805 ? notSetValue
5806 : mapper.call(context, v, key, collection);
5807 };
5808 mappedSequence.__iterateUncached = function(fn, reverse) {
5809 var this$1 = this;
5810
5811 return collection.__iterate(
5812 function (v, k, c) { return fn(mapper.call(context, v, k, c), k, this$1) !== false; },
5813 reverse
5814 );
5815 };
5816 mappedSequence.__iteratorUncached = function(type, reverse) {
5817 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
5818 return new Iterator(function () {
5819 var step = iterator.next();
5820 if (step.done) {
5821 return step;
5822 }
5823 var entry = step.value;
5824 var key = entry[0];
5825 return iteratorValue(
5826 type,
5827 key,
5828 mapper.call(context, entry[1], key, collection),
5829 step
5830 );
5831 });
5832 };
5833 return mappedSequence;
5834}
5835
5836function reverseFactory(collection, useKeys) {
5837 var this$1 = this;
5838
5839 var reversedSequence = makeSequence(collection);
5840 reversedSequence._iter = collection;
5841 reversedSequence.size = collection.size;
5842 reversedSequence.reverse = function () { return collection; };
5843 if (collection.flip) {
5844 reversedSequence.flip = function() {
5845 var flipSequence = flipFactory(collection);
5846 flipSequence.reverse = function () { return collection.flip(); };
5847 return flipSequence;
5848 };
5849 }
5850 reversedSequence.get = function (key, notSetValue) { return collection.get(useKeys ? key : -1 - key, notSetValue); };
5851 reversedSequence.has = function (key) { return collection.has(useKeys ? key : -1 - key); };
5852 reversedSequence.includes = function (value) { return collection.includes(value); };
5853 reversedSequence.cacheResult = cacheResultThrough;
5854 reversedSequence.__iterate = function(fn, reverse) {
5855 var this$1 = this;
5856
5857 var i = 0;
5858 reverse && ensureSize(collection);
5859 return collection.__iterate(
5860 function (v, k) { return fn(v, useKeys ? k : reverse ? this$1.size - ++i : i++, this$1); },
5861 !reverse
5862 );
5863 };
5864 reversedSequence.__iterator = function (type, reverse) {
5865 var i = 0;
5866 reverse && ensureSize(collection);
5867 var iterator = collection.__iterator(ITERATE_ENTRIES, !reverse);
5868 return new Iterator(function () {
5869 var step = iterator.next();
5870 if (step.done) {
5871 return step;
5872 }
5873 var entry = step.value;
5874 return iteratorValue(
5875 type,
5876 useKeys ? entry[0] : reverse ? this$1.size - ++i : i++,
5877 entry[1],
5878 step
5879 );
5880 });
5881 };
5882 return reversedSequence;
5883}
5884
5885function filterFactory(collection, predicate, context, useKeys) {
5886 var filterSequence = makeSequence(collection);
5887 if (useKeys) {
5888 filterSequence.has = function (key) {
5889 var v = collection.get(key, NOT_SET);
5890 return v !== NOT_SET && !!predicate.call(context, v, key, collection);
5891 };
5892 filterSequence.get = function (key, notSetValue) {
5893 var v = collection.get(key, NOT_SET);
5894 return v !== NOT_SET && predicate.call(context, v, key, collection)
5895 ? v
5896 : notSetValue;
5897 };
5898 }
5899 filterSequence.__iterateUncached = function(fn, reverse) {
5900 var this$1 = this;
5901
5902 var iterations = 0;
5903 collection.__iterate(function (v, k, c) {
5904 if (predicate.call(context, v, k, c)) {
5905 iterations++;
5906 return fn(v, useKeys ? k : iterations - 1, this$1);
5907 }
5908 }, reverse);
5909 return iterations;
5910 };
5911 filterSequence.__iteratorUncached = function(type, reverse) {
5912 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
5913 var iterations = 0;
5914 return new Iterator(function () {
5915 while (true) {
5916 var step = iterator.next();
5917 if (step.done) {
5918 return step;
5919 }
5920 var entry = step.value;
5921 var key = entry[0];
5922 var value = entry[1];
5923 if (predicate.call(context, value, key, collection)) {
5924 return iteratorValue(type, useKeys ? key : iterations++, value, step);
5925 }
5926 }
5927 });
5928 };
5929 return filterSequence;
5930}
5931
5932function countByFactory(collection, grouper, context) {
5933 var groups = Map$1().asMutable();
5934 collection.__iterate(function (v, k) {
5935 groups.update(grouper.call(context, v, k, collection), 0, function (a) { return a + 1; });
5936 });
5937 return groups.asImmutable();
5938}
5939
5940function groupByFactory(collection, grouper, context) {
5941 var isKeyedIter = isKeyed(collection);
5942 var groups = (isOrdered(collection) ? OrderedMap() : Map$1()).asMutable();
5943 collection.__iterate(function (v, k) {
5944 groups.update(
5945 grouper.call(context, v, k, collection),
5946 function (a) { return ((a = a || []), a.push(isKeyedIter ? [k, v] : v), a); }
5947 );
5948 });
5949 var coerce = collectionClass(collection);
5950 return groups.map(function (arr) { return reify(collection, coerce(arr)); }).asImmutable();
5951}
5952
5953function sliceFactory(collection, begin, end, useKeys) {
5954 var originalSize = collection.size;
5955
5956 if (wholeSlice(begin, end, originalSize)) {
5957 return collection;
5958 }
5959
5960 var resolvedBegin = resolveBegin(begin, originalSize);
5961 var resolvedEnd = resolveEnd(end, originalSize);
5962
5963 // begin or end will be NaN if they were provided as negative numbers and
5964 // this collection's size is unknown. In that case, cache first so there is
5965 // a known size and these do not resolve to NaN.
5966 if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
5967 return sliceFactory(collection.toSeq().cacheResult(), begin, end, useKeys);
5968 }
5969
5970 // Note: resolvedEnd is undefined when the original sequence's length is
5971 // unknown and this slice did not supply an end and should contain all
5972 // elements after resolvedBegin.
5973 // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
5974 var resolvedSize = resolvedEnd - resolvedBegin;
5975 var sliceSize;
5976 if (resolvedSize === resolvedSize) {
5977 sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
5978 }
5979
5980 var sliceSeq = makeSequence(collection);
5981
5982 // If collection.size is undefined, the size of the realized sliceSeq is
5983 // unknown at this point unless the number of items to slice is 0
5984 sliceSeq.size =
5985 sliceSize === 0 ? sliceSize : (collection.size && sliceSize) || undefined;
5986
5987 if (!useKeys && isSeq(collection) && sliceSize >= 0) {
5988 sliceSeq.get = function(index, notSetValue) {
5989 index = wrapIndex(this, index);
5990 return index >= 0 && index < sliceSize
5991 ? collection.get(index + resolvedBegin, notSetValue)
5992 : notSetValue;
5993 };
5994 }
5995
5996 sliceSeq.__iterateUncached = function(fn, reverse) {
5997 var this$1 = this;
5998
5999 if (sliceSize === 0) {
6000 return 0;
6001 }
6002 if (reverse) {
6003 return this.cacheResult().__iterate(fn, reverse);
6004 }
6005 var skipped = 0;
6006 var isSkipping = true;
6007 var iterations = 0;
6008 collection.__iterate(function (v, k) {
6009 if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
6010 iterations++;
6011 return (
6012 fn(v, useKeys ? k : iterations - 1, this$1) !== false &&
6013 iterations !== sliceSize
6014 );
6015 }
6016 });
6017 return iterations;
6018 };
6019
6020 sliceSeq.__iteratorUncached = function(type, reverse) {
6021 if (sliceSize !== 0 && reverse) {
6022 return this.cacheResult().__iterator(type, reverse);
6023 }
6024 // Don't bother instantiating parent iterator if taking 0.
6025 if (sliceSize === 0) {
6026 return new Iterator(iteratorDone);
6027 }
6028 var iterator = collection.__iterator(type, reverse);
6029 var skipped = 0;
6030 var iterations = 0;
6031 return new Iterator(function () {
6032 while (skipped++ < resolvedBegin) {
6033 iterator.next();
6034 }
6035 if (++iterations > sliceSize) {
6036 return iteratorDone();
6037 }
6038 var step = iterator.next();
6039 if (useKeys || type === ITERATE_VALUES || step.done) {
6040 return step;
6041 }
6042 if (type === ITERATE_KEYS) {
6043 return iteratorValue(type, iterations - 1, undefined, step);
6044 }
6045 return iteratorValue(type, iterations - 1, step.value[1], step);
6046 });
6047 };
6048
6049 return sliceSeq;
6050}
6051
6052function takeWhileFactory(collection, predicate, context) {
6053 var takeSequence = makeSequence(collection);
6054 takeSequence.__iterateUncached = function(fn, reverse) {
6055 var this$1 = this;
6056
6057 if (reverse) {
6058 return this.cacheResult().__iterate(fn, reverse);
6059 }
6060 var iterations = 0;
6061 collection.__iterate(
6062 function (v, k, c) { return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$1); }
6063 );
6064 return iterations;
6065 };
6066 takeSequence.__iteratorUncached = function(type, reverse) {
6067 var this$1 = this;
6068
6069 if (reverse) {
6070 return this.cacheResult().__iterator(type, reverse);
6071 }
6072 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
6073 var iterating = true;
6074 return new Iterator(function () {
6075 if (!iterating) {
6076 return iteratorDone();
6077 }
6078 var step = iterator.next();
6079 if (step.done) {
6080 return step;
6081 }
6082 var entry = step.value;
6083 var k = entry[0];
6084 var v = entry[1];
6085 if (!predicate.call(context, v, k, this$1)) {
6086 iterating = false;
6087 return iteratorDone();
6088 }
6089 return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
6090 });
6091 };
6092 return takeSequence;
6093}
6094
6095function skipWhileFactory(collection, predicate, context, useKeys) {
6096 var skipSequence = makeSequence(collection);
6097 skipSequence.__iterateUncached = function(fn, reverse) {
6098 var this$1 = this;
6099
6100 if (reverse) {
6101 return this.cacheResult().__iterate(fn, reverse);
6102 }
6103 var isSkipping = true;
6104 var iterations = 0;
6105 collection.__iterate(function (v, k, c) {
6106 if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
6107 iterations++;
6108 return fn(v, useKeys ? k : iterations - 1, this$1);
6109 }
6110 });
6111 return iterations;
6112 };
6113 skipSequence.__iteratorUncached = function(type, reverse) {
6114 var this$1 = this;
6115
6116 if (reverse) {
6117 return this.cacheResult().__iterator(type, reverse);
6118 }
6119 var iterator = collection.__iterator(ITERATE_ENTRIES, reverse);
6120 var skipping = true;
6121 var iterations = 0;
6122 return new Iterator(function () {
6123 var step;
6124 var k;
6125 var v;
6126 do {
6127 step = iterator.next();
6128 if (step.done) {
6129 if (useKeys || type === ITERATE_VALUES) {
6130 return step;
6131 }
6132 if (type === ITERATE_KEYS) {
6133 return iteratorValue(type, iterations++, undefined, step);
6134 }
6135 return iteratorValue(type, iterations++, step.value[1], step);
6136 }
6137 var entry = step.value;
6138 k = entry[0];
6139 v = entry[1];
6140 skipping && (skipping = predicate.call(context, v, k, this$1));
6141 } while (skipping);
6142 return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step);
6143 });
6144 };
6145 return skipSequence;
6146}
6147
6148function concatFactory(collection, values) {
6149 var isKeyedCollection = isKeyed(collection);
6150 var iters = [collection]
6151 .concat(values)
6152 .map(function (v) {
6153 if (!isCollection(v)) {
6154 v = isKeyedCollection
6155 ? keyedSeqFromValue(v)
6156 : indexedSeqFromValue(Array.isArray(v) ? v : [v]);
6157 } else if (isKeyedCollection) {
6158 v = KeyedCollection(v);
6159 }
6160 return v;
6161 })
6162 .filter(function (v) { return v.size !== 0; });
6163
6164 if (iters.length === 0) {
6165 return collection;
6166 }
6167
6168 if (iters.length === 1) {
6169 var singleton = iters[0];
6170 if (
6171 singleton === collection ||
6172 (isKeyedCollection && isKeyed(singleton)) ||
6173 (isIndexed(collection) && isIndexed(singleton))
6174 ) {
6175 return singleton;
6176 }
6177 }
6178
6179 var concatSeq = new ArraySeq(iters);
6180 if (isKeyedCollection) {
6181 concatSeq = concatSeq.toKeyedSeq();
6182 } else if (!isIndexed(collection)) {
6183 concatSeq = concatSeq.toSetSeq();
6184 }
6185 concatSeq = concatSeq.flatten(true);
6186 concatSeq.size = iters.reduce(function (sum, seq) {
6187 if (sum !== undefined) {
6188 var size = seq.size;
6189 if (size !== undefined) {
6190 return sum + size;
6191 }
6192 }
6193 }, 0);
6194 return concatSeq;
6195}
6196
6197function flattenFactory(collection, depth, useKeys) {
6198 var flatSequence = makeSequence(collection);
6199 flatSequence.__iterateUncached = function(fn, reverse) {
6200 if (reverse) {
6201 return this.cacheResult().__iterate(fn, reverse);
6202 }
6203 var iterations = 0;
6204 var stopped = false;
6205 function flatDeep(iter, currentDepth) {
6206 iter.__iterate(function (v, k) {
6207 if ((!depth || currentDepth < depth) && isCollection(v)) {
6208 flatDeep(v, currentDepth + 1);
6209 } else {
6210 iterations++;
6211 if (fn(v, useKeys ? k : iterations - 1, flatSequence) === false) {
6212 stopped = true;
6213 }
6214 }
6215 return !stopped;
6216 }, reverse);
6217 }
6218 flatDeep(collection, 0);
6219 return iterations;
6220 };
6221 flatSequence.__iteratorUncached = function(type, reverse) {
6222 if (reverse) {
6223 return this.cacheResult().__iterator(type, reverse);
6224 }
6225 var iterator = collection.__iterator(type, reverse);
6226 var stack = [];
6227 var iterations = 0;
6228 return new Iterator(function () {
6229 while (iterator) {
6230 var step = iterator.next();
6231 if (step.done !== false) {
6232 iterator = stack.pop();
6233 continue;
6234 }
6235 var v = step.value;
6236 if (type === ITERATE_ENTRIES) {
6237 v = v[1];
6238 }
6239 if ((!depth || stack.length < depth) && isCollection(v)) {
6240 stack.push(iterator);
6241 iterator = v.__iterator(type, reverse);
6242 } else {
6243 return useKeys ? step : iteratorValue(type, iterations++, v, step);
6244 }
6245 }
6246 return iteratorDone();
6247 });
6248 };
6249 return flatSequence;
6250}
6251
6252function flatMapFactory(collection, mapper, context) {
6253 var coerce = collectionClass(collection);
6254 return collection
6255 .toSeq()
6256 .map(function (v, k) { return coerce(mapper.call(context, v, k, collection)); })
6257 .flatten(true);
6258}
6259
6260function interposeFactory(collection, separator) {
6261 var interposedSequence = makeSequence(collection);
6262 interposedSequence.size = collection.size && collection.size * 2 - 1;
6263 interposedSequence.__iterateUncached = function(fn, reverse) {
6264 var this$1 = this;
6265
6266 var iterations = 0;
6267 collection.__iterate(
6268 function (v) { return (!iterations || fn(separator, iterations++, this$1) !== false) &&
6269 fn(v, iterations++, this$1) !== false; },
6270 reverse
6271 );
6272 return iterations;
6273 };
6274 interposedSequence.__iteratorUncached = function(type, reverse) {
6275 var iterator = collection.__iterator(ITERATE_VALUES, reverse);
6276 var iterations = 0;
6277 var step;
6278 return new Iterator(function () {
6279 if (!step || iterations % 2) {
6280 step = iterator.next();
6281 if (step.done) {
6282 return step;
6283 }
6284 }
6285 return iterations % 2
6286 ? iteratorValue(type, iterations++, separator)
6287 : iteratorValue(type, iterations++, step.value, step);
6288 });
6289 };
6290 return interposedSequence;
6291}
6292
6293function sortFactory(collection, comparator, mapper) {
6294 if (!comparator) {
6295 comparator = defaultComparator;
6296 }
6297 var isKeyedCollection = isKeyed(collection);
6298 var index = 0;
6299 var entries = collection
6300 .toSeq()
6301 .map(function (v, k) { return [k, v, index++, mapper ? mapper(v, k, collection) : v]; })
6302 .valueSeq()
6303 .toArray();
6304 entries.sort(function (a, b) { return comparator(a[3], b[3]) || a[2] - b[2]; }).forEach(
6305 isKeyedCollection
6306 ? function (v, i) {
6307 entries[i].length = 2;
6308 }
6309 : function (v, i) {
6310 entries[i] = v[1];
6311 }
6312 );
6313 return isKeyedCollection
6314 ? KeyedSeq(entries)
6315 : isIndexed(collection)
6316 ? IndexedSeq(entries)
6317 : SetSeq(entries);
6318}
6319
6320function maxFactory(collection, comparator, mapper) {
6321 if (!comparator) {
6322 comparator = defaultComparator;
6323 }
6324 if (mapper) {
6325 var entry = collection
6326 .toSeq()
6327 .map(function (v, k) { return [v, mapper(v, k, collection)]; })
6328 .reduce(function (a, b) { return (maxCompare(comparator, a[1], b[1]) ? b : a); });
6329 return entry && entry[0];
6330 }
6331 return collection.reduce(function (a, b) { return (maxCompare(comparator, a, b) ? b : a); });
6332}
6333
6334function maxCompare(comparator, a, b) {
6335 var comp = comparator(b, a);
6336 // b is considered the new max if the comparator declares them equal, but
6337 // they are not equal and b is in fact a nullish value.
6338 return (
6339 (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) ||
6340 comp > 0
6341 );
6342}
6343
6344function zipWithFactory(keyIter, zipper, iters, zipAll) {
6345 var zipSequence = makeSequence(keyIter);
6346 var sizes = new ArraySeq(iters).map(function (i) { return i.size; });
6347 zipSequence.size = zipAll ? sizes.max() : sizes.min();
6348 // Note: this a generic base implementation of __iterate in terms of
6349 // __iterator which may be more generically useful in the future.
6350 zipSequence.__iterate = function(fn, reverse) {
6351 /* generic:
6352 var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
6353 var step;
6354 var iterations = 0;
6355 while (!(step = iterator.next()).done) {
6356 iterations++;
6357 if (fn(step.value[1], step.value[0], this) === false) {
6358 break;
6359 }
6360 }
6361 return iterations;
6362 */
6363 // indexed:
6364 var iterator = this.__iterator(ITERATE_VALUES, reverse);
6365 var step;
6366 var iterations = 0;
6367 while (!(step = iterator.next()).done) {
6368 if (fn(step.value, iterations++, this) === false) {
6369 break;
6370 }
6371 }
6372 return iterations;
6373 };
6374 zipSequence.__iteratorUncached = function(type, reverse) {
6375 var iterators = iters.map(
6376 function (i) { return ((i = Collection(i)), getIterator(reverse ? i.reverse() : i)); }
6377 );
6378 var iterations = 0;
6379 var isDone = false;
6380 return new Iterator(function () {
6381 var steps;
6382 if (!isDone) {
6383 steps = iterators.map(function (i) { return i.next(); });
6384 isDone = zipAll ? steps.every(function (s) { return s.done; }) : steps.some(function (s) { return s.done; });
6385 }
6386 if (isDone) {
6387 return iteratorDone();
6388 }
6389 return iteratorValue(
6390 type,
6391 iterations++,
6392 zipper.apply(null, steps.map(function (s) { return s.value; }))
6393 );
6394 });
6395 };
6396 return zipSequence;
6397}
6398
6399// #pragma Helper Functions
6400
6401function reify(iter, seq) {
6402 return iter === seq ? iter : isSeq(iter) ? seq : iter.constructor(seq);
6403}
6404
6405function validateEntry(entry) {
6406 if (entry !== Object(entry)) {
6407 throw new TypeError('Expected [K, V] tuple: ' + entry);
6408 }
6409}
6410
6411function collectionClass(collection) {
6412 return isKeyed(collection)
6413 ? KeyedCollection
6414 : isIndexed(collection)
6415 ? IndexedCollection
6416 : SetCollection;
6417}
6418
6419function makeSequence(collection) {
6420 return Object.create(
6421 (isKeyed(collection)
6422 ? KeyedSeq
6423 : isIndexed(collection)
6424 ? IndexedSeq
6425 : SetSeq
6426 ).prototype
6427 );
6428}
6429
6430function cacheResultThrough() {
6431 if (this._iter.cacheResult) {
6432 this._iter.cacheResult();
6433 this.size = this._iter.size;
6434 return this;
6435 }
6436 return Seq.prototype.cacheResult.call(this);
6437}
6438
6439function defaultComparator(a, b) {
6440 if (a === undefined && b === undefined) {
6441 return 0;
6442 }
6443
6444 if (a === undefined) {
6445 return 1;
6446 }
6447
6448 if (b === undefined) {
6449 return -1;
6450 }
6451
6452 return a > b ? 1 : a < b ? -1 : 0;
6453}
6454
6455// http://jsperf.com/copy-array-inline
6456function arrCopy(arr, offset) {
6457 offset = offset || 0;
6458 var len = Math.max(0, arr.length - offset);
6459 var newArr = new Array(len);
6460 for (var ii = 0; ii < len; ii++) {
6461 newArr[ii] = arr[ii + offset];
6462 }
6463 return newArr;
6464}
6465
6466function invariant(condition, error) {
6467 if (!condition) { throw new Error(error); }
6468}
6469
6470function assertNotInfinite(size) {
6471 invariant(
6472 size !== Infinity,
6473 'Cannot perform this action with an infinite size.'
6474 );
6475}
6476
6477function coerceKeyPath(keyPath) {
6478 if (isArrayLike(keyPath) && typeof keyPath !== 'string') {
6479 return keyPath;
6480 }
6481 if (isOrdered(keyPath)) {
6482 return keyPath.toArray();
6483 }
6484 throw new TypeError(
6485 'Invalid keyPath: expected Ordered Collection or Array: ' + keyPath
6486 );
6487}
6488
6489function isPlainObj(value) {
6490 return (
6491 value &&
6492 (typeof value.constructor !== 'function' ||
6493 value.constructor.name === 'Object')
6494 );
6495}
6496
6497/**
6498 * Returns true if the value is a potentially-persistent data structure, either
6499 * provided by Immutable.js or a plain Array or Object.
6500 */
6501function isDataStructure(value) {
6502 return (
6503 typeof value === 'object' &&
6504 (isImmutable(value) || Array.isArray(value) || isPlainObj(value))
6505 );
6506}
6507
6508/**
6509 * Converts a value to a string, adding quotes if a string was provided.
6510 */
6511function quoteString(value) {
6512 try {
6513 return typeof value === 'string' ? JSON.stringify(value) : String(value);
6514 } catch (_ignoreError) {
6515 return JSON.stringify(value);
6516 }
6517}
6518
6519function has(collection, key) {
6520 return isImmutable(collection)
6521 ? collection.has(key)
6522 : isDataStructure(collection) && hasOwnProperty.call(collection, key);
6523}
6524
6525function get(collection, key, notSetValue) {
6526 return isImmutable(collection)
6527 ? collection.get(key, notSetValue)
6528 : !has(collection, key)
6529 ? notSetValue
6530 : typeof collection.get === 'function'
6531 ? collection.get(key)
6532 : collection[key];
6533}
6534
6535function shallowCopy(from) {
6536 if (Array.isArray(from)) {
6537 return arrCopy(from);
6538 }
6539 var to = {};
6540 for (var key in from) {
6541 if (hasOwnProperty.call(from, key)) {
6542 to[key] = from[key];
6543 }
6544 }
6545 return to;
6546}
6547
6548function remove(collection, key) {
6549 if (!isDataStructure(collection)) {
6550 throw new TypeError(
6551 'Cannot update non-data-structure value: ' + collection
6552 );
6553 }
6554 if (isImmutable(collection)) {
6555 if (!collection.remove) {
6556 throw new TypeError(
6557 'Cannot update immutable value without .remove() method: ' + collection
6558 );
6559 }
6560 return collection.remove(key);
6561 }
6562 if (!hasOwnProperty.call(collection, key)) {
6563 return collection;
6564 }
6565 var collectionCopy = shallowCopy(collection);
6566 if (Array.isArray(collectionCopy)) {
6567 collectionCopy.splice(key, 1);
6568 } else {
6569 delete collectionCopy[key];
6570 }
6571 return collectionCopy;
6572}
6573
6574function set(collection, key, value) {
6575 if (!isDataStructure(collection)) {
6576 throw new TypeError(
6577 'Cannot update non-data-structure value: ' + collection
6578 );
6579 }
6580 if (isImmutable(collection)) {
6581 if (!collection.set) {
6582 throw new TypeError(
6583 'Cannot update immutable value without .set() method: ' + collection
6584 );
6585 }
6586 return collection.set(key, value);
6587 }
6588 if (hasOwnProperty.call(collection, key) && value === collection[key]) {
6589 return collection;
6590 }
6591 var collectionCopy = shallowCopy(collection);
6592 collectionCopy[key] = value;
6593 return collectionCopy;
6594}
6595
6596function updateIn(collection, keyPath, notSetValue, updater) {
6597 if (!updater) {
6598 updater = notSetValue;
6599 notSetValue = undefined;
6600 }
6601 var updatedValue = updateInDeeply(
6602 isImmutable(collection),
6603 collection,
6604 coerceKeyPath(keyPath),
6605 0,
6606 notSetValue,
6607 updater
6608 );
6609 return updatedValue === NOT_SET ? notSetValue : updatedValue;
6610}
6611
6612function updateInDeeply(
6613 inImmutable,
6614 existing,
6615 keyPath,
6616 i,
6617 notSetValue,
6618 updater
6619) {
6620 var wasNotSet = existing === NOT_SET;
6621 if (i === keyPath.length) {
6622 var existingValue = wasNotSet ? notSetValue : existing;
6623 var newValue = updater(existingValue);
6624 return newValue === existingValue ? existing : newValue;
6625 }
6626 if (!wasNotSet && !isDataStructure(existing)) {
6627 throw new TypeError(
6628 'Cannot update within non-data-structure value in path [' +
6629 keyPath.slice(0, i).map(quoteString) +
6630 ']: ' +
6631 existing
6632 );
6633 }
6634 var key = keyPath[i];
6635 var nextExisting = wasNotSet ? NOT_SET : get(existing, key, NOT_SET);
6636 var nextUpdated = updateInDeeply(
6637 nextExisting === NOT_SET ? inImmutable : isImmutable(nextExisting),
6638 nextExisting,
6639 keyPath,
6640 i + 1,
6641 notSetValue,
6642 updater
6643 );
6644 return nextUpdated === nextExisting
6645 ? existing
6646 : nextUpdated === NOT_SET
6647 ? remove(existing, key)
6648 : set(
6649 wasNotSet ? (inImmutable ? emptyMap() : {}) : existing,
6650 key,
6651 nextUpdated
6652 );
6653}
6654
6655function setIn(collection, keyPath, value) {
6656 return updateIn(collection, keyPath, NOT_SET, function () { return value; });
6657}
6658
6659function setIn$1(keyPath, v) {
6660 return setIn(this, keyPath, v);
6661}
6662
6663function removeIn(collection, keyPath) {
6664 return updateIn(collection, keyPath, function () { return NOT_SET; });
6665}
6666
6667function deleteIn(keyPath) {
6668 return removeIn(this, keyPath);
6669}
6670
6671function update(collection, key, notSetValue, updater) {
6672 return updateIn(collection, [key], notSetValue, updater);
6673}
6674
6675function update$1(key, notSetValue, updater) {
6676 return arguments.length === 1
6677 ? key(this)
6678 : update(this, key, notSetValue, updater);
6679}
6680
6681function updateIn$1(keyPath, notSetValue, updater) {
6682 return updateIn(this, keyPath, notSetValue, updater);
6683}
6684
6685function merge() {
6686 var iters = [], len = arguments.length;
6687 while ( len-- ) iters[ len ] = arguments[ len ];
6688
6689 return mergeIntoKeyedWith(this, iters);
6690}
6691
6692function mergeWith(merger) {
6693 var iters = [], len = arguments.length - 1;
6694 while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
6695
6696 if (typeof merger !== 'function') {
6697 throw new TypeError('Invalid merger function: ' + merger);
6698 }
6699 return mergeIntoKeyedWith(this, iters, merger);
6700}
6701
6702function mergeIntoKeyedWith(collection, collections, merger) {
6703 var iters = [];
6704 for (var ii = 0; ii < collections.length; ii++) {
6705 var collection$1 = KeyedCollection(collections[ii]);
6706 if (collection$1.size !== 0) {
6707 iters.push(collection$1);
6708 }
6709 }
6710 if (iters.length === 0) {
6711 return collection;
6712 }
6713 if (
6714 collection.toSeq().size === 0 &&
6715 !collection.__ownerID &&
6716 iters.length === 1
6717 ) {
6718 return collection.constructor(iters[0]);
6719 }
6720 return collection.withMutations(function (collection) {
6721 var mergeIntoCollection = merger
6722 ? function (value, key) {
6723 update(
6724 collection,
6725 key,
6726 NOT_SET,
6727 function (oldVal) { return (oldVal === NOT_SET ? value : merger(oldVal, value, key)); }
6728 );
6729 }
6730 : function (value, key) {
6731 collection.set(key, value);
6732 };
6733 for (var ii = 0; ii < iters.length; ii++) {
6734 iters[ii].forEach(mergeIntoCollection);
6735 }
6736 });
6737}
6738
6739function merge$1(collection) {
6740 var sources = [], len = arguments.length - 1;
6741 while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
6742
6743 return mergeWithSources(collection, sources);
6744}
6745
6746function mergeWith$1(merger, collection) {
6747 var sources = [], len = arguments.length - 2;
6748 while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
6749
6750 return mergeWithSources(collection, sources, merger);
6751}
6752
6753function mergeDeep(collection) {
6754 var sources = [], len = arguments.length - 1;
6755 while ( len-- > 0 ) sources[ len ] = arguments[ len + 1 ];
6756
6757 return mergeDeepWithSources(collection, sources);
6758}
6759
6760function mergeDeepWith(merger, collection) {
6761 var sources = [], len = arguments.length - 2;
6762 while ( len-- > 0 ) sources[ len ] = arguments[ len + 2 ];
6763
6764 return mergeDeepWithSources(collection, sources, merger);
6765}
6766
6767function mergeDeepWithSources(collection, sources, merger) {
6768 return mergeWithSources(collection, sources, deepMergerWith(merger));
6769}
6770
6771function mergeWithSources(collection, sources, merger) {
6772 if (!isDataStructure(collection)) {
6773 throw new TypeError(
6774 'Cannot merge into non-data-structure value: ' + collection
6775 );
6776 }
6777 if (isImmutable(collection)) {
6778 return typeof merger === 'function' && collection.mergeWith
6779 ? collection.mergeWith.apply(collection, [ merger ].concat( sources ))
6780 : collection.merge
6781 ? collection.merge.apply(collection, sources)
6782 : collection.concat.apply(collection, sources);
6783 }
6784 var isArray = Array.isArray(collection);
6785 var merged = collection;
6786 var Collection$$1 = isArray ? IndexedCollection : KeyedCollection;
6787 var mergeItem = isArray
6788 ? function (value) {
6789 // Copy on write
6790 if (merged === collection) {
6791 merged = shallowCopy(merged);
6792 }
6793 merged.push(value);
6794 }
6795 : function (value, key) {
6796 var hasVal = hasOwnProperty.call(merged, key);
6797 var nextVal =
6798 hasVal && merger ? merger(merged[key], value, key) : value;
6799 if (!hasVal || nextVal !== merged[key]) {
6800 // Copy on write
6801 if (merged === collection) {
6802 merged = shallowCopy(merged);
6803 }
6804 merged[key] = nextVal;
6805 }
6806 };
6807 for (var i = 0; i < sources.length; i++) {
6808 Collection$$1(sources[i]).forEach(mergeItem);
6809 }
6810 return merged;
6811}
6812
6813function deepMergerWith(merger) {
6814 function deepMerger(oldValue, newValue, key) {
6815 return isDataStructure(oldValue) && isDataStructure(newValue)
6816 ? mergeWithSources(oldValue, [newValue], deepMerger)
6817 : merger
6818 ? merger(oldValue, newValue, key)
6819 : newValue;
6820 }
6821 return deepMerger;
6822}
6823
6824function mergeDeep$1() {
6825 var iters = [], len = arguments.length;
6826 while ( len-- ) iters[ len ] = arguments[ len ];
6827
6828 return mergeDeepWithSources(this, iters);
6829}
6830
6831function mergeDeepWith$1(merger) {
6832 var iters = [], len = arguments.length - 1;
6833 while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
6834
6835 return mergeDeepWithSources(this, iters, merger);
6836}
6837
6838function mergeIn(keyPath) {
6839 var iters = [], len = arguments.length - 1;
6840 while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
6841
6842 return updateIn(this, keyPath, emptyMap(), function (m) { return mergeWithSources(m, iters); });
6843}
6844
6845function mergeDeepIn(keyPath) {
6846 var iters = [], len = arguments.length - 1;
6847 while ( len-- > 0 ) iters[ len ] = arguments[ len + 1 ];
6848
6849 return updateIn(this, keyPath, emptyMap(), function (m) { return mergeDeepWithSources(m, iters); }
6850 );
6851}
6852
6853function withMutations(fn) {
6854 var mutable = this.asMutable();
6855 fn(mutable);
6856 return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
6857}
6858
6859function asMutable() {
6860 return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
6861}
6862
6863function asImmutable() {
6864 return this.__ensureOwner();
6865}
6866
6867function wasAltered() {
6868 return this.__altered;
6869}
6870
6871var Map$1 = /*@__PURE__*/(function (KeyedCollection$$1) {
6872 function Map(value) {
6873 return value === null || value === undefined
6874 ? emptyMap()
6875 : isMap(value) && !isOrdered(value)
6876 ? value
6877 : emptyMap().withMutations(function (map) {
6878 var iter = KeyedCollection$$1(value);
6879 assertNotInfinite(iter.size);
6880 iter.forEach(function (v, k) { return map.set(k, v); });
6881 });
6882 }
6883
6884 if ( KeyedCollection$$1 ) Map.__proto__ = KeyedCollection$$1;
6885 Map.prototype = Object.create( KeyedCollection$$1 && KeyedCollection$$1.prototype );
6886 Map.prototype.constructor = Map;
6887
6888 Map.of = function of () {
6889 var keyValues = [], len = arguments.length;
6890 while ( len-- ) keyValues[ len ] = arguments[ len ];
6891
6892 return emptyMap().withMutations(function (map) {
6893 for (var i = 0; i < keyValues.length; i += 2) {
6894 if (i + 1 >= keyValues.length) {
6895 throw new Error('Missing value for key: ' + keyValues[i]);
6896 }
6897 map.set(keyValues[i], keyValues[i + 1]);
6898 }
6899 });
6900 };
6901
6902 Map.prototype.toString = function toString () {
6903 return this.__toString('Map {', '}');
6904 };
6905
6906 // @pragma Access
6907
6908 Map.prototype.get = function get (k, notSetValue) {
6909 return this._root
6910 ? this._root.get(0, undefined, k, notSetValue)
6911 : notSetValue;
6912 };
6913
6914 // @pragma Modification
6915
6916 Map.prototype.set = function set (k, v) {
6917 return updateMap(this, k, v);
6918 };
6919
6920 Map.prototype.remove = function remove (k) {
6921 return updateMap(this, k, NOT_SET);
6922 };
6923
6924 Map.prototype.deleteAll = function deleteAll (keys) {
6925 var collection = Collection(keys);
6926
6927 if (collection.size === 0) {
6928 return this;
6929 }
6930
6931 return this.withMutations(function (map) {
6932 collection.forEach(function (key) { return map.remove(key); });
6933 });
6934 };
6935
6936 Map.prototype.clear = function clear () {
6937 if (this.size === 0) {
6938 return this;
6939 }
6940 if (this.__ownerID) {
6941 this.size = 0;
6942 this._root = null;
6943 this.__hash = undefined;
6944 this.__altered = true;
6945 return this;
6946 }
6947 return emptyMap();
6948 };
6949
6950 // @pragma Composition
6951
6952 Map.prototype.sort = function sort (comparator) {
6953 // Late binding
6954 return OrderedMap(sortFactory(this, comparator));
6955 };
6956
6957 Map.prototype.sortBy = function sortBy (mapper, comparator) {
6958 // Late binding
6959 return OrderedMap(sortFactory(this, comparator, mapper));
6960 };
6961
6962 Map.prototype.map = function map (mapper, context) {
6963 return this.withMutations(function (map) {
6964 map.forEach(function (value, key) {
6965 map.set(key, mapper.call(context, value, key, map));
6966 });
6967 });
6968 };
6969
6970 // @pragma Mutability
6971
6972 Map.prototype.__iterator = function __iterator (type, reverse) {
6973 return new MapIterator(this, type, reverse);
6974 };
6975
6976 Map.prototype.__iterate = function __iterate (fn, reverse) {
6977 var this$1 = this;
6978
6979 var iterations = 0;
6980 this._root &&
6981 this._root.iterate(function (entry) {
6982 iterations++;
6983 return fn(entry[1], entry[0], this$1);
6984 }, reverse);
6985 return iterations;
6986 };
6987
6988 Map.prototype.__ensureOwner = function __ensureOwner (ownerID) {
6989 if (ownerID === this.__ownerID) {
6990 return this;
6991 }
6992 if (!ownerID) {
6993 if (this.size === 0) {
6994 return emptyMap();
6995 }
6996 this.__ownerID = ownerID;
6997 this.__altered = false;
6998 return this;
6999 }
7000 return makeMap(this.size, this._root, ownerID, this.__hash);
7001 };
7002
7003 return Map;
7004}(KeyedCollection));
7005
7006Map$1.isMap = isMap;
7007
7008var MapPrototype = Map$1.prototype;
7009MapPrototype[IS_MAP_SYMBOL] = true;
7010MapPrototype[DELETE] = MapPrototype.remove;
7011MapPrototype.removeAll = MapPrototype.deleteAll;
7012MapPrototype.setIn = setIn$1;
7013MapPrototype.removeIn = MapPrototype.deleteIn = deleteIn;
7014MapPrototype.update = update$1;
7015MapPrototype.updateIn = updateIn$1;
7016MapPrototype.merge = MapPrototype.concat = merge;
7017MapPrototype.mergeWith = mergeWith;
7018MapPrototype.mergeDeep = mergeDeep$1;
7019MapPrototype.mergeDeepWith = mergeDeepWith$1;
7020MapPrototype.mergeIn = mergeIn;
7021MapPrototype.mergeDeepIn = mergeDeepIn;
7022MapPrototype.withMutations = withMutations;
7023MapPrototype.wasAltered = wasAltered;
7024MapPrototype.asImmutable = asImmutable;
7025MapPrototype['@@transducer/init'] = MapPrototype.asMutable = asMutable;
7026MapPrototype['@@transducer/step'] = function(result, arr) {
7027 return result.set(arr[0], arr[1]);
7028};
7029MapPrototype['@@transducer/result'] = function(obj) {
7030 return obj.asImmutable();
7031};
7032
7033// #pragma Trie Nodes
7034
7035var ArrayMapNode = function ArrayMapNode(ownerID, entries) {
7036 this.ownerID = ownerID;
7037 this.entries = entries;
7038};
7039
7040ArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
7041 var entries = this.entries;
7042 for (var ii = 0, len = entries.length; ii < len; ii++) {
7043 if (is(key, entries[ii][0])) {
7044 return entries[ii][1];
7045 }
7046 }
7047 return notSetValue;
7048};
7049
7050ArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
7051 var removed = value === NOT_SET;
7052
7053 var entries = this.entries;
7054 var idx = 0;
7055 var len = entries.length;
7056 for (; idx < len; idx++) {
7057 if (is(key, entries[idx][0])) {
7058 break;
7059 }
7060 }
7061 var exists = idx < len;
7062
7063 if (exists ? entries[idx][1] === value : removed) {
7064 return this;
7065 }
7066
7067 SetRef(didAlter);
7068 (removed || !exists) && SetRef(didChangeSize);
7069
7070 if (removed && entries.length === 1) {
7071 return; // undefined
7072 }
7073
7074 if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
7075 return createNodes(ownerID, entries, key, value);
7076 }
7077
7078 var isEditable = ownerID && ownerID === this.ownerID;
7079 var newEntries = isEditable ? entries : arrCopy(entries);
7080
7081 if (exists) {
7082 if (removed) {
7083 idx === len - 1
7084 ? newEntries.pop()
7085 : (newEntries[idx] = newEntries.pop());
7086 } else {
7087 newEntries[idx] = [key, value];
7088 }
7089 } else {
7090 newEntries.push([key, value]);
7091 }
7092
7093 if (isEditable) {
7094 this.entries = newEntries;
7095 return this;
7096 }
7097
7098 return new ArrayMapNode(ownerID, newEntries);
7099};
7100
7101var BitmapIndexedNode = function BitmapIndexedNode(ownerID, bitmap, nodes) {
7102 this.ownerID = ownerID;
7103 this.bitmap = bitmap;
7104 this.nodes = nodes;
7105};
7106
7107BitmapIndexedNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
7108 if (keyHash === undefined) {
7109 keyHash = hash(key);
7110 }
7111 var bit = 1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK);
7112 var bitmap = this.bitmap;
7113 return (bitmap & bit) === 0
7114 ? notSetValue
7115 : this.nodes[popCount(bitmap & (bit - 1))].get(
7116 shift + SHIFT,
7117 keyHash,
7118 key,
7119 notSetValue
7120 );
7121};
7122
7123BitmapIndexedNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
7124 if (keyHash === undefined) {
7125 keyHash = hash(key);
7126 }
7127 var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
7128 var bit = 1 << keyHashFrag;
7129 var bitmap = this.bitmap;
7130 var exists = (bitmap & bit) !== 0;
7131
7132 if (!exists && value === NOT_SET) {
7133 return this;
7134 }
7135
7136 var idx = popCount(bitmap & (bit - 1));
7137 var nodes = this.nodes;
7138 var node = exists ? nodes[idx] : undefined;
7139 var newNode = updateNode(
7140 node,
7141 ownerID,
7142 shift + SHIFT,
7143 keyHash,
7144 key,
7145 value,
7146 didChangeSize,
7147 didAlter
7148 );
7149
7150 if (newNode === node) {
7151 return this;
7152 }
7153
7154 if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
7155 return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
7156 }
7157
7158 if (
7159 exists &&
7160 !newNode &&
7161 nodes.length === 2 &&
7162 isLeafNode(nodes[idx ^ 1])
7163 ) {
7164 return nodes[idx ^ 1];
7165 }
7166
7167 if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
7168 return newNode;
7169 }
7170
7171 var isEditable = ownerID && ownerID === this.ownerID;
7172 var newBitmap = exists ? (newNode ? bitmap : bitmap ^ bit) : bitmap | bit;
7173 var newNodes = exists
7174 ? newNode
7175 ? setAt(nodes, idx, newNode, isEditable)
7176 : spliceOut(nodes, idx, isEditable)
7177 : spliceIn(nodes, idx, newNode, isEditable);
7178
7179 if (isEditable) {
7180 this.bitmap = newBitmap;
7181 this.nodes = newNodes;
7182 return this;
7183 }
7184
7185 return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
7186};
7187
7188var HashArrayMapNode = function HashArrayMapNode(ownerID, count, nodes) {
7189 this.ownerID = ownerID;
7190 this.count = count;
7191 this.nodes = nodes;
7192};
7193
7194HashArrayMapNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
7195 if (keyHash === undefined) {
7196 keyHash = hash(key);
7197 }
7198 var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
7199 var node = this.nodes[idx];
7200 return node
7201 ? node.get(shift + SHIFT, keyHash, key, notSetValue)
7202 : notSetValue;
7203};
7204
7205HashArrayMapNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
7206 if (keyHash === undefined) {
7207 keyHash = hash(key);
7208 }
7209 var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
7210 var removed = value === NOT_SET;
7211 var nodes = this.nodes;
7212 var node = nodes[idx];
7213
7214 if (removed && !node) {
7215 return this;
7216 }
7217
7218 var newNode = updateNode(
7219 node,
7220 ownerID,
7221 shift + SHIFT,
7222 keyHash,
7223 key,
7224 value,
7225 didChangeSize,
7226 didAlter
7227 );
7228 if (newNode === node) {
7229 return this;
7230 }
7231
7232 var newCount = this.count;
7233 if (!node) {
7234 newCount++;
7235 } else if (!newNode) {
7236 newCount--;
7237 if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
7238 return packNodes(ownerID, nodes, newCount, idx);
7239 }
7240 }
7241
7242 var isEditable = ownerID && ownerID === this.ownerID;
7243 var newNodes = setAt(nodes, idx, newNode, isEditable);
7244
7245 if (isEditable) {
7246 this.count = newCount;
7247 this.nodes = newNodes;
7248 return this;
7249 }
7250
7251 return new HashArrayMapNode(ownerID, newCount, newNodes);
7252};
7253
7254var HashCollisionNode = function HashCollisionNode(ownerID, keyHash, entries) {
7255 this.ownerID = ownerID;
7256 this.keyHash = keyHash;
7257 this.entries = entries;
7258};
7259
7260HashCollisionNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
7261 var entries = this.entries;
7262 for (var ii = 0, len = entries.length; ii < len; ii++) {
7263 if (is(key, entries[ii][0])) {
7264 return entries[ii][1];
7265 }
7266 }
7267 return notSetValue;
7268};
7269
7270HashCollisionNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
7271 if (keyHash === undefined) {
7272 keyHash = hash(key);
7273 }
7274
7275 var removed = value === NOT_SET;
7276
7277 if (keyHash !== this.keyHash) {
7278 if (removed) {
7279 return this;
7280 }
7281 SetRef(didAlter);
7282 SetRef(didChangeSize);
7283 return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
7284 }
7285
7286 var entries = this.entries;
7287 var idx = 0;
7288 var len = entries.length;
7289 for (; idx < len; idx++) {
7290 if (is(key, entries[idx][0])) {
7291 break;
7292 }
7293 }
7294 var exists = idx < len;
7295
7296 if (exists ? entries[idx][1] === value : removed) {
7297 return this;
7298 }
7299
7300 SetRef(didAlter);
7301 (removed || !exists) && SetRef(didChangeSize);
7302
7303 if (removed && len === 2) {
7304 return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
7305 }
7306
7307 var isEditable = ownerID && ownerID === this.ownerID;
7308 var newEntries = isEditable ? entries : arrCopy(entries);
7309
7310 if (exists) {
7311 if (removed) {
7312 idx === len - 1
7313 ? newEntries.pop()
7314 : (newEntries[idx] = newEntries.pop());
7315 } else {
7316 newEntries[idx] = [key, value];
7317 }
7318 } else {
7319 newEntries.push([key, value]);
7320 }
7321
7322 if (isEditable) {
7323 this.entries = newEntries;
7324 return this;
7325 }
7326
7327 return new HashCollisionNode(ownerID, this.keyHash, newEntries);
7328};
7329
7330var ValueNode = function ValueNode(ownerID, keyHash, entry) {
7331 this.ownerID = ownerID;
7332 this.keyHash = keyHash;
7333 this.entry = entry;
7334};
7335
7336ValueNode.prototype.get = function get (shift, keyHash, key, notSetValue) {
7337 return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
7338};
7339
7340ValueNode.prototype.update = function update (ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
7341 var removed = value === NOT_SET;
7342 var keyMatch = is(key, this.entry[0]);
7343 if (keyMatch ? value === this.entry[1] : removed) {
7344 return this;
7345 }
7346
7347 SetRef(didAlter);
7348
7349 if (removed) {
7350 SetRef(didChangeSize);
7351 return; // undefined
7352 }
7353
7354 if (keyMatch) {
7355 if (ownerID && ownerID === this.ownerID) {
7356 this.entry[1] = value;
7357 return this;
7358 }
7359 return new ValueNode(ownerID, this.keyHash, [key, value]);
7360 }
7361
7362 SetRef(didChangeSize);
7363 return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
7364};
7365
7366// #pragma Iterators
7367
7368ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function(
7369 fn,
7370 reverse
7371) {
7372 var entries = this.entries;
7373 for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
7374 if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
7375 return false;
7376 }
7377 }
7378};
7379
7380BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function(
7381 fn,
7382 reverse
7383) {
7384 var nodes = this.nodes;
7385 for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
7386 var node = nodes[reverse ? maxIndex - ii : ii];
7387 if (node && node.iterate(fn, reverse) === false) {
7388 return false;
7389 }
7390 }
7391};
7392
7393// eslint-disable-next-line no-unused-vars
7394ValueNode.prototype.iterate = function(fn, reverse) {
7395 return fn(this.entry);
7396};
7397
7398var MapIterator = /*@__PURE__*/(function (Iterator$$1) {
7399 function MapIterator(map, type, reverse) {
7400 this._type = type;
7401 this._reverse = reverse;
7402 this._stack = map._root && mapIteratorFrame(map._root);
7403 }
7404
7405 if ( Iterator$$1 ) MapIterator.__proto__ = Iterator$$1;
7406 MapIterator.prototype = Object.create( Iterator$$1 && Iterator$$1.prototype );
7407 MapIterator.prototype.constructor = MapIterator;
7408
7409 MapIterator.prototype.next = function next () {
7410 var type = this._type;
7411 var stack = this._stack;
7412 while (stack) {
7413 var node = stack.node;
7414 var index = stack.index++;
7415 var maxIndex = (void 0);
7416 if (node.entry) {
7417 if (index === 0) {
7418 return mapIteratorValue(type, node.entry);
7419 }
7420 } else if (node.entries) {
7421 maxIndex = node.entries.length - 1;
7422 if (index <= maxIndex) {
7423 return mapIteratorValue(
7424 type,
7425 node.entries[this._reverse ? maxIndex - index : index]
7426 );
7427 }
7428 } else {
7429 maxIndex = node.nodes.length - 1;
7430 if (index <= maxIndex) {
7431 var subNode = node.nodes[this._reverse ? maxIndex - index : index];
7432 if (subNode) {
7433 if (subNode.entry) {
7434 return mapIteratorValue(type, subNode.entry);
7435 }
7436 stack = this._stack = mapIteratorFrame(subNode, stack);
7437 }
7438 continue;
7439 }
7440 }
7441 stack = this._stack = this._stack.__prev;
7442 }
7443 return iteratorDone();
7444 };
7445
7446 return MapIterator;
7447}(Iterator));
7448
7449function mapIteratorValue(type, entry) {
7450 return iteratorValue(type, entry[0], entry[1]);
7451}
7452
7453function mapIteratorFrame(node, prev) {
7454 return {
7455 node: node,
7456 index: 0,
7457 __prev: prev,
7458 };
7459}
7460
7461function makeMap(size, root, ownerID, hash$$1) {
7462 var map = Object.create(MapPrototype);
7463 map.size = size;
7464 map._root = root;
7465 map.__ownerID = ownerID;
7466 map.__hash = hash$$1;
7467 map.__altered = false;
7468 return map;
7469}
7470
7471var EMPTY_MAP;
7472function emptyMap() {
7473 return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
7474}
7475
7476function updateMap(map, k, v) {
7477 var newRoot;
7478 var newSize;
7479 if (!map._root) {
7480 if (v === NOT_SET) {
7481 return map;
7482 }
7483 newSize = 1;
7484 newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
7485 } else {
7486 var didChangeSize = MakeRef();
7487 var didAlter = MakeRef();
7488 newRoot = updateNode(
7489 map._root,
7490 map.__ownerID,
7491 0,
7492 undefined,
7493 k,
7494 v,
7495 didChangeSize,
7496 didAlter
7497 );
7498 if (!didAlter.value) {
7499 return map;
7500 }
7501 newSize = map.size + (didChangeSize.value ? (v === NOT_SET ? -1 : 1) : 0);
7502 }
7503 if (map.__ownerID) {
7504 map.size = newSize;
7505 map._root = newRoot;
7506 map.__hash = undefined;
7507 map.__altered = true;
7508 return map;
7509 }
7510 return newRoot ? makeMap(newSize, newRoot) : emptyMap();
7511}
7512
7513function updateNode(
7514 node,
7515 ownerID,
7516 shift,
7517 keyHash,
7518 key,
7519 value,
7520 didChangeSize,
7521 didAlter
7522) {
7523 if (!node) {
7524 if (value === NOT_SET) {
7525 return node;
7526 }
7527 SetRef(didAlter);
7528 SetRef(didChangeSize);
7529 return new ValueNode(ownerID, keyHash, [key, value]);
7530 }
7531 return node.update(
7532 ownerID,
7533 shift,
7534 keyHash,
7535 key,
7536 value,
7537 didChangeSize,
7538 didAlter
7539 );
7540}
7541
7542function isLeafNode(node) {
7543 return (
7544 node.constructor === ValueNode || node.constructor === HashCollisionNode
7545 );
7546}
7547
7548function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
7549 if (node.keyHash === keyHash) {
7550 return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
7551 }
7552
7553 var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
7554 var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
7555
7556 var newNode;
7557 var nodes =
7558 idx1 === idx2
7559 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)]
7560 : ((newNode = new ValueNode(ownerID, keyHash, entry)),
7561 idx1 < idx2 ? [node, newNode] : [newNode, node]);
7562
7563 return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
7564}
7565
7566function createNodes(ownerID, entries, key, value) {
7567 if (!ownerID) {
7568 ownerID = new OwnerID();
7569 }
7570 var node = new ValueNode(ownerID, hash(key), [key, value]);
7571 for (var ii = 0; ii < entries.length; ii++) {
7572 var entry = entries[ii];
7573 node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
7574 }
7575 return node;
7576}
7577
7578function packNodes(ownerID, nodes, count, excluding) {
7579 var bitmap = 0;
7580 var packedII = 0;
7581 var packedNodes = new Array(count);
7582 for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
7583 var node = nodes[ii];
7584 if (node !== undefined && ii !== excluding) {
7585 bitmap |= bit;
7586 packedNodes[packedII++] = node;
7587 }
7588 }
7589 return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
7590}
7591
7592function expandNodes(ownerID, nodes, bitmap, including, node) {
7593 var count = 0;
7594 var expandedNodes = new Array(SIZE);
7595 for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
7596 expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
7597 }
7598 expandedNodes[including] = node;
7599 return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
7600}
7601
7602function popCount(x) {
7603 x -= (x >> 1) & 0x55555555;
7604 x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
7605 x = (x + (x >> 4)) & 0x0f0f0f0f;
7606 x += x >> 8;
7607 x += x >> 16;
7608 return x & 0x7f;
7609}
7610
7611function setAt(array, idx, val, canEdit) {
7612 var newArray = canEdit ? array : arrCopy(array);
7613 newArray[idx] = val;
7614 return newArray;
7615}
7616
7617function spliceIn(array, idx, val, canEdit) {
7618 var newLen = array.length + 1;
7619 if (canEdit && idx + 1 === newLen) {
7620 array[idx] = val;
7621 return array;
7622 }
7623 var newArray = new Array(newLen);
7624 var after = 0;
7625 for (var ii = 0; ii < newLen; ii++) {
7626 if (ii === idx) {
7627 newArray[ii] = val;
7628 after = -1;
7629 } else {
7630 newArray[ii] = array[ii + after];
7631 }
7632 }
7633 return newArray;
7634}
7635
7636function spliceOut(array, idx, canEdit) {
7637 var newLen = array.length - 1;
7638 if (canEdit && idx === newLen) {
7639 array.pop();
7640 return array;
7641 }
7642 var newArray = new Array(newLen);
7643 var after = 0;
7644 for (var ii = 0; ii < newLen; ii++) {
7645 if (ii === idx) {
7646 after = 1;
7647 }
7648 newArray[ii] = array[ii + after];
7649 }
7650 return newArray;
7651}
7652
7653var MAX_ARRAY_MAP_SIZE = SIZE / 4;
7654var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
7655var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;
7656
7657var IS_LIST_SYMBOL = '@@__IMMUTABLE_LIST__@@';
7658
7659function isList(maybeList) {
7660 return Boolean(maybeList && maybeList[IS_LIST_SYMBOL]);
7661}
7662
7663var List = /*@__PURE__*/(function (IndexedCollection$$1) {
7664 function List(value) {
7665 var empty = emptyList();
7666 if (value === null || value === undefined) {
7667 return empty;
7668 }
7669 if (isList(value)) {
7670 return value;
7671 }
7672 var iter = IndexedCollection$$1(value);
7673 var size = iter.size;
7674 if (size === 0) {
7675 return empty;
7676 }
7677 assertNotInfinite(size);
7678 if (size > 0 && size < SIZE) {
7679 return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
7680 }
7681 return empty.withMutations(function (list) {
7682 list.setSize(size);
7683 iter.forEach(function (v, i) { return list.set(i, v); });
7684 });
7685 }
7686
7687 if ( IndexedCollection$$1 ) List.__proto__ = IndexedCollection$$1;
7688 List.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype );
7689 List.prototype.constructor = List;
7690
7691 List.of = function of (/*...values*/) {
7692 return this(arguments);
7693 };
7694
7695 List.prototype.toString = function toString () {
7696 return this.__toString('List [', ']');
7697 };
7698
7699 // @pragma Access
7700
7701 List.prototype.get = function get (index, notSetValue) {
7702 index = wrapIndex(this, index);
7703 if (index >= 0 && index < this.size) {
7704 index += this._origin;
7705 var node = listNodeFor(this, index);
7706 return node && node.array[index & MASK];
7707 }
7708 return notSetValue;
7709 };
7710
7711 // @pragma Modification
7712
7713 List.prototype.set = function set (index, value) {
7714 return updateList(this, index, value);
7715 };
7716
7717 List.prototype.remove = function remove (index) {
7718 return !this.has(index)
7719 ? this
7720 : index === 0
7721 ? this.shift()
7722 : index === this.size - 1
7723 ? this.pop()
7724 : this.splice(index, 1);
7725 };
7726
7727 List.prototype.insert = function insert (index, value) {
7728 return this.splice(index, 0, value);
7729 };
7730
7731 List.prototype.clear = function clear () {
7732 if (this.size === 0) {
7733 return this;
7734 }
7735 if (this.__ownerID) {
7736 this.size = this._origin = this._capacity = 0;
7737 this._level = SHIFT;
7738 this._root = this._tail = null;
7739 this.__hash = undefined;
7740 this.__altered = true;
7741 return this;
7742 }
7743 return emptyList();
7744 };
7745
7746 List.prototype.push = function push (/*...values*/) {
7747 var values = arguments;
7748 var oldSize = this.size;
7749 return this.withMutations(function (list) {
7750 setListBounds(list, 0, oldSize + values.length);
7751 for (var ii = 0; ii < values.length; ii++) {
7752 list.set(oldSize + ii, values[ii]);
7753 }
7754 });
7755 };
7756
7757 List.prototype.pop = function pop () {
7758 return setListBounds(this, 0, -1);
7759 };
7760
7761 List.prototype.unshift = function unshift (/*...values*/) {
7762 var values = arguments;
7763 return this.withMutations(function (list) {
7764 setListBounds(list, -values.length);
7765 for (var ii = 0; ii < values.length; ii++) {
7766 list.set(ii, values[ii]);
7767 }
7768 });
7769 };
7770
7771 List.prototype.shift = function shift () {
7772 return setListBounds(this, 1);
7773 };
7774
7775 // @pragma Composition
7776
7777 List.prototype.concat = function concat (/*...collections*/) {
7778 var arguments$1 = arguments;
7779
7780 var seqs = [];
7781 for (var i = 0; i < arguments.length; i++) {
7782 var argument = arguments$1[i];
7783 var seq = IndexedCollection$$1(
7784 typeof argument !== 'string' && hasIterator(argument)
7785 ? argument
7786 : [argument]
7787 );
7788 if (seq.size !== 0) {
7789 seqs.push(seq);
7790 }
7791 }
7792 if (seqs.length === 0) {
7793 return this;
7794 }
7795 if (this.size === 0 && !this.__ownerID && seqs.length === 1) {
7796 return this.constructor(seqs[0]);
7797 }
7798 return this.withMutations(function (list) {
7799 seqs.forEach(function (seq) { return seq.forEach(function (value) { return list.push(value); }); });
7800 });
7801 };
7802
7803 List.prototype.setSize = function setSize (size) {
7804 return setListBounds(this, 0, size);
7805 };
7806
7807 List.prototype.map = function map (mapper, context) {
7808 var this$1 = this;
7809
7810 return this.withMutations(function (list) {
7811 for (var i = 0; i < this$1.size; i++) {
7812 list.set(i, mapper.call(context, list.get(i), i, list));
7813 }
7814 });
7815 };
7816
7817 // @pragma Iteration
7818
7819 List.prototype.slice = function slice (begin, end) {
7820 var size = this.size;
7821 if (wholeSlice(begin, end, size)) {
7822 return this;
7823 }
7824 return setListBounds(
7825 this,
7826 resolveBegin(begin, size),
7827 resolveEnd(end, size)
7828 );
7829 };
7830
7831 List.prototype.__iterator = function __iterator (type, reverse) {
7832 var index = reverse ? this.size : 0;
7833 var values = iterateList(this, reverse);
7834 return new Iterator(function () {
7835 var value = values();
7836 return value === DONE
7837 ? iteratorDone()
7838 : iteratorValue(type, reverse ? --index : index++, value);
7839 });
7840 };
7841
7842 List.prototype.__iterate = function __iterate (fn, reverse) {
7843 var index = reverse ? this.size : 0;
7844 var values = iterateList(this, reverse);
7845 var value;
7846 while ((value = values()) !== DONE) {
7847 if (fn(value, reverse ? --index : index++, this) === false) {
7848 break;
7849 }
7850 }
7851 return index;
7852 };
7853
7854 List.prototype.__ensureOwner = function __ensureOwner (ownerID) {
7855 if (ownerID === this.__ownerID) {
7856 return this;
7857 }
7858 if (!ownerID) {
7859 if (this.size === 0) {
7860 return emptyList();
7861 }
7862 this.__ownerID = ownerID;
7863 this.__altered = false;
7864 return this;
7865 }
7866 return makeList(
7867 this._origin,
7868 this._capacity,
7869 this._level,
7870 this._root,
7871 this._tail,
7872 ownerID,
7873 this.__hash
7874 );
7875 };
7876
7877 return List;
7878}(IndexedCollection));
7879
7880List.isList = isList;
7881
7882var ListPrototype = List.prototype;
7883ListPrototype[IS_LIST_SYMBOL] = true;
7884ListPrototype[DELETE] = ListPrototype.remove;
7885ListPrototype.merge = ListPrototype.concat;
7886ListPrototype.setIn = setIn$1;
7887ListPrototype.deleteIn = ListPrototype.removeIn = deleteIn;
7888ListPrototype.update = update$1;
7889ListPrototype.updateIn = updateIn$1;
7890ListPrototype.mergeIn = mergeIn;
7891ListPrototype.mergeDeepIn = mergeDeepIn;
7892ListPrototype.withMutations = withMutations;
7893ListPrototype.wasAltered = wasAltered;
7894ListPrototype.asImmutable = asImmutable;
7895ListPrototype['@@transducer/init'] = ListPrototype.asMutable = asMutable;
7896ListPrototype['@@transducer/step'] = function(result, arr) {
7897 return result.push(arr);
7898};
7899ListPrototype['@@transducer/result'] = function(obj) {
7900 return obj.asImmutable();
7901};
7902
7903var VNode = function VNode(array, ownerID) {
7904 this.array = array;
7905 this.ownerID = ownerID;
7906};
7907
7908// TODO: seems like these methods are very similar
7909
7910VNode.prototype.removeBefore = function removeBefore (ownerID, level, index) {
7911 if (index === level ? 1 << level : this.array.length === 0) {
7912 return this;
7913 }
7914 var originIndex = (index >>> level) & MASK;
7915 if (originIndex >= this.array.length) {
7916 return new VNode([], ownerID);
7917 }
7918 var removingFirst = originIndex === 0;
7919 var newChild;
7920 if (level > 0) {
7921 var oldChild = this.array[originIndex];
7922 newChild =
7923 oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
7924 if (newChild === oldChild && removingFirst) {
7925 return this;
7926 }
7927 }
7928 if (removingFirst && !newChild) {
7929 return this;
7930 }
7931 var editable = editableVNode(this, ownerID);
7932 if (!removingFirst) {
7933 for (var ii = 0; ii < originIndex; ii++) {
7934 editable.array[ii] = undefined;
7935 }
7936 }
7937 if (newChild) {
7938 editable.array[originIndex] = newChild;
7939 }
7940 return editable;
7941};
7942
7943VNode.prototype.removeAfter = function removeAfter (ownerID, level, index) {
7944 if (index === (level ? 1 << level : 0) || this.array.length === 0) {
7945 return this;
7946 }
7947 var sizeIndex = ((index - 1) >>> level) & MASK;
7948 if (sizeIndex >= this.array.length) {
7949 return this;
7950 }
7951
7952 var newChild;
7953 if (level > 0) {
7954 var oldChild = this.array[sizeIndex];
7955 newChild =
7956 oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
7957 if (newChild === oldChild && sizeIndex === this.array.length - 1) {
7958 return this;
7959 }
7960 }
7961
7962 var editable = editableVNode(this, ownerID);
7963 editable.array.splice(sizeIndex + 1);
7964 if (newChild) {
7965 editable.array[sizeIndex] = newChild;
7966 }
7967 return editable;
7968};
7969
7970var DONE = {};
7971
7972function iterateList(list, reverse) {
7973 var left = list._origin;
7974 var right = list._capacity;
7975 var tailPos = getTailOffset(right);
7976 var tail = list._tail;
7977
7978 return iterateNodeOrLeaf(list._root, list._level, 0);
7979
7980 function iterateNodeOrLeaf(node, level, offset) {
7981 return level === 0
7982 ? iterateLeaf(node, offset)
7983 : iterateNode(node, level, offset);
7984 }
7985
7986 function iterateLeaf(node, offset) {
7987 var array = offset === tailPos ? tail && tail.array : node && node.array;
7988 var from = offset > left ? 0 : left - offset;
7989 var to = right - offset;
7990 if (to > SIZE) {
7991 to = SIZE;
7992 }
7993 return function () {
7994 if (from === to) {
7995 return DONE;
7996 }
7997 var idx = reverse ? --to : from++;
7998 return array && array[idx];
7999 };
8000 }
8001
8002 function iterateNode(node, level, offset) {
8003 var values;
8004 var array = node && node.array;
8005 var from = offset > left ? 0 : (left - offset) >> level;
8006 var to = ((right - offset) >> level) + 1;
8007 if (to > SIZE) {
8008 to = SIZE;
8009 }
8010 return function () {
8011 while (true) {
8012 if (values) {
8013 var value = values();
8014 if (value !== DONE) {
8015 return value;
8016 }
8017 values = null;
8018 }
8019 if (from === to) {
8020 return DONE;
8021 }
8022 var idx = reverse ? --to : from++;
8023 values = iterateNodeOrLeaf(
8024 array && array[idx],
8025 level - SHIFT,
8026 offset + (idx << level)
8027 );
8028 }
8029 };
8030 }
8031}
8032
8033function makeList(origin, capacity, level, root, tail, ownerID, hash) {
8034 var list = Object.create(ListPrototype);
8035 list.size = capacity - origin;
8036 list._origin = origin;
8037 list._capacity = capacity;
8038 list._level = level;
8039 list._root = root;
8040 list._tail = tail;
8041 list.__ownerID = ownerID;
8042 list.__hash = hash;
8043 list.__altered = false;
8044 return list;
8045}
8046
8047var EMPTY_LIST;
8048function emptyList() {
8049 return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
8050}
8051
8052function updateList(list, index, value) {
8053 index = wrapIndex(list, index);
8054
8055 if (index !== index) {
8056 return list;
8057 }
8058
8059 if (index >= list.size || index < 0) {
8060 return list.withMutations(function (list) {
8061 index < 0
8062 ? setListBounds(list, index).set(0, value)
8063 : setListBounds(list, 0, index + 1).set(index, value);
8064 });
8065 }
8066
8067 index += list._origin;
8068
8069 var newTail = list._tail;
8070 var newRoot = list._root;
8071 var didAlter = MakeRef();
8072 if (index >= getTailOffset(list._capacity)) {
8073 newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
8074 } else {
8075 newRoot = updateVNode(
8076 newRoot,
8077 list.__ownerID,
8078 list._level,
8079 index,
8080 value,
8081 didAlter
8082 );
8083 }
8084
8085 if (!didAlter.value) {
8086 return list;
8087 }
8088
8089 if (list.__ownerID) {
8090 list._root = newRoot;
8091 list._tail = newTail;
8092 list.__hash = undefined;
8093 list.__altered = true;
8094 return list;
8095 }
8096 return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
8097}
8098
8099function updateVNode(node, ownerID, level, index, value, didAlter) {
8100 var idx = (index >>> level) & MASK;
8101 var nodeHas = node && idx < node.array.length;
8102 if (!nodeHas && value === undefined) {
8103 return node;
8104 }
8105
8106 var newNode;
8107
8108 if (level > 0) {
8109 var lowerNode = node && node.array[idx];
8110 var newLowerNode = updateVNode(
8111 lowerNode,
8112 ownerID,
8113 level - SHIFT,
8114 index,
8115 value,
8116 didAlter
8117 );
8118 if (newLowerNode === lowerNode) {
8119 return node;
8120 }
8121 newNode = editableVNode(node, ownerID);
8122 newNode.array[idx] = newLowerNode;
8123 return newNode;
8124 }
8125
8126 if (nodeHas && node.array[idx] === value) {
8127 return node;
8128 }
8129
8130 if (didAlter) {
8131 SetRef(didAlter);
8132 }
8133
8134 newNode = editableVNode(node, ownerID);
8135 if (value === undefined && idx === newNode.array.length - 1) {
8136 newNode.array.pop();
8137 } else {
8138 newNode.array[idx] = value;
8139 }
8140 return newNode;
8141}
8142
8143function editableVNode(node, ownerID) {
8144 if (ownerID && node && ownerID === node.ownerID) {
8145 return node;
8146 }
8147 return new VNode(node ? node.array.slice() : [], ownerID);
8148}
8149
8150function listNodeFor(list, rawIndex) {
8151 if (rawIndex >= getTailOffset(list._capacity)) {
8152 return list._tail;
8153 }
8154 if (rawIndex < 1 << (list._level + SHIFT)) {
8155 var node = list._root;
8156 var level = list._level;
8157 while (node && level > 0) {
8158 node = node.array[(rawIndex >>> level) & MASK];
8159 level -= SHIFT;
8160 }
8161 return node;
8162 }
8163}
8164
8165function setListBounds(list, begin, end) {
8166 // Sanitize begin & end using this shorthand for ToInt32(argument)
8167 // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
8168 if (begin !== undefined) {
8169 begin |= 0;
8170 }
8171 if (end !== undefined) {
8172 end |= 0;
8173 }
8174 var owner = list.__ownerID || new OwnerID();
8175 var oldOrigin = list._origin;
8176 var oldCapacity = list._capacity;
8177 var newOrigin = oldOrigin + begin;
8178 var newCapacity =
8179 end === undefined
8180 ? oldCapacity
8181 : end < 0
8182 ? oldCapacity + end
8183 : oldOrigin + end;
8184 if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
8185 return list;
8186 }
8187
8188 // If it's going to end after it starts, it's empty.
8189 if (newOrigin >= newCapacity) {
8190 return list.clear();
8191 }
8192
8193 var newLevel = list._level;
8194 var newRoot = list._root;
8195
8196 // New origin might need creating a higher root.
8197 var offsetShift = 0;
8198 while (newOrigin + offsetShift < 0) {
8199 newRoot = new VNode(
8200 newRoot && newRoot.array.length ? [undefined, newRoot] : [],
8201 owner
8202 );
8203 newLevel += SHIFT;
8204 offsetShift += 1 << newLevel;
8205 }
8206 if (offsetShift) {
8207 newOrigin += offsetShift;
8208 oldOrigin += offsetShift;
8209 newCapacity += offsetShift;
8210 oldCapacity += offsetShift;
8211 }
8212
8213 var oldTailOffset = getTailOffset(oldCapacity);
8214 var newTailOffset = getTailOffset(newCapacity);
8215
8216 // New size might need creating a higher root.
8217 while (newTailOffset >= 1 << (newLevel + SHIFT)) {
8218 newRoot = new VNode(
8219 newRoot && newRoot.array.length ? [newRoot] : [],
8220 owner
8221 );
8222 newLevel += SHIFT;
8223 }
8224
8225 // Locate or create the new tail.
8226 var oldTail = list._tail;
8227 var newTail =
8228 newTailOffset < oldTailOffset
8229 ? listNodeFor(list, newCapacity - 1)
8230 : newTailOffset > oldTailOffset
8231 ? new VNode([], owner)
8232 : oldTail;
8233
8234 // Merge Tail into tree.
8235 if (
8236 oldTail &&
8237 newTailOffset > oldTailOffset &&
8238 newOrigin < oldCapacity &&
8239 oldTail.array.length
8240 ) {
8241 newRoot = editableVNode(newRoot, owner);
8242 var node = newRoot;
8243 for (var level = newLevel; level > SHIFT; level -= SHIFT) {
8244 var idx = (oldTailOffset >>> level) & MASK;
8245 node = node.array[idx] = editableVNode(node.array[idx], owner);
8246 }
8247 node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
8248 }
8249
8250 // If the size has been reduced, there's a chance the tail needs to be trimmed.
8251 if (newCapacity < oldCapacity) {
8252 newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
8253 }
8254
8255 // If the new origin is within the tail, then we do not need a root.
8256 if (newOrigin >= newTailOffset) {
8257 newOrigin -= newTailOffset;
8258 newCapacity -= newTailOffset;
8259 newLevel = SHIFT;
8260 newRoot = null;
8261 newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);
8262
8263 // Otherwise, if the root has been trimmed, garbage collect.
8264 } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
8265 offsetShift = 0;
8266
8267 // Identify the new top root node of the subtree of the old root.
8268 while (newRoot) {
8269 var beginIndex = (newOrigin >>> newLevel) & MASK;
8270 if ((beginIndex !== newTailOffset >>> newLevel) & MASK) {
8271 break;
8272 }
8273 if (beginIndex) {
8274 offsetShift += (1 << newLevel) * beginIndex;
8275 }
8276 newLevel -= SHIFT;
8277 newRoot = newRoot.array[beginIndex];
8278 }
8279
8280 // Trim the new sides of the new root.
8281 if (newRoot && newOrigin > oldOrigin) {
8282 newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
8283 }
8284 if (newRoot && newTailOffset < oldTailOffset) {
8285 newRoot = newRoot.removeAfter(
8286 owner,
8287 newLevel,
8288 newTailOffset - offsetShift
8289 );
8290 }
8291 if (offsetShift) {
8292 newOrigin -= offsetShift;
8293 newCapacity -= offsetShift;
8294 }
8295 }
8296
8297 if (list.__ownerID) {
8298 list.size = newCapacity - newOrigin;
8299 list._origin = newOrigin;
8300 list._capacity = newCapacity;
8301 list._level = newLevel;
8302 list._root = newRoot;
8303 list._tail = newTail;
8304 list.__hash = undefined;
8305 list.__altered = true;
8306 return list;
8307 }
8308 return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
8309}
8310
8311function getTailOffset(size) {
8312 return size < SIZE ? 0 : ((size - 1) >>> SHIFT) << SHIFT;
8313}
8314
8315var OrderedMap = /*@__PURE__*/(function (Map$$1) {
8316 function OrderedMap(value) {
8317 return value === null || value === undefined
8318 ? emptyOrderedMap()
8319 : isOrderedMap(value)
8320 ? value
8321 : emptyOrderedMap().withMutations(function (map) {
8322 var iter = KeyedCollection(value);
8323 assertNotInfinite(iter.size);
8324 iter.forEach(function (v, k) { return map.set(k, v); });
8325 });
8326 }
8327
8328 if ( Map$$1 ) OrderedMap.__proto__ = Map$$1;
8329 OrderedMap.prototype = Object.create( Map$$1 && Map$$1.prototype );
8330 OrderedMap.prototype.constructor = OrderedMap;
8331
8332 OrderedMap.of = function of (/*...values*/) {
8333 return this(arguments);
8334 };
8335
8336 OrderedMap.prototype.toString = function toString () {
8337 return this.__toString('OrderedMap {', '}');
8338 };
8339
8340 // @pragma Access
8341
8342 OrderedMap.prototype.get = function get (k, notSetValue) {
8343 var index = this._map.get(k);
8344 return index !== undefined ? this._list.get(index)[1] : notSetValue;
8345 };
8346
8347 // @pragma Modification
8348
8349 OrderedMap.prototype.clear = function clear () {
8350 if (this.size === 0) {
8351 return this;
8352 }
8353 if (this.__ownerID) {
8354 this.size = 0;
8355 this._map.clear();
8356 this._list.clear();
8357 return this;
8358 }
8359 return emptyOrderedMap();
8360 };
8361
8362 OrderedMap.prototype.set = function set (k, v) {
8363 return updateOrderedMap(this, k, v);
8364 };
8365
8366 OrderedMap.prototype.remove = function remove (k) {
8367 return updateOrderedMap(this, k, NOT_SET);
8368 };
8369
8370 OrderedMap.prototype.wasAltered = function wasAltered () {
8371 return this._map.wasAltered() || this._list.wasAltered();
8372 };
8373
8374 OrderedMap.prototype.__iterate = function __iterate (fn, reverse) {
8375 var this$1 = this;
8376
8377 return this._list.__iterate(
8378 function (entry) { return entry && fn(entry[1], entry[0], this$1); },
8379 reverse
8380 );
8381 };
8382
8383 OrderedMap.prototype.__iterator = function __iterator (type, reverse) {
8384 return this._list.fromEntrySeq().__iterator(type, reverse);
8385 };
8386
8387 OrderedMap.prototype.__ensureOwner = function __ensureOwner (ownerID) {
8388 if (ownerID === this.__ownerID) {
8389 return this;
8390 }
8391 var newMap = this._map.__ensureOwner(ownerID);
8392 var newList = this._list.__ensureOwner(ownerID);
8393 if (!ownerID) {
8394 if (this.size === 0) {
8395 return emptyOrderedMap();
8396 }
8397 this.__ownerID = ownerID;
8398 this._map = newMap;
8399 this._list = newList;
8400 return this;
8401 }
8402 return makeOrderedMap(newMap, newList, ownerID, this.__hash);
8403 };
8404
8405 return OrderedMap;
8406}(Map$1));
8407
8408OrderedMap.isOrderedMap = isOrderedMap;
8409
8410OrderedMap.prototype[IS_ORDERED_SYMBOL] = true;
8411OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;
8412
8413function makeOrderedMap(map, list, ownerID, hash) {
8414 var omap = Object.create(OrderedMap.prototype);
8415 omap.size = map ? map.size : 0;
8416 omap._map = map;
8417 omap._list = list;
8418 omap.__ownerID = ownerID;
8419 omap.__hash = hash;
8420 return omap;
8421}
8422
8423var EMPTY_ORDERED_MAP;
8424function emptyOrderedMap() {
8425 return (
8426 EMPTY_ORDERED_MAP ||
8427 (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()))
8428 );
8429}
8430
8431function updateOrderedMap(omap, k, v) {
8432 var map = omap._map;
8433 var list = omap._list;
8434 var i = map.get(k);
8435 var has = i !== undefined;
8436 var newMap;
8437 var newList;
8438 if (v === NOT_SET) {
8439 // removed
8440 if (!has) {
8441 return omap;
8442 }
8443 if (list.size >= SIZE && list.size >= map.size * 2) {
8444 newList = list.filter(function (entry, idx) { return entry !== undefined && i !== idx; });
8445 newMap = newList
8446 .toKeyedSeq()
8447 .map(function (entry) { return entry[0]; })
8448 .flip()
8449 .toMap();
8450 if (omap.__ownerID) {
8451 newMap.__ownerID = newList.__ownerID = omap.__ownerID;
8452 }
8453 } else {
8454 newMap = map.remove(k);
8455 newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
8456 }
8457 } else if (has) {
8458 if (v === list.get(i)[1]) {
8459 return omap;
8460 }
8461 newMap = map;
8462 newList = list.set(i, [k, v]);
8463 } else {
8464 newMap = map.set(k, list.size);
8465 newList = list.set(list.size, [k, v]);
8466 }
8467 if (omap.__ownerID) {
8468 omap.size = newMap.size;
8469 omap._map = newMap;
8470 omap._list = newList;
8471 omap.__hash = undefined;
8472 return omap;
8473 }
8474 return makeOrderedMap(newMap, newList);
8475}
8476
8477var IS_STACK_SYMBOL = '@@__IMMUTABLE_STACK__@@';
8478
8479function isStack(maybeStack) {
8480 return Boolean(maybeStack && maybeStack[IS_STACK_SYMBOL]);
8481}
8482
8483var Stack = /*@__PURE__*/(function (IndexedCollection$$1) {
8484 function Stack(value) {
8485 return value === null || value === undefined
8486 ? emptyStack()
8487 : isStack(value)
8488 ? value
8489 : emptyStack().pushAll(value);
8490 }
8491
8492 if ( IndexedCollection$$1 ) Stack.__proto__ = IndexedCollection$$1;
8493 Stack.prototype = Object.create( IndexedCollection$$1 && IndexedCollection$$1.prototype );
8494 Stack.prototype.constructor = Stack;
8495
8496 Stack.of = function of (/*...values*/) {
8497 return this(arguments);
8498 };
8499
8500 Stack.prototype.toString = function toString () {
8501 return this.__toString('Stack [', ']');
8502 };
8503
8504 // @pragma Access
8505
8506 Stack.prototype.get = function get (index, notSetValue) {
8507 var head = this._head;
8508 index = wrapIndex(this, index);
8509 while (head && index--) {
8510 head = head.next;
8511 }
8512 return head ? head.value : notSetValue;
8513 };
8514
8515 Stack.prototype.peek = function peek () {
8516 return this._head && this._head.value;
8517 };
8518
8519 // @pragma Modification
8520
8521 Stack.prototype.push = function push (/*...values*/) {
8522 var arguments$1 = arguments;
8523
8524 if (arguments.length === 0) {
8525 return this;
8526 }
8527 var newSize = this.size + arguments.length;
8528 var head = this._head;
8529 for (var ii = arguments.length - 1; ii >= 0; ii--) {
8530 head = {
8531 value: arguments$1[ii],
8532 next: head,
8533 };
8534 }
8535 if (this.__ownerID) {
8536 this.size = newSize;
8537 this._head = head;
8538 this.__hash = undefined;
8539 this.__altered = true;
8540 return this;
8541 }
8542 return makeStack(newSize, head);
8543 };
8544
8545 Stack.prototype.pushAll = function pushAll (iter) {
8546 iter = IndexedCollection$$1(iter);
8547 if (iter.size === 0) {
8548 return this;
8549 }
8550 if (this.size === 0 && isStack(iter)) {
8551 return iter;
8552 }
8553 assertNotInfinite(iter.size);
8554 var newSize = this.size;
8555 var head = this._head;
8556 iter.__iterate(function (value) {
8557 newSize++;
8558 head = {
8559 value: value,
8560 next: head,
8561 };
8562 }, /* reverse */ true);
8563 if (this.__ownerID) {
8564 this.size = newSize;
8565 this._head = head;
8566 this.__hash = undefined;
8567 this.__altered = true;
8568 return this;
8569 }
8570 return makeStack(newSize, head);
8571 };
8572
8573 Stack.prototype.pop = function pop () {
8574 return this.slice(1);
8575 };
8576
8577 Stack.prototype.clear = function clear () {
8578 if (this.size === 0) {
8579 return this;
8580 }
8581 if (this.__ownerID) {
8582 this.size = 0;
8583 this._head = undefined;
8584 this.__hash = undefined;
8585 this.__altered = true;
8586 return this;
8587 }
8588 return emptyStack();
8589 };
8590
8591 Stack.prototype.slice = function slice (begin, end) {
8592 if (wholeSlice(begin, end, this.size)) {
8593 return this;
8594 }
8595 var resolvedBegin = resolveBegin(begin, this.size);
8596 var resolvedEnd = resolveEnd(end, this.size);
8597 if (resolvedEnd !== this.size) {
8598 // super.slice(begin, end);
8599 return IndexedCollection$$1.prototype.slice.call(this, begin, end);
8600 }
8601 var newSize = this.size - resolvedBegin;
8602 var head = this._head;
8603 while (resolvedBegin--) {
8604 head = head.next;
8605 }
8606 if (this.__ownerID) {
8607 this.size = newSize;
8608 this._head = head;
8609 this.__hash = undefined;
8610 this.__altered = true;
8611 return this;
8612 }
8613 return makeStack(newSize, head);
8614 };
8615
8616 // @pragma Mutability
8617
8618 Stack.prototype.__ensureOwner = function __ensureOwner (ownerID) {
8619 if (ownerID === this.__ownerID) {
8620 return this;
8621 }
8622 if (!ownerID) {
8623 if (this.size === 0) {
8624 return emptyStack();
8625 }
8626 this.__ownerID = ownerID;
8627 this.__altered = false;
8628 return this;
8629 }
8630 return makeStack(this.size, this._head, ownerID, this.__hash);
8631 };
8632
8633 // @pragma Iteration
8634
8635 Stack.prototype.__iterate = function __iterate (fn, reverse) {
8636 var this$1 = this;
8637
8638 if (reverse) {
8639 return new ArraySeq(this.toArray()).__iterate(
8640 function (v, k) { return fn(v, k, this$1); },
8641 reverse
8642 );
8643 }
8644 var iterations = 0;
8645 var node = this._head;
8646 while (node) {
8647 if (fn(node.value, iterations++, this) === false) {
8648 break;
8649 }
8650 node = node.next;
8651 }
8652 return iterations;
8653 };
8654
8655 Stack.prototype.__iterator = function __iterator (type, reverse) {
8656 if (reverse) {
8657 return new ArraySeq(this.toArray()).__iterator(type, reverse);
8658 }
8659 var iterations = 0;
8660 var node = this._head;
8661 return new Iterator(function () {
8662 if (node) {
8663 var value = node.value;
8664 node = node.next;
8665 return iteratorValue(type, iterations++, value);
8666 }
8667 return iteratorDone();
8668 });
8669 };
8670
8671 return Stack;
8672}(IndexedCollection));
8673
8674Stack.isStack = isStack;
8675
8676var StackPrototype = Stack.prototype;
8677StackPrototype[IS_STACK_SYMBOL] = true;
8678StackPrototype.shift = StackPrototype.pop;
8679StackPrototype.unshift = StackPrototype.push;
8680StackPrototype.unshiftAll = StackPrototype.pushAll;
8681StackPrototype.withMutations = withMutations;
8682StackPrototype.wasAltered = wasAltered;
8683StackPrototype.asImmutable = asImmutable;
8684StackPrototype['@@transducer/init'] = StackPrototype.asMutable = asMutable;
8685StackPrototype['@@transducer/step'] = function(result, arr) {
8686 return result.unshift(arr);
8687};
8688StackPrototype['@@transducer/result'] = function(obj) {
8689 return obj.asImmutable();
8690};
8691
8692function makeStack(size, head, ownerID, hash) {
8693 var map = Object.create(StackPrototype);
8694 map.size = size;
8695 map._head = head;
8696 map.__ownerID = ownerID;
8697 map.__hash = hash;
8698 map.__altered = false;
8699 return map;
8700}
8701
8702var EMPTY_STACK;
8703function emptyStack() {
8704 return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
8705}
8706
8707var IS_SET_SYMBOL = '@@__IMMUTABLE_SET__@@';
8708
8709function isSet(maybeSet) {
8710 return Boolean(maybeSet && maybeSet[IS_SET_SYMBOL]);
8711}
8712
8713function isOrderedSet(maybeOrderedSet) {
8714 return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
8715}
8716
8717function deepEqual(a, b) {
8718 if (a === b) {
8719 return true;
8720 }
8721
8722 if (
8723 !isCollection(b) ||
8724 (a.size !== undefined && b.size !== undefined && a.size !== b.size) ||
8725 (a.__hash !== undefined &&
8726 b.__hash !== undefined &&
8727 a.__hash !== b.__hash) ||
8728 isKeyed(a) !== isKeyed(b) ||
8729 isIndexed(a) !== isIndexed(b) ||
8730 isOrdered(a) !== isOrdered(b)
8731 ) {
8732 return false;
8733 }
8734
8735 if (a.size === 0 && b.size === 0) {
8736 return true;
8737 }
8738
8739 var notAssociative = !isAssociative(a);
8740
8741 if (isOrdered(a)) {
8742 var entries = a.entries();
8743 return (
8744 b.every(function (v, k) {
8745 var entry = entries.next().value;
8746 return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
8747 }) && entries.next().done
8748 );
8749 }
8750
8751 var flipped = false;
8752
8753 if (a.size === undefined) {
8754 if (b.size === undefined) {
8755 if (typeof a.cacheResult === 'function') {
8756 a.cacheResult();
8757 }
8758 } else {
8759 flipped = true;
8760 var _ = a;
8761 a = b;
8762 b = _;
8763 }
8764 }
8765
8766 var allEqual = true;
8767 var bSize = b.__iterate(function (v, k) {
8768 if (
8769 notAssociative
8770 ? !a.has(v)
8771 : flipped
8772 ? !is(v, a.get(k, NOT_SET))
8773 : !is(a.get(k, NOT_SET), v)
8774 ) {
8775 allEqual = false;
8776 return false;
8777 }
8778 });
8779
8780 return allEqual && a.size === bSize;
8781}
8782
8783/**
8784 * Contributes additional methods to a constructor
8785 */
8786function mixin(ctor, methods) {
8787 var keyCopier = function (key) {
8788 ctor.prototype[key] = methods[key];
8789 };
8790 Object.keys(methods).forEach(keyCopier);
8791 Object.getOwnPropertySymbols &&
8792 Object.getOwnPropertySymbols(methods).forEach(keyCopier);
8793 return ctor;
8794}
8795
8796function toJS(value) {
8797 if (!value || typeof value !== 'object') {
8798 return value;
8799 }
8800 if (!isCollection(value)) {
8801 if (!isDataStructure(value)) {
8802 return value;
8803 }
8804 value = Seq(value);
8805 }
8806 if (isKeyed(value)) {
8807 var result$1 = {};
8808 value.__iterate(function (v, k) {
8809 result$1[k] = toJS(v);
8810 });
8811 return result$1;
8812 }
8813 var result = [];
8814 value.__iterate(function (v) {
8815 result.push(toJS(v));
8816 });
8817 return result;
8818}
8819
8820var Set$1 = /*@__PURE__*/(function (SetCollection$$1) {
8821 function Set(value) {
8822 return value === null || value === undefined
8823 ? emptySet()
8824 : isSet(value) && !isOrdered(value)
8825 ? value
8826 : emptySet().withMutations(function (set) {
8827 var iter = SetCollection$$1(value);
8828 assertNotInfinite(iter.size);
8829 iter.forEach(function (v) { return set.add(v); });
8830 });
8831 }
8832
8833 if ( SetCollection$$1 ) Set.__proto__ = SetCollection$$1;
8834 Set.prototype = Object.create( SetCollection$$1 && SetCollection$$1.prototype );
8835 Set.prototype.constructor = Set;
8836
8837 Set.of = function of (/*...values*/) {
8838 return this(arguments);
8839 };
8840
8841 Set.fromKeys = function fromKeys (value) {
8842 return this(KeyedCollection(value).keySeq());
8843 };
8844
8845 Set.intersect = function intersect (sets) {
8846 sets = Collection(sets).toArray();
8847 return sets.length
8848 ? SetPrototype.intersect.apply(Set(sets.pop()), sets)
8849 : emptySet();
8850 };
8851
8852 Set.union = function union (sets) {
8853 sets = Collection(sets).toArray();
8854 return sets.length
8855 ? SetPrototype.union.apply(Set(sets.pop()), sets)
8856 : emptySet();
8857 };
8858
8859 Set.prototype.toString = function toString () {
8860 return this.__toString('Set {', '}');
8861 };
8862
8863 // @pragma Access
8864
8865 Set.prototype.has = function has (value) {
8866 return this._map.has(value);
8867 };
8868
8869 // @pragma Modification
8870
8871 Set.prototype.add = function add (value) {
8872 return updateSet(this, this._map.set(value, value));
8873 };
8874
8875 Set.prototype.remove = function remove (value) {
8876 return updateSet(this, this._map.remove(value));
8877 };
8878
8879 Set.prototype.clear = function clear () {
8880 return updateSet(this, this._map.clear());
8881 };
8882
8883 // @pragma Composition
8884
8885 Set.prototype.map = function map (mapper, context) {
8886 var this$1 = this;
8887
8888 var removes = [];
8889 var adds = [];
8890 this.forEach(function (value) {
8891 var mapped = mapper.call(context, value, value, this$1);
8892 if (mapped !== value) {
8893 removes.push(value);
8894 adds.push(mapped);
8895 }
8896 });
8897 return this.withMutations(function (set) {
8898 removes.forEach(function (value) { return set.remove(value); });
8899 adds.forEach(function (value) { return set.add(value); });
8900 });
8901 };
8902
8903 Set.prototype.union = function union () {
8904 var iters = [], len = arguments.length;
8905 while ( len-- ) iters[ len ] = arguments[ len ];
8906
8907 iters = iters.filter(function (x) { return x.size !== 0; });
8908 if (iters.length === 0) {
8909 return this;
8910 }
8911 if (this.size === 0 && !this.__ownerID && iters.length === 1) {
8912 return this.constructor(iters[0]);
8913 }
8914 return this.withMutations(function (set) {
8915 for (var ii = 0; ii < iters.length; ii++) {
8916 SetCollection$$1(iters[ii]).forEach(function (value) { return set.add(value); });
8917 }
8918 });
8919 };
8920
8921 Set.prototype.intersect = function intersect () {
8922 var iters = [], len = arguments.length;
8923 while ( len-- ) iters[ len ] = arguments[ len ];
8924
8925 if (iters.length === 0) {
8926 return this;
8927 }
8928 iters = iters.map(function (iter) { return SetCollection$$1(iter); });
8929 var toRemove = [];
8930 this.forEach(function (value) {
8931 if (!iters.every(function (iter) { return iter.includes(value); })) {
8932 toRemove.push(value);
8933 }
8934 });
8935 return this.withMutations(function (set) {
8936 toRemove.forEach(function (value) {
8937 set.remove(value);
8938 });
8939 });
8940 };
8941
8942 Set.prototype.subtract = function subtract () {
8943 var iters = [], len = arguments.length;
8944 while ( len-- ) iters[ len ] = arguments[ len ];
8945
8946 if (iters.length === 0) {
8947 return this;
8948 }
8949 iters = iters.map(function (iter) { return SetCollection$$1(iter); });
8950 var toRemove = [];
8951 this.forEach(function (value) {
8952 if (iters.some(function (iter) { return iter.includes(value); })) {
8953 toRemove.push(value);
8954 }
8955 });
8956 return this.withMutations(function (set) {
8957 toRemove.forEach(function (value) {
8958 set.remove(value);
8959 });
8960 });
8961 };
8962
8963 Set.prototype.sort = function sort (comparator) {
8964 // Late binding
8965 return OrderedSet(sortFactory(this, comparator));
8966 };
8967
8968 Set.prototype.sortBy = function sortBy (mapper, comparator) {
8969 // Late binding
8970 return OrderedSet(sortFactory(this, comparator, mapper));
8971 };
8972
8973 Set.prototype.wasAltered = function wasAltered () {
8974 return this._map.wasAltered();
8975 };
8976
8977 Set.prototype.__iterate = function __iterate (fn, reverse) {
8978 var this$1 = this;
8979
8980 return this._map.__iterate(function (k) { return fn(k, k, this$1); }, reverse);
8981 };
8982
8983 Set.prototype.__iterator = function __iterator (type, reverse) {
8984 return this._map.__iterator(type, reverse);
8985 };
8986
8987 Set.prototype.__ensureOwner = function __ensureOwner (ownerID) {
8988 if (ownerID === this.__ownerID) {
8989 return this;
8990 }
8991 var newMap = this._map.__ensureOwner(ownerID);
8992 if (!ownerID) {
8993 if (this.size === 0) {
8994 return this.__empty();
8995 }
8996 this.__ownerID = ownerID;
8997 this._map = newMap;
8998 return this;
8999 }
9000 return this.__make(newMap, ownerID);
9001 };
9002
9003 return Set;
9004}(SetCollection));
9005
9006Set$1.isSet = isSet;
9007
9008var SetPrototype = Set$1.prototype;
9009SetPrototype[IS_SET_SYMBOL] = true;
9010SetPrototype[DELETE] = SetPrototype.remove;
9011SetPrototype.merge = SetPrototype.concat = SetPrototype.union;
9012SetPrototype.withMutations = withMutations;
9013SetPrototype.asImmutable = asImmutable;
9014SetPrototype['@@transducer/init'] = SetPrototype.asMutable = asMutable;
9015SetPrototype['@@transducer/step'] = function(result, arr) {
9016 return result.add(arr);
9017};
9018SetPrototype['@@transducer/result'] = function(obj) {
9019 return obj.asImmutable();
9020};
9021
9022SetPrototype.__empty = emptySet;
9023SetPrototype.__make = makeSet;
9024
9025function updateSet(set, newMap) {
9026 if (set.__ownerID) {
9027 set.size = newMap.size;
9028 set._map = newMap;
9029 return set;
9030 }
9031 return newMap === set._map
9032 ? set
9033 : newMap.size === 0
9034 ? set.__empty()
9035 : set.__make(newMap);
9036}
9037
9038function makeSet(map, ownerID) {
9039 var set = Object.create(SetPrototype);
9040 set.size = map ? map.size : 0;
9041 set._map = map;
9042 set.__ownerID = ownerID;
9043 return set;
9044}
9045
9046var EMPTY_SET;
9047function emptySet() {
9048 return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
9049}
9050
9051/**
9052 * Returns a lazy seq of nums from start (inclusive) to end
9053 * (exclusive), by step, where start defaults to 0, step to 1, and end to
9054 * infinity. When start is equal to end, returns empty list.
9055 */
9056var Range = /*@__PURE__*/(function (IndexedSeq$$1) {
9057 function Range(start, end, step) {
9058 if (!(this instanceof Range)) {
9059 return new Range(start, end, step);
9060 }
9061 invariant(step !== 0, 'Cannot step a Range by 0');
9062 start = start || 0;
9063 if (end === undefined) {
9064 end = Infinity;
9065 }
9066 step = step === undefined ? 1 : Math.abs(step);
9067 if (end < start) {
9068 step = -step;
9069 }
9070 this._start = start;
9071 this._end = end;
9072 this._step = step;
9073 this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
9074 if (this.size === 0) {
9075 if (EMPTY_RANGE) {
9076 return EMPTY_RANGE;
9077 }
9078 EMPTY_RANGE = this;
9079 }
9080 }
9081
9082 if ( IndexedSeq$$1 ) Range.__proto__ = IndexedSeq$$1;
9083 Range.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
9084 Range.prototype.constructor = Range;
9085
9086 Range.prototype.toString = function toString () {
9087 if (this.size === 0) {
9088 return 'Range []';
9089 }
9090 return (
9091 'Range [ ' +
9092 this._start +
9093 '...' +
9094 this._end +
9095 (this._step !== 1 ? ' by ' + this._step : '') +
9096 ' ]'
9097 );
9098 };
9099
9100 Range.prototype.get = function get (index, notSetValue) {
9101 return this.has(index)
9102 ? this._start + wrapIndex(this, index) * this._step
9103 : notSetValue;
9104 };
9105
9106 Range.prototype.includes = function includes (searchValue) {
9107 var possibleIndex = (searchValue - this._start) / this._step;
9108 return (
9109 possibleIndex >= 0 &&
9110 possibleIndex < this.size &&
9111 possibleIndex === Math.floor(possibleIndex)
9112 );
9113 };
9114
9115 Range.prototype.slice = function slice (begin, end) {
9116 if (wholeSlice(begin, end, this.size)) {
9117 return this;
9118 }
9119 begin = resolveBegin(begin, this.size);
9120 end = resolveEnd(end, this.size);
9121 if (end <= begin) {
9122 return new Range(0, 0);
9123 }
9124 return new Range(
9125 this.get(begin, this._end),
9126 this.get(end, this._end),
9127 this._step
9128 );
9129 };
9130
9131 Range.prototype.indexOf = function indexOf (searchValue) {
9132 var offsetValue = searchValue - this._start;
9133 if (offsetValue % this._step === 0) {
9134 var index = offsetValue / this._step;
9135 if (index >= 0 && index < this.size) {
9136 return index;
9137 }
9138 }
9139 return -1;
9140 };
9141
9142 Range.prototype.lastIndexOf = function lastIndexOf (searchValue) {
9143 return this.indexOf(searchValue);
9144 };
9145
9146 Range.prototype.__iterate = function __iterate (fn, reverse) {
9147 var size = this.size;
9148 var step = this._step;
9149 var value = reverse ? this._start + (size - 1) * step : this._start;
9150 var i = 0;
9151 while (i !== size) {
9152 if (fn(value, reverse ? size - ++i : i++, this) === false) {
9153 break;
9154 }
9155 value += reverse ? -step : step;
9156 }
9157 return i;
9158 };
9159
9160 Range.prototype.__iterator = function __iterator (type, reverse) {
9161 var size = this.size;
9162 var step = this._step;
9163 var value = reverse ? this._start + (size - 1) * step : this._start;
9164 var i = 0;
9165 return new Iterator(function () {
9166 if (i === size) {
9167 return iteratorDone();
9168 }
9169 var v = value;
9170 value += reverse ? -step : step;
9171 return iteratorValue(type, reverse ? size - ++i : i++, v);
9172 });
9173 };
9174
9175 Range.prototype.equals = function equals (other) {
9176 return other instanceof Range
9177 ? this._start === other._start &&
9178 this._end === other._end &&
9179 this._step === other._step
9180 : deepEqual(this, other);
9181 };
9182
9183 return Range;
9184}(IndexedSeq));
9185
9186var EMPTY_RANGE;
9187
9188function getIn(collection, searchKeyPath, notSetValue) {
9189 var keyPath = coerceKeyPath(searchKeyPath);
9190 var i = 0;
9191 while (i !== keyPath.length) {
9192 collection = get(collection, keyPath[i++], NOT_SET);
9193 if (collection === NOT_SET) {
9194 return notSetValue;
9195 }
9196 }
9197 return collection;
9198}
9199
9200function getIn$1(searchKeyPath, notSetValue) {
9201 return getIn(this, searchKeyPath, notSetValue);
9202}
9203
9204function hasIn(collection, keyPath) {
9205 return getIn(collection, keyPath, NOT_SET) !== NOT_SET;
9206}
9207
9208function hasIn$1(searchKeyPath) {
9209 return hasIn(this, searchKeyPath);
9210}
9211
9212function toObject() {
9213 assertNotInfinite(this.size);
9214 var object = {};
9215 this.__iterate(function (v, k) {
9216 object[k] = v;
9217 });
9218 return object;
9219}
9220
9221// Note: all of these methods are deprecated.
9222Collection.isIterable = isCollection;
9223Collection.isKeyed = isKeyed;
9224Collection.isIndexed = isIndexed;
9225Collection.isAssociative = isAssociative;
9226Collection.isOrdered = isOrdered;
9227
9228Collection.Iterator = Iterator;
9229
9230mixin(Collection, {
9231 // ### Conversion to other types
9232
9233 toArray: function toArray() {
9234 assertNotInfinite(this.size);
9235 var array = new Array(this.size || 0);
9236 var useTuples = isKeyed(this);
9237 var i = 0;
9238 this.__iterate(function (v, k) {
9239 // Keyed collections produce an array of tuples.
9240 array[i++] = useTuples ? [k, v] : v;
9241 });
9242 return array;
9243 },
9244
9245 toIndexedSeq: function toIndexedSeq() {
9246 return new ToIndexedSequence(this);
9247 },
9248
9249 toJS: function toJS$1() {
9250 return toJS(this);
9251 },
9252
9253 toKeyedSeq: function toKeyedSeq() {
9254 return new ToKeyedSequence(this, true);
9255 },
9256
9257 toMap: function toMap() {
9258 // Use Late Binding here to solve the circular dependency.
9259 return Map$1(this.toKeyedSeq());
9260 },
9261
9262 toObject: toObject,
9263
9264 toOrderedMap: function toOrderedMap() {
9265 // Use Late Binding here to solve the circular dependency.
9266 return OrderedMap(this.toKeyedSeq());
9267 },
9268
9269 toOrderedSet: function toOrderedSet() {
9270 // Use Late Binding here to solve the circular dependency.
9271 return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
9272 },
9273
9274 toSet: function toSet() {
9275 // Use Late Binding here to solve the circular dependency.
9276 return Set$1(isKeyed(this) ? this.valueSeq() : this);
9277 },
9278
9279 toSetSeq: function toSetSeq() {
9280 return new ToSetSequence(this);
9281 },
9282
9283 toSeq: function toSeq() {
9284 return isIndexed(this)
9285 ? this.toIndexedSeq()
9286 : isKeyed(this)
9287 ? this.toKeyedSeq()
9288 : this.toSetSeq();
9289 },
9290
9291 toStack: function toStack() {
9292 // Use Late Binding here to solve the circular dependency.
9293 return Stack(isKeyed(this) ? this.valueSeq() : this);
9294 },
9295
9296 toList: function toList() {
9297 // Use Late Binding here to solve the circular dependency.
9298 return List(isKeyed(this) ? this.valueSeq() : this);
9299 },
9300
9301 // ### Common JavaScript methods and properties
9302
9303 toString: function toString() {
9304 return '[Collection]';
9305 },
9306
9307 __toString: function __toString(head, tail) {
9308 if (this.size === 0) {
9309 return head + tail;
9310 }
9311 return (
9312 head +
9313 ' ' +
9314 this.toSeq()
9315 .map(this.__toStringMapper)
9316 .join(', ') +
9317 ' ' +
9318 tail
9319 );
9320 },
9321
9322 // ### ES6 Collection methods (ES6 Array and Map)
9323
9324 concat: function concat() {
9325 var values = [], len = arguments.length;
9326 while ( len-- ) values[ len ] = arguments[ len ];
9327
9328 return reify(this, concatFactory(this, values));
9329 },
9330
9331 includes: function includes(searchValue) {
9332 return this.some(function (value) { return is(value, searchValue); });
9333 },
9334
9335 entries: function entries() {
9336 return this.__iterator(ITERATE_ENTRIES);
9337 },
9338
9339 every: function every(predicate, context) {
9340 assertNotInfinite(this.size);
9341 var returnValue = true;
9342 this.__iterate(function (v, k, c) {
9343 if (!predicate.call(context, v, k, c)) {
9344 returnValue = false;
9345 return false;
9346 }
9347 });
9348 return returnValue;
9349 },
9350
9351 filter: function filter(predicate, context) {
9352 return reify(this, filterFactory(this, predicate, context, true));
9353 },
9354
9355 find: function find(predicate, context, notSetValue) {
9356 var entry = this.findEntry(predicate, context);
9357 return entry ? entry[1] : notSetValue;
9358 },
9359
9360 forEach: function forEach(sideEffect, context) {
9361 assertNotInfinite(this.size);
9362 return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
9363 },
9364
9365 join: function join(separator) {
9366 assertNotInfinite(this.size);
9367 separator = separator !== undefined ? '' + separator : ',';
9368 var joined = '';
9369 var isFirst = true;
9370 this.__iterate(function (v) {
9371 isFirst ? (isFirst = false) : (joined += separator);
9372 joined += v !== null && v !== undefined ? v.toString() : '';
9373 });
9374 return joined;
9375 },
9376
9377 keys: function keys() {
9378 return this.__iterator(ITERATE_KEYS);
9379 },
9380
9381 map: function map(mapper, context) {
9382 return reify(this, mapFactory(this, mapper, context));
9383 },
9384
9385 reduce: function reduce$1(reducer, initialReduction, context) {
9386 return reduce(
9387 this,
9388 reducer,
9389 initialReduction,
9390 context,
9391 arguments.length < 2,
9392 false
9393 );
9394 },
9395
9396 reduceRight: function reduceRight(reducer, initialReduction, context) {
9397 return reduce(
9398 this,
9399 reducer,
9400 initialReduction,
9401 context,
9402 arguments.length < 2,
9403 true
9404 );
9405 },
9406
9407 reverse: function reverse() {
9408 return reify(this, reverseFactory(this, true));
9409 },
9410
9411 slice: function slice(begin, end) {
9412 return reify(this, sliceFactory(this, begin, end, true));
9413 },
9414
9415 some: function some(predicate, context) {
9416 return !this.every(not(predicate), context);
9417 },
9418
9419 sort: function sort(comparator) {
9420 return reify(this, sortFactory(this, comparator));
9421 },
9422
9423 values: function values() {
9424 return this.__iterator(ITERATE_VALUES);
9425 },
9426
9427 // ### More sequential methods
9428
9429 butLast: function butLast() {
9430 return this.slice(0, -1);
9431 },
9432
9433 isEmpty: function isEmpty() {
9434 return this.size !== undefined ? this.size === 0 : !this.some(function () { return true; });
9435 },
9436
9437 count: function count(predicate, context) {
9438 return ensureSize(
9439 predicate ? this.toSeq().filter(predicate, context) : this
9440 );
9441 },
9442
9443 countBy: function countBy(grouper, context) {
9444 return countByFactory(this, grouper, context);
9445 },
9446
9447 equals: function equals(other) {
9448 return deepEqual(this, other);
9449 },
9450
9451 entrySeq: function entrySeq() {
9452 var collection = this;
9453 if (collection._cache) {
9454 // We cache as an entries array, so we can just return the cache!
9455 return new ArraySeq(collection._cache);
9456 }
9457 var entriesSequence = collection
9458 .toSeq()
9459 .map(entryMapper)
9460 .toIndexedSeq();
9461 entriesSequence.fromEntrySeq = function () { return collection.toSeq(); };
9462 return entriesSequence;
9463 },
9464
9465 filterNot: function filterNot(predicate, context) {
9466 return this.filter(not(predicate), context);
9467 },
9468
9469 findEntry: function findEntry(predicate, context, notSetValue) {
9470 var found = notSetValue;
9471 this.__iterate(function (v, k, c) {
9472 if (predicate.call(context, v, k, c)) {
9473 found = [k, v];
9474 return false;
9475 }
9476 });
9477 return found;
9478 },
9479
9480 findKey: function findKey(predicate, context) {
9481 var entry = this.findEntry(predicate, context);
9482 return entry && entry[0];
9483 },
9484
9485 findLast: function findLast(predicate, context, notSetValue) {
9486 return this.toKeyedSeq()
9487 .reverse()
9488 .find(predicate, context, notSetValue);
9489 },
9490
9491 findLastEntry: function findLastEntry(predicate, context, notSetValue) {
9492 return this.toKeyedSeq()
9493 .reverse()
9494 .findEntry(predicate, context, notSetValue);
9495 },
9496
9497 findLastKey: function findLastKey(predicate, context) {
9498 return this.toKeyedSeq()
9499 .reverse()
9500 .findKey(predicate, context);
9501 },
9502
9503 first: function first(notSetValue) {
9504 return this.find(returnTrue, null, notSetValue);
9505 },
9506
9507 flatMap: function flatMap(mapper, context) {
9508 return reify(this, flatMapFactory(this, mapper, context));
9509 },
9510
9511 flatten: function flatten(depth) {
9512 return reify(this, flattenFactory(this, depth, true));
9513 },
9514
9515 fromEntrySeq: function fromEntrySeq() {
9516 return new FromEntriesSequence(this);
9517 },
9518
9519 get: function get(searchKey, notSetValue) {
9520 return this.find(function (_, key) { return is(key, searchKey); }, undefined, notSetValue);
9521 },
9522
9523 getIn: getIn$1,
9524
9525 groupBy: function groupBy(grouper, context) {
9526 return groupByFactory(this, grouper, context);
9527 },
9528
9529 has: function has(searchKey) {
9530 return this.get(searchKey, NOT_SET) !== NOT_SET;
9531 },
9532
9533 hasIn: hasIn$1,
9534
9535 isSubset: function isSubset(iter) {
9536 iter = typeof iter.includes === 'function' ? iter : Collection(iter);
9537 return this.every(function (value) { return iter.includes(value); });
9538 },
9539
9540 isSuperset: function isSuperset(iter) {
9541 iter = typeof iter.isSubset === 'function' ? iter : Collection(iter);
9542 return iter.isSubset(this);
9543 },
9544
9545 keyOf: function keyOf(searchValue) {
9546 return this.findKey(function (value) { return is(value, searchValue); });
9547 },
9548
9549 keySeq: function keySeq() {
9550 return this.toSeq()
9551 .map(keyMapper)
9552 .toIndexedSeq();
9553 },
9554
9555 last: function last(notSetValue) {
9556 return this.toSeq()
9557 .reverse()
9558 .first(notSetValue);
9559 },
9560
9561 lastKeyOf: function lastKeyOf(searchValue) {
9562 return this.toKeyedSeq()
9563 .reverse()
9564 .keyOf(searchValue);
9565 },
9566
9567 max: function max(comparator) {
9568 return maxFactory(this, comparator);
9569 },
9570
9571 maxBy: function maxBy(mapper, comparator) {
9572 return maxFactory(this, comparator, mapper);
9573 },
9574
9575 min: function min(comparator) {
9576 return maxFactory(
9577 this,
9578 comparator ? neg(comparator) : defaultNegComparator
9579 );
9580 },
9581
9582 minBy: function minBy(mapper, comparator) {
9583 return maxFactory(
9584 this,
9585 comparator ? neg(comparator) : defaultNegComparator,
9586 mapper
9587 );
9588 },
9589
9590 rest: function rest() {
9591 return this.slice(1);
9592 },
9593
9594 skip: function skip(amount) {
9595 return amount === 0 ? this : this.slice(Math.max(0, amount));
9596 },
9597
9598 skipLast: function skipLast(amount) {
9599 return amount === 0 ? this : this.slice(0, -Math.max(0, amount));
9600 },
9601
9602 skipWhile: function skipWhile(predicate, context) {
9603 return reify(this, skipWhileFactory(this, predicate, context, true));
9604 },
9605
9606 skipUntil: function skipUntil(predicate, context) {
9607 return this.skipWhile(not(predicate), context);
9608 },
9609
9610 sortBy: function sortBy(mapper, comparator) {
9611 return reify(this, sortFactory(this, comparator, mapper));
9612 },
9613
9614 take: function take(amount) {
9615 return this.slice(0, Math.max(0, amount));
9616 },
9617
9618 takeLast: function takeLast(amount) {
9619 return this.slice(-Math.max(0, amount));
9620 },
9621
9622 takeWhile: function takeWhile(predicate, context) {
9623 return reify(this, takeWhileFactory(this, predicate, context));
9624 },
9625
9626 takeUntil: function takeUntil(predicate, context) {
9627 return this.takeWhile(not(predicate), context);
9628 },
9629
9630 update: function update(fn) {
9631 return fn(this);
9632 },
9633
9634 valueSeq: function valueSeq() {
9635 return this.toIndexedSeq();
9636 },
9637
9638 // ### Hashable Object
9639
9640 hashCode: function hashCode() {
9641 return this.__hash || (this.__hash = hashCollection(this));
9642 },
9643
9644 // ### Internal
9645
9646 // abstract __iterate(fn, reverse)
9647
9648 // abstract __iterator(type, reverse)
9649});
9650
9651var CollectionPrototype = Collection.prototype;
9652CollectionPrototype[IS_COLLECTION_SYMBOL] = true;
9653CollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.values;
9654CollectionPrototype.toJSON = CollectionPrototype.toArray;
9655CollectionPrototype.__toStringMapper = quoteString;
9656CollectionPrototype.inspect = CollectionPrototype.toSource = function() {
9657 return this.toString();
9658};
9659CollectionPrototype.chain = CollectionPrototype.flatMap;
9660CollectionPrototype.contains = CollectionPrototype.includes;
9661
9662mixin(KeyedCollection, {
9663 // ### More sequential methods
9664
9665 flip: function flip() {
9666 return reify(this, flipFactory(this));
9667 },
9668
9669 mapEntries: function mapEntries(mapper, context) {
9670 var this$1 = this;
9671
9672 var iterations = 0;
9673 return reify(
9674 this,
9675 this.toSeq()
9676 .map(function (v, k) { return mapper.call(context, [k, v], iterations++, this$1); })
9677 .fromEntrySeq()
9678 );
9679 },
9680
9681 mapKeys: function mapKeys(mapper, context) {
9682 var this$1 = this;
9683
9684 return reify(
9685 this,
9686 this.toSeq()
9687 .flip()
9688 .map(function (k, v) { return mapper.call(context, k, v, this$1); })
9689 .flip()
9690 );
9691 },
9692});
9693
9694var KeyedCollectionPrototype = KeyedCollection.prototype;
9695KeyedCollectionPrototype[IS_KEYED_SYMBOL] = true;
9696KeyedCollectionPrototype[ITERATOR_SYMBOL] = CollectionPrototype.entries;
9697KeyedCollectionPrototype.toJSON = toObject;
9698KeyedCollectionPrototype.__toStringMapper = function (v, k) { return quoteString(k) + ': ' + quoteString(v); };
9699
9700mixin(IndexedCollection, {
9701 // ### Conversion to other types
9702
9703 toKeyedSeq: function toKeyedSeq() {
9704 return new ToKeyedSequence(this, false);
9705 },
9706
9707 // ### ES6 Collection methods (ES6 Array and Map)
9708
9709 filter: function filter(predicate, context) {
9710 return reify(this, filterFactory(this, predicate, context, false));
9711 },
9712
9713 findIndex: function findIndex(predicate, context) {
9714 var entry = this.findEntry(predicate, context);
9715 return entry ? entry[0] : -1;
9716 },
9717
9718 indexOf: function indexOf(searchValue) {
9719 var key = this.keyOf(searchValue);
9720 return key === undefined ? -1 : key;
9721 },
9722
9723 lastIndexOf: function lastIndexOf(searchValue) {
9724 var key = this.lastKeyOf(searchValue);
9725 return key === undefined ? -1 : key;
9726 },
9727
9728 reverse: function reverse() {
9729 return reify(this, reverseFactory(this, false));
9730 },
9731
9732 slice: function slice(begin, end) {
9733 return reify(this, sliceFactory(this, begin, end, false));
9734 },
9735
9736 splice: function splice(index, removeNum /*, ...values*/) {
9737 var numArgs = arguments.length;
9738 removeNum = Math.max(removeNum || 0, 0);
9739 if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
9740 return this;
9741 }
9742 // If index is negative, it should resolve relative to the size of the
9743 // collection. However size may be expensive to compute if not cached, so
9744 // only call count() if the number is in fact negative.
9745 index = resolveBegin(index, index < 0 ? this.count() : this.size);
9746 var spliced = this.slice(0, index);
9747 return reify(
9748 this,
9749 numArgs === 1
9750 ? spliced
9751 : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
9752 );
9753 },
9754
9755 // ### More collection methods
9756
9757 findLastIndex: function findLastIndex(predicate, context) {
9758 var entry = this.findLastEntry(predicate, context);
9759 return entry ? entry[0] : -1;
9760 },
9761
9762 first: function first(notSetValue) {
9763 return this.get(0, notSetValue);
9764 },
9765
9766 flatten: function flatten(depth) {
9767 return reify(this, flattenFactory(this, depth, false));
9768 },
9769
9770 get: function get(index, notSetValue) {
9771 index = wrapIndex(this, index);
9772 return index < 0 ||
9773 (this.size === Infinity || (this.size !== undefined && index > this.size))
9774 ? notSetValue
9775 : this.find(function (_, key) { return key === index; }, undefined, notSetValue);
9776 },
9777
9778 has: function has(index) {
9779 index = wrapIndex(this, index);
9780 return (
9781 index >= 0 &&
9782 (this.size !== undefined
9783 ? this.size === Infinity || index < this.size
9784 : this.indexOf(index) !== -1)
9785 );
9786 },
9787
9788 interpose: function interpose(separator) {
9789 return reify(this, interposeFactory(this, separator));
9790 },
9791
9792 interleave: function interleave(/*...collections*/) {
9793 var collections = [this].concat(arrCopy(arguments));
9794 var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, collections);
9795 var interleaved = zipped.flatten(true);
9796 if (zipped.size) {
9797 interleaved.size = zipped.size * collections.length;
9798 }
9799 return reify(this, interleaved);
9800 },
9801
9802 keySeq: function keySeq() {
9803 return Range(0, this.size);
9804 },
9805
9806 last: function last(notSetValue) {
9807 return this.get(-1, notSetValue);
9808 },
9809
9810 skipWhile: function skipWhile(predicate, context) {
9811 return reify(this, skipWhileFactory(this, predicate, context, false));
9812 },
9813
9814 zip: function zip(/*, ...collections */) {
9815 var collections = [this].concat(arrCopy(arguments));
9816 return reify(this, zipWithFactory(this, defaultZipper, collections));
9817 },
9818
9819 zipAll: function zipAll(/*, ...collections */) {
9820 var collections = [this].concat(arrCopy(arguments));
9821 return reify(this, zipWithFactory(this, defaultZipper, collections, true));
9822 },
9823
9824 zipWith: function zipWith(zipper /*, ...collections */) {
9825 var collections = arrCopy(arguments);
9826 collections[0] = this;
9827 return reify(this, zipWithFactory(this, zipper, collections));
9828 },
9829});
9830
9831var IndexedCollectionPrototype = IndexedCollection.prototype;
9832IndexedCollectionPrototype[IS_INDEXED_SYMBOL] = true;
9833IndexedCollectionPrototype[IS_ORDERED_SYMBOL] = true;
9834
9835mixin(SetCollection, {
9836 // ### ES6 Collection methods (ES6 Array and Map)
9837
9838 get: function get(value, notSetValue) {
9839 return this.has(value) ? value : notSetValue;
9840 },
9841
9842 includes: function includes(value) {
9843 return this.has(value);
9844 },
9845
9846 // ### More sequential methods
9847
9848 keySeq: function keySeq() {
9849 return this.valueSeq();
9850 },
9851});
9852
9853SetCollection.prototype.has = CollectionPrototype.includes;
9854SetCollection.prototype.contains = SetCollection.prototype.includes;
9855
9856// Mixin subclasses
9857
9858mixin(KeyedSeq, KeyedCollection.prototype);
9859mixin(IndexedSeq, IndexedCollection.prototype);
9860mixin(SetSeq, SetCollection.prototype);
9861
9862// #pragma Helper functions
9863
9864function reduce(collection, reducer, reduction, context, useFirst, reverse) {
9865 assertNotInfinite(collection.size);
9866 collection.__iterate(function (v, k, c) {
9867 if (useFirst) {
9868 useFirst = false;
9869 reduction = v;
9870 } else {
9871 reduction = reducer.call(context, reduction, v, k, c);
9872 }
9873 }, reverse);
9874 return reduction;
9875}
9876
9877function keyMapper(v, k) {
9878 return k;
9879}
9880
9881function entryMapper(v, k) {
9882 return [k, v];
9883}
9884
9885function not(predicate) {
9886 return function() {
9887 return !predicate.apply(this, arguments);
9888 };
9889}
9890
9891function neg(predicate) {
9892 return function() {
9893 return -predicate.apply(this, arguments);
9894 };
9895}
9896
9897function defaultZipper() {
9898 return arrCopy(arguments);
9899}
9900
9901function defaultNegComparator(a, b) {
9902 return a < b ? 1 : a > b ? -1 : 0;
9903}
9904
9905function hashCollection(collection) {
9906 if (collection.size === Infinity) {
9907 return 0;
9908 }
9909 var ordered = isOrdered(collection);
9910 var keyed = isKeyed(collection);
9911 var h = ordered ? 1 : 0;
9912 var size = collection.__iterate(
9913 keyed
9914 ? ordered
9915 ? function (v, k) {
9916 h = (31 * h + hashMerge(hash(v), hash(k))) | 0;
9917 }
9918 : function (v, k) {
9919 h = (h + hashMerge(hash(v), hash(k))) | 0;
9920 }
9921 : ordered
9922 ? function (v) {
9923 h = (31 * h + hash(v)) | 0;
9924 }
9925 : function (v) {
9926 h = (h + hash(v)) | 0;
9927 }
9928 );
9929 return murmurHashOfSize(size, h);
9930}
9931
9932function murmurHashOfSize(size, h) {
9933 h = imul(h, 0xcc9e2d51);
9934 h = imul((h << 15) | (h >>> -15), 0x1b873593);
9935 h = imul((h << 13) | (h >>> -13), 5);
9936 h = ((h + 0xe6546b64) | 0) ^ size;
9937 h = imul(h ^ (h >>> 16), 0x85ebca6b);
9938 h = imul(h ^ (h >>> 13), 0xc2b2ae35);
9939 h = smi(h ^ (h >>> 16));
9940 return h;
9941}
9942
9943function hashMerge(a, b) {
9944 return (a ^ (b + 0x9e3779b9 + (a << 6) + (a >> 2))) | 0; // int
9945}
9946
9947var OrderedSet = /*@__PURE__*/(function (Set$$1) {
9948 function OrderedSet(value) {
9949 return value === null || value === undefined
9950 ? emptyOrderedSet()
9951 : isOrderedSet(value)
9952 ? value
9953 : emptyOrderedSet().withMutations(function (set) {
9954 var iter = SetCollection(value);
9955 assertNotInfinite(iter.size);
9956 iter.forEach(function (v) { return set.add(v); });
9957 });
9958 }
9959
9960 if ( Set$$1 ) OrderedSet.__proto__ = Set$$1;
9961 OrderedSet.prototype = Object.create( Set$$1 && Set$$1.prototype );
9962 OrderedSet.prototype.constructor = OrderedSet;
9963
9964 OrderedSet.of = function of (/*...values*/) {
9965 return this(arguments);
9966 };
9967
9968 OrderedSet.fromKeys = function fromKeys (value) {
9969 return this(KeyedCollection(value).keySeq());
9970 };
9971
9972 OrderedSet.prototype.toString = function toString () {
9973 return this.__toString('OrderedSet {', '}');
9974 };
9975
9976 return OrderedSet;
9977}(Set$1));
9978
9979OrderedSet.isOrderedSet = isOrderedSet;
9980
9981var OrderedSetPrototype = OrderedSet.prototype;
9982OrderedSetPrototype[IS_ORDERED_SYMBOL] = true;
9983OrderedSetPrototype.zip = IndexedCollectionPrototype.zip;
9984OrderedSetPrototype.zipWith = IndexedCollectionPrototype.zipWith;
9985
9986OrderedSetPrototype.__empty = emptyOrderedSet;
9987OrderedSetPrototype.__make = makeOrderedSet;
9988
9989function makeOrderedSet(map, ownerID) {
9990 var set = Object.create(OrderedSetPrototype);
9991 set.size = map ? map.size : 0;
9992 set._map = map;
9993 set.__ownerID = ownerID;
9994 return set;
9995}
9996
9997var EMPTY_ORDERED_SET;
9998function emptyOrderedSet() {
9999 return (
10000 EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()))
10001 );
10002}
10003
10004var Record = function Record(defaultValues, name) {
10005 var hasInitialized;
10006
10007 var RecordType = function Record(values) {
10008 var this$1 = this;
10009
10010 if (values instanceof RecordType) {
10011 return values;
10012 }
10013 if (!(this instanceof RecordType)) {
10014 return new RecordType(values);
10015 }
10016 if (!hasInitialized) {
10017 hasInitialized = true;
10018 var keys = Object.keys(defaultValues);
10019 var indices = (RecordTypePrototype._indices = {});
10020 // Deprecated: left to attempt not to break any external code which
10021 // relies on a ._name property existing on record instances.
10022 // Use Record.getDescriptiveName() instead
10023 RecordTypePrototype._name = name;
10024 RecordTypePrototype._keys = keys;
10025 RecordTypePrototype._defaultValues = defaultValues;
10026 for (var i = 0; i < keys.length; i++) {
10027 var propName = keys[i];
10028 indices[propName] = i;
10029 if (RecordTypePrototype[propName]) {
10030 /* eslint-disable no-console */
10031 typeof console === 'object' &&
10032 console.warn &&
10033 console.warn(
10034 'Cannot define ' +
10035 recordName(this) +
10036 ' with property "' +
10037 propName +
10038 '" since that property name is part of the Record API.'
10039 );
10040 /* eslint-enable no-console */
10041 } else {
10042 setProp(RecordTypePrototype, propName);
10043 }
10044 }
10045 }
10046 this.__ownerID = undefined;
10047 this._values = List().withMutations(function (l) {
10048 l.setSize(this$1._keys.length);
10049 KeyedCollection(values).forEach(function (v, k) {
10050 l.set(this$1._indices[k], v === this$1._defaultValues[k] ? undefined : v);
10051 });
10052 });
10053 };
10054
10055 var RecordTypePrototype = (RecordType.prototype = Object.create(
10056 RecordPrototype
10057 ));
10058 RecordTypePrototype.constructor = RecordType;
10059
10060 if (name) {
10061 RecordType.displayName = name;
10062 }
10063
10064 return RecordType;
10065};
10066
10067Record.prototype.toString = function toString () {
10068 var str = recordName(this) + ' { ';
10069 var keys = this._keys;
10070 var k;
10071 for (var i = 0, l = keys.length; i !== l; i++) {
10072 k = keys[i];
10073 str += (i ? ', ' : '') + k + ': ' + quoteString(this.get(k));
10074 }
10075 return str + ' }';
10076};
10077
10078Record.prototype.equals = function equals (other) {
10079 return (
10080 this === other ||
10081 (other &&
10082 this._keys === other._keys &&
10083 recordSeq(this).equals(recordSeq(other)))
10084 );
10085};
10086
10087Record.prototype.hashCode = function hashCode () {
10088 return recordSeq(this).hashCode();
10089};
10090
10091// @pragma Access
10092
10093Record.prototype.has = function has (k) {
10094 return this._indices.hasOwnProperty(k);
10095};
10096
10097Record.prototype.get = function get (k, notSetValue) {
10098 if (!this.has(k)) {
10099 return notSetValue;
10100 }
10101 var index = this._indices[k];
10102 var value = this._values.get(index);
10103 return value === undefined ? this._defaultValues[k] : value;
10104};
10105
10106// @pragma Modification
10107
10108Record.prototype.set = function set (k, v) {
10109 if (this.has(k)) {
10110 var newValues = this._values.set(
10111 this._indices[k],
10112 v === this._defaultValues[k] ? undefined : v
10113 );
10114 if (newValues !== this._values && !this.__ownerID) {
10115 return makeRecord(this, newValues);
10116 }
10117 }
10118 return this;
10119};
10120
10121Record.prototype.remove = function remove (k) {
10122 return this.set(k);
10123};
10124
10125Record.prototype.clear = function clear () {
10126 var newValues = this._values.clear().setSize(this._keys.length);
10127 return this.__ownerID ? this : makeRecord(this, newValues);
10128};
10129
10130Record.prototype.wasAltered = function wasAltered () {
10131 return this._values.wasAltered();
10132};
10133
10134Record.prototype.toSeq = function toSeq () {
10135 return recordSeq(this);
10136};
10137
10138Record.prototype.toJS = function toJS$1 () {
10139 return toJS(this);
10140};
10141
10142Record.prototype.entries = function entries () {
10143 return this.__iterator(ITERATE_ENTRIES);
10144};
10145
10146Record.prototype.__iterator = function __iterator (type, reverse) {
10147 return recordSeq(this).__iterator(type, reverse);
10148};
10149
10150Record.prototype.__iterate = function __iterate (fn, reverse) {
10151 return recordSeq(this).__iterate(fn, reverse);
10152};
10153
10154Record.prototype.__ensureOwner = function __ensureOwner (ownerID) {
10155 if (ownerID === this.__ownerID) {
10156 return this;
10157 }
10158 var newValues = this._values.__ensureOwner(ownerID);
10159 if (!ownerID) {
10160 this.__ownerID = ownerID;
10161 this._values = newValues;
10162 return this;
10163 }
10164 return makeRecord(this, newValues, ownerID);
10165};
10166
10167Record.isRecord = isRecord;
10168Record.getDescriptiveName = recordName;
10169var RecordPrototype = Record.prototype;
10170RecordPrototype[IS_RECORD_SYMBOL] = true;
10171RecordPrototype[DELETE] = RecordPrototype.remove;
10172RecordPrototype.deleteIn = RecordPrototype.removeIn = deleteIn;
10173RecordPrototype.getIn = getIn$1;
10174RecordPrototype.hasIn = CollectionPrototype.hasIn;
10175RecordPrototype.merge = merge;
10176RecordPrototype.mergeWith = mergeWith;
10177RecordPrototype.mergeIn = mergeIn;
10178RecordPrototype.mergeDeep = mergeDeep$1;
10179RecordPrototype.mergeDeepWith = mergeDeepWith$1;
10180RecordPrototype.mergeDeepIn = mergeDeepIn;
10181RecordPrototype.setIn = setIn$1;
10182RecordPrototype.update = update$1;
10183RecordPrototype.updateIn = updateIn$1;
10184RecordPrototype.withMutations = withMutations;
10185RecordPrototype.asMutable = asMutable;
10186RecordPrototype.asImmutable = asImmutable;
10187RecordPrototype[ITERATOR_SYMBOL] = RecordPrototype.entries;
10188RecordPrototype.toJSON = RecordPrototype.toObject =
10189 CollectionPrototype.toObject;
10190RecordPrototype.inspect = RecordPrototype.toSource = function() {
10191 return this.toString();
10192};
10193
10194function makeRecord(likeRecord, values, ownerID) {
10195 var record = Object.create(Object.getPrototypeOf(likeRecord));
10196 record._values = values;
10197 record.__ownerID = ownerID;
10198 return record;
10199}
10200
10201function recordName(record) {
10202 return record.constructor.displayName || record.constructor.name || 'Record';
10203}
10204
10205function recordSeq(record) {
10206 return keyedSeqFromValue(record._keys.map(function (k) { return [k, record.get(k)]; }));
10207}
10208
10209function setProp(prototype, name) {
10210 try {
10211 Object.defineProperty(prototype, name, {
10212 get: function() {
10213 return this.get(name);
10214 },
10215 set: function(value) {
10216 invariant(this.__ownerID, 'Cannot set on an immutable record.');
10217 this.set(name, value);
10218 },
10219 });
10220 } catch (error) {
10221 // Object.defineProperty failed. Probably IE8.
10222 }
10223}
10224
10225/**
10226 * Returns a lazy Seq of `value` repeated `times` times. When `times` is
10227 * undefined, returns an infinite sequence of `value`.
10228 */
10229var Repeat = /*@__PURE__*/(function (IndexedSeq$$1) {
10230 function Repeat(value, times) {
10231 if (!(this instanceof Repeat)) {
10232 return new Repeat(value, times);
10233 }
10234 this._value = value;
10235 this.size = times === undefined ? Infinity : Math.max(0, times);
10236 if (this.size === 0) {
10237 if (EMPTY_REPEAT) {
10238 return EMPTY_REPEAT;
10239 }
10240 EMPTY_REPEAT = this;
10241 }
10242 }
10243
10244 if ( IndexedSeq$$1 ) Repeat.__proto__ = IndexedSeq$$1;
10245 Repeat.prototype = Object.create( IndexedSeq$$1 && IndexedSeq$$1.prototype );
10246 Repeat.prototype.constructor = Repeat;
10247
10248 Repeat.prototype.toString = function toString () {
10249 if (this.size === 0) {
10250 return 'Repeat []';
10251 }
10252 return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
10253 };
10254
10255 Repeat.prototype.get = function get (index, notSetValue) {
10256 return this.has(index) ? this._value : notSetValue;
10257 };
10258
10259 Repeat.prototype.includes = function includes (searchValue) {
10260 return is(this._value, searchValue);
10261 };
10262
10263 Repeat.prototype.slice = function slice (begin, end) {
10264 var size = this.size;
10265 return wholeSlice(begin, end, size)
10266 ? this
10267 : new Repeat(
10268 this._value,
10269 resolveEnd(end, size) - resolveBegin(begin, size)
10270 );
10271 };
10272
10273 Repeat.prototype.reverse = function reverse () {
10274 return this;
10275 };
10276
10277 Repeat.prototype.indexOf = function indexOf (searchValue) {
10278 if (is(this._value, searchValue)) {
10279 return 0;
10280 }
10281 return -1;
10282 };
10283
10284 Repeat.prototype.lastIndexOf = function lastIndexOf (searchValue) {
10285 if (is(this._value, searchValue)) {
10286 return this.size;
10287 }
10288 return -1;
10289 };
10290
10291 Repeat.prototype.__iterate = function __iterate (fn, reverse) {
10292 var size = this.size;
10293 var i = 0;
10294 while (i !== size) {
10295 if (fn(this._value, reverse ? size - ++i : i++, this) === false) {
10296 break;
10297 }
10298 }
10299 return i;
10300 };
10301
10302 Repeat.prototype.__iterator = function __iterator (type, reverse) {
10303 var this$1 = this;
10304
10305 var size = this.size;
10306 var i = 0;
10307 return new Iterator(
10308 function () { return i === size
10309 ? iteratorDone()
10310 : iteratorValue(type, reverse ? size - ++i : i++, this$1._value); }
10311 );
10312 };
10313
10314 Repeat.prototype.equals = function equals (other) {
10315 return other instanceof Repeat
10316 ? is(this._value, other._value)
10317 : deepEqual(other);
10318 };
10319
10320 return Repeat;
10321}(IndexedSeq));
10322
10323var EMPTY_REPEAT;
10324
10325function fromJS(value, converter) {
10326 return fromJSWith(
10327 [],
10328 converter || defaultConverter,
10329 value,
10330 '',
10331 converter && converter.length > 2 ? [] : undefined,
10332 { '': value }
10333 );
10334}
10335
10336function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
10337 var toSeq = Array.isArray(value)
10338 ? IndexedSeq
10339 : isPlainObj(value)
10340 ? KeyedSeq
10341 : null;
10342 if (toSeq) {
10343 if (~stack.indexOf(value)) {
10344 throw new TypeError('Cannot convert circular structure to Immutable');
10345 }
10346 stack.push(value);
10347 keyPath && key !== '' && keyPath.push(key);
10348 var converted = converter.call(
10349 parentValue,
10350 key,
10351 toSeq(value).map(function (v, k) { return fromJSWith(stack, converter, v, k, keyPath, value); }
10352 ),
10353 keyPath && keyPath.slice()
10354 );
10355 stack.pop();
10356 keyPath && keyPath.pop();
10357 return converted;
10358 }
10359 return value;
10360}
10361
10362function defaultConverter(k, v) {
10363 return isKeyed(v) ? v.toMap() : v.toList();
10364}
10365
10366var version$1 = "4.0.0-rc.11";
10367
10368var Immutable = {
10369 version: version$1,
10370
10371 Collection: Collection,
10372 // Note: Iterable is deprecated
10373 Iterable: Collection,
10374
10375 Seq: Seq,
10376 Map: Map$1,
10377 OrderedMap: OrderedMap,
10378 List: List,
10379 Stack: Stack,
10380 Set: Set$1,
10381 OrderedSet: OrderedSet,
10382
10383 Record: Record,
10384 Range: Range,
10385 Repeat: Repeat,
10386
10387 is: is,
10388 fromJS: fromJS,
10389 hash: hash,
10390
10391 isImmutable: isImmutable,
10392 isCollection: isCollection,
10393 isKeyed: isKeyed,
10394 isIndexed: isIndexed,
10395 isAssociative: isAssociative,
10396 isOrdered: isOrdered,
10397 isValueObject: isValueObject,
10398 isSeq: isSeq,
10399 isList: isList,
10400 isMap: isMap,
10401 isOrderedMap: isOrderedMap,
10402 isStack: isStack,
10403 isSet: isSet,
10404 isOrderedSet: isOrderedSet,
10405 isRecord: isRecord,
10406
10407 get: get,
10408 getIn: getIn,
10409 has: has,
10410 hasIn: hasIn,
10411 merge: merge$1,
10412 mergeDeep: mergeDeep,
10413 mergeWith: mergeWith$1,
10414 mergeDeepWith: mergeDeepWith,
10415 remove: remove,
10416 removeIn: removeIn,
10417 set: set,
10418 setIn: setIn,
10419 update: update,
10420 updateIn: updateIn,
10421};
10422
10423var OptionTypes;
10424(function (OptionTypes) {
10425 OptionTypes[OptionTypes["IGNORED_LABELS"] = 0] = "IGNORED_LABELS";
10426 OptionTypes[OptionTypes["ACCESSED_NODES"] = 1] = "ACCESSED_NODES";
10427 OptionTypes[OptionTypes["ARGUMENTS_VARIABLES"] = 2] = "ARGUMENTS_VARIABLES";
10428 OptionTypes[OptionTypes["ASSIGNED_NODES"] = 3] = "ASSIGNED_NODES";
10429 OptionTypes[OptionTypes["IGNORE_BREAK_STATEMENTS"] = 4] = "IGNORE_BREAK_STATEMENTS";
10430 OptionTypes[OptionTypes["IGNORE_RETURN_AWAIT_YIELD"] = 5] = "IGNORE_RETURN_AWAIT_YIELD";
10431 OptionTypes[OptionTypes["NODES_CALLED_AT_PATH_WITH_OPTIONS"] = 6] = "NODES_CALLED_AT_PATH_WITH_OPTIONS";
10432 OptionTypes[OptionTypes["REPLACED_VARIABLE_INITS"] = 7] = "REPLACED_VARIABLE_INITS";
10433 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ACCESSED_AT_PATH"] = 8] = "RETURN_EXPRESSIONS_ACCESSED_AT_PATH";
10434 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_ASSIGNED_AT_PATH"] = 9] = "RETURN_EXPRESSIONS_ASSIGNED_AT_PATH";
10435 OptionTypes[OptionTypes["RETURN_EXPRESSIONS_CALLED_AT_PATH"] = 10] = "RETURN_EXPRESSIONS_CALLED_AT_PATH";
10436})(OptionTypes || (OptionTypes = {}));
10437var RESULT_KEY = {};
10438var ExecutionPathOptions = /** @class */ (function () {
10439 function ExecutionPathOptions(optionValues) {
10440 this.optionValues = optionValues;
10441 }
10442 ExecutionPathOptions.create = function () {
10443 return new this(Immutable.Map());
10444 };
10445 ExecutionPathOptions.prototype.addAccessedNodeAtPath = function (path, node) {
10446 return this.setIn([OptionTypes.ACCESSED_NODES, node].concat(path, [RESULT_KEY]), true);
10447 };
10448 ExecutionPathOptions.prototype.addAccessedReturnExpressionAtPath = function (path, callExpression) {
10449 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
10450 };
10451 ExecutionPathOptions.prototype.addAssignedNodeAtPath = function (path, node) {
10452 return this.setIn([OptionTypes.ASSIGNED_NODES, node].concat(path, [RESULT_KEY]), true);
10453 };
10454 ExecutionPathOptions.prototype.addAssignedReturnExpressionAtPath = function (path, callExpression) {
10455 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
10456 };
10457 ExecutionPathOptions.prototype.addCalledNodeAtPathWithOptions = function (path, node, callOptions) {
10458 return this.setIn([OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS, node].concat(path, [RESULT_KEY, callOptions]), true);
10459 };
10460 ExecutionPathOptions.prototype.addCalledReturnExpressionAtPath = function (path, callExpression) {
10461 return this.setIn([OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH, callExpression].concat(path, [RESULT_KEY]), true);
10462 };
10463 ExecutionPathOptions.prototype.getArgumentsVariables = function () {
10464 return (this.get(OptionTypes.ARGUMENTS_VARIABLES) || []);
10465 };
10466 ExecutionPathOptions.prototype.getHasEffectsWhenCalledOptions = function () {
10467 return this.setIgnoreReturnAwaitYield()
10468 .setIgnoreBreakStatements(false)
10469 .setIgnoreNoLabels();
10470 };
10471 ExecutionPathOptions.prototype.getReplacedVariableInit = function (variable) {
10472 return this.optionValues.getIn([OptionTypes.REPLACED_VARIABLE_INITS, variable]);
10473 };
10474 ExecutionPathOptions.prototype.hasNodeBeenAccessedAtPath = function (path, node) {
10475 return this.optionValues.getIn([OptionTypes.ACCESSED_NODES, node].concat(path, [RESULT_KEY]));
10476 };
10477 ExecutionPathOptions.prototype.hasNodeBeenAssignedAtPath = function (path, node) {
10478 return this.optionValues.getIn([OptionTypes.ASSIGNED_NODES, node].concat(path, [RESULT_KEY]));
10479 };
10480 ExecutionPathOptions.prototype.hasNodeBeenCalledAtPathWithOptions = function (path, node, callOptions) {
10481 var previousCallOptions = this.optionValues.getIn([
10482 OptionTypes.NODES_CALLED_AT_PATH_WITH_OPTIONS,
10483 node
10484 ].concat(path, [
10485 RESULT_KEY
10486 ]));
10487 return (previousCallOptions &&
10488 previousCallOptions.find(function (_, otherCallOptions) {
10489 return otherCallOptions.equals(callOptions);
10490 }));
10491 };
10492 ExecutionPathOptions.prototype.hasReturnExpressionBeenAccessedAtPath = function (path, callExpression) {
10493 return this.optionValues.getIn([
10494 OptionTypes.RETURN_EXPRESSIONS_ACCESSED_AT_PATH,
10495 callExpression
10496 ].concat(path, [
10497 RESULT_KEY
10498 ]));
10499 };
10500 ExecutionPathOptions.prototype.hasReturnExpressionBeenAssignedAtPath = function (path, callExpression) {
10501 return this.optionValues.getIn([
10502 OptionTypes.RETURN_EXPRESSIONS_ASSIGNED_AT_PATH,
10503 callExpression
10504 ].concat(path, [
10505 RESULT_KEY
10506 ]));
10507 };
10508 ExecutionPathOptions.prototype.hasReturnExpressionBeenCalledAtPath = function (path, callExpression) {
10509 return this.optionValues.getIn([
10510 OptionTypes.RETURN_EXPRESSIONS_CALLED_AT_PATH,
10511 callExpression
10512 ].concat(path, [
10513 RESULT_KEY
10514 ]));
10515 };
10516 ExecutionPathOptions.prototype.ignoreBreakStatements = function () {
10517 return this.get(OptionTypes.IGNORE_BREAK_STATEMENTS);
10518 };
10519 ExecutionPathOptions.prototype.ignoreLabel = function (labelName) {
10520 return this.optionValues.getIn([OptionTypes.IGNORED_LABELS, labelName]);
10521 };
10522 ExecutionPathOptions.prototype.ignoreReturnAwaitYield = function () {
10523 return this.get(OptionTypes.IGNORE_RETURN_AWAIT_YIELD);
10524 };
10525 ExecutionPathOptions.prototype.replaceVariableInit = function (variable, init) {
10526 return this.setIn([OptionTypes.REPLACED_VARIABLE_INITS, variable], init);
10527 };
10528 ExecutionPathOptions.prototype.setArgumentsVariables = function (variables) {
10529 return this.set(OptionTypes.ARGUMENTS_VARIABLES, variables);
10530 };
10531 ExecutionPathOptions.prototype.setIgnoreBreakStatements = function (value) {
10532 if (value === void 0) { value = true; }
10533 return this.set(OptionTypes.IGNORE_BREAK_STATEMENTS, value);
10534 };
10535 ExecutionPathOptions.prototype.setIgnoreLabel = function (labelName) {
10536 return this.setIn([OptionTypes.IGNORED_LABELS, labelName], true);
10537 };
10538 ExecutionPathOptions.prototype.setIgnoreNoLabels = function () {
10539 return this.remove(OptionTypes.IGNORED_LABELS);
10540 };
10541 ExecutionPathOptions.prototype.setIgnoreReturnAwaitYield = function (value) {
10542 if (value === void 0) { value = true; }
10543 return this.set(OptionTypes.IGNORE_RETURN_AWAIT_YIELD, value);
10544 };
10545 ExecutionPathOptions.prototype.get = function (option) {
10546 return this.optionValues.get(option);
10547 };
10548 ExecutionPathOptions.prototype.remove = function (option) {
10549 return new ExecutionPathOptions(this.optionValues.remove(option));
10550 };
10551 ExecutionPathOptions.prototype.set = function (option, value) {
10552 return new ExecutionPathOptions(this.optionValues.set(option, value));
10553 };
10554 ExecutionPathOptions.prototype.setIn = function (optionPath, value) {
10555 return new ExecutionPathOptions(this.optionValues.setIn(optionPath, value));
10556 };
10557 return ExecutionPathOptions;
10558}());
10559
10560var keys = {
10561 Literal: [],
10562 Program: ['body']
10563};
10564function getAndCreateKeys(esTreeNode) {
10565 keys[esTreeNode.type] = Object.keys(esTreeNode).filter(function (key) { return typeof esTreeNode[key] === 'object'; });
10566 return keys[esTreeNode.type];
10567}
10568
10569var NEW_EXECUTION_PATH = ExecutionPathOptions.create();
10570var NodeBase = /** @class */ (function () {
10571 function NodeBase(esTreeNode, parent, parentScope) {
10572 this.keys = keys[esTreeNode.type] || getAndCreateKeys(esTreeNode);
10573 this.parent = parent;
10574 this.context = parent.context;
10575 this.createScope(parentScope);
10576 this.parseNode(esTreeNode);
10577 this.initialise();
10578 this.context.magicString.addSourcemapLocation(this.start);
10579 this.context.magicString.addSourcemapLocation(this.end);
10580 }
10581 /**
10582 * Override this to bind assignments to variables and do any initialisations that
10583 * require the scopes to be populated with variables.
10584 */
10585 NodeBase.prototype.bind = function () {
10586 for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
10587 var key = _a[_i];
10588 var value = this[key];
10589 if (value === null || key === 'annotations')
10590 continue;
10591 if (Array.isArray(value)) {
10592 for (var _b = 0, value_1 = value; _b < value_1.length; _b++) {
10593 var child = value_1[_b];
10594 if (child !== null)
10595 child.bind();
10596 }
10597 }
10598 else {
10599 value.bind();
10600 }
10601 }
10602 };
10603 /**
10604 * Override if this node should receive a different scope than the parent scope.
10605 */
10606 NodeBase.prototype.createScope = function (parentScope) {
10607 this.scope = parentScope;
10608 };
10609 NodeBase.prototype.declare = function (_kind, _init) { };
10610 NodeBase.prototype.deoptimizePath = function (_path) { };
10611 NodeBase.prototype.getLiteralValueAtPath = function (_path, _recursionTracker, _origin) {
10612 return UNKNOWN_VALUE;
10613 };
10614 NodeBase.prototype.getReturnExpressionWhenCalledAtPath = function (_path, _recursionTracker, _origin) {
10615 return UNKNOWN_EXPRESSION;
10616 };
10617 NodeBase.prototype.hasEffects = function (options) {
10618 for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
10619 var key = _a[_i];
10620 var value = this[key];
10621 if (value === null || key === 'annotations')
10622 continue;
10623 if (Array.isArray(value)) {
10624 for (var _b = 0, value_2 = value; _b < value_2.length; _b++) {
10625 var child = value_2[_b];
10626 if (child !== null && child.hasEffects(options))
10627 return true;
10628 }
10629 }
10630 else if (value.hasEffects(options))
10631 return true;
10632 }
10633 return false;
10634 };
10635 NodeBase.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
10636 return path.length > 0;
10637 };
10638 NodeBase.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
10639 return true;
10640 };
10641 NodeBase.prototype.hasEffectsWhenCalledAtPath = function (_path, _callOptions, _options) {
10642 return true;
10643 };
10644 NodeBase.prototype.include = function (includeAllChildrenRecursively) {
10645 this.included = true;
10646 for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
10647 var key = _a[_i];
10648 var value = this[key];
10649 if (value === null || key === 'annotations')
10650 continue;
10651 if (Array.isArray(value)) {
10652 for (var _b = 0, value_3 = value; _b < value_3.length; _b++) {
10653 var child = value_3[_b];
10654 if (child !== null)
10655 child.include(includeAllChildrenRecursively);
10656 }
10657 }
10658 else {
10659 value.include(includeAllChildrenRecursively);
10660 }
10661 }
10662 };
10663 NodeBase.prototype.includeWithAllDeclaredVariables = function (includeAllChildrenRecursively) {
10664 this.include(includeAllChildrenRecursively);
10665 };
10666 /**
10667 * Override to perform special initialisation steps after the scope is initialised
10668 */
10669 NodeBase.prototype.initialise = function () {
10670 this.included = false;
10671 };
10672 NodeBase.prototype.insertSemicolon = function (code) {
10673 if (code.original[this.end - 1] !== ';') {
10674 code.appendLeft(this.end, ';');
10675 }
10676 };
10677 NodeBase.prototype.locate = function () {
10678 // useful for debugging
10679 var location = locate(this.context.code, this.start, { offsetLine: 1 });
10680 location.file = this.context.fileName;
10681 location.toString = function () { return JSON.stringify(location); };
10682 return location;
10683 };
10684 NodeBase.prototype.parseNode = function (esTreeNode) {
10685 for (var _i = 0, _a = Object.keys(esTreeNode); _i < _a.length; _i++) {
10686 var key = _a[_i];
10687 // That way, we can override this function to add custom initialisation and then call super.parseNode
10688 if (this.hasOwnProperty(key))
10689 continue;
10690 var value = esTreeNode[key];
10691 if (typeof value !== 'object' || value === null || key === 'annotations') {
10692 this[key] = value;
10693 }
10694 else if (Array.isArray(value)) {
10695 this[key] = [];
10696 for (var _b = 0, value_4 = value; _b < value_4.length; _b++) {
10697 var child = value_4[_b];
10698 this[key].push(child === null
10699 ? null
10700 : new (this.context.nodeConstructors[child.type] ||
10701 this.context.nodeConstructors.UnknownNode)(child, this, this.scope));
10702 }
10703 }
10704 else {
10705 this[key] = new (this.context.nodeConstructors[value.type] ||
10706 this.context.nodeConstructors.UnknownNode)(value, this, this.scope);
10707 }
10708 }
10709 };
10710 NodeBase.prototype.render = function (code, options) {
10711 for (var _i = 0, _a = this.keys; _i < _a.length; _i++) {
10712 var key = _a[_i];
10713 var value = this[key];
10714 if (value === null || key === 'annotations')
10715 continue;
10716 if (Array.isArray(value)) {
10717 for (var _b = 0, value_5 = value; _b < value_5.length; _b++) {
10718 var child = value_5[_b];
10719 if (child !== null)
10720 child.render(code, options);
10721 }
10722 }
10723 else {
10724 value.render(code, options);
10725 }
10726 }
10727 };
10728 NodeBase.prototype.shouldBeIncluded = function () {
10729 return this.included || this.hasEffects(NEW_EXECUTION_PATH);
10730 };
10731 NodeBase.prototype.toString = function () {
10732 return this.context.code.slice(this.start, this.end);
10733 };
10734 return NodeBase;
10735}());
10736
10737var ClassNode = /** @class */ (function (_super) {
10738 __extends(ClassNode, _super);
10739 function ClassNode() {
10740 return _super !== null && _super.apply(this, arguments) || this;
10741 }
10742 ClassNode.prototype.createScope = function (parentScope) {
10743 this.scope = new ChildScope(parentScope);
10744 };
10745 ClassNode.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
10746 return path.length > 1;
10747 };
10748 ClassNode.prototype.hasEffectsWhenAssignedAtPath = function (path, _options) {
10749 return path.length > 1;
10750 };
10751 ClassNode.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
10752 return (this.body.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
10753 (this.superClass && this.superClass.hasEffectsWhenCalledAtPath(path, callOptions, options)));
10754 };
10755 ClassNode.prototype.initialise = function () {
10756 this.included = false;
10757 if (this.id !== null) {
10758 this.id.declare('class', this);
10759 }
10760 };
10761 return ClassNode;
10762}(NodeBase));
10763
10764function isClassDeclaration(node) {
10765 return node.type === ClassDeclaration;
10766}
10767var ClassDeclaration$1 = /** @class */ (function (_super) {
10768 __extends(ClassDeclaration, _super);
10769 function ClassDeclaration() {
10770 return _super !== null && _super.apply(this, arguments) || this;
10771 }
10772 ClassDeclaration.prototype.initialise = function () {
10773 _super.prototype.initialise.call(this);
10774 if (this.id !== null) {
10775 this.id.variable.isId = true;
10776 }
10777 };
10778 ClassDeclaration.prototype.parseNode = function (esTreeNode) {
10779 if (esTreeNode.id !== null) {
10780 this.id = (new this.context.nodeConstructors.Identifier(esTreeNode.id, this, (this.scope.parent)));
10781 }
10782 _super.prototype.parseNode.call(this, esTreeNode);
10783 };
10784 ClassDeclaration.prototype.render = function (code, options) {
10785 if (options.format === 'system' && this.id && this.id.variable.exportName) {
10786 code.appendLeft(this.end, " exports('" + this.id.variable.exportName + "', " + this.id.variable.getName() + ");");
10787 }
10788 _super.prototype.render.call(this, code, options);
10789 };
10790 return ClassDeclaration;
10791}(ClassNode));
10792
10793var getParameterVariable = function (path, options) {
10794 var firstArgNum = parseInt(path[0], 10);
10795 return ((firstArgNum < options.getArgumentsVariables().length &&
10796 options.getArgumentsVariables()[firstArgNum]) ||
10797 UNKNOWN_EXPRESSION);
10798};
10799var ArgumentsVariable = /** @class */ (function (_super) {
10800 __extends(ArgumentsVariable, _super);
10801 function ArgumentsVariable(parameters, context) {
10802 var _this = _super.call(this, 'arguments', null, UNKNOWN_EXPRESSION, context) || this;
10803 _this.parameters = parameters;
10804 return _this;
10805 }
10806 ArgumentsVariable.prototype.deoptimizePath = function (path) {
10807 var firstArgNum = parseInt(path[0], 10);
10808 if (path.length > 0) {
10809 if (firstArgNum >= 0 && this.parameters[firstArgNum]) {
10810 this.parameters[firstArgNum].deoptimizePath(path.slice(1));
10811 }
10812 }
10813 };
10814 ArgumentsVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
10815 return (path.length > 1 &&
10816 getParameterVariable(path, options).hasEffectsWhenAccessedAtPath(path.slice(1), options));
10817 };
10818 ArgumentsVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
10819 return (path.length === 0 ||
10820 this.included ||
10821 getParameterVariable(path, options).hasEffectsWhenAssignedAtPath(path.slice(1), options));
10822 };
10823 ArgumentsVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
10824 if (path.length === 0) {
10825 return true;
10826 }
10827 return getParameterVariable(path, options).hasEffectsWhenCalledAtPath(path.slice(1), callOptions, options);
10828 };
10829 return ArgumentsVariable;
10830}(LocalVariable));
10831
10832var ThisVariable = /** @class */ (function (_super) {
10833 __extends(ThisVariable, _super);
10834 function ThisVariable(context) {
10835 return _super.call(this, 'this', null, null, context) || this;
10836 }
10837 ThisVariable.prototype._getInit = function (options) {
10838 return options.getReplacedVariableInit(this) || UNKNOWN_EXPRESSION;
10839 };
10840 ThisVariable.prototype.getLiteralValueAtPath = function () {
10841 return UNKNOWN_VALUE;
10842 };
10843 ThisVariable.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
10844 return (this._getInit(options).hasEffectsWhenAccessedAtPath(path, options) ||
10845 _super.prototype.hasEffectsWhenAccessedAtPath.call(this, path, options));
10846 };
10847 ThisVariable.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
10848 return (this._getInit(options).hasEffectsWhenAssignedAtPath(path, options) ||
10849 _super.prototype.hasEffectsWhenAssignedAtPath.call(this, path, options));
10850 };
10851 ThisVariable.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
10852 return (this._getInit(options).hasEffectsWhenCalledAtPath(path, callOptions, options) ||
10853 _super.prototype.hasEffectsWhenCalledAtPath.call(this, path, callOptions, options));
10854 };
10855 return ThisVariable;
10856}(LocalVariable));
10857
10858var ParameterScope = /** @class */ (function (_super) {
10859 __extends(ParameterScope, _super);
10860 function ParameterScope(parent, context) {
10861 var _this = _super.call(this, parent) || this;
10862 _this.parameters = [];
10863 _this.context = context;
10864 _this.hoistedBodyVarScope = new ChildScope(_this);
10865 return _this;
10866 }
10867 /**
10868 * Adds a parameter to this scope. Parameters must be added in the correct
10869 * order, e.g. from left to right.
10870 */
10871 ParameterScope.prototype.addParameterDeclaration = function (identifier) {
10872 var name = identifier.name;
10873 var variable;
10874 if (name in this.hoistedBodyVarScope.variables) {
10875 variable = this.hoistedBodyVarScope.variables[name];
10876 variable.addDeclaration(identifier, null);
10877 }
10878 else {
10879 variable = new LocalVariable(name, identifier, UNKNOWN_EXPRESSION, this.context);
10880 }
10881 this.variables[name] = variable;
10882 this.parameters.push(variable);
10883 return variable;
10884 };
10885 ParameterScope.prototype.getParameterVariables = function () {
10886 return this.parameters;
10887 };
10888 return ParameterScope;
10889}(ChildScope));
10890
10891var ReturnValueScope = /** @class */ (function (_super) {
10892 __extends(ReturnValueScope, _super);
10893 function ReturnValueScope() {
10894 var _this = _super !== null && _super.apply(this, arguments) || this;
10895 _this.returnExpression = null;
10896 _this.returnExpressions = [];
10897 return _this;
10898 }
10899 ReturnValueScope.prototype.addReturnExpression = function (expression) {
10900 this.returnExpressions.push(expression);
10901 };
10902 ReturnValueScope.prototype.getReturnExpression = function () {
10903 if (this.returnExpression === null)
10904 this.updateReturnExpression();
10905 return this.returnExpression;
10906 };
10907 ReturnValueScope.prototype.updateReturnExpression = function () {
10908 if (this.returnExpressions.length === 1) {
10909 this.returnExpression = this.returnExpressions[0];
10910 }
10911 else {
10912 this.returnExpression = UNKNOWN_EXPRESSION;
10913 for (var _i = 0, _a = this.returnExpressions; _i < _a.length; _i++) {
10914 var expression = _a[_i];
10915 expression.deoptimizePath(UNKNOWN_PATH);
10916 }
10917 }
10918 };
10919 return ReturnValueScope;
10920}(ParameterScope));
10921
10922var FunctionScope = /** @class */ (function (_super) {
10923 __extends(FunctionScope, _super);
10924 function FunctionScope(parent, context) {
10925 var _this = _super.call(this, parent, context) || this;
10926 _this.variables.arguments = new ArgumentsVariable(_super.prototype.getParameterVariables.call(_this), context);
10927 _this.variables.this = new ThisVariable(context);
10928 return _this;
10929 }
10930 FunctionScope.prototype.findLexicalBoundary = function () {
10931 return this;
10932 };
10933 FunctionScope.prototype.getOptionsWhenCalledWith = function (_a, options) {
10934 var _this = this;
10935 var args = _a.args, withNew = _a.withNew;
10936 return options
10937 .replaceVariableInit(this.variables.this, withNew ? new UnknownObjectExpression() : UNKNOWN_EXPRESSION)
10938 .setArgumentsVariables(args.map(function (parameter, index) { return _super.prototype.getParameterVariables.call(_this)[index] || parameter; }));
10939 };
10940 return FunctionScope;
10941}(ReturnValueScope));
10942
10943var FunctionNode = /** @class */ (function (_super) {
10944 __extends(FunctionNode, _super);
10945 function FunctionNode() {
10946 return _super !== null && _super.apply(this, arguments) || this;
10947 }
10948 FunctionNode.prototype.createScope = function (parentScope) {
10949 this.scope = new FunctionScope(parentScope, this.context);
10950 };
10951 FunctionNode.prototype.deoptimizePath = function (path) {
10952 if (path.length === 1) {
10953 if (path[0] === 'prototype') {
10954 this.isPrototypeDeoptimized = true;
10955 }
10956 else if (path[0] === UNKNOWN_KEY) {
10957 this.isPrototypeDeoptimized = true;
10958 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
10959 // which means the return expression needs to be reassigned as well
10960 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
10961 }
10962 }
10963 };
10964 FunctionNode.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
10965 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
10966 };
10967 FunctionNode.prototype.hasEffects = function (options) {
10968 return this.id && this.id.hasEffects(options);
10969 };
10970 FunctionNode.prototype.hasEffectsWhenAccessedAtPath = function (path) {
10971 if (path.length <= 1) {
10972 return false;
10973 }
10974 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
10975 };
10976 FunctionNode.prototype.hasEffectsWhenAssignedAtPath = function (path) {
10977 if (path.length <= 1) {
10978 return false;
10979 }
10980 return path.length > 2 || path[0] !== 'prototype' || this.isPrototypeDeoptimized;
10981 };
10982 FunctionNode.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
10983 if (path.length > 0) {
10984 return true;
10985 }
10986 var innerOptions = this.scope.getOptionsWhenCalledWith(callOptions, options);
10987 for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
10988 var param = _a[_i];
10989 if (param.hasEffects(innerOptions))
10990 return true;
10991 }
10992 return this.body.hasEffects(innerOptions);
10993 };
10994 FunctionNode.prototype.include = function (includeAllChildrenRecursively) {
10995 this.scope.variables.arguments.include();
10996 _super.prototype.include.call(this, includeAllChildrenRecursively);
10997 };
10998 FunctionNode.prototype.initialise = function () {
10999 this.included = false;
11000 this.isPrototypeDeoptimized = false;
11001 if (this.id !== null) {
11002 this.id.declare('function', this);
11003 }
11004 for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
11005 var param = _a[_i];
11006 param.declare('parameter', UNKNOWN_EXPRESSION);
11007 }
11008 this.body.addImplicitReturnExpressionToScope();
11009 };
11010 FunctionNode.prototype.parseNode = function (esTreeNode) {
11011 this.body = (new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope));
11012 _super.prototype.parseNode.call(this, esTreeNode);
11013 };
11014 return FunctionNode;
11015}(NodeBase));
11016FunctionNode.prototype.preventChildBlockScope = true;
11017
11018function isFunctionDeclaration(node) {
11019 return node.type === FunctionDeclaration;
11020}
11021var FunctionDeclaration$1 = /** @class */ (function (_super) {
11022 __extends(FunctionDeclaration, _super);
11023 function FunctionDeclaration() {
11024 return _super !== null && _super.apply(this, arguments) || this;
11025 }
11026 FunctionDeclaration.prototype.initialise = function () {
11027 _super.prototype.initialise.call(this);
11028 if (this.id !== null) {
11029 this.id.variable.isId = true;
11030 }
11031 };
11032 FunctionDeclaration.prototype.parseNode = function (esTreeNode) {
11033 if (esTreeNode.id !== null) {
11034 this.id = (new this.context.nodeConstructors.Identifier(esTreeNode.id, this, (this.scope.parent)));
11035 }
11036 _super.prototype.parseNode.call(this, esTreeNode);
11037 };
11038 return FunctionDeclaration;
11039}(FunctionNode));
11040
11041var WHITESPACE = /\s/;
11042// The header ends at the first non-white-space after "default"
11043function getDeclarationStart(code, start) {
11044 if (start === void 0) { start = 0; }
11045 start = findFirstOccurrenceOutsideComment(code, 'default', start) + 7;
11046 while (WHITESPACE.test(code[start]))
11047 start++;
11048 return start;
11049}
11050function getIdInsertPosition(code, declarationKeyword, start) {
11051 if (start === void 0) { start = 0; }
11052 var declarationEnd = findFirstOccurrenceOutsideComment(code, declarationKeyword, start) + declarationKeyword.length;
11053 code = code.slice(declarationEnd, findFirstOccurrenceOutsideComment(code, '{', declarationEnd));
11054 var generatorStarPos = findFirstOccurrenceOutsideComment(code, '*');
11055 if (generatorStarPos === -1) {
11056 return declarationEnd;
11057 }
11058 return declarationEnd + generatorStarPos + 1;
11059}
11060function isExportDefaultDeclaration(node) {
11061 return node.type === ExportDefaultDeclaration;
11062}
11063var ExportDefaultDeclaration$1 = /** @class */ (function (_super) {
11064 __extends(ExportDefaultDeclaration, _super);
11065 function ExportDefaultDeclaration() {
11066 return _super !== null && _super.apply(this, arguments) || this;
11067 }
11068 ExportDefaultDeclaration.prototype.include = function (includeAllChildrenRecursively) {
11069 _super.prototype.include.call(this, includeAllChildrenRecursively);
11070 if (includeAllChildrenRecursively) {
11071 this.context.includeVariable(this.variable);
11072 }
11073 };
11074 ExportDefaultDeclaration.prototype.initialise = function () {
11075 this.included = false;
11076 this.declarationName =
11077 (this.declaration.id &&
11078 this.declaration.id.name) ||
11079 this.declaration.name;
11080 this.variable = this.scope.addExportDefaultDeclaration(this.declarationName || this.context.getModuleName(), this, this.context);
11081 this.context.addExport(this);
11082 };
11083 ExportDefaultDeclaration.prototype.render = function (code, options, _a) {
11084 var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
11085 var declarationStart = getDeclarationStart(code.original, this.start);
11086 if (isFunctionDeclaration(this.declaration)) {
11087 this.renderNamedDeclaration(code, declarationStart, 'function', this.declaration.id === null, options);
11088 }
11089 else if (isClassDeclaration(this.declaration)) {
11090 this.renderNamedDeclaration(code, declarationStart, 'class', this.declaration.id === null, options);
11091 }
11092 else if (this.variable.referencesOriginal()) {
11093 // Remove altogether to prevent re-declaring the same variable
11094 if (options.format === 'system' && this.variable.exportName) {
11095 code.overwrite(start, end, "exports('" + this.variable.exportName + "', " + this.variable.getName() + ");");
11096 }
11097 else {
11098 treeshakeNode(this, code, start, end);
11099 }
11100 return;
11101 }
11102 else if (this.variable.included) {
11103 this.renderVariableDeclaration(code, declarationStart, options);
11104 }
11105 else {
11106 code.remove(this.start, declarationStart);
11107 this.declaration.render(code, options, {
11108 isCalleeOfRenderedParent: false,
11109 renderedParentType: ExpressionStatement
11110 });
11111 if (code.original[this.end - 1] !== ';') {
11112 code.appendLeft(this.end, ';');
11113 }
11114 return;
11115 }
11116 this.declaration.render(code, options);
11117 };
11118 ExportDefaultDeclaration.prototype.renderNamedDeclaration = function (code, declarationStart, declarationKeyword, needsId, options) {
11119 var name = this.variable.getName();
11120 // Remove `export default`
11121 code.remove(this.start, declarationStart);
11122 if (needsId) {
11123 code.appendLeft(getIdInsertPosition(code.original, declarationKeyword, declarationStart), " " + name);
11124 }
11125 if (options.format === 'system' &&
11126 isClassDeclaration(this.declaration) &&
11127 this.variable.exportName) {
11128 code.appendLeft(this.end, " exports('" + this.variable.exportName + "', " + name + ");");
11129 }
11130 };
11131 ExportDefaultDeclaration.prototype.renderVariableDeclaration = function (code, declarationStart, options) {
11132 var systemBinding = options.format === 'system' && this.variable.exportName
11133 ? "exports('" + this.variable.exportName + "', "
11134 : '';
11135 code.overwrite(this.start, declarationStart, options.varOrConst + " " + this.variable.getName() + " = " + systemBinding);
11136 var hasTrailingSemicolon = code.original.charCodeAt(this.end - 1) === 59; /*";"*/
11137 if (systemBinding) {
11138 code.appendRight(hasTrailingSemicolon ? this.end - 1 : this.end, ')' + (hasTrailingSemicolon ? '' : ';'));
11139 }
11140 else if (!hasTrailingSemicolon) {
11141 code.appendLeft(this.end, ';');
11142 }
11143 };
11144 return ExportDefaultDeclaration;
11145}(NodeBase));
11146ExportDefaultDeclaration$1.prototype.needsBoundaries = true;
11147
11148var ArrayExpression = /** @class */ (function (_super) {
11149 __extends(ArrayExpression, _super);
11150 function ArrayExpression() {
11151 return _super !== null && _super.apply(this, arguments) || this;
11152 }
11153 ArrayExpression.prototype.bind = function () {
11154 _super.prototype.bind.call(this);
11155 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11156 var element = _a[_i];
11157 if (element !== null)
11158 element.deoptimizePath(UNKNOWN_PATH);
11159 }
11160 };
11161 ArrayExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
11162 if (path.length !== 1)
11163 return UNKNOWN_EXPRESSION;
11164 return getMemberReturnExpressionWhenCalled(arrayMembers, path[0]);
11165 };
11166 ArrayExpression.prototype.hasEffectsWhenAccessedAtPath = function (path) {
11167 return path.length > 1;
11168 };
11169 ArrayExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11170 if (path.length === 1) {
11171 return hasMemberEffectWhenCalled(arrayMembers, path[0], this.included, callOptions, options);
11172 }
11173 return true;
11174 };
11175 return ArrayExpression;
11176}(NodeBase));
11177
11178var ArrayPattern = /** @class */ (function (_super) {
11179 __extends(ArrayPattern, _super);
11180 function ArrayPattern() {
11181 return _super !== null && _super.apply(this, arguments) || this;
11182 }
11183 ArrayPattern.prototype.addExportedVariables = function (variables) {
11184 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11185 var element = _a[_i];
11186 if (element !== null) {
11187 element.addExportedVariables(variables);
11188 }
11189 }
11190 };
11191 ArrayPattern.prototype.declare = function (kind, _init) {
11192 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11193 var element = _a[_i];
11194 if (element !== null) {
11195 element.declare(kind, UNKNOWN_EXPRESSION);
11196 }
11197 }
11198 };
11199 ArrayPattern.prototype.deoptimizePath = function (path) {
11200 if (path.length === 0) {
11201 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11202 var element = _a[_i];
11203 if (element !== null) {
11204 element.deoptimizePath(path);
11205 }
11206 }
11207 }
11208 };
11209 ArrayPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11210 if (path.length > 0)
11211 return true;
11212 for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {
11213 var element = _a[_i];
11214 if (element !== null && element.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))
11215 return true;
11216 }
11217 return false;
11218 };
11219 return ArrayPattern;
11220}(NodeBase));
11221
11222var BlockScope = /** @class */ (function (_super) {
11223 __extends(BlockScope, _super);
11224 function BlockScope() {
11225 return _super !== null && _super.apply(this, arguments) || this;
11226 }
11227 BlockScope.prototype.addDeclaration = function (identifier, context, init, isHoisted) {
11228 if (init === void 0) { init = null; }
11229 if (isHoisted === void 0) { isHoisted = false; }
11230 if (isHoisted) {
11231 return this.parent.addDeclaration(identifier, context, UNKNOWN_EXPRESSION, true);
11232 }
11233 else {
11234 return _super.prototype.addDeclaration.call(this, identifier, context, init, false);
11235 }
11236 };
11237 return BlockScope;
11238}(ChildScope));
11239
11240var BlockStatement$1 = /** @class */ (function (_super) {
11241 __extends(BlockStatement, _super);
11242 function BlockStatement() {
11243 return _super !== null && _super.apply(this, arguments) || this;
11244 }
11245 BlockStatement.prototype.addImplicitReturnExpressionToScope = function () {
11246 var lastStatement = this.body[this.body.length - 1];
11247 if (!lastStatement || lastStatement.type !== ReturnStatement) {
11248 this.scope.addReturnExpression(UNKNOWN_EXPRESSION);
11249 }
11250 };
11251 BlockStatement.prototype.createScope = function (parentScope) {
11252 this.scope = this.parent.preventChildBlockScope
11253 ? parentScope
11254 : new BlockScope(parentScope);
11255 };
11256 BlockStatement.prototype.hasEffects = function (options) {
11257 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
11258 var node = _a[_i];
11259 if (node.hasEffects(options))
11260 return true;
11261 }
11262 };
11263 BlockStatement.prototype.include = function (includeAllChildrenRecursively) {
11264 this.included = true;
11265 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
11266 var node = _a[_i];
11267 if (includeAllChildrenRecursively || node.shouldBeIncluded())
11268 node.include(includeAllChildrenRecursively);
11269 }
11270 };
11271 BlockStatement.prototype.render = function (code, options) {
11272 if (this.body.length) {
11273 renderStatementList(this.body, code, this.start + 1, this.end - 1, options);
11274 }
11275 else {
11276 _super.prototype.render.call(this, code, options);
11277 }
11278 };
11279 return BlockStatement;
11280}(NodeBase));
11281
11282var ArrowFunctionExpression = /** @class */ (function (_super) {
11283 __extends(ArrowFunctionExpression, _super);
11284 function ArrowFunctionExpression() {
11285 return _super !== null && _super.apply(this, arguments) || this;
11286 }
11287 ArrowFunctionExpression.prototype.createScope = function (parentScope) {
11288 this.scope = new ReturnValueScope(parentScope, this.context);
11289 };
11290 ArrowFunctionExpression.prototype.deoptimizePath = function (path) {
11291 // A reassignment of UNKNOWN_PATH is considered equivalent to having lost track
11292 // which means the return expression needs to be reassigned
11293 if (path.length === 1 && path[0] === UNKNOWN_KEY) {
11294 this.scope.getReturnExpression().deoptimizePath(UNKNOWN_PATH);
11295 }
11296 };
11297 ArrowFunctionExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
11298 return path.length === 0 ? this.scope.getReturnExpression() : UNKNOWN_EXPRESSION;
11299 };
11300 ArrowFunctionExpression.prototype.hasEffects = function (_options) {
11301 return false;
11302 };
11303 ArrowFunctionExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
11304 return path.length > 1;
11305 };
11306 ArrowFunctionExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, _options) {
11307 return path.length > 1;
11308 };
11309 ArrowFunctionExpression.prototype.hasEffectsWhenCalledAtPath = function (path, _callOptions, options) {
11310 if (path.length > 0) {
11311 return true;
11312 }
11313 for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
11314 var param = _a[_i];
11315 if (param.hasEffects(options))
11316 return true;
11317 }
11318 return this.body.hasEffects(options);
11319 };
11320 ArrowFunctionExpression.prototype.initialise = function () {
11321 this.included = false;
11322 for (var _i = 0, _a = this.params; _i < _a.length; _i++) {
11323 var param = _a[_i];
11324 param.declare('parameter', UNKNOWN_EXPRESSION);
11325 }
11326 if (this.body instanceof BlockStatement$1) {
11327 this.body.addImplicitReturnExpressionToScope();
11328 }
11329 else {
11330 this.scope.addReturnExpression(this.body);
11331 }
11332 };
11333 ArrowFunctionExpression.prototype.parseNode = function (esTreeNode) {
11334 if (esTreeNode.body.type === BlockStatement) {
11335 this.body = new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope.hoistedBodyVarScope);
11336 }
11337 _super.prototype.parseNode.call(this, esTreeNode);
11338 };
11339 return ArrowFunctionExpression;
11340}(NodeBase));
11341ArrowFunctionExpression.prototype.preventChildBlockScope = true;
11342
11343function getSystemExportStatement(exportedVariables) {
11344 if (exportedVariables.length === 1) {
11345 return "exports('" + (exportedVariables[0].safeExportName ||
11346 exportedVariables[0].exportName) + "', " + exportedVariables[0].getName() + ");";
11347 }
11348 else {
11349 return "exports({" + exportedVariables
11350 .map(function (variable) { return (variable.safeExportName || variable.exportName) + ": " + variable.getName(); })
11351 .join(', ') + "});";
11352 }
11353}
11354
11355var AssignmentExpression = /** @class */ (function (_super) {
11356 __extends(AssignmentExpression, _super);
11357 function AssignmentExpression() {
11358 return _super !== null && _super.apply(this, arguments) || this;
11359 }
11360 AssignmentExpression.prototype.bind = function () {
11361 _super.prototype.bind.call(this);
11362 this.left.deoptimizePath(EMPTY_PATH);
11363 // We cannot propagate mutations of the new binding to the old binding with certainty
11364 this.right.deoptimizePath(UNKNOWN_PATH);
11365 };
11366 AssignmentExpression.prototype.hasEffects = function (options) {
11367 return (this.right.hasEffects(options) ||
11368 this.left.hasEffects(options) ||
11369 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options));
11370 };
11371 AssignmentExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11372 return path.length > 0 && this.right.hasEffectsWhenAccessedAtPath(path, options);
11373 };
11374 AssignmentExpression.prototype.render = function (code, options) {
11375 this.left.render(code, options);
11376 this.right.render(code, options);
11377 if (options.format === 'system') {
11378 if (this.left.variable && this.left.variable.exportName) {
11379 code.prependLeft(code.original.indexOf('=', this.left.end) + 1, " exports('" + this.left.variable.exportName + "',");
11380 code.appendLeft(this.right.end, ")");
11381 }
11382 else if ('addExportedVariables' in this.left) {
11383 var systemPatternExports = [];
11384 this.left.addExportedVariables(systemPatternExports);
11385 if (systemPatternExports.length > 0) {
11386 code.prependRight(this.start, "function (v) {" + getSystemExportStatement(systemPatternExports) + " return v;} (");
11387 code.appendLeft(this.end, ')');
11388 }
11389 }
11390 }
11391 };
11392 return AssignmentExpression;
11393}(NodeBase));
11394
11395var AssignmentPattern = /** @class */ (function (_super) {
11396 __extends(AssignmentPattern, _super);
11397 function AssignmentPattern() {
11398 return _super !== null && _super.apply(this, arguments) || this;
11399 }
11400 AssignmentPattern.prototype.addExportedVariables = function (variables) {
11401 this.left.addExportedVariables(variables);
11402 };
11403 AssignmentPattern.prototype.bind = function () {
11404 _super.prototype.bind.call(this);
11405 this.left.deoptimizePath(EMPTY_PATH);
11406 this.right.deoptimizePath(UNKNOWN_PATH);
11407 };
11408 AssignmentPattern.prototype.declare = function (kind, init) {
11409 this.left.declare(kind, init);
11410 };
11411 AssignmentPattern.prototype.deoptimizePath = function (path) {
11412 path.length === 0 && this.left.deoptimizePath(path);
11413 };
11414 AssignmentPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11415 return path.length > 0 || this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options);
11416 };
11417 AssignmentPattern.prototype.render = function (code, options, _a) {
11418 var isShorthandProperty = (_a === void 0 ? BLANK : _a).isShorthandProperty;
11419 this.left.render(code, options, { isShorthandProperty: isShorthandProperty });
11420 this.right.render(code, options);
11421 };
11422 return AssignmentPattern;
11423}(NodeBase));
11424
11425var AwaitExpression = /** @class */ (function (_super) {
11426 __extends(AwaitExpression, _super);
11427 function AwaitExpression() {
11428 return _super !== null && _super.apply(this, arguments) || this;
11429 }
11430 AwaitExpression.prototype.hasEffects = function (options) {
11431 return _super.prototype.hasEffects.call(this, options) || !options.ignoreReturnAwaitYield();
11432 };
11433 AwaitExpression.prototype.include = function (includeAllChildrenRecursively) {
11434 _super.prototype.include.call(this, includeAllChildrenRecursively);
11435 if (!this.context.usesTopLevelAwait) {
11436 var parent = this.parent;
11437 do {
11438 if (parent instanceof FunctionNode || parent instanceof ArrowFunctionExpression)
11439 return;
11440 } while ((parent = parent.parent));
11441 this.context.usesTopLevelAwait = true;
11442 }
11443 };
11444 AwaitExpression.prototype.render = function (code, options) {
11445 _super.prototype.render.call(this, code, options);
11446 };
11447 return AwaitExpression;
11448}(NodeBase));
11449
11450var binaryOperators = {
11451 '!=': function (left, right) { return left != right; },
11452 '!==': function (left, right) { return left !== right; },
11453 '%': function (left, right) { return left % right; },
11454 '&': function (left, right) { return left & right; },
11455 '*': function (left, right) { return left * right; },
11456 // At the moment, "**" will be transpiled to Math.pow
11457 '**': function (left, right) { return Math.pow(left, right); },
11458 '+': function (left, right) { return left + right; },
11459 '-': function (left, right) { return left - right; },
11460 '/': function (left, right) { return left / right; },
11461 '<': function (left, right) { return left < right; },
11462 '<<': function (left, right) { return left << right; },
11463 '<=': function (left, right) { return left <= right; },
11464 '==': function (left, right) { return left == right; },
11465 '===': function (left, right) { return left === right; },
11466 '>': function (left, right) { return left > right; },
11467 '>=': function (left, right) { return left >= right; },
11468 '>>': function (left, right) { return left >> right; },
11469 '>>>': function (left, right) { return left >>> right; },
11470 '^': function (left, right) { return left ^ right; },
11471 in: function () { return UNKNOWN_VALUE; },
11472 instanceof: function () { return UNKNOWN_VALUE; },
11473 '|': function (left, right) { return left | right; }
11474};
11475var BinaryExpression = /** @class */ (function (_super) {
11476 __extends(BinaryExpression, _super);
11477 function BinaryExpression() {
11478 return _super !== null && _super.apply(this, arguments) || this;
11479 }
11480 BinaryExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
11481 if (path.length > 0)
11482 return UNKNOWN_VALUE;
11483 var leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
11484 if (leftValue === UNKNOWN_VALUE)
11485 return UNKNOWN_VALUE;
11486 var rightValue = this.right.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
11487 if (rightValue === UNKNOWN_VALUE)
11488 return UNKNOWN_VALUE;
11489 var operatorFn = binaryOperators[this.operator];
11490 if (!operatorFn)
11491 return UNKNOWN_VALUE;
11492 return operatorFn(leftValue, rightValue);
11493 };
11494 BinaryExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
11495 return path.length > 1;
11496 };
11497 return BinaryExpression;
11498}(NodeBase));
11499
11500var BreakStatement = /** @class */ (function (_super) {
11501 __extends(BreakStatement, _super);
11502 function BreakStatement() {
11503 return _super !== null && _super.apply(this, arguments) || this;
11504 }
11505 BreakStatement.prototype.hasEffects = function (options) {
11506 return (_super.prototype.hasEffects.call(this, options) ||
11507 !options.ignoreBreakStatements() ||
11508 (this.label && !options.ignoreLabel(this.label.name)));
11509 };
11510 return BreakStatement;
11511}(NodeBase));
11512
11513var RESULT_KEY$1 = {};
11514var ImmutableEntityPathTracker = /** @class */ (function () {
11515 function ImmutableEntityPathTracker(existingEntityPaths) {
11516 if (existingEntityPaths === void 0) { existingEntityPaths = Immutable.Map(); }
11517 this.entityPaths = existingEntityPaths;
11518 }
11519 ImmutableEntityPathTracker.prototype.isTracked = function (entity, path) {
11520 return this.entityPaths.getIn([entity].concat(path, [RESULT_KEY$1]));
11521 };
11522 ImmutableEntityPathTracker.prototype.track = function (entity, path) {
11523 return new ImmutableEntityPathTracker(this.entityPaths.setIn([entity].concat(path, [RESULT_KEY$1]), true));
11524 };
11525 return ImmutableEntityPathTracker;
11526}());
11527var EMPTY_IMMUTABLE_TRACKER = new ImmutableEntityPathTracker();
11528
11529function isReference(node, parent) {
11530 if (node.type === 'MemberExpression') {
11531 return !node.computed && isReference(node.object, node);
11532 }
11533 if (node.type === 'Identifier') {
11534 switch (parent.type) {
11535 // disregard `bar` in `foo.bar`
11536 case 'MemberExpression': return parent.computed || node === parent.object;
11537 // disregard the `foo` in `class {foo(){}}` but keep it in `class {[foo](){}}`
11538 case 'MethodDefinition': return parent.computed;
11539 // disregard the `bar` in `{ bar: foo }`, but keep it in `{ [bar]: foo }`
11540 case 'Property': return parent.computed || node === parent.value;
11541 // disregard the `bar` in `export { foo as bar }`
11542 case 'ExportSpecifier': return node === parent.local;
11543 // disregard the `foo` in `foo: while (...) { ... break foo; ... continue foo;}`
11544 case 'LabeledStatement':
11545 case 'BreakStatement':
11546 case 'ContinueStatement': return false;
11547 default: return true;
11548 }
11549 }
11550 return false;
11551}
11552
11553function isIdentifier(node) {
11554 return node.type === Identifier;
11555}
11556var Identifier$1 = /** @class */ (function (_super) {
11557 __extends(Identifier, _super);
11558 function Identifier() {
11559 return _super !== null && _super.apply(this, arguments) || this;
11560 }
11561 Identifier.prototype.addExportedVariables = function (variables) {
11562 if (this.variable.exportName) {
11563 variables.push(this.variable);
11564 }
11565 };
11566 Identifier.prototype.bind = function () {
11567 if (this.bound)
11568 return;
11569 this.bound = true;
11570 if (this.variable === null && isReference(this, this.parent)) {
11571 this.variable = this.scope.findVariable(this.name);
11572 this.variable.addReference(this);
11573 }
11574 if (this.variable !== null &&
11575 this.variable.isLocal &&
11576 this.variable.additionalInitializers !== null) {
11577 this.variable.consolidateInitializers();
11578 }
11579 };
11580 Identifier.prototype.declare = function (kind, init) {
11581 switch (kind) {
11582 case 'var':
11583 case 'function':
11584 this.variable = this.scope.addDeclaration(this, this.context, init, true);
11585 break;
11586 case 'let':
11587 case 'const':
11588 case 'class':
11589 this.variable = this.scope.addDeclaration(this, this.context, init, false);
11590 break;
11591 case 'parameter':
11592 this.variable = this.scope.addParameterDeclaration(this);
11593 break;
11594 default:
11595 throw new Error("Unexpected identifier kind " + kind + ".");
11596 }
11597 };
11598 Identifier.prototype.deoptimizePath = function (path) {
11599 if (!this.bound)
11600 this.bind();
11601 if (this.variable !== null) {
11602 if (path.length === 0 &&
11603 this.name in this.context.importDescriptions &&
11604 !this.scope.contains(this.name)) {
11605 this.disallowImportReassignment();
11606 }
11607 this.variable.deoptimizePath(path);
11608 }
11609 };
11610 Identifier.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
11611 if (!this.bound)
11612 this.bind();
11613 if (this.variable !== null) {
11614 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
11615 }
11616 return UNKNOWN_VALUE;
11617 };
11618 Identifier.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
11619 if (!this.bound)
11620 this.bind();
11621 if (this.variable !== null) {
11622 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
11623 }
11624 return UNKNOWN_EXPRESSION;
11625 };
11626 Identifier.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11627 return this.variable && this.variable.hasEffectsWhenAccessedAtPath(path, options);
11628 };
11629 Identifier.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11630 return !this.variable || this.variable.hasEffectsWhenAssignedAtPath(path, options);
11631 };
11632 Identifier.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11633 return !this.variable || this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options);
11634 };
11635 Identifier.prototype.include = function (_includeAllChildrenRecursively) {
11636 if (!this.included) {
11637 this.included = true;
11638 if (this.variable !== null) {
11639 this.context.includeVariable(this.variable);
11640 }
11641 }
11642 };
11643 Identifier.prototype.initialise = function () {
11644 this.included = false;
11645 this.bound = false;
11646 // To avoid later shape mutations
11647 if (!this.variable) {
11648 this.variable = null;
11649 }
11650 };
11651 Identifier.prototype.render = function (code, _options, _a) {
11652 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent, isShorthandProperty = _b.isShorthandProperty;
11653 if (this.variable) {
11654 var name = this.variable.getName();
11655 if (name !== this.name) {
11656 code.overwrite(this.start, this.end, name, {
11657 contentOnly: true,
11658 storeName: true
11659 });
11660 if (isShorthandProperty) {
11661 code.prependRight(this.start, this.name + ": ");
11662 }
11663 }
11664 // In strict mode, any variable named "eval" must be the actual "eval" function
11665 if (name === 'eval' &&
11666 renderedParentType === CallExpression &&
11667 isCalleeOfRenderedParent) {
11668 code.appendRight(this.start, '0, ');
11669 }
11670 }
11671 };
11672 Identifier.prototype.disallowImportReassignment = function () {
11673 this.context.error({
11674 code: 'ILLEGAL_REASSIGNMENT',
11675 message: "Illegal reassignment to import '" + this.name + "'"
11676 }, this.start);
11677 };
11678 return Identifier;
11679}(NodeBase));
11680
11681var CallExpression$1 = /** @class */ (function (_super) {
11682 __extends(CallExpression, _super);
11683 function CallExpression() {
11684 return _super !== null && _super.apply(this, arguments) || this;
11685 }
11686 CallExpression.prototype.bind = function () {
11687 _super.prototype.bind.call(this);
11688 if (this.callee instanceof Identifier$1) {
11689 var variable = this.scope.findVariable(this.callee.name);
11690 if (variable.isNamespace) {
11691 this.context.error({
11692 code: 'CANNOT_CALL_NAMESPACE',
11693 message: "Cannot call a namespace ('" + this.callee.name + "')"
11694 }, this.start);
11695 }
11696 if (this.callee.name === 'eval') {
11697 this.context.warn({
11698 code: 'EVAL',
11699 message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
11700 url: 'https://rollupjs.org/guide/en#avoiding-eval'
11701 }, this.start);
11702 }
11703 }
11704 if (this.returnExpression === null) {
11705 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
11706 }
11707 for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
11708 var argument = _a[_i];
11709 // This will make sure all properties of parameters behave as "unknown"
11710 argument.deoptimizePath(UNKNOWN_PATH);
11711 }
11712 };
11713 CallExpression.prototype.deoptimizeCache = function () {
11714 if (this.returnExpression !== UNKNOWN_EXPRESSION) {
11715 this.returnExpression = UNKNOWN_EXPRESSION;
11716 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
11717 var expression = _a[_i];
11718 expression.deoptimizeCache();
11719 }
11720 }
11721 };
11722 CallExpression.prototype.deoptimizePath = function (path) {
11723 if (path.length > 0 && !this.context.deoptimizationTracker.track(this, path)) {
11724 if (this.returnExpression === null) {
11725 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
11726 }
11727 this.returnExpression.deoptimizePath(path);
11728 }
11729 };
11730 CallExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
11731 if (this.returnExpression === null) {
11732 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
11733 }
11734 if (this.returnExpression === UNKNOWN_EXPRESSION ||
11735 recursionTracker.isTracked(this.returnExpression, path)) {
11736 return UNKNOWN_VALUE;
11737 }
11738 this.expressionsToBeDeoptimized.push(origin);
11739 return this.returnExpression.getLiteralValueAtPath(path, recursionTracker.track(this.returnExpression, path), origin);
11740 };
11741 CallExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
11742 if (this.returnExpression === null) {
11743 this.returnExpression = this.callee.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, recursionTracker, this);
11744 }
11745 if (this.returnExpression === UNKNOWN_EXPRESSION ||
11746 recursionTracker.isTracked(this.returnExpression, path)) {
11747 return UNKNOWN_EXPRESSION;
11748 }
11749 this.expressionsToBeDeoptimized.push(origin);
11750 return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker.track(this.returnExpression, path), origin);
11751 };
11752 CallExpression.prototype.hasEffects = function (options) {
11753 for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
11754 var argument = _a[_i];
11755 if (argument.hasEffects(options))
11756 return true;
11757 }
11758 if (this.context.annotations && this.annotatedPure)
11759 return false;
11760 return (this.callee.hasEffects(options) ||
11761 this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()));
11762 };
11763 CallExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11764 return (path.length > 0 &&
11765 !options.hasReturnExpressionBeenAccessedAtPath(path, this) &&
11766 this.returnExpression.hasEffectsWhenAccessedAtPath(path, options.addAccessedReturnExpressionAtPath(path, this)));
11767 };
11768 CallExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11769 return (path.length === 0 ||
11770 (!options.hasReturnExpressionBeenAssignedAtPath(path, this) &&
11771 this.returnExpression.hasEffectsWhenAssignedAtPath(path, options.addAssignedReturnExpressionAtPath(path, this))));
11772 };
11773 CallExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11774 if (options.hasReturnExpressionBeenCalledAtPath(path, this))
11775 return false;
11776 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options.addCalledReturnExpressionAtPath(path, this));
11777 };
11778 CallExpression.prototype.include = function (includeAllChildrenRecursively) {
11779 _super.prototype.include.call(this, includeAllChildrenRecursively);
11780 if (!this.returnExpression.included) {
11781 this.returnExpression.include(false);
11782 }
11783 };
11784 CallExpression.prototype.initialise = function () {
11785 this.included = false;
11786 this.returnExpression = null;
11787 this.callOptions = CallOptions.create({
11788 args: this.arguments,
11789 callIdentifier: this,
11790 withNew: false
11791 });
11792 this.expressionsToBeDeoptimized = [];
11793 };
11794 CallExpression.prototype.render = function (code, options, _a) {
11795 var renderedParentType = (_a === void 0 ? BLANK : _a).renderedParentType;
11796 _super.prototype.render.call(this, code, options);
11797 if (renderedParentType === ExpressionStatement &&
11798 this.callee.type === FunctionExpression) {
11799 code.appendRight(this.start, '(');
11800 code.prependLeft(this.end, ')');
11801 }
11802 };
11803 return CallExpression;
11804}(NodeBase));
11805
11806var CatchScope = /** @class */ (function (_super) {
11807 __extends(CatchScope, _super);
11808 function CatchScope() {
11809 return _super !== null && _super.apply(this, arguments) || this;
11810 }
11811 CatchScope.prototype.addDeclaration = function (identifier, context, init, isHoisted) {
11812 if (init === void 0) { init = null; }
11813 if (isHoisted === void 0) { isHoisted = false; }
11814 if (isHoisted) {
11815 return this.parent.addDeclaration(identifier, context, init, true);
11816 }
11817 else {
11818 return _super.prototype.addDeclaration.call(this, identifier, context, init, false);
11819 }
11820 };
11821 return CatchScope;
11822}(ParameterScope));
11823
11824var CatchClause = /** @class */ (function (_super) {
11825 __extends(CatchClause, _super);
11826 function CatchClause() {
11827 return _super !== null && _super.apply(this, arguments) || this;
11828 }
11829 CatchClause.prototype.createScope = function (parentScope) {
11830 this.scope = new CatchScope(parentScope, this.context);
11831 };
11832 CatchClause.prototype.initialise = function () {
11833 this.included = false;
11834 if (this.param) {
11835 this.param.declare('parameter', UNKNOWN_EXPRESSION);
11836 }
11837 };
11838 CatchClause.prototype.parseNode = function (esTreeNode) {
11839 this.body = (new this.context.nodeConstructors.BlockStatement(esTreeNode.body, this, this.scope));
11840 _super.prototype.parseNode.call(this, esTreeNode);
11841 };
11842 return CatchClause;
11843}(NodeBase));
11844CatchClause.prototype.preventChildBlockScope = true;
11845
11846var ClassBody = /** @class */ (function (_super) {
11847 __extends(ClassBody, _super);
11848 function ClassBody() {
11849 return _super !== null && _super.apply(this, arguments) || this;
11850 }
11851 ClassBody.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11852 if (path.length > 0) {
11853 return true;
11854 }
11855 return (this.classConstructor !== null &&
11856 this.classConstructor.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options));
11857 };
11858 ClassBody.prototype.initialise = function () {
11859 this.included = false;
11860 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
11861 var method = _a[_i];
11862 if (method.kind === 'constructor') {
11863 this.classConstructor = method;
11864 return;
11865 }
11866 }
11867 this.classConstructor = null;
11868 };
11869 return ClassBody;
11870}(NodeBase));
11871
11872var ClassExpression = /** @class */ (function (_super) {
11873 __extends(ClassExpression, _super);
11874 function ClassExpression() {
11875 return _super !== null && _super.apply(this, arguments) || this;
11876 }
11877 return ClassExpression;
11878}(ClassNode));
11879
11880var MultiExpression = /** @class */ (function () {
11881 function MultiExpression(expressions) {
11882 this.expressions = expressions;
11883 }
11884 MultiExpression.prototype.deoptimizePath = function (path) {
11885 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
11886 var expression = _a[_i];
11887 expression.deoptimizePath(path);
11888 }
11889 };
11890 MultiExpression.prototype.getLiteralValueAtPath = function () {
11891 return UNKNOWN_VALUE;
11892 };
11893 MultiExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
11894 return new MultiExpression(this.expressions.map(function (expression) {
11895 return expression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
11896 }));
11897 };
11898 MultiExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11899 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
11900 var expression = _a[_i];
11901 if (expression.hasEffectsWhenAccessedAtPath(path, options))
11902 return true;
11903 }
11904 return false;
11905 };
11906 MultiExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11907 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
11908 var expression = _a[_i];
11909 if (expression.hasEffectsWhenAssignedAtPath(path, options))
11910 return true;
11911 }
11912 return false;
11913 };
11914 MultiExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
11915 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
11916 var expression = _a[_i];
11917 if (expression.hasEffectsWhenCalledAtPath(path, callOptions, options))
11918 return true;
11919 }
11920 return false;
11921 };
11922 MultiExpression.prototype.include = function () { };
11923 return MultiExpression;
11924}());
11925
11926var ConditionalExpression = /** @class */ (function (_super) {
11927 __extends(ConditionalExpression, _super);
11928 function ConditionalExpression() {
11929 return _super !== null && _super.apply(this, arguments) || this;
11930 }
11931 ConditionalExpression.prototype.bind = function () {
11932 _super.prototype.bind.call(this);
11933 if (!this.isBranchResolutionAnalysed)
11934 this.analyseBranchResolution();
11935 };
11936 ConditionalExpression.prototype.deoptimizeCache = function () {
11937 if (this.usedBranch !== null) {
11938 // We did not track if there were reassignments to the previous branch.
11939 // Also, the return value might need to be reassigned.
11940 this.usedBranch = null;
11941 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
11942 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
11943 var expression = _a[_i];
11944 expression.deoptimizeCache();
11945 }
11946 }
11947 };
11948 ConditionalExpression.prototype.deoptimizePath = function (path) {
11949 if (path.length > 0) {
11950 if (!this.isBranchResolutionAnalysed)
11951 this.analyseBranchResolution();
11952 if (this.usedBranch === null) {
11953 this.consequent.deoptimizePath(path);
11954 this.alternate.deoptimizePath(path);
11955 }
11956 else {
11957 this.usedBranch.deoptimizePath(path);
11958 }
11959 }
11960 };
11961 ConditionalExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
11962 if (!this.isBranchResolutionAnalysed)
11963 this.analyseBranchResolution();
11964 if (this.usedBranch === null)
11965 return UNKNOWN_VALUE;
11966 this.expressionsToBeDeoptimized.push(origin);
11967 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
11968 };
11969 ConditionalExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
11970 if (!this.isBranchResolutionAnalysed)
11971 this.analyseBranchResolution();
11972 if (this.usedBranch === null)
11973 return new MultiExpression([
11974 this.consequent.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
11975 this.alternate.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
11976 ]);
11977 this.expressionsToBeDeoptimized.push(origin);
11978 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
11979 };
11980 ConditionalExpression.prototype.hasEffects = function (options) {
11981 if (this.test.hasEffects(options))
11982 return true;
11983 if (this.usedBranch === null) {
11984 return this.consequent.hasEffects(options) || this.alternate.hasEffects(options);
11985 }
11986 return this.usedBranch.hasEffects(options);
11987 };
11988 ConditionalExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
11989 if (path.length === 0)
11990 return false;
11991 if (this.usedBranch === null) {
11992 return (this.consequent.hasEffectsWhenAccessedAtPath(path, options) ||
11993 this.alternate.hasEffectsWhenAccessedAtPath(path, options));
11994 }
11995 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options);
11996 };
11997 ConditionalExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
11998 if (path.length === 0)
11999 return true;
12000 if (this.usedBranch === null) {
12001 return (this.consequent.hasEffectsWhenAssignedAtPath(path, options) ||
12002 this.alternate.hasEffectsWhenAssignedAtPath(path, options));
12003 }
12004 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options);
12005 };
12006 ConditionalExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12007 if (this.usedBranch === null) {
12008 return (this.consequent.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
12009 this.alternate.hasEffectsWhenCalledAtPath(path, callOptions, options));
12010 }
12011 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options);
12012 };
12013 ConditionalExpression.prototype.include = function (includeAllChildrenRecursively) {
12014 this.included = true;
12015 if (includeAllChildrenRecursively || this.usedBranch === null || this.test.shouldBeIncluded()) {
12016 this.test.include(includeAllChildrenRecursively);
12017 this.consequent.include(includeAllChildrenRecursively);
12018 this.alternate.include(includeAllChildrenRecursively);
12019 }
12020 else {
12021 this.usedBranch.include(includeAllChildrenRecursively);
12022 }
12023 };
12024 ConditionalExpression.prototype.initialise = function () {
12025 this.included = false;
12026 this.isBranchResolutionAnalysed = false;
12027 this.usedBranch = null;
12028 this.unusedBranch = null;
12029 this.expressionsToBeDeoptimized = [];
12030 };
12031 ConditionalExpression.prototype.render = function (code, options, _a) {
12032 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
12033 if (!this.test.included) {
12034 code.remove(this.start, this.usedBranch.start);
12035 code.remove(this.usedBranch.end, this.end);
12036 removeAnnotations(this, code);
12037 this.usedBranch.render(code, options, {
12038 isCalleeOfRenderedParent: renderedParentType
12039 ? isCalleeOfRenderedParent
12040 : this.parent.callee === this,
12041 renderedParentType: renderedParentType || this.parent.type
12042 });
12043 }
12044 else {
12045 _super.prototype.render.call(this, code, options);
12046 }
12047 };
12048 ConditionalExpression.prototype.analyseBranchResolution = function () {
12049 this.isBranchResolutionAnalysed = true;
12050 var testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
12051 if (testValue !== UNKNOWN_VALUE) {
12052 if (testValue) {
12053 this.usedBranch = this.consequent;
12054 this.unusedBranch = this.alternate;
12055 }
12056 else {
12057 this.usedBranch = this.alternate;
12058 this.unusedBranch = this.consequent;
12059 }
12060 }
12061 };
12062 return ConditionalExpression;
12063}(NodeBase));
12064
12065var DoWhileStatement = /** @class */ (function (_super) {
12066 __extends(DoWhileStatement, _super);
12067 function DoWhileStatement() {
12068 return _super !== null && _super.apply(this, arguments) || this;
12069 }
12070 DoWhileStatement.prototype.hasEffects = function (options) {
12071 return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements()));
12072 };
12073 return DoWhileStatement;
12074}(NodeBase));
12075
12076var EmptyStatement = /** @class */ (function (_super) {
12077 __extends(EmptyStatement, _super);
12078 function EmptyStatement() {
12079 return _super !== null && _super.apply(this, arguments) || this;
12080 }
12081 EmptyStatement.prototype.hasEffects = function () {
12082 return false;
12083 };
12084 return EmptyStatement;
12085}(NodeBase));
12086
12087var ExportAllDeclaration$1 = /** @class */ (function (_super) {
12088 __extends(ExportAllDeclaration, _super);
12089 function ExportAllDeclaration() {
12090 return _super !== null && _super.apply(this, arguments) || this;
12091 }
12092 ExportAllDeclaration.prototype.hasEffects = function () {
12093 return false;
12094 };
12095 ExportAllDeclaration.prototype.initialise = function () {
12096 this.included = false;
12097 this.context.addExport(this);
12098 };
12099 ExportAllDeclaration.prototype.render = function (code, _options, _a) {
12100 var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
12101 code.remove(start, end);
12102 };
12103 return ExportAllDeclaration;
12104}(NodeBase));
12105ExportAllDeclaration$1.prototype.needsBoundaries = true;
12106
12107var ExportNamedDeclaration = /** @class */ (function (_super) {
12108 __extends(ExportNamedDeclaration, _super);
12109 function ExportNamedDeclaration() {
12110 return _super !== null && _super.apply(this, arguments) || this;
12111 }
12112 ExportNamedDeclaration.prototype.bind = function () {
12113 // Do not bind specifiers
12114 if (this.declaration !== null)
12115 this.declaration.bind();
12116 };
12117 ExportNamedDeclaration.prototype.hasEffects = function (options) {
12118 return this.declaration && this.declaration.hasEffects(options);
12119 };
12120 ExportNamedDeclaration.prototype.initialise = function () {
12121 this.included = false;
12122 this.context.addExport(this);
12123 };
12124 ExportNamedDeclaration.prototype.render = function (code, options, _a) {
12125 var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
12126 if (this.declaration === null) {
12127 code.remove(start, end);
12128 }
12129 else {
12130 code.remove(this.start, this.declaration.start);
12131 this.declaration.render(code, options, { start: start, end: end });
12132 }
12133 };
12134 return ExportNamedDeclaration;
12135}(NodeBase));
12136ExportNamedDeclaration.prototype.needsBoundaries = true;
12137
12138var ExpressionStatement$1 = /** @class */ (function (_super) {
12139 __extends(ExpressionStatement, _super);
12140 function ExpressionStatement() {
12141 return _super !== null && _super.apply(this, arguments) || this;
12142 }
12143 ExpressionStatement.prototype.initialise = function () {
12144 this.included = false;
12145 if (this.directive &&
12146 this.directive !== 'use strict' &&
12147 this.parent.type === Program) {
12148 this.context.warn(
12149 // This is necessary, because either way (deleting or not) can lead to errors.
12150 {
12151 code: 'MODULE_LEVEL_DIRECTIVE',
12152 message: "Module level directives cause errors when bundled, '" + this.directive + "' was ignored."
12153 }, this.start);
12154 }
12155 };
12156 ExpressionStatement.prototype.render = function (code, options) {
12157 _super.prototype.render.call(this, code, options);
12158 if (this.included)
12159 this.insertSemicolon(code);
12160 };
12161 ExpressionStatement.prototype.shouldBeIncluded = function () {
12162 if (this.directive && this.directive !== 'use strict')
12163 return this.parent.type !== Program;
12164 return _super.prototype.shouldBeIncluded.call(this);
12165 };
12166 return ExpressionStatement;
12167}(NodeBase));
12168
12169var ForInStatement = /** @class */ (function (_super) {
12170 __extends(ForInStatement, _super);
12171 function ForInStatement() {
12172 return _super !== null && _super.apply(this, arguments) || this;
12173 }
12174 ForInStatement.prototype.bind = function () {
12175 this.left.bind();
12176 this.left.deoptimizePath(EMPTY_PATH);
12177 this.right.bind();
12178 this.body.bind();
12179 };
12180 ForInStatement.prototype.createScope = function (parentScope) {
12181 this.scope = new BlockScope(parentScope);
12182 };
12183 ForInStatement.prototype.hasEffects = function (options) {
12184 return ((this.left &&
12185 (this.left.hasEffects(options) ||
12186 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) ||
12187 (this.right && this.right.hasEffects(options)) ||
12188 this.body.hasEffects(options.setIgnoreBreakStatements()));
12189 };
12190 ForInStatement.prototype.include = function (includeAllChildrenRecursively) {
12191 this.included = true;
12192 this.left.includeWithAllDeclaredVariables(includeAllChildrenRecursively);
12193 this.left.deoptimizePath(EMPTY_PATH);
12194 this.right.include(includeAllChildrenRecursively);
12195 this.body.include(includeAllChildrenRecursively);
12196 };
12197 ForInStatement.prototype.render = function (code, options) {
12198 this.left.render(code, options, NO_SEMICOLON);
12199 this.right.render(code, options, NO_SEMICOLON);
12200 this.body.render(code, options);
12201 };
12202 return ForInStatement;
12203}(NodeBase));
12204
12205var ForOfStatement = /** @class */ (function (_super) {
12206 __extends(ForOfStatement, _super);
12207 function ForOfStatement() {
12208 return _super !== null && _super.apply(this, arguments) || this;
12209 }
12210 ForOfStatement.prototype.bind = function () {
12211 this.left.bind();
12212 this.left.deoptimizePath(EMPTY_PATH);
12213 this.right.bind();
12214 this.body.bind();
12215 };
12216 ForOfStatement.prototype.createScope = function (parentScope) {
12217 this.scope = new BlockScope(parentScope);
12218 };
12219 ForOfStatement.prototype.hasEffects = function (options) {
12220 return ((this.left &&
12221 (this.left.hasEffects(options) ||
12222 this.left.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))) ||
12223 (this.right && this.right.hasEffects(options)) ||
12224 this.body.hasEffects(options.setIgnoreBreakStatements()));
12225 };
12226 ForOfStatement.prototype.include = function (includeAllChildrenRecursively) {
12227 this.included = true;
12228 this.left.includeWithAllDeclaredVariables(includeAllChildrenRecursively);
12229 this.left.deoptimizePath(EMPTY_PATH);
12230 this.right.include(includeAllChildrenRecursively);
12231 this.body.include(includeAllChildrenRecursively);
12232 };
12233 ForOfStatement.prototype.render = function (code, options) {
12234 this.left.render(code, options, NO_SEMICOLON);
12235 this.right.render(code, options, NO_SEMICOLON);
12236 this.body.render(code, options);
12237 };
12238 return ForOfStatement;
12239}(NodeBase));
12240
12241var ForStatement = /** @class */ (function (_super) {
12242 __extends(ForStatement, _super);
12243 function ForStatement() {
12244 return _super !== null && _super.apply(this, arguments) || this;
12245 }
12246 ForStatement.prototype.createScope = function (parentScope) {
12247 this.scope = new BlockScope(parentScope);
12248 };
12249 ForStatement.prototype.hasEffects = function (options) {
12250 return ((this.init && this.init.hasEffects(options)) ||
12251 (this.test && this.test.hasEffects(options)) ||
12252 (this.update && this.update.hasEffects(options)) ||
12253 this.body.hasEffects(options.setIgnoreBreakStatements()));
12254 };
12255 ForStatement.prototype.render = function (code, options) {
12256 if (this.init)
12257 this.init.render(code, options, NO_SEMICOLON);
12258 if (this.test)
12259 this.test.render(code, options, NO_SEMICOLON);
12260 if (this.update)
12261 this.update.render(code, options, NO_SEMICOLON);
12262 this.body.render(code, options);
12263 };
12264 return ForStatement;
12265}(NodeBase));
12266
12267var FunctionExpression$1 = /** @class */ (function (_super) {
12268 __extends(FunctionExpression, _super);
12269 function FunctionExpression() {
12270 return _super !== null && _super.apply(this, arguments) || this;
12271 }
12272 return FunctionExpression;
12273}(FunctionNode));
12274
12275var IfStatement = /** @class */ (function (_super) {
12276 __extends(IfStatement, _super);
12277 function IfStatement() {
12278 return _super !== null && _super.apply(this, arguments) || this;
12279 }
12280 IfStatement.prototype.bind = function () {
12281 _super.prototype.bind.call(this);
12282 if (!this.isTestValueAnalysed) {
12283 this.testValue = UNKNOWN_VALUE;
12284 this.isTestValueAnalysed = true;
12285 this.testValue = this.test.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
12286 }
12287 };
12288 IfStatement.prototype.deoptimizeCache = function () {
12289 this.testValue = UNKNOWN_VALUE;
12290 };
12291 IfStatement.prototype.hasEffects = function (options) {
12292 if (this.test.hasEffects(options))
12293 return true;
12294 if (this.testValue === UNKNOWN_VALUE) {
12295 return (this.consequent.hasEffects(options) ||
12296 (this.alternate !== null && this.alternate.hasEffects(options)));
12297 }
12298 return this.testValue
12299 ? this.consequent.hasEffects(options)
12300 : this.alternate !== null && this.alternate.hasEffects(options);
12301 };
12302 IfStatement.prototype.include = function (includeAllChildrenRecursively) {
12303 this.included = true;
12304 if (includeAllChildrenRecursively) {
12305 this.test.include(true);
12306 this.consequent.include(true);
12307 if (this.alternate !== null) {
12308 this.alternate.include(true);
12309 }
12310 return;
12311 }
12312 var hasUnknownTest = this.testValue === UNKNOWN_VALUE;
12313 if (hasUnknownTest || this.test.shouldBeIncluded()) {
12314 this.test.include(false);
12315 }
12316 if ((hasUnknownTest || this.testValue) && this.consequent.shouldBeIncluded()) {
12317 this.consequent.include(false);
12318 }
12319 if (this.alternate !== null &&
12320 ((hasUnknownTest || !this.testValue) && this.alternate.shouldBeIncluded())) {
12321 this.alternate.include(false);
12322 }
12323 };
12324 IfStatement.prototype.initialise = function () {
12325 this.included = false;
12326 this.isTestValueAnalysed = false;
12327 };
12328 IfStatement.prototype.render = function (code, options) {
12329 // Note that unknown test values are always included
12330 if (!this.test.included &&
12331 (this.testValue
12332 ? this.alternate === null || !this.alternate.included
12333 : !this.consequent.included)) {
12334 var singleRetainedBranch = this.testValue ? this.consequent : this.alternate;
12335 code.remove(this.start, singleRetainedBranch.start);
12336 code.remove(singleRetainedBranch.end, this.end);
12337 removeAnnotations(this, code);
12338 singleRetainedBranch.render(code, options);
12339 }
12340 else {
12341 if (this.test.included) {
12342 this.test.render(code, options);
12343 }
12344 else {
12345 code.overwrite(this.test.start, this.test.end, this.testValue ? 'true' : 'false');
12346 }
12347 if (this.consequent.included) {
12348 this.consequent.render(code, options);
12349 }
12350 else {
12351 code.overwrite(this.consequent.start, this.consequent.end, ';');
12352 }
12353 if (this.alternate !== null) {
12354 if (this.alternate.included) {
12355 this.alternate.render(code, options);
12356 }
12357 else {
12358 code.remove(this.consequent.end, this.alternate.end);
12359 }
12360 }
12361 }
12362 };
12363 return IfStatement;
12364}(NodeBase));
12365
12366var getDynamicImportMechanism = function (options) {
12367 switch (options.format) {
12368 case 'cjs': {
12369 var _ = options.compact ? '' : ' ';
12370 return {
12371 interopLeft: "Promise.resolve({" + _ + "default:" + _ + "require(",
12372 interopRight: ")" + _ + "})",
12373 left: 'Promise.resolve(require(',
12374 right: '))'
12375 };
12376 }
12377 case 'amd': {
12378 var _ = options.compact ? '' : ' ';
12379 var resolve = options.compact ? 'c' : 'resolve';
12380 var reject = options.compact ? 'e' : 'reject';
12381 return {
12382 interopLeft: "new Promise(function" + _ + "(" + resolve + "," + _ + reject + ")" + _ + "{" + _ + "require([",
12383 interopRight: "]," + _ + "function" + _ + "(m)" + _ + "{" + _ + resolve + "({" + _ + "default:" + _ + "m" + _ + "})" + _ + "}," + _ + reject + ")" + _ + "})",
12384 left: "new Promise(function" + _ + "(" + resolve + "," + _ + reject + ")" + _ + "{" + _ + "require([",
12385 right: "]," + _ + resolve + "," + _ + reject + ")" + _ + "})"
12386 };
12387 }
12388 case 'system':
12389 return {
12390 left: 'module.import(',
12391 right: ')'
12392 };
12393 case 'es':
12394 return {
12395 left: (options.dynamicImportFunction || 'import') + "(",
12396 right: ')'
12397 };
12398 }
12399};
12400var Import = /** @class */ (function (_super) {
12401 __extends(Import, _super);
12402 function Import() {
12403 return _super !== null && _super.apply(this, arguments) || this;
12404 }
12405 Import.prototype.include = function () {
12406 this.included = true;
12407 this.context.includeDynamicImport(this);
12408 };
12409 Import.prototype.initialise = function () {
12410 this.included = false;
12411 this.resolutionNamespace = undefined;
12412 this.resolutionInterop = false;
12413 this.context.addDynamicImport(this);
12414 };
12415 Import.prototype.render = function (code, options) {
12416 if (this.resolutionNamespace) {
12417 var _ = options.compact ? '' : ' ';
12418 var s = options.compact ? '' : ';';
12419 code.overwrite(this.parent.start, this.parent.end, "Promise.resolve().then(function" + _ + "()" + _ + "{" + _ + "return " + this.resolutionNamespace + s + _ + "})");
12420 return;
12421 }
12422 var importMechanism = getDynamicImportMechanism(options);
12423 if (importMechanism) {
12424 var leftMechanism = (this.resolutionInterop && importMechanism.interopLeft) || importMechanism.left;
12425 var leftMechanismEnd = findFirstOccurrenceOutsideComment(code.original, '(', this.parent.callee.end) + 1;
12426 code.overwrite(this.parent.start, leftMechanismEnd, leftMechanism);
12427 var rightMechanism = (this.resolutionInterop && importMechanism.interopRight) || importMechanism.right;
12428 code.overwrite(this.parent.end - 1, this.parent.end, rightMechanism);
12429 }
12430 };
12431 Import.prototype.renderFinalResolution = function (code, resolution, format) {
12432 if (this.included) {
12433 if (format === 'amd' && resolution.startsWith("'.") && resolution.endsWith(".js'")) {
12434 resolution = resolution.slice(0, -4) + "'";
12435 }
12436 code.overwrite(this.parent.arguments[0].start, this.parent.arguments[0].end, resolution);
12437 }
12438 };
12439 Import.prototype.setResolution = function (interop, namespace) {
12440 if (namespace === void 0) { namespace = undefined; }
12441 this.resolutionInterop = interop;
12442 this.resolutionNamespace = namespace;
12443 };
12444 return Import;
12445}(NodeBase));
12446
12447var ImportDeclaration = /** @class */ (function (_super) {
12448 __extends(ImportDeclaration, _super);
12449 function ImportDeclaration() {
12450 return _super !== null && _super.apply(this, arguments) || this;
12451 }
12452 ImportDeclaration.prototype.bind = function () { };
12453 ImportDeclaration.prototype.hasEffects = function () {
12454 return false;
12455 };
12456 ImportDeclaration.prototype.initialise = function () {
12457 this.included = false;
12458 this.context.addImport(this);
12459 };
12460 ImportDeclaration.prototype.render = function (code, _options, _a) {
12461 var _b = _a === void 0 ? BLANK : _a, start = _b.start, end = _b.end;
12462 code.remove(start, end);
12463 };
12464 return ImportDeclaration;
12465}(NodeBase));
12466ImportDeclaration.prototype.needsBoundaries = true;
12467
12468var LabeledStatement = /** @class */ (function (_super) {
12469 __extends(LabeledStatement, _super);
12470 function LabeledStatement() {
12471 return _super !== null && _super.apply(this, arguments) || this;
12472 }
12473 LabeledStatement.prototype.hasEffects = function (options) {
12474 return this.body.hasEffects(options.setIgnoreLabel(this.label.name).setIgnoreBreakStatements());
12475 };
12476 return LabeledStatement;
12477}(NodeBase));
12478
12479function isLiteral(node) {
12480 return node.type === Literal;
12481}
12482var Literal$1 = /** @class */ (function (_super) {
12483 __extends(Literal, _super);
12484 function Literal() {
12485 return _super !== null && _super.apply(this, arguments) || this;
12486 }
12487 Literal.prototype.getLiteralValueAtPath = function (path) {
12488 if (path.length > 0 ||
12489 // unknown literals such as bigints can also be null but do not start with an "n"
12490 (this.value === null && this.context.code.charCodeAt(this.start) !== 110) ||
12491 typeof this.value === 'bigint') {
12492 return UNKNOWN_VALUE;
12493 }
12494 return this.value;
12495 };
12496 Literal.prototype.getReturnExpressionWhenCalledAtPath = function (path) {
12497 if (path.length !== 1)
12498 return UNKNOWN_EXPRESSION;
12499 return getMemberReturnExpressionWhenCalled(this.members, path[0]);
12500 };
12501 Literal.prototype.hasEffectsWhenAccessedAtPath = function (path) {
12502 if (this.value === null) {
12503 return path.length > 0;
12504 }
12505 return path.length > 1;
12506 };
12507 Literal.prototype.hasEffectsWhenAssignedAtPath = function (path) {
12508 return path.length > 0;
12509 };
12510 Literal.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12511 if (path.length === 1) {
12512 return hasMemberEffectWhenCalled(this.members, path[0], this.included, callOptions, options);
12513 }
12514 return true;
12515 };
12516 Literal.prototype.initialise = function () {
12517 this.included = false;
12518 this.members = getLiteralMembersForValue(this.value);
12519 };
12520 Literal.prototype.render = function (code, _options) {
12521 if (typeof this.value === 'string') {
12522 code.indentExclusionRanges.push([this.start + 1, this.end - 1]);
12523 }
12524 };
12525 return Literal;
12526}(NodeBase));
12527
12528var LogicalExpression = /** @class */ (function (_super) {
12529 __extends(LogicalExpression, _super);
12530 function LogicalExpression() {
12531 return _super !== null && _super.apply(this, arguments) || this;
12532 }
12533 LogicalExpression.prototype.bind = function () {
12534 _super.prototype.bind.call(this);
12535 if (!this.isBranchResolutionAnalysed)
12536 this.analyseBranchResolution();
12537 };
12538 LogicalExpression.prototype.deoptimizeCache = function () {
12539 if (this.usedBranch !== null) {
12540 // We did not track if there were reassignments to any of the branches.
12541 // Also, the return values might need reassignment.
12542 this.usedBranch = null;
12543 this.unusedBranch.deoptimizePath(UNKNOWN_PATH);
12544 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
12545 var expression = _a[_i];
12546 expression.deoptimizeCache();
12547 }
12548 }
12549 };
12550 LogicalExpression.prototype.deoptimizePath = function (path) {
12551 if (path.length > 0) {
12552 if (!this.isBranchResolutionAnalysed)
12553 this.analyseBranchResolution();
12554 if (this.usedBranch === null) {
12555 this.left.deoptimizePath(path);
12556 this.right.deoptimizePath(path);
12557 }
12558 else {
12559 this.usedBranch.deoptimizePath(path);
12560 }
12561 }
12562 };
12563 LogicalExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
12564 if (!this.isBranchResolutionAnalysed)
12565 this.analyseBranchResolution();
12566 if (this.usedBranch === null)
12567 return UNKNOWN_VALUE;
12568 this.expressionsToBeDeoptimized.push(origin);
12569 return this.usedBranch.getLiteralValueAtPath(path, recursionTracker, origin);
12570 };
12571 LogicalExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
12572 if (!this.isBranchResolutionAnalysed)
12573 this.analyseBranchResolution();
12574 if (this.usedBranch === null)
12575 return new MultiExpression([
12576 this.left.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin),
12577 this.right.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin)
12578 ]);
12579 this.expressionsToBeDeoptimized.push(origin);
12580 return this.usedBranch.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
12581 };
12582 LogicalExpression.prototype.hasEffects = function (options) {
12583 if (this.usedBranch === null) {
12584 return this.left.hasEffects(options) || this.right.hasEffects(options);
12585 }
12586 return this.usedBranch.hasEffects(options);
12587 };
12588 LogicalExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
12589 if (path.length === 0)
12590 return false;
12591 if (this.usedBranch === null) {
12592 return (this.left.hasEffectsWhenAccessedAtPath(path, options) ||
12593 this.right.hasEffectsWhenAccessedAtPath(path, options));
12594 }
12595 return this.usedBranch.hasEffectsWhenAccessedAtPath(path, options);
12596 };
12597 LogicalExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
12598 if (path.length === 0)
12599 return true;
12600 if (this.usedBranch === null) {
12601 return (this.left.hasEffectsWhenAssignedAtPath(path, options) ||
12602 this.right.hasEffectsWhenAssignedAtPath(path, options));
12603 }
12604 return this.usedBranch.hasEffectsWhenAssignedAtPath(path, options);
12605 };
12606 LogicalExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12607 if (this.usedBranch === null) {
12608 return (this.left.hasEffectsWhenCalledAtPath(path, callOptions, options) ||
12609 this.right.hasEffectsWhenCalledAtPath(path, callOptions, options));
12610 }
12611 return this.usedBranch.hasEffectsWhenCalledAtPath(path, callOptions, options);
12612 };
12613 LogicalExpression.prototype.include = function (includeAllChildrenRecursively) {
12614 this.included = true;
12615 if (includeAllChildrenRecursively ||
12616 this.usedBranch === null ||
12617 this.unusedBranch.shouldBeIncluded()) {
12618 this.left.include(includeAllChildrenRecursively);
12619 this.right.include(includeAllChildrenRecursively);
12620 }
12621 else {
12622 this.usedBranch.include(includeAllChildrenRecursively);
12623 }
12624 };
12625 LogicalExpression.prototype.initialise = function () {
12626 this.included = false;
12627 this.isBranchResolutionAnalysed = false;
12628 this.usedBranch = null;
12629 this.unusedBranch = null;
12630 this.expressionsToBeDeoptimized = [];
12631 };
12632 LogicalExpression.prototype.render = function (code, options, _a) {
12633 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
12634 if (!this.left.included || !this.right.included) {
12635 code.remove(this.start, this.usedBranch.start);
12636 code.remove(this.usedBranch.end, this.end);
12637 removeAnnotations(this, code);
12638 this.usedBranch.render(code, options, {
12639 isCalleeOfRenderedParent: renderedParentType
12640 ? isCalleeOfRenderedParent
12641 : this.parent.callee === this,
12642 renderedParentType: renderedParentType || this.parent.type
12643 });
12644 }
12645 else {
12646 _super.prototype.render.call(this, code, options);
12647 }
12648 };
12649 LogicalExpression.prototype.analyseBranchResolution = function () {
12650 this.isBranchResolutionAnalysed = true;
12651 var leftValue = this.left.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
12652 if (leftValue !== UNKNOWN_VALUE) {
12653 if (this.operator === '||' ? leftValue : !leftValue) {
12654 this.usedBranch = this.left;
12655 this.unusedBranch = this.right;
12656 }
12657 else {
12658 this.usedBranch = this.right;
12659 this.unusedBranch = this.left;
12660 }
12661 }
12662 };
12663 return LogicalExpression;
12664}(NodeBase));
12665
12666function getResolvablePropertyKey(memberExpression) {
12667 return memberExpression.computed
12668 ? getResolvableComputedPropertyKey(memberExpression.property)
12669 : memberExpression.property.name;
12670}
12671function getResolvableComputedPropertyKey(propertyKey) {
12672 if (propertyKey instanceof Literal$1) {
12673 return String(propertyKey.value);
12674 }
12675 return null;
12676}
12677function getPathIfNotComputed(memberExpression) {
12678 var nextPathKey = memberExpression.propertyKey;
12679 var object = memberExpression.object;
12680 if (typeof nextPathKey === 'string') {
12681 if (object instanceof Identifier$1) {
12682 return [
12683 { key: object.name, pos: object.start },
12684 { key: nextPathKey, pos: memberExpression.property.start }
12685 ];
12686 }
12687 if (isMemberExpression(object)) {
12688 var parentPath = getPathIfNotComputed(object);
12689 return (parentPath && parentPath.concat([{ key: nextPathKey, pos: memberExpression.property.start }]));
12690 }
12691 }
12692 return null;
12693}
12694function getStringFromPath(path) {
12695 var pathString = path[0].key;
12696 for (var index = 1; index < path.length; index++) {
12697 pathString += '.' + path[index].key;
12698 }
12699 return pathString;
12700}
12701function isMemberExpression(node) {
12702 return node.type === MemberExpression;
12703}
12704var MemberExpression$1 = /** @class */ (function (_super) {
12705 __extends(MemberExpression, _super);
12706 function MemberExpression() {
12707 var _this = _super !== null && _super.apply(this, arguments) || this;
12708 _this.variable = null;
12709 return _this;
12710 }
12711 MemberExpression.prototype.addExportedVariables = function () { };
12712 MemberExpression.prototype.bind = function () {
12713 if (this.bound)
12714 return;
12715 this.bound = true;
12716 var path = getPathIfNotComputed(this);
12717 var baseVariable = path && this.scope.findVariable(path[0].key);
12718 if (baseVariable && baseVariable.isNamespace) {
12719 var resolvedVariable = this.resolveNamespaceVariables(baseVariable, path.slice(1));
12720 if (!resolvedVariable) {
12721 _super.prototype.bind.call(this);
12722 }
12723 else if (typeof resolvedVariable === 'string') {
12724 this.replacement = resolvedVariable;
12725 }
12726 else {
12727 if (resolvedVariable.isExternal && resolvedVariable.module) {
12728 resolvedVariable.module.suggestName(path[0].key);
12729 }
12730 this.variable = resolvedVariable;
12731 this.scope.addNamespaceMemberAccess(getStringFromPath(path), resolvedVariable);
12732 }
12733 }
12734 else {
12735 _super.prototype.bind.call(this);
12736 if (this.propertyKey === null)
12737 this.analysePropertyKey();
12738 }
12739 };
12740 MemberExpression.prototype.deoptimizeCache = function () {
12741 for (var _i = 0, _a = this.expressionsToBeDeoptimized; _i < _a.length; _i++) {
12742 var expression = _a[_i];
12743 expression.deoptimizeCache();
12744 }
12745 };
12746 MemberExpression.prototype.deoptimizePath = function (path) {
12747 if (!this.bound)
12748 this.bind();
12749 if (path.length === 0)
12750 this.disallowNamespaceReassignment();
12751 if (this.variable) {
12752 this.variable.deoptimizePath(path);
12753 }
12754 else {
12755 if (this.propertyKey === null)
12756 this.analysePropertyKey();
12757 this.object.deoptimizePath([this.propertyKey].concat(path));
12758 }
12759 };
12760 MemberExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
12761 if (this.variable !== null) {
12762 return this.variable.getLiteralValueAtPath(path, recursionTracker, origin);
12763 }
12764 if (this.propertyKey === null)
12765 this.analysePropertyKey();
12766 this.expressionsToBeDeoptimized.push(origin);
12767 return this.object.getLiteralValueAtPath([this.propertyKey].concat(path), recursionTracker, origin);
12768 };
12769 MemberExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
12770 if (this.variable !== null) {
12771 return this.variable.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
12772 }
12773 if (this.propertyKey === null)
12774 this.analysePropertyKey();
12775 this.expressionsToBeDeoptimized.push(origin);
12776 return this.object.getReturnExpressionWhenCalledAtPath([this.propertyKey].concat(path), recursionTracker, origin);
12777 };
12778 MemberExpression.prototype.hasEffects = function (options) {
12779 return (this.property.hasEffects(options) ||
12780 this.object.hasEffects(options) ||
12781 (this.context.propertyReadSideEffects &&
12782 this.object.hasEffectsWhenAccessedAtPath([this.propertyKey], options)));
12783 };
12784 MemberExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
12785 if (path.length === 0) {
12786 return false;
12787 }
12788 if (this.variable !== null) {
12789 return this.variable.hasEffectsWhenAccessedAtPath(path, options);
12790 }
12791 return this.object.hasEffectsWhenAccessedAtPath([this.propertyKey].concat(path), options);
12792 };
12793 MemberExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
12794 if (this.variable !== null) {
12795 return this.variable.hasEffectsWhenAssignedAtPath(path, options);
12796 }
12797 return this.object.hasEffectsWhenAssignedAtPath([this.propertyKey].concat(path), options);
12798 };
12799 MemberExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12800 if (this.variable !== null) {
12801 return this.variable.hasEffectsWhenCalledAtPath(path, callOptions, options);
12802 }
12803 return this.object.hasEffectsWhenCalledAtPath([this.propertyKey].concat(path), callOptions, options);
12804 };
12805 MemberExpression.prototype.include = function (includeAllChildrenRecursively) {
12806 if (!this.included) {
12807 this.included = true;
12808 if (this.variable !== null) {
12809 this.context.includeVariable(this.variable);
12810 }
12811 }
12812 this.object.include(includeAllChildrenRecursively);
12813 this.property.include(includeAllChildrenRecursively);
12814 };
12815 MemberExpression.prototype.initialise = function () {
12816 this.included = false;
12817 this.propertyKey = getResolvablePropertyKey(this);
12818 this.variable = null;
12819 this.bound = false;
12820 this.replacement = null;
12821 this.expressionsToBeDeoptimized = [];
12822 };
12823 MemberExpression.prototype.render = function (code, options, _a) {
12824 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
12825 var isCalleeOfDifferentParent = renderedParentType === CallExpression && isCalleeOfRenderedParent;
12826 if (this.variable || this.replacement) {
12827 var replacement = this.variable ? this.variable.getName() : this.replacement;
12828 if (isCalleeOfDifferentParent)
12829 replacement = '0, ' + replacement;
12830 code.overwrite(this.start, this.end, replacement, {
12831 contentOnly: true,
12832 storeName: true
12833 });
12834 }
12835 else {
12836 if (isCalleeOfDifferentParent) {
12837 code.appendRight(this.start, '0, ');
12838 }
12839 _super.prototype.render.call(this, code, options);
12840 }
12841 };
12842 MemberExpression.prototype.analysePropertyKey = function () {
12843 this.propertyKey = UNKNOWN_KEY;
12844 var value = this.property.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
12845 this.propertyKey = value === UNKNOWN_VALUE ? UNKNOWN_KEY : String(value);
12846 };
12847 MemberExpression.prototype.disallowNamespaceReassignment = function () {
12848 if (this.object instanceof Identifier$1 &&
12849 this.scope.findVariable(this.object.name).isNamespace) {
12850 this.context.error({
12851 code: 'ILLEGAL_NAMESPACE_REASSIGNMENT',
12852 message: "Illegal reassignment to import '" + this.object.name + "'"
12853 }, this.start);
12854 }
12855 };
12856 MemberExpression.prototype.resolveNamespaceVariables = function (baseVariable, path) {
12857 if (path.length === 0)
12858 return baseVariable;
12859 if (!baseVariable.isNamespace)
12860 return null;
12861 var exportName = path[0].key;
12862 var variable = baseVariable.isExternal
12863 ? baseVariable.module.getVariableForExportName(exportName)
12864 : baseVariable.context.traceExport(exportName);
12865 if (!variable) {
12866 var fileName = baseVariable.isExternal
12867 ? baseVariable.module.id
12868 : baseVariable.context.fileName;
12869 this.context.warn({
12870 code: 'MISSING_EXPORT',
12871 exporter: relativeId(fileName),
12872 importer: relativeId(this.context.fileName),
12873 message: "'" + exportName + "' is not exported by '" + relativeId(fileName) + "'",
12874 missing: exportName,
12875 url: "https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-"
12876 }, path[0].pos);
12877 return 'undefined';
12878 }
12879 return this.resolveNamespaceVariables(variable, path.slice(1));
12880 };
12881 return MemberExpression;
12882}(NodeBase));
12883
12884var ASSET_PREFIX = 'ROLLUP_ASSET_URL_';
12885var CHUNK_PREFIX = 'ROLLUP_CHUNK_URL_';
12886var MetaProperty = /** @class */ (function (_super) {
12887 __extends(MetaProperty, _super);
12888 function MetaProperty() {
12889 return _super !== null && _super.apply(this, arguments) || this;
12890 }
12891 MetaProperty.prototype.hasEffectsWhenAccessedAtPath = function (path) {
12892 return path.length > 1;
12893 };
12894 MetaProperty.prototype.initialise = function () {
12895 if (this.meta.name === 'import') {
12896 this.context.addImportMeta(this);
12897 }
12898 this.included = false;
12899 };
12900 MetaProperty.prototype.renderFinalMechanism = function (code, chunkId, format, pluginDriver) {
12901 if (!this.included)
12902 return false;
12903 var parent = this.parent;
12904 var importMetaProperty = parent instanceof MemberExpression$1 && typeof parent.propertyKey === 'string'
12905 ? parent.propertyKey
12906 : null;
12907 if (importMetaProperty &&
12908 (importMetaProperty.startsWith(ASSET_PREFIX) || importMetaProperty.startsWith(CHUNK_PREFIX))) {
12909 var assetReferenceId = null;
12910 var chunkReferenceId = null;
12911 var fileName = void 0;
12912 if (importMetaProperty.startsWith(ASSET_PREFIX)) {
12913 assetReferenceId = importMetaProperty.substr(ASSET_PREFIX.length);
12914 fileName = this.context.getAssetFileName(assetReferenceId);
12915 }
12916 else {
12917 chunkReferenceId = importMetaProperty.substr(CHUNK_PREFIX.length);
12918 fileName = this.context.getChunkFileName(chunkReferenceId);
12919 }
12920 var relativePath = normalize(relative(dirname(chunkId), fileName));
12921 var replacement_1;
12922 if (assetReferenceId !== null) {
12923 // deprecated hook for assets
12924 replacement_1 = pluginDriver.hookFirstSync('resolveAssetUrl', [
12925 {
12926 assetFileName: fileName,
12927 chunkId: chunkId,
12928 format: format,
12929 moduleId: this.context.module.id,
12930 relativeAssetPath: relativePath
12931 }
12932 ]);
12933 }
12934 if (!replacement_1) {
12935 replacement_1 = pluginDriver.hookFirstSync('resolveFileUrl', [
12936 {
12937 assetReferenceId: assetReferenceId,
12938 chunkId: chunkId,
12939 chunkReferenceId: chunkReferenceId,
12940 fileName: fileName,
12941 format: format,
12942 moduleId: this.context.module.id,
12943 relativePath: relativePath
12944 }
12945 ]);
12946 }
12947 code.overwrite(parent.start, parent.end, replacement_1);
12948 return true;
12949 }
12950 var replacement = pluginDriver.hookFirstSync('resolveImportMeta', [
12951 importMetaProperty,
12952 {
12953 chunkId: chunkId,
12954 format: format,
12955 moduleId: this.context.module.id
12956 }
12957 ]);
12958 if (typeof replacement === 'string') {
12959 if (parent instanceof MemberExpression$1) {
12960 code.overwrite(parent.start, parent.end, replacement);
12961 }
12962 else {
12963 code.overwrite(this.start, this.end, replacement);
12964 }
12965 return true;
12966 }
12967 return false;
12968 };
12969 return MetaProperty;
12970}(NodeBase));
12971
12972var MethodDefinition = /** @class */ (function (_super) {
12973 __extends(MethodDefinition, _super);
12974 function MethodDefinition() {
12975 return _super !== null && _super.apply(this, arguments) || this;
12976 }
12977 MethodDefinition.prototype.hasEffects = function (options) {
12978 return this.key.hasEffects(options);
12979 };
12980 MethodDefinition.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
12981 return (path.length > 0 || this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, callOptions, options));
12982 };
12983 return MethodDefinition;
12984}(NodeBase));
12985
12986var NewExpression = /** @class */ (function (_super) {
12987 __extends(NewExpression, _super);
12988 function NewExpression() {
12989 return _super !== null && _super.apply(this, arguments) || this;
12990 }
12991 NewExpression.prototype.bind = function () {
12992 _super.prototype.bind.call(this);
12993 for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
12994 var argument = _a[_i];
12995 // This will make sure all properties of parameters behave as "unknown"
12996 argument.deoptimizePath(UNKNOWN_PATH);
12997 }
12998 };
12999 NewExpression.prototype.hasEffects = function (options) {
13000 for (var _i = 0, _a = this.arguments; _i < _a.length; _i++) {
13001 var argument = _a[_i];
13002 if (argument.hasEffects(options))
13003 return true;
13004 }
13005 if (this.annotatedPure)
13006 return false;
13007 return this.callee.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions());
13008 };
13009 NewExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
13010 return path.length > 1;
13011 };
13012 NewExpression.prototype.initialise = function () {
13013 this.included = false;
13014 this.callOptions = CallOptions.create({
13015 args: this.arguments,
13016 callIdentifier: this,
13017 withNew: true
13018 });
13019 };
13020 return NewExpression;
13021}(NodeBase));
13022
13023var SpreadElement = /** @class */ (function (_super) {
13024 __extends(SpreadElement, _super);
13025 function SpreadElement() {
13026 return _super !== null && _super.apply(this, arguments) || this;
13027 }
13028 SpreadElement.prototype.bind = function () {
13029 _super.prototype.bind.call(this);
13030 // Only properties of properties of the argument could become subject to reassignment
13031 // This will also reassign the return values of iterators
13032 this.argument.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
13033 };
13034 return SpreadElement;
13035}(NodeBase));
13036
13037var ObjectExpression = /** @class */ (function (_super) {
13038 __extends(ObjectExpression, _super);
13039 function ObjectExpression() {
13040 return _super !== null && _super.apply(this, arguments) || this;
13041 }
13042 ObjectExpression.prototype.bind = function () {
13043 _super.prototype.bind.call(this);
13044 if (this.propertyMap === null)
13045 this.buildPropertyMap();
13046 };
13047 // We could also track this per-property but this would quickly become much more complex
13048 ObjectExpression.prototype.deoptimizeCache = function () {
13049 if (!this.hasUnknownDeoptimizedProperty)
13050 this.deoptimizeAllProperties();
13051 };
13052 ObjectExpression.prototype.deoptimizePath = function (path) {
13053 if (this.hasUnknownDeoptimizedProperty)
13054 return;
13055 if (this.propertyMap === null)
13056 this.buildPropertyMap();
13057 if (path.length === 0) {
13058 this.deoptimizeAllProperties();
13059 return;
13060 }
13061 var key = path[0];
13062 if (path.length === 1) {
13063 if (typeof key !== 'string') {
13064 this.deoptimizeAllProperties();
13065 return;
13066 }
13067 if (!this.deoptimizedPaths[key]) {
13068 this.deoptimizedPaths[key] = true;
13069 // we only deoptimizeCache exact matches as in all other cases,
13070 // we do not return a literal value or return expression
13071 if (this.expressionsToBeDeoptimized[key]) {
13072 for (var _i = 0, _a = this.expressionsToBeDeoptimized[key]; _i < _a.length; _i++) {
13073 var expression = _a[_i];
13074 expression.deoptimizeCache();
13075 }
13076 }
13077 }
13078 }
13079 var subPath = path.length === 1 ? UNKNOWN_PATH : path.slice(1);
13080 for (var _b = 0, _c = typeof key === 'string'
13081 ? this.propertyMap[key]
13082 ? this.propertyMap[key].propertiesRead
13083 : []
13084 : this.properties; _b < _c.length; _b++) {
13085 var property = _c[_b];
13086 property.deoptimizePath(subPath);
13087 }
13088 };
13089 ObjectExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
13090 if (this.propertyMap === null)
13091 this.buildPropertyMap();
13092 var key = path[0];
13093 if (path.length === 0 ||
13094 this.hasUnknownDeoptimizedProperty ||
13095 typeof key !== 'string' ||
13096 this.deoptimizedPaths[key])
13097 return UNKNOWN_VALUE;
13098 if (path.length === 1 &&
13099 !this.propertyMap[key] &&
13100 !objectMembers[key] &&
13101 this.unmatchablePropertiesRead.length === 0) {
13102 if (!this.expressionsToBeDeoptimized[key]) {
13103 this.expressionsToBeDeoptimized[key] = [origin];
13104 }
13105 else {
13106 this.expressionsToBeDeoptimized[key].push(origin);
13107 }
13108 return undefined;
13109 }
13110 if (!this.propertyMap[key] ||
13111 this.propertyMap[key].exactMatchRead === null ||
13112 this.propertyMap[key].propertiesRead.length > 1)
13113 return UNKNOWN_VALUE;
13114 if (!this.expressionsToBeDeoptimized[key]) {
13115 this.expressionsToBeDeoptimized[key] = [origin];
13116 }
13117 else {
13118 this.expressionsToBeDeoptimized[key].push(origin);
13119 }
13120 return this.propertyMap[key].exactMatchRead.getLiteralValueAtPath(path.slice(1), recursionTracker, origin);
13121 };
13122 ObjectExpression.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
13123 if (this.propertyMap === null)
13124 this.buildPropertyMap();
13125 var key = path[0];
13126 if (path.length === 0 ||
13127 this.hasUnknownDeoptimizedProperty ||
13128 typeof key !== 'string' ||
13129 this.deoptimizedPaths[key])
13130 return UNKNOWN_EXPRESSION;
13131 if (path.length === 1 &&
13132 objectMembers[key] &&
13133 this.unmatchablePropertiesRead.length === 0 &&
13134 (!this.propertyMap[key] || this.propertyMap[key].exactMatchRead === null))
13135 return getMemberReturnExpressionWhenCalled(objectMembers, key);
13136 if (!this.propertyMap[key] ||
13137 this.propertyMap[key].exactMatchRead === null ||
13138 this.propertyMap[key].propertiesRead.length > 1)
13139 return UNKNOWN_EXPRESSION;
13140 if (!this.expressionsToBeDeoptimized[key]) {
13141 this.expressionsToBeDeoptimized[key] = [origin];
13142 }
13143 else {
13144 this.expressionsToBeDeoptimized[key].push(origin);
13145 }
13146 return this.propertyMap[key].exactMatchRead.getReturnExpressionWhenCalledAtPath(path.slice(1), recursionTracker, origin);
13147 };
13148 ObjectExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
13149 if (path.length === 0)
13150 return false;
13151 var key = path[0];
13152 if (path.length > 1 &&
13153 (this.hasUnknownDeoptimizedProperty ||
13154 typeof key !== 'string' ||
13155 this.deoptimizedPaths[key] ||
13156 !this.propertyMap[key] ||
13157 this.propertyMap[key].exactMatchRead === null))
13158 return true;
13159 var subPath = path.slice(1);
13160 for (var _i = 0, _a = typeof key !== 'string'
13161 ? this.properties
13162 : this.propertyMap[key]
13163 ? this.propertyMap[key].propertiesRead
13164 : []; _i < _a.length; _i++) {
13165 var property = _a[_i];
13166 if (property.hasEffectsWhenAccessedAtPath(subPath, options))
13167 return true;
13168 }
13169 return false;
13170 };
13171 ObjectExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13172 if (path.length === 0)
13173 return false;
13174 var key = path[0];
13175 if (path.length > 1 &&
13176 (this.hasUnknownDeoptimizedProperty ||
13177 typeof key !== 'string' ||
13178 this.deoptimizedPaths[key] ||
13179 !this.propertyMap[key] ||
13180 this.propertyMap[key].exactMatchRead === null))
13181 return true;
13182 var subPath = path.slice(1);
13183 for (var _i = 0, _a = typeof key !== 'string'
13184 ? this.properties
13185 : path.length > 1
13186 ? this.propertyMap[key].propertiesRead
13187 : this.propertyMap[key]
13188 ? this.propertyMap[key].propertiesSet
13189 : []; _i < _a.length; _i++) {
13190 var property = _a[_i];
13191 if (property.hasEffectsWhenAssignedAtPath(subPath, options))
13192 return true;
13193 }
13194 return false;
13195 };
13196 ObjectExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
13197 var key = path[0];
13198 if (path.length === 0 ||
13199 this.hasUnknownDeoptimizedProperty ||
13200 typeof key !== 'string' ||
13201 this.deoptimizedPaths[key] ||
13202 (this.propertyMap[key]
13203 ? !this.propertyMap[key].exactMatchRead
13204 : path.length > 1 || !objectMembers[key]))
13205 return true;
13206 var subPath = path.slice(1);
13207 for (var _i = 0, _a = this.propertyMap[key] ? this.propertyMap[key].propertiesRead : []; _i < _a.length; _i++) {
13208 var property = _a[_i];
13209 if (property.hasEffectsWhenCalledAtPath(subPath, callOptions, options))
13210 return true;
13211 }
13212 if (path.length === 1 && objectMembers[key])
13213 return hasMemberEffectWhenCalled(objectMembers, key, this.included, callOptions, options);
13214 return false;
13215 };
13216 ObjectExpression.prototype.initialise = function () {
13217 this.included = false;
13218 this.hasUnknownDeoptimizedProperty = false;
13219 this.deoptimizedPaths = Object.create(null);
13220 this.propertyMap = null;
13221 this.expressionsToBeDeoptimized = Object.create(null);
13222 };
13223 ObjectExpression.prototype.render = function (code, options, _a) {
13224 var renderedParentType = (_a === void 0 ? BLANK : _a).renderedParentType;
13225 _super.prototype.render.call(this, code, options);
13226 if (renderedParentType === ExpressionStatement) {
13227 code.appendRight(this.start, '(');
13228 code.prependLeft(this.end, ')');
13229 }
13230 };
13231 ObjectExpression.prototype.buildPropertyMap = function () {
13232 var _a, _b;
13233 this.propertyMap = Object.create(null);
13234 this.unmatchablePropertiesRead = [];
13235 this.unmatchablePropertiesWrite = [];
13236 for (var index = this.properties.length - 1; index >= 0; index--) {
13237 var property = this.properties[index];
13238 if (property instanceof SpreadElement) {
13239 this.unmatchablePropertiesRead.push(property);
13240 continue;
13241 }
13242 var isWrite = property.kind !== 'get';
13243 var isRead = property.kind !== 'set';
13244 var key = void 0;
13245 if (property.computed) {
13246 var keyValue = property.key.getLiteralValueAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
13247 if (keyValue === UNKNOWN_VALUE) {
13248 if (isRead) {
13249 this.unmatchablePropertiesRead.push(property);
13250 }
13251 else {
13252 this.unmatchablePropertiesWrite.push(property);
13253 }
13254 continue;
13255 }
13256 key = String(keyValue);
13257 }
13258 else if (property.key instanceof Identifier$1) {
13259 key = property.key.name;
13260 }
13261 else {
13262 key = String(property.key.value);
13263 }
13264 var propertyMapProperty = this.propertyMap[key];
13265 if (!propertyMapProperty) {
13266 this.propertyMap[key] = {
13267 exactMatchRead: isRead ? property : null,
13268 exactMatchWrite: isWrite ? property : null,
13269 propertiesRead: isRead ? [property].concat(this.unmatchablePropertiesRead) : [],
13270 propertiesSet: isWrite && !isRead ? [property].concat(this.unmatchablePropertiesWrite) : []
13271 };
13272 continue;
13273 }
13274 if (isRead && propertyMapProperty.exactMatchRead === null) {
13275 propertyMapProperty.exactMatchRead = property;
13276 (_a = propertyMapProperty.propertiesRead).push.apply(_a, [property].concat(this.unmatchablePropertiesRead));
13277 }
13278 if (isWrite && !isRead && propertyMapProperty.exactMatchWrite === null) {
13279 propertyMapProperty.exactMatchWrite = property;
13280 (_b = propertyMapProperty.propertiesSet).push.apply(_b, [property].concat(this.unmatchablePropertiesWrite));
13281 }
13282 }
13283 };
13284 ObjectExpression.prototype.deoptimizeAllProperties = function () {
13285 this.hasUnknownDeoptimizedProperty = true;
13286 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13287 var property = _a[_i];
13288 property.deoptimizePath(UNKNOWN_PATH);
13289 }
13290 for (var _b = 0, _c = Object.keys(this.expressionsToBeDeoptimized); _b < _c.length; _b++) {
13291 var key = _c[_b];
13292 for (var _d = 0, _e = this.expressionsToBeDeoptimized[key]; _d < _e.length; _d++) {
13293 var expression = _e[_d];
13294 expression.deoptimizeCache();
13295 }
13296 }
13297 };
13298 return ObjectExpression;
13299}(NodeBase));
13300
13301var ObjectPattern = /** @class */ (function (_super) {
13302 __extends(ObjectPattern, _super);
13303 function ObjectPattern() {
13304 return _super !== null && _super.apply(this, arguments) || this;
13305 }
13306 ObjectPattern.prototype.addExportedVariables = function (variables) {
13307 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13308 var property = _a[_i];
13309 if (property.type === Property) {
13310 property.value.addExportedVariables(variables);
13311 }
13312 else {
13313 property.argument.addExportedVariables(variables);
13314 }
13315 }
13316 };
13317 ObjectPattern.prototype.declare = function (kind, init) {
13318 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13319 var property = _a[_i];
13320 property.declare(kind, init);
13321 }
13322 };
13323 ObjectPattern.prototype.deoptimizePath = function (path) {
13324 if (path.length === 0) {
13325 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13326 var property = _a[_i];
13327 property.deoptimizePath(path);
13328 }
13329 }
13330 };
13331 ObjectPattern.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13332 if (path.length > 0)
13333 return true;
13334 for (var _i = 0, _a = this.properties; _i < _a.length; _i++) {
13335 var property = _a[_i];
13336 if (property.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options))
13337 return true;
13338 }
13339 return false;
13340 };
13341 return ObjectPattern;
13342}(NodeBase));
13343
13344var Program$1 = /** @class */ (function (_super) {
13345 __extends(Program, _super);
13346 function Program() {
13347 return _super !== null && _super.apply(this, arguments) || this;
13348 }
13349 Program.prototype.hasEffects = function (options) {
13350 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
13351 var node = _a[_i];
13352 if (node.hasEffects(options))
13353 return true;
13354 }
13355 };
13356 Program.prototype.include = function (includeAllChildrenRecursively) {
13357 this.included = true;
13358 for (var _i = 0, _a = this.body; _i < _a.length; _i++) {
13359 var node = _a[_i];
13360 if (includeAllChildrenRecursively || node.shouldBeIncluded()) {
13361 node.include(includeAllChildrenRecursively);
13362 }
13363 }
13364 };
13365 Program.prototype.render = function (code, options) {
13366 if (this.body.length) {
13367 renderStatementList(this.body, code, this.start, this.end, options);
13368 }
13369 else {
13370 _super.prototype.render.call(this, code, options);
13371 }
13372 };
13373 return Program;
13374}(NodeBase));
13375
13376var Property$1 = /** @class */ (function (_super) {
13377 __extends(Property, _super);
13378 function Property() {
13379 var _this = _super !== null && _super.apply(this, arguments) || this;
13380 _this.declarationInit = null;
13381 return _this;
13382 }
13383 Property.prototype.bind = function () {
13384 _super.prototype.bind.call(this);
13385 if (this.kind === 'get' && this.returnExpression === null)
13386 this.updateReturnExpression();
13387 if (this.declarationInit !== null) {
13388 this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
13389 }
13390 };
13391 Property.prototype.declare = function (kind, init) {
13392 this.declarationInit = init;
13393 this.value.declare(kind, UNKNOWN_EXPRESSION);
13394 };
13395 Property.prototype.deoptimizeCache = function () {
13396 // As getter properties directly receive their values from function expressions that always
13397 // have a fixed return value, there is no known situation where a getter is deoptimized.
13398 throw new Error('Unexpected deoptimization');
13399 };
13400 Property.prototype.deoptimizePath = function (path) {
13401 if (this.kind === 'get') {
13402 if (path.length > 0) {
13403 if (this.returnExpression === null)
13404 this.updateReturnExpression();
13405 this.returnExpression.deoptimizePath(path);
13406 }
13407 }
13408 else if (this.kind !== 'set') {
13409 this.value.deoptimizePath(path);
13410 }
13411 };
13412 Property.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
13413 if (this.kind === 'set') {
13414 return UNKNOWN_VALUE;
13415 }
13416 if (this.kind === 'get') {
13417 if (this.returnExpression === null)
13418 this.updateReturnExpression();
13419 return this.returnExpression.getLiteralValueAtPath(path, recursionTracker, origin);
13420 }
13421 return this.value.getLiteralValueAtPath(path, recursionTracker, origin);
13422 };
13423 Property.prototype.getReturnExpressionWhenCalledAtPath = function (path, recursionTracker, origin) {
13424 if (this.kind === 'set') {
13425 return UNKNOWN_EXPRESSION;
13426 }
13427 if (this.kind === 'get') {
13428 if (this.returnExpression === null)
13429 this.updateReturnExpression();
13430 return this.returnExpression.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
13431 }
13432 return this.value.getReturnExpressionWhenCalledAtPath(path, recursionTracker, origin);
13433 };
13434 Property.prototype.hasEffects = function (options) {
13435 return this.key.hasEffects(options) || this.value.hasEffects(options);
13436 };
13437 Property.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
13438 if (this.kind === 'get') {
13439 return (this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()) ||
13440 (path.length > 0 && this.returnExpression.hasEffectsWhenAccessedAtPath(path, options)));
13441 }
13442 return this.value.hasEffectsWhenAccessedAtPath(path, options);
13443 };
13444 Property.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13445 if (this.kind === 'get') {
13446 return path.length === 0 || this.returnExpression.hasEffectsWhenAssignedAtPath(path, options);
13447 }
13448 if (this.kind === 'set') {
13449 return (path.length > 0 ||
13450 this.value.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.accessorCallOptions, options.getHasEffectsWhenCalledOptions()));
13451 }
13452 return this.value.hasEffectsWhenAssignedAtPath(path, options);
13453 };
13454 Property.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
13455 if (this.kind === 'get') {
13456 return this.returnExpression.hasEffectsWhenCalledAtPath(path, callOptions, options);
13457 }
13458 return this.value.hasEffectsWhenCalledAtPath(path, callOptions, options);
13459 };
13460 Property.prototype.initialise = function () {
13461 this.included = false;
13462 this.returnExpression = null;
13463 this.accessorCallOptions = CallOptions.create({
13464 callIdentifier: this,
13465 withNew: false
13466 });
13467 };
13468 Property.prototype.render = function (code, options) {
13469 if (!this.shorthand) {
13470 this.key.render(code, options);
13471 }
13472 this.value.render(code, options, { isShorthandProperty: this.shorthand });
13473 };
13474 Property.prototype.updateReturnExpression = function () {
13475 this.returnExpression = UNKNOWN_EXPRESSION;
13476 this.returnExpression = this.value.getReturnExpressionWhenCalledAtPath(EMPTY_PATH, EMPTY_IMMUTABLE_TRACKER, this);
13477 };
13478 return Property;
13479}(NodeBase));
13480
13481var RestElement = /** @class */ (function (_super) {
13482 __extends(RestElement, _super);
13483 function RestElement() {
13484 var _this = _super !== null && _super.apply(this, arguments) || this;
13485 _this.declarationInit = null;
13486 return _this;
13487 }
13488 RestElement.prototype.addExportedVariables = function (variables) {
13489 this.argument.addExportedVariables(variables);
13490 };
13491 RestElement.prototype.bind = function () {
13492 _super.prototype.bind.call(this);
13493 if (this.declarationInit !== null) {
13494 this.declarationInit.deoptimizePath([UNKNOWN_KEY, UNKNOWN_KEY]);
13495 }
13496 };
13497 RestElement.prototype.declare = function (kind, init) {
13498 this.argument.declare(kind, UNKNOWN_EXPRESSION);
13499 this.declarationInit = init;
13500 };
13501 RestElement.prototype.deoptimizePath = function (path) {
13502 path.length === 0 && this.argument.deoptimizePath(EMPTY_PATH);
13503 };
13504 RestElement.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13505 return path.length > 0 || this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options);
13506 };
13507 return RestElement;
13508}(NodeBase));
13509
13510var ReturnStatement$1 = /** @class */ (function (_super) {
13511 __extends(ReturnStatement, _super);
13512 function ReturnStatement() {
13513 return _super !== null && _super.apply(this, arguments) || this;
13514 }
13515 ReturnStatement.prototype.hasEffects = function (options) {
13516 return (!options.ignoreReturnAwaitYield() || (this.argument && this.argument.hasEffects(options)));
13517 };
13518 ReturnStatement.prototype.initialise = function () {
13519 this.included = false;
13520 this.scope.addReturnExpression(this.argument || UNKNOWN_EXPRESSION);
13521 };
13522 ReturnStatement.prototype.render = function (code, options) {
13523 if (this.argument) {
13524 this.argument.render(code, options);
13525 if (this.argument.start === this.start + 6 /* 'return'.length */) {
13526 code.prependLeft(this.start + 6, ' ');
13527 }
13528 }
13529 };
13530 return ReturnStatement;
13531}(NodeBase));
13532
13533var SequenceExpression = /** @class */ (function (_super) {
13534 __extends(SequenceExpression, _super);
13535 function SequenceExpression() {
13536 return _super !== null && _super.apply(this, arguments) || this;
13537 }
13538 SequenceExpression.prototype.deoptimizePath = function (path) {
13539 if (path.length > 0)
13540 this.expressions[this.expressions.length - 1].deoptimizePath(path);
13541 };
13542 SequenceExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
13543 return this.expressions[this.expressions.length - 1].getLiteralValueAtPath(path, recursionTracker, origin);
13544 };
13545 SequenceExpression.prototype.hasEffects = function (options) {
13546 for (var _i = 0, _a = this.expressions; _i < _a.length; _i++) {
13547 var expression = _a[_i];
13548 if (expression.hasEffects(options))
13549 return true;
13550 }
13551 return false;
13552 };
13553 SequenceExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
13554 return (path.length > 0 &&
13555 this.expressions[this.expressions.length - 1].hasEffectsWhenAccessedAtPath(path, options));
13556 };
13557 SequenceExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13558 return (path.length === 0 ||
13559 this.expressions[this.expressions.length - 1].hasEffectsWhenAssignedAtPath(path, options));
13560 };
13561 SequenceExpression.prototype.hasEffectsWhenCalledAtPath = function (path, callOptions, options) {
13562 return this.expressions[this.expressions.length - 1].hasEffectsWhenCalledAtPath(path, callOptions, options);
13563 };
13564 SequenceExpression.prototype.include = function (includeAllChildrenRecursively) {
13565 this.included = true;
13566 for (var i = 0; i < this.expressions.length - 1; i++) {
13567 var node = this.expressions[i];
13568 if (includeAllChildrenRecursively || node.shouldBeIncluded())
13569 node.include(includeAllChildrenRecursively);
13570 }
13571 this.expressions[this.expressions.length - 1].include(includeAllChildrenRecursively);
13572 };
13573 SequenceExpression.prototype.render = function (code, options, _a) {
13574 var _b = _a === void 0 ? BLANK : _a, renderedParentType = _b.renderedParentType, isCalleeOfRenderedParent = _b.isCalleeOfRenderedParent;
13575 var firstStart = 0, lastEnd, includedNodes = 0;
13576 for (var _i = 0, _c = getCommaSeparatedNodesWithBoundaries(this.expressions, code, this.start, this.end); _i < _c.length; _i++) {
13577 var _d = _c[_i], node = _d.node, start = _d.start, end = _d.end;
13578 if (!node.included) {
13579 treeshakeNode(node, code, start, end);
13580 continue;
13581 }
13582 includedNodes++;
13583 if (firstStart === 0)
13584 firstStart = start;
13585 lastEnd = end;
13586 if (node === this.expressions[this.expressions.length - 1] && includedNodes === 1) {
13587 node.render(code, options, {
13588 isCalleeOfRenderedParent: renderedParentType
13589 ? isCalleeOfRenderedParent
13590 : this.parent.callee === this,
13591 renderedParentType: renderedParentType || this.parent.type
13592 });
13593 }
13594 else {
13595 node.render(code, options);
13596 }
13597 }
13598 // Round brackets are part of the actual parent and should be re-added in case the parent changed
13599 if (includedNodes > 1 && renderedParentType) {
13600 code.prependRight(firstStart, '(');
13601 code.appendLeft(lastEnd, ')');
13602 }
13603 };
13604 return SequenceExpression;
13605}(NodeBase));
13606
13607var SwitchCase = /** @class */ (function (_super) {
13608 __extends(SwitchCase, _super);
13609 function SwitchCase() {
13610 return _super !== null && _super.apply(this, arguments) || this;
13611 }
13612 SwitchCase.prototype.include = function (includeAllChildrenRecursively) {
13613 this.included = true;
13614 if (this.test)
13615 this.test.include(includeAllChildrenRecursively);
13616 for (var _i = 0, _a = this.consequent; _i < _a.length; _i++) {
13617 var node = _a[_i];
13618 if (includeAllChildrenRecursively || node.shouldBeIncluded())
13619 node.include(includeAllChildrenRecursively);
13620 }
13621 };
13622 SwitchCase.prototype.render = function (code, options) {
13623 if (this.consequent.length) {
13624 this.test && this.test.render(code, options);
13625 var testEnd = this.test
13626 ? this.test.end
13627 : findFirstOccurrenceOutsideComment(code.original, 'default', this.start) + 7;
13628 var consequentStart = findFirstOccurrenceOutsideComment(code.original, ':', testEnd) + 1;
13629 renderStatementList(this.consequent, code, consequentStart, this.end, options);
13630 }
13631 else {
13632 _super.prototype.render.call(this, code, options);
13633 }
13634 };
13635 return SwitchCase;
13636}(NodeBase));
13637
13638var SwitchStatement = /** @class */ (function (_super) {
13639 __extends(SwitchStatement, _super);
13640 function SwitchStatement() {
13641 return _super !== null && _super.apply(this, arguments) || this;
13642 }
13643 SwitchStatement.prototype.createScope = function (parentScope) {
13644 this.scope = new BlockScope(parentScope);
13645 };
13646 SwitchStatement.prototype.hasEffects = function (options) {
13647 return _super.prototype.hasEffects.call(this, options.setIgnoreBreakStatements());
13648 };
13649 return SwitchStatement;
13650}(NodeBase));
13651
13652var TaggedTemplateExpression = /** @class */ (function (_super) {
13653 __extends(TaggedTemplateExpression, _super);
13654 function TaggedTemplateExpression() {
13655 return _super !== null && _super.apply(this, arguments) || this;
13656 }
13657 TaggedTemplateExpression.prototype.bind = function () {
13658 _super.prototype.bind.call(this);
13659 if (this.tag.type === Identifier) {
13660 var variable = this.scope.findVariable(this.tag.name);
13661 if (variable.isNamespace) {
13662 this.context.error({
13663 code: 'CANNOT_CALL_NAMESPACE',
13664 message: "Cannot call a namespace ('" + this.tag.name + "')"
13665 }, this.start);
13666 }
13667 if (this.tag.name === 'eval') {
13668 this.context.warn({
13669 code: 'EVAL',
13670 message: "Use of eval is strongly discouraged, as it poses security risks and may cause issues with minification",
13671 url: 'https://rollupjs.org/guide/en#avoiding-eval'
13672 }, this.start);
13673 }
13674 }
13675 };
13676 TaggedTemplateExpression.prototype.hasEffects = function (options) {
13677 return (_super.prototype.hasEffects.call(this, options) ||
13678 this.tag.hasEffectsWhenCalledAtPath(EMPTY_PATH, this.callOptions, options.getHasEffectsWhenCalledOptions()));
13679 };
13680 TaggedTemplateExpression.prototype.initialise = function () {
13681 this.included = false;
13682 this.callOptions = CallOptions.create({
13683 callIdentifier: this,
13684 withNew: false
13685 });
13686 };
13687 return TaggedTemplateExpression;
13688}(NodeBase));
13689
13690var TemplateElement = /** @class */ (function (_super) {
13691 __extends(TemplateElement, _super);
13692 function TemplateElement() {
13693 return _super !== null && _super.apply(this, arguments) || this;
13694 }
13695 TemplateElement.prototype.hasEffects = function (_options) {
13696 return false;
13697 };
13698 return TemplateElement;
13699}(NodeBase));
13700
13701function isTemplateLiteral(node) {
13702 return node.type === TemplateLiteral;
13703}
13704var TemplateLiteral$1 = /** @class */ (function (_super) {
13705 __extends(TemplateLiteral, _super);
13706 function TemplateLiteral() {
13707 return _super !== null && _super.apply(this, arguments) || this;
13708 }
13709 TemplateLiteral.prototype.getLiteralValueAtPath = function (path) {
13710 if (path.length > 0 || this.quasis.length !== 1) {
13711 return UNKNOWN_VALUE;
13712 }
13713 return this.quasis[0].value.cooked;
13714 };
13715 TemplateLiteral.prototype.render = function (code, options) {
13716 code.indentExclusionRanges.push([this.start, this.end]);
13717 _super.prototype.render.call(this, code, options);
13718 };
13719 return TemplateLiteral;
13720}(NodeBase));
13721
13722var ModuleScope = /** @class */ (function (_super) {
13723 __extends(ModuleScope, _super);
13724 function ModuleScope(parent, context) {
13725 var _this = _super.call(this, parent) || this;
13726 _this.context = context;
13727 _this.variables.this = new LocalVariable('this', null, UNDEFINED_EXPRESSION, context);
13728 return _this;
13729 }
13730 ModuleScope.prototype.addExportDefaultDeclaration = function (name, exportDefaultDeclaration, context) {
13731 return (this.variables.default = new ExportDefaultVariable(name, exportDefaultDeclaration, context));
13732 };
13733 ModuleScope.prototype.addNamespaceMemberAccess = function (_name, variable) {
13734 if (variable instanceof GlobalVariable) {
13735 this.accessedOutsideVariables[variable.name] = variable;
13736 }
13737 };
13738 ModuleScope.prototype.deconflict = function (forbiddenNames) {
13739 // all module level variables are already deconflicted when deconflicting the chunk
13740 for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
13741 var scope = _a[_i];
13742 scope.deconflict(forbiddenNames);
13743 }
13744 };
13745 ModuleScope.prototype.findLexicalBoundary = function () {
13746 return this;
13747 };
13748 ModuleScope.prototype.findVariable = function (name) {
13749 var knownVariable = this.variables[name] || this.accessedOutsideVariables[name];
13750 if (knownVariable) {
13751 return knownVariable;
13752 }
13753 var variable = this.context.traceVariable(name) || this.parent.findVariable(name);
13754 if (variable instanceof GlobalVariable) {
13755 this.accessedOutsideVariables[name] = variable;
13756 }
13757 return variable;
13758 };
13759 return ModuleScope;
13760}(ChildScope));
13761
13762var ThisExpression = /** @class */ (function (_super) {
13763 __extends(ThisExpression, _super);
13764 function ThisExpression() {
13765 return _super !== null && _super.apply(this, arguments) || this;
13766 }
13767 ThisExpression.prototype.bind = function () {
13768 _super.prototype.bind.call(this);
13769 this.variable = this.scope.findVariable('this');
13770 };
13771 ThisExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, options) {
13772 return path.length > 0 && this.variable.hasEffectsWhenAccessedAtPath(path, options);
13773 };
13774 ThisExpression.prototype.hasEffectsWhenAssignedAtPath = function (path, options) {
13775 return this.variable.hasEffectsWhenAssignedAtPath(path, options);
13776 };
13777 ThisExpression.prototype.initialise = function () {
13778 this.included = false;
13779 this.variable = null;
13780 this.alias =
13781 this.scope.findLexicalBoundary() instanceof ModuleScope ? this.context.moduleContext : null;
13782 if (this.alias === 'undefined') {
13783 this.context.warn({
13784 code: 'THIS_IS_UNDEFINED',
13785 message: "The 'this' keyword is equivalent to 'undefined' at the top level of an ES module, and has been rewritten",
13786 url: "https://rollupjs.org/guide/en#error-this-is-undefined"
13787 }, this.start);
13788 }
13789 };
13790 ThisExpression.prototype.render = function (code, _options) {
13791 if (this.alias !== null) {
13792 code.overwrite(this.start, this.end, this.alias, {
13793 contentOnly: false,
13794 storeName: true
13795 });
13796 }
13797 };
13798 return ThisExpression;
13799}(NodeBase));
13800
13801var ThrowStatement = /** @class */ (function (_super) {
13802 __extends(ThrowStatement, _super);
13803 function ThrowStatement() {
13804 return _super !== null && _super.apply(this, arguments) || this;
13805 }
13806 ThrowStatement.prototype.hasEffects = function (_options) {
13807 return true;
13808 };
13809 return ThrowStatement;
13810}(NodeBase));
13811
13812var unaryOperators = {
13813 '!': function (value) { return !value; },
13814 '+': function (value) { return +value; },
13815 '-': function (value) { return -value; },
13816 delete: function () { return UNKNOWN_VALUE; },
13817 typeof: function (value) { return typeof value; },
13818 void: function () { return undefined; },
13819 '~': function (value) { return ~value; }
13820};
13821var UnaryExpression = /** @class */ (function (_super) {
13822 __extends(UnaryExpression, _super);
13823 function UnaryExpression() {
13824 return _super !== null && _super.apply(this, arguments) || this;
13825 }
13826 UnaryExpression.prototype.bind = function () {
13827 _super.prototype.bind.call(this);
13828 if (this.operator === 'delete') {
13829 this.argument.deoptimizePath(EMPTY_PATH);
13830 }
13831 };
13832 UnaryExpression.prototype.getLiteralValueAtPath = function (path, recursionTracker, origin) {
13833 if (path.length > 0)
13834 return UNKNOWN_VALUE;
13835 var argumentValue = this.argument.getLiteralValueAtPath(EMPTY_PATH, recursionTracker, origin);
13836 if (argumentValue === UNKNOWN_VALUE)
13837 return UNKNOWN_VALUE;
13838 return unaryOperators[this.operator](argumentValue);
13839 };
13840 UnaryExpression.prototype.hasEffects = function (options) {
13841 return (this.argument.hasEffects(options) ||
13842 (this.operator === 'delete' &&
13843 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options)));
13844 };
13845 UnaryExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
13846 if (this.operator === 'void') {
13847 return path.length > 0;
13848 }
13849 return path.length > 1;
13850 };
13851 return UnaryExpression;
13852}(NodeBase));
13853
13854var UnknownNode = /** @class */ (function (_super) {
13855 __extends(UnknownNode, _super);
13856 function UnknownNode() {
13857 return _super !== null && _super.apply(this, arguments) || this;
13858 }
13859 UnknownNode.prototype.hasEffects = function (_options) {
13860 return true;
13861 };
13862 UnknownNode.prototype.include = function () {
13863 _super.prototype.include.call(this, true);
13864 };
13865 return UnknownNode;
13866}(NodeBase));
13867
13868var UpdateExpression = /** @class */ (function (_super) {
13869 __extends(UpdateExpression, _super);
13870 function UpdateExpression() {
13871 return _super !== null && _super.apply(this, arguments) || this;
13872 }
13873 UpdateExpression.prototype.bind = function () {
13874 _super.prototype.bind.call(this);
13875 this.argument.deoptimizePath(EMPTY_PATH);
13876 if (isIdentifier(this.argument)) {
13877 var variable = this.scope.findVariable(this.argument.name);
13878 variable.isReassigned = true;
13879 }
13880 };
13881 UpdateExpression.prototype.hasEffects = function (options) {
13882 return (this.argument.hasEffects(options) ||
13883 this.argument.hasEffectsWhenAssignedAtPath(EMPTY_PATH, options));
13884 };
13885 UpdateExpression.prototype.hasEffectsWhenAccessedAtPath = function (path, _options) {
13886 return path.length > 1;
13887 };
13888 UpdateExpression.prototype.render = function (code, options) {
13889 this.argument.render(code, options);
13890 var variable = this.argument.variable;
13891 if (options.format === 'system' && variable && variable.exportName) {
13892 var name = variable.getName();
13893 if (this.prefix) {
13894 code.overwrite(this.start, this.end, "exports('" + variable.exportName + "', " + this.operator + name + ")");
13895 }
13896 else {
13897 var op = void 0;
13898 switch (this.operator) {
13899 case '++':
13900 op = name + " + 1";
13901 break;
13902 case '--':
13903 op = name + " - 1";
13904 break;
13905 }
13906 code.overwrite(this.start, this.end, "(exports('" + variable.exportName + "', " + op + "), " + name + this.operator + ")");
13907 }
13908 }
13909 };
13910 return UpdateExpression;
13911}(NodeBase));
13912
13913function isReassignedExportsMember(variable) {
13914 return variable.renderBaseName && variable.exportName && variable.isReassigned;
13915}
13916function areAllDeclarationsIncludedAndNotExported(declarations) {
13917 for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
13918 var declarator = declarations_1[_i];
13919 if (!declarator.included) {
13920 return false;
13921 }
13922 if (declarator.id.type === Identifier) {
13923 if (declarator.id.variable.exportName)
13924 return false;
13925 }
13926 else {
13927 var exportedVariables = [];
13928 declarator.id.addExportedVariables(exportedVariables);
13929 if (exportedVariables.length > 0)
13930 return false;
13931 }
13932 }
13933 return true;
13934}
13935var VariableDeclaration$1 = /** @class */ (function (_super) {
13936 __extends(VariableDeclaration, _super);
13937 function VariableDeclaration() {
13938 return _super !== null && _super.apply(this, arguments) || this;
13939 }
13940 VariableDeclaration.prototype.deoptimizePath = function (_path) {
13941 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13942 var declarator = _a[_i];
13943 declarator.deoptimizePath(EMPTY_PATH);
13944 }
13945 };
13946 VariableDeclaration.prototype.hasEffectsWhenAssignedAtPath = function (_path, _options) {
13947 return false;
13948 };
13949 VariableDeclaration.prototype.include = function (includeAllChildrenRecursively) {
13950 this.included = true;
13951 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13952 var declarator = _a[_i];
13953 if (includeAllChildrenRecursively || declarator.shouldBeIncluded())
13954 declarator.include(includeAllChildrenRecursively);
13955 }
13956 };
13957 VariableDeclaration.prototype.includeWithAllDeclaredVariables = function (includeAllChildrenRecursively) {
13958 this.included = true;
13959 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13960 var declarator = _a[_i];
13961 declarator.include(includeAllChildrenRecursively);
13962 }
13963 };
13964 VariableDeclaration.prototype.initialise = function () {
13965 this.included = false;
13966 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13967 var declarator = _a[_i];
13968 declarator.declareDeclarator(this.kind);
13969 }
13970 };
13971 VariableDeclaration.prototype.render = function (code, options, nodeRenderOptions) {
13972 if (nodeRenderOptions === void 0) { nodeRenderOptions = BLANK; }
13973 if (areAllDeclarationsIncludedAndNotExported(this.declarations)) {
13974 for (var _i = 0, _a = this.declarations; _i < _a.length; _i++) {
13975 var declarator = _a[_i];
13976 declarator.render(code, options);
13977 }
13978 if (!nodeRenderOptions.isNoStatement &&
13979 code.original.charCodeAt(this.end - 1) !== 59 /*";"*/) {
13980 code.appendLeft(this.end, ';');
13981 }
13982 }
13983 else {
13984 this.renderReplacedDeclarations(code, options, nodeRenderOptions);
13985 }
13986 };
13987 VariableDeclaration.prototype.renderDeclarationEnd = function (code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, addSemicolon, systemPatternExports) {
13988 if (code.original.charCodeAt(this.end - 1) === 59 /*";"*/) {
13989 code.remove(this.end - 1, this.end);
13990 }
13991 if (addSemicolon) {
13992 separatorString += ';';
13993 }
13994 if (lastSeparatorPos !== null) {
13995 if (code.original.charCodeAt(actualContentEnd - 1) === 10 /*"\n"*/ &&
13996 (code.original.charCodeAt(this.end) === 10 /*"\n"*/ ||
13997 code.original.charCodeAt(this.end) === 13) /*"\r"*/) {
13998 actualContentEnd--;
13999 if (code.original.charCodeAt(actualContentEnd) === 13 /*"\r"*/) {
14000 actualContentEnd--;
14001 }
14002 }
14003 if (actualContentEnd === lastSeparatorPos + 1) {
14004 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString);
14005 }
14006 else {
14007 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
14008 code.remove(actualContentEnd, renderedContentEnd);
14009 }
14010 }
14011 else {
14012 code.appendLeft(renderedContentEnd, separatorString);
14013 }
14014 if (systemPatternExports.length > 0) {
14015 code.appendLeft(renderedContentEnd, ' ' + getSystemExportStatement(systemPatternExports));
14016 }
14017 };
14018 VariableDeclaration.prototype.renderReplacedDeclarations = function (code, options, _a) {
14019 var _b = _a.start, start = _b === void 0 ? this.start : _b, _c = _a.end, end = _c === void 0 ? this.end : _c, isNoStatement = _a.isNoStatement;
14020 var separatedNodes = getCommaSeparatedNodesWithBoundaries(this.declarations, code, this.start + this.kind.length, this.end - (code.original.charCodeAt(this.end - 1) === 59 /*";"*/ ? 1 : 0));
14021 var actualContentEnd, renderedContentEnd;
14022 if (/\n\s*$/.test(code.slice(this.start, separatedNodes[0].start))) {
14023 renderedContentEnd = this.start + this.kind.length;
14024 }
14025 else {
14026 renderedContentEnd = separatedNodes[0].start;
14027 }
14028 var lastSeparatorPos = renderedContentEnd - 1;
14029 code.remove(this.start, lastSeparatorPos);
14030 var isInDeclaration = false;
14031 var hasRenderedContent = false;
14032 var separatorString = '', leadingString, nextSeparatorString;
14033 var systemPatternExports = [];
14034 for (var _i = 0, separatedNodes_1 = separatedNodes; _i < separatedNodes_1.length; _i++) {
14035 var _d = separatedNodes_1[_i], node = _d.node, start_1 = _d.start, separator = _d.separator, contentEnd = _d.contentEnd, end_1 = _d.end;
14036 if (!node.included ||
14037 (isIdentifier(node.id) && isReassignedExportsMember(node.id.variable) && node.init === null)) {
14038 code.remove(start_1, end_1);
14039 continue;
14040 }
14041 leadingString = '';
14042 nextSeparatorString = '';
14043 if (isIdentifier(node.id) && isReassignedExportsMember(node.id.variable)) {
14044 if (hasRenderedContent) {
14045 separatorString += ';';
14046 }
14047 isInDeclaration = false;
14048 }
14049 else {
14050 if (options.format === 'system' && node.init !== null) {
14051 if (node.id.type !== Identifier) {
14052 node.id.addExportedVariables(systemPatternExports);
14053 }
14054 else if (node.id.variable.exportName) {
14055 code.prependLeft(code.original.indexOf('=', node.id.end) + 1, " exports('" + (node.id.variable.safeExportName || node.id.variable.exportName) + "',");
14056 nextSeparatorString += ')';
14057 }
14058 }
14059 if (isInDeclaration) {
14060 separatorString += ',';
14061 }
14062 else {
14063 if (hasRenderedContent) {
14064 separatorString += ';';
14065 }
14066 leadingString += this.kind + " ";
14067 isInDeclaration = true;
14068 }
14069 }
14070 if (renderedContentEnd === lastSeparatorPos + 1) {
14071 code.overwrite(lastSeparatorPos, renderedContentEnd, separatorString + leadingString);
14072 }
14073 else {
14074 code.overwrite(lastSeparatorPos, lastSeparatorPos + 1, separatorString);
14075 code.appendLeft(renderedContentEnd, leadingString);
14076 }
14077 node.render(code, options);
14078 actualContentEnd = contentEnd;
14079 renderedContentEnd = end_1;
14080 hasRenderedContent = true;
14081 lastSeparatorPos = separator;
14082 separatorString = nextSeparatorString;
14083 }
14084 if (hasRenderedContent) {
14085 this.renderDeclarationEnd(code, separatorString, lastSeparatorPos, actualContentEnd, renderedContentEnd, !isNoStatement, systemPatternExports);
14086 }
14087 else {
14088 code.remove(start, end);
14089 }
14090 };
14091 return VariableDeclaration;
14092}(NodeBase));
14093
14094var VariableDeclarator = /** @class */ (function (_super) {
14095 __extends(VariableDeclarator, _super);
14096 function VariableDeclarator() {
14097 return _super !== null && _super.apply(this, arguments) || this;
14098 }
14099 VariableDeclarator.prototype.declareDeclarator = function (kind) {
14100 this.id.declare(kind, this.init || UNDEFINED_EXPRESSION);
14101 };
14102 VariableDeclarator.prototype.deoptimizePath = function (path) {
14103 this.id.deoptimizePath(path);
14104 };
14105 VariableDeclarator.prototype.render = function (code, options) {
14106 // This can happen for hoisted variables in dead branches
14107 if (this.init !== null && !this.init.included) {
14108 code.remove(this.id.end, this.end);
14109 this.id.render(code, options);
14110 }
14111 else {
14112 _super.prototype.render.call(this, code, options);
14113 }
14114 };
14115 return VariableDeclarator;
14116}(NodeBase));
14117
14118var WhileStatement = /** @class */ (function (_super) {
14119 __extends(WhileStatement, _super);
14120 function WhileStatement() {
14121 return _super !== null && _super.apply(this, arguments) || this;
14122 }
14123 WhileStatement.prototype.hasEffects = function (options) {
14124 return (this.test.hasEffects(options) || this.body.hasEffects(options.setIgnoreBreakStatements()));
14125 };
14126 return WhileStatement;
14127}(NodeBase));
14128
14129var YieldExpression = /** @class */ (function (_super) {
14130 __extends(YieldExpression, _super);
14131 function YieldExpression() {
14132 return _super !== null && _super.apply(this, arguments) || this;
14133 }
14134 YieldExpression.prototype.bind = function () {
14135 _super.prototype.bind.call(this);
14136 if (this.argument !== null) {
14137 this.argument.deoptimizePath(UNKNOWN_PATH);
14138 }
14139 };
14140 YieldExpression.prototype.hasEffects = function (options) {
14141 return (!options.ignoreReturnAwaitYield() || (this.argument && this.argument.hasEffects(options)));
14142 };
14143 YieldExpression.prototype.render = function (code, options) {
14144 if (this.argument) {
14145 this.argument.render(code, options);
14146 if (this.argument.start === this.start + 5 /* 'yield'.length */) {
14147 code.prependLeft(this.start + 5, ' ');
14148 }
14149 }
14150 };
14151 return YieldExpression;
14152}(NodeBase));
14153
14154var nodeConstructors = {
14155 ArrayExpression: ArrayExpression,
14156 ArrayPattern: ArrayPattern,
14157 ArrowFunctionExpression: ArrowFunctionExpression,
14158 AssignmentExpression: AssignmentExpression,
14159 AssignmentPattern: AssignmentPattern,
14160 AwaitExpression: AwaitExpression,
14161 BinaryExpression: BinaryExpression,
14162 BlockStatement: BlockStatement$1,
14163 BreakStatement: BreakStatement,
14164 CallExpression: CallExpression$1,
14165 CatchClause: CatchClause,
14166 ClassBody: ClassBody,
14167 ClassDeclaration: ClassDeclaration$1,
14168 ClassExpression: ClassExpression,
14169 ConditionalExpression: ConditionalExpression,
14170 DoWhileStatement: DoWhileStatement,
14171 EmptyStatement: EmptyStatement,
14172 ExportAllDeclaration: ExportAllDeclaration$1,
14173 ExportDefaultDeclaration: ExportDefaultDeclaration$1,
14174 ExportNamedDeclaration: ExportNamedDeclaration,
14175 ExpressionStatement: ExpressionStatement$1,
14176 ForInStatement: ForInStatement,
14177 ForOfStatement: ForOfStatement,
14178 ForStatement: ForStatement,
14179 FunctionDeclaration: FunctionDeclaration$1,
14180 FunctionExpression: FunctionExpression$1,
14181 Identifier: Identifier$1,
14182 IfStatement: IfStatement,
14183 Import: Import,
14184 ImportDeclaration: ImportDeclaration,
14185 LabeledStatement: LabeledStatement,
14186 Literal: Literal$1,
14187 LogicalExpression: LogicalExpression,
14188 MemberExpression: MemberExpression$1,
14189 MetaProperty: MetaProperty,
14190 MethodDefinition: MethodDefinition,
14191 NewExpression: NewExpression,
14192 ObjectExpression: ObjectExpression,
14193 ObjectPattern: ObjectPattern,
14194 Program: Program$1,
14195 Property: Property$1,
14196 RestElement: RestElement,
14197 ReturnStatement: ReturnStatement$1,
14198 SequenceExpression: SequenceExpression,
14199 SpreadElement: SpreadElement,
14200 SwitchCase: SwitchCase,
14201 SwitchStatement: SwitchStatement,
14202 TaggedTemplateExpression: TaggedTemplateExpression,
14203 TemplateElement: TemplateElement,
14204 TemplateLiteral: TemplateLiteral$1,
14205 ThisExpression: ThisExpression,
14206 ThrowStatement: ThrowStatement,
14207 TryStatement: NodeBase,
14208 UnaryExpression: UnaryExpression,
14209 UnknownNode: UnknownNode,
14210 UpdateExpression: UpdateExpression,
14211 VariableDeclaration: VariableDeclaration$1,
14212 VariableDeclarator: VariableDeclarator,
14213 WhileStatement: WhileStatement,
14214 YieldExpression: YieldExpression
14215};
14216
14217function getOriginalLocation(sourcemapChain, location) {
14218 var filteredSourcemapChain = sourcemapChain.filter(function (sourcemap) { return sourcemap.mappings; });
14219 while (filteredSourcemapChain.length > 0) {
14220 var sourcemap = filteredSourcemapChain.pop();
14221 var line = sourcemap.mappings[location.line - 1];
14222 var locationFound = false;
14223 if (line !== undefined) {
14224 for (var _i = 0, line_1 = line; _i < line_1.length; _i++) {
14225 var segment = line_1[_i];
14226 if (segment[0] >= location.column) {
14227 if (segment.length < 4)
14228 break;
14229 location = {
14230 column: segment[3],
14231 line: segment[2] + 1,
14232 name: sourcemap.names[segment[4]],
14233 source: sourcemap.sources[segment[1]]
14234 };
14235 locationFound = true;
14236 break;
14237 }
14238 }
14239 }
14240 if (!locationFound) {
14241 throw new Error("Can't resolve original location of error.");
14242 }
14243 }
14244 return location;
14245}
14246
14247// AST walker module for Mozilla Parser API compatible trees
14248
14249function skipThrough(node, st, c) { c(node, st); }
14250function ignore(_node, _st, _c) {}
14251
14252// Node walkers.
14253
14254var base$1 = {};
14255
14256base$1.Program = base$1.BlockStatement = function (node, st, c) {
14257 for (var i = 0, list = node.body; i < list.length; i += 1)
14258 {
14259 var stmt = list[i];
14260
14261 c(stmt, st, "Statement");
14262 }
14263};
14264base$1.Statement = skipThrough;
14265base$1.EmptyStatement = ignore;
14266base$1.ExpressionStatement = base$1.ParenthesizedExpression =
14267 function (node, st, c) { return c(node.expression, st, "Expression"); };
14268base$1.IfStatement = function (node, st, c) {
14269 c(node.test, st, "Expression");
14270 c(node.consequent, st, "Statement");
14271 if (node.alternate) { c(node.alternate, st, "Statement"); }
14272};
14273base$1.LabeledStatement = function (node, st, c) { return c(node.body, st, "Statement"); };
14274base$1.BreakStatement = base$1.ContinueStatement = ignore;
14275base$1.WithStatement = function (node, st, c) {
14276 c(node.object, st, "Expression");
14277 c(node.body, st, "Statement");
14278};
14279base$1.SwitchStatement = function (node, st, c) {
14280 c(node.discriminant, st, "Expression");
14281 for (var i = 0, list = node.cases; i < list.length; i += 1) {
14282 var cs = list[i];
14283
14284 if (cs.test) { c(cs.test, st, "Expression"); }
14285 for (var i$1 = 0, list$1 = cs.consequent; i$1 < list$1.length; i$1 += 1)
14286 {
14287 var cons = list$1[i$1];
14288
14289 c(cons, st, "Statement");
14290 }
14291 }
14292};
14293base$1.SwitchCase = function (node, st, c) {
14294 if (node.test) { c(node.test, st, "Expression"); }
14295 for (var i = 0, list = node.consequent; i < list.length; i += 1)
14296 {
14297 var cons = list[i];
14298
14299 c(cons, st, "Statement");
14300 }
14301};
14302base$1.ReturnStatement = base$1.YieldExpression = base$1.AwaitExpression = function (node, st, c) {
14303 if (node.argument) { c(node.argument, st, "Expression"); }
14304};
14305base$1.ThrowStatement = base$1.SpreadElement =
14306 function (node, st, c) { return c(node.argument, st, "Expression"); };
14307base$1.TryStatement = function (node, st, c) {
14308 c(node.block, st, "Statement");
14309 if (node.handler) { c(node.handler, st); }
14310 if (node.finalizer) { c(node.finalizer, st, "Statement"); }
14311};
14312base$1.CatchClause = function (node, st, c) {
14313 if (node.param) { c(node.param, st, "Pattern"); }
14314 c(node.body, st, "Statement");
14315};
14316base$1.WhileStatement = base$1.DoWhileStatement = function (node, st, c) {
14317 c(node.test, st, "Expression");
14318 c(node.body, st, "Statement");
14319};
14320base$1.ForStatement = function (node, st, c) {
14321 if (node.init) { c(node.init, st, "ForInit"); }
14322 if (node.test) { c(node.test, st, "Expression"); }
14323 if (node.update) { c(node.update, st, "Expression"); }
14324 c(node.body, st, "Statement");
14325};
14326base$1.ForInStatement = base$1.ForOfStatement = function (node, st, c) {
14327 c(node.left, st, "ForInit");
14328 c(node.right, st, "Expression");
14329 c(node.body, st, "Statement");
14330};
14331base$1.ForInit = function (node, st, c) {
14332 if (node.type === "VariableDeclaration") { c(node, st); }
14333 else { c(node, st, "Expression"); }
14334};
14335base$1.DebuggerStatement = ignore;
14336
14337base$1.FunctionDeclaration = function (node, st, c) { return c(node, st, "Function"); };
14338base$1.VariableDeclaration = function (node, st, c) {
14339 for (var i = 0, list = node.declarations; i < list.length; i += 1)
14340 {
14341 var decl = list[i];
14342
14343 c(decl, st);
14344 }
14345};
14346base$1.VariableDeclarator = function (node, st, c) {
14347 c(node.id, st, "Pattern");
14348 if (node.init) { c(node.init, st, "Expression"); }
14349};
14350
14351base$1.Function = function (node, st, c) {
14352 if (node.id) { c(node.id, st, "Pattern"); }
14353 for (var i = 0, list = node.params; i < list.length; i += 1)
14354 {
14355 var param = list[i];
14356
14357 c(param, st, "Pattern");
14358 }
14359 c(node.body, st, node.expression ? "Expression" : "Statement");
14360};
14361
14362base$1.Pattern = function (node, st, c) {
14363 if (node.type === "Identifier")
14364 { c(node, st, "VariablePattern"); }
14365 else if (node.type === "MemberExpression")
14366 { c(node, st, "MemberPattern"); }
14367 else
14368 { c(node, st); }
14369};
14370base$1.VariablePattern = ignore;
14371base$1.MemberPattern = skipThrough;
14372base$1.RestElement = function (node, st, c) { return c(node.argument, st, "Pattern"); };
14373base$1.ArrayPattern = function (node, st, c) {
14374 for (var i = 0, list = node.elements; i < list.length; i += 1) {
14375 var elt = list[i];
14376
14377 if (elt) { c(elt, st, "Pattern"); }
14378 }
14379};
14380base$1.ObjectPattern = function (node, st, c) {
14381 for (var i = 0, list = node.properties; i < list.length; i += 1) {
14382 var prop = list[i];
14383
14384 if (prop.type === "Property") {
14385 if (prop.computed) { c(prop.key, st, "Expression"); }
14386 c(prop.value, st, "Pattern");
14387 } else if (prop.type === "RestElement") {
14388 c(prop.argument, st, "Pattern");
14389 }
14390 }
14391};
14392
14393base$1.Expression = skipThrough;
14394base$1.ThisExpression = base$1.Super = base$1.MetaProperty = ignore;
14395base$1.ArrayExpression = function (node, st, c) {
14396 for (var i = 0, list = node.elements; i < list.length; i += 1) {
14397 var elt = list[i];
14398
14399 if (elt) { c(elt, st, "Expression"); }
14400 }
14401};
14402base$1.ObjectExpression = function (node, st, c) {
14403 for (var i = 0, list = node.properties; i < list.length; i += 1)
14404 {
14405 var prop = list[i];
14406
14407 c(prop, st);
14408 }
14409};
14410base$1.FunctionExpression = base$1.ArrowFunctionExpression = base$1.FunctionDeclaration;
14411base$1.SequenceExpression = function (node, st, c) {
14412 for (var i = 0, list = node.expressions; i < list.length; i += 1)
14413 {
14414 var expr = list[i];
14415
14416 c(expr, st, "Expression");
14417 }
14418};
14419base$1.TemplateLiteral = function (node, st, c) {
14420 for (var i = 0, list = node.quasis; i < list.length; i += 1)
14421 {
14422 var quasi = list[i];
14423
14424 c(quasi, st);
14425 }
14426
14427 for (var i$1 = 0, list$1 = node.expressions; i$1 < list$1.length; i$1 += 1)
14428 {
14429 var expr = list$1[i$1];
14430
14431 c(expr, st, "Expression");
14432 }
14433};
14434base$1.TemplateElement = ignore;
14435base$1.UnaryExpression = base$1.UpdateExpression = function (node, st, c) {
14436 c(node.argument, st, "Expression");
14437};
14438base$1.BinaryExpression = base$1.LogicalExpression = function (node, st, c) {
14439 c(node.left, st, "Expression");
14440 c(node.right, st, "Expression");
14441};
14442base$1.AssignmentExpression = base$1.AssignmentPattern = function (node, st, c) {
14443 c(node.left, st, "Pattern");
14444 c(node.right, st, "Expression");
14445};
14446base$1.ConditionalExpression = function (node, st, c) {
14447 c(node.test, st, "Expression");
14448 c(node.consequent, st, "Expression");
14449 c(node.alternate, st, "Expression");
14450};
14451base$1.NewExpression = base$1.CallExpression = function (node, st, c) {
14452 c(node.callee, st, "Expression");
14453 if (node.arguments)
14454 { for (var i = 0, list = node.arguments; i < list.length; i += 1)
14455 {
14456 var arg = list[i];
14457
14458 c(arg, st, "Expression");
14459 } }
14460};
14461base$1.MemberExpression = function (node, st, c) {
14462 c(node.object, st, "Expression");
14463 if (node.computed) { c(node.property, st, "Expression"); }
14464};
14465base$1.ExportNamedDeclaration = base$1.ExportDefaultDeclaration = function (node, st, c) {
14466 if (node.declaration)
14467 { c(node.declaration, st, node.type === "ExportNamedDeclaration" || node.declaration.id ? "Statement" : "Expression"); }
14468 if (node.source) { c(node.source, st, "Expression"); }
14469};
14470base$1.ExportAllDeclaration = function (node, st, c) {
14471 c(node.source, st, "Expression");
14472};
14473base$1.ImportDeclaration = function (node, st, c) {
14474 for (var i = 0, list = node.specifiers; i < list.length; i += 1)
14475 {
14476 var spec = list[i];
14477
14478 c(spec, st);
14479 }
14480 c(node.source, st, "Expression");
14481};
14482base$1.ImportSpecifier = base$1.ImportDefaultSpecifier = base$1.ImportNamespaceSpecifier = base$1.Identifier = base$1.Literal = ignore;
14483
14484base$1.TaggedTemplateExpression = function (node, st, c) {
14485 c(node.tag, st, "Expression");
14486 c(node.quasi, st, "Expression");
14487};
14488base$1.ClassDeclaration = base$1.ClassExpression = function (node, st, c) { return c(node, st, "Class"); };
14489base$1.Class = function (node, st, c) {
14490 if (node.id) { c(node.id, st, "Pattern"); }
14491 if (node.superClass) { c(node.superClass, st, "Expression"); }
14492 c(node.body, st);
14493};
14494base$1.ClassBody = function (node, st, c) {
14495 for (var i = 0, list = node.body; i < list.length; i += 1)
14496 {
14497 var elt = list[i];
14498
14499 c(elt, st);
14500 }
14501};
14502base$1.MethodDefinition = base$1.Property = function (node, st, c) {
14503 if (node.computed) { c(node.key, st, "Expression"); }
14504 c(node.value, st, "Expression");
14505};
14506
14507// @ts-ignore
14508function handlePureAnnotationsOfNode(node, state, type) {
14509 if (type === void 0) { type = node.type; }
14510 var commentNode = state.commentNodes[state.commentIndex];
14511 while (commentNode && node.start >= commentNode.end) {
14512 markPureNode(node, commentNode);
14513 commentNode = state.commentNodes[++state.commentIndex];
14514 }
14515 if (commentNode && commentNode.end <= node.end) {
14516 base$1[type](node, state, handlePureAnnotationsOfNode);
14517 }
14518}
14519function markPureNode(node, comment) {
14520 if (node.annotations) {
14521 node.annotations.push(comment);
14522 }
14523 else {
14524 node.annotations = [comment];
14525 }
14526 if (node.type === 'ExpressionStatement') {
14527 node = node.expression;
14528 }
14529 if (node.type === 'CallExpression' || node.type === 'NewExpression') {
14530 node.annotatedPure = true;
14531 }
14532}
14533var pureCommentRegex = /[@#]__PURE__/;
14534var isPureComment = function (comment) { return pureCommentRegex.test(comment.text); };
14535function markPureCallExpressions(comments, esTreeAst) {
14536 handlePureAnnotationsOfNode(esTreeAst, {
14537 commentIndex: 0,
14538 commentNodes: comments.filter(isPureComment)
14539 });
14540}
14541
14542// this looks ridiculous, but it prevents sourcemap tooling from mistaking
14543// this for an actual sourceMappingURL
14544var SOURCEMAPPING_URL = 'sourceMa';
14545SOURCEMAPPING_URL += 'ppingURL';
14546var SOURCEMAPPING_URL_RE = new RegExp("^#\\s+" + SOURCEMAPPING_URL + "=.+\\n?");
14547
14548var NOOP = function () { };
14549var getStartTime = function () { return 0; };
14550var getElapsedTime = function () { return 0; };
14551var getMemory = function () { return 0; };
14552var timers = {};
14553var normalizeHrTime = function (time) { return time[0] * 1e3 + time[1] / 1e6; };
14554function setTimeHelpers() {
14555 if (typeof process !== 'undefined' && typeof process.hrtime === 'function') {
14556 getStartTime = process.hrtime.bind(process);
14557 getElapsedTime = function (previous) { return normalizeHrTime(process.hrtime(previous)); };
14558 }
14559 else if (typeof performance !== 'undefined' && typeof performance.now === 'function') {
14560 getStartTime = performance.now.bind(performance);
14561 getElapsedTime = function (previous) { return performance.now() - previous; };
14562 }
14563 if (typeof process !== 'undefined' && typeof process.memoryUsage === 'function') {
14564 getMemory = function () { return process.memoryUsage().heapUsed; };
14565 }
14566}
14567function getPersistedLabel(label, level) {
14568 switch (level) {
14569 case 1:
14570 return "# " + label;
14571 case 2:
14572 return "## " + label;
14573 case 3:
14574 return label;
14575 default:
14576 return ' '.repeat(level - 4) + "- " + label;
14577 }
14578}
14579function timeStartImpl(label, level) {
14580 if (level === void 0) { level = 3; }
14581 label = getPersistedLabel(label, level);
14582 if (!timers.hasOwnProperty(label)) {
14583 timers[label] = {
14584 memory: 0,
14585 startMemory: undefined,
14586 startTime: undefined,
14587 time: 0,
14588 totalMemory: 0
14589 };
14590 }
14591 var currentMemory = getMemory();
14592 timers[label].startTime = getStartTime();
14593 timers[label].startMemory = currentMemory;
14594}
14595function timeEndImpl(label, level) {
14596 if (level === void 0) { level = 3; }
14597 label = getPersistedLabel(label, level);
14598 if (timers.hasOwnProperty(label)) {
14599 var currentMemory = getMemory();
14600 timers[label].time += getElapsedTime(timers[label].startTime);
14601 timers[label].totalMemory = Math.max(timers[label].totalMemory, currentMemory);
14602 timers[label].memory += currentMemory - timers[label].startMemory;
14603 }
14604}
14605function getTimings() {
14606 var newTimings = {};
14607 Object.keys(timers).forEach(function (label) {
14608 newTimings[label] = [timers[label].time, timers[label].memory, timers[label].totalMemory];
14609 });
14610 return newTimings;
14611}
14612var timeStart = NOOP, timeEnd = NOOP;
14613var TIMED_PLUGIN_HOOKS = {
14614 load: true,
14615 ongenerate: true,
14616 onwrite: true,
14617 resolveDynamicImport: true,
14618 resolveId: true,
14619 transform: true,
14620 transformBundle: true
14621};
14622function getPluginWithTimers(plugin, index) {
14623 var timedPlugin = {};
14624 var _loop_1 = function (hook) {
14625 if (TIMED_PLUGIN_HOOKS[hook] === true) {
14626 var timerLabel_1 = "plugin " + index;
14627 if (plugin.name) {
14628 timerLabel_1 += " (" + plugin.name + ")";
14629 }
14630 timerLabel_1 += " - " + hook;
14631 timedPlugin[hook] = function () {
14632 timeStart(timerLabel_1, 4);
14633 var result = plugin[hook].apply(this === timedPlugin ? plugin : this, arguments);
14634 timeEnd(timerLabel_1, 4);
14635 if (result && typeof result.then === 'function') {
14636 timeStart(timerLabel_1 + " (async)", 4);
14637 result.then(function () { return timeEnd(timerLabel_1 + " (async)", 4); });
14638 }
14639 return result;
14640 };
14641 }
14642 else {
14643 timedPlugin[hook] = plugin[hook];
14644 }
14645 };
14646 for (var _i = 0, _a = Object.keys(plugin); _i < _a.length; _i++) {
14647 var hook = _a[_i];
14648 _loop_1(hook);
14649 }
14650 return timedPlugin;
14651}
14652function initialiseTimers(inputOptions) {
14653 if (inputOptions.perf) {
14654 timers = {};
14655 setTimeHelpers();
14656 timeStart = timeStartImpl;
14657 timeEnd = timeEndImpl;
14658 inputOptions.plugins = inputOptions.plugins.map(getPluginWithTimers);
14659 }
14660 else {
14661 timeStart = NOOP;
14662 timeEnd = NOOP;
14663 }
14664}
14665
14666function visitStaticModuleDependencies(baseModule, areDependenciesSkipped) {
14667 var modules = [baseModule];
14668 var visitedModules = {};
14669 for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
14670 var module = modules_1[_i];
14671 if (areDependenciesSkipped(module) || module instanceof ExternalModule)
14672 continue;
14673 for (var _a = 0, _b = module.dependencies; _a < _b.length; _a++) {
14674 var dependency = _b[_a];
14675 if (!visitedModules[dependency.id]) {
14676 visitedModules[dependency.id] = true;
14677 modules.push(dependency);
14678 }
14679 }
14680 }
14681}
14682
14683var defaultAcornOptions = {
14684 ecmaVersion: 2019,
14685 preserveParens: false,
14686 sourceType: 'module'
14687};
14688function tryParse(module, Parser, acornOptions) {
14689 try {
14690 return Parser.parse(module.code, __assign({}, defaultAcornOptions, acornOptions, { onComment: function (block, text, start, end) {
14691 return module.comments.push({ block: block, text: text, start: start, end: end });
14692 } }));
14693 }
14694 catch (err) {
14695 var message = err.message.replace(/ \(\d+:\d+\)$/, '');
14696 if (module.id.endsWith('.json')) {
14697 message += ' (Note that you need rollup-plugin-json to import JSON files)';
14698 }
14699 else if (!module.id.endsWith('.js')) {
14700 message += ' (Note that you need plugins to import files that are not JavaScript)';
14701 }
14702 module.error({
14703 code: 'PARSE_ERROR',
14704 message: message
14705 }, err.pos);
14706 }
14707}
14708function handleMissingExport(exportName, importingModule, importedModule, importerStart) {
14709 importingModule.error({
14710 code: 'MISSING_EXPORT',
14711 message: "'" + exportName + "' is not exported by " + relativeId(importedModule),
14712 url: "https://rollupjs.org/guide/en#error-name-is-not-exported-by-module-"
14713 }, importerStart);
14714}
14715var MISSING_EXPORT_SHIM_DESCRIPTION = {
14716 localName: MISSING_EXPORT_SHIM_VARIABLE
14717};
14718var Module = /** @class */ (function () {
14719 function Module(graph, id) {
14720 this.chunkAlias = null;
14721 this.comments = [];
14722 this.dependencies = [];
14723 this.dynamicallyImportedBy = [];
14724 this.dynamicDependencies = [];
14725 this.dynamicImports = [];
14726 this.entryPointsHash = new Uint8Array(10);
14727 this.execIndex = Infinity;
14728 this.exportAllModules = null;
14729 this.exportAllSources = [];
14730 this.exports = Object.create(null);
14731 this.exportsAll = Object.create(null);
14732 this.exportShimVariable = new ExportShimVariable(this);
14733 this.facadeChunk = null;
14734 this.importDescriptions = Object.create(null);
14735 this.importMetas = [];
14736 this.imports = new Set();
14737 this.isEntryPoint = false;
14738 this.isExecuted = false;
14739 this.isUserDefinedEntryPoint = false;
14740 this.manualChunkAlias = null;
14741 this.reexports = Object.create(null);
14742 this.sources = [];
14743 this.usesTopLevelAwait = false;
14744 this.namespaceVariable = undefined;
14745 this.id = id;
14746 this.graph = graph;
14747 this.excludeFromSourcemap = /\0/.test(id);
14748 this.context = graph.getModuleContext(id);
14749 }
14750 Module.prototype.basename = function () {
14751 var base = basename(this.id);
14752 var ext = extname(this.id);
14753 return makeLegal(ext ? base.slice(0, -ext.length) : base);
14754 };
14755 Module.prototype.bindReferences = function () {
14756 this.ast.bind();
14757 };
14758 Module.prototype.error = function (props, pos) {
14759 if (pos !== undefined) {
14760 props.pos = pos;
14761 var location = locate(this.code, pos, { offsetLine: 1 });
14762 try {
14763 location = getOriginalLocation(this.sourcemapChain, location);
14764 }
14765 catch (e) {
14766 this.warn({
14767 code: 'SOURCEMAP_ERROR',
14768 loc: {
14769 column: location.column,
14770 file: this.id,
14771 line: location.line
14772 },
14773 message: "Error when using sourcemap for reporting an error: " + e.message,
14774 pos: pos
14775 }, undefined);
14776 }
14777 props.loc = {
14778 column: location.column,
14779 file: this.id,
14780 line: location.line
14781 };
14782 props.frame = getCodeFrame(this.originalCode, location.line, location.column);
14783 }
14784 error(props);
14785 };
14786 Module.prototype.getAllExports = function () {
14787 var allExports = Object.assign(Object.create(null), this.exports, this.reexports);
14788 this.exportAllModules.forEach(function (module) {
14789 if (module.isExternal) {
14790 allExports["*" + module.id] = true;
14791 return;
14792 }
14793 for (var _i = 0, _a = module.getAllExports(); _i < _a.length; _i++) {
14794 var name = _a[_i];
14795 if (name !== 'default')
14796 allExports[name] = true;
14797 }
14798 });
14799 return Object.keys(allExports);
14800 };
14801 Module.prototype.getDynamicImportExpressions = function () {
14802 return this.dynamicImports.map(function (_a) {
14803 var node = _a.node;
14804 var importArgument = node.parent.arguments[0];
14805 if (isTemplateLiteral(importArgument)) {
14806 if (importArgument.expressions.length === 0 && importArgument.quasis.length === 1) {
14807 return importArgument.quasis[0].value.cooked;
14808 }
14809 }
14810 else if (isLiteral(importArgument)) {
14811 if (typeof importArgument.value === 'string') {
14812 return importArgument.value;
14813 }
14814 }
14815 else {
14816 return importArgument;
14817 }
14818 });
14819 };
14820 Module.prototype.getExports = function () {
14821 return Object.keys(this.exports);
14822 };
14823 Module.prototype.getOrCreateNamespace = function () {
14824 return (this.namespaceVariable || (this.namespaceVariable = new NamespaceVariable(this.astContext)));
14825 };
14826 Module.prototype.getReexports = function () {
14827 var reexports = Object.create(null);
14828 for (var name in this.reexports) {
14829 reexports[name] = true;
14830 }
14831 this.exportAllModules.forEach(function (module) {
14832 if (module.isExternal) {
14833 reexports["*" + module.id] = true;
14834 return;
14835 }
14836 for (var _i = 0, _a = module.getExports().concat(module.getReexports()); _i < _a.length; _i++) {
14837 var name = _a[_i];
14838 if (name !== 'default')
14839 reexports[name] = true;
14840 }
14841 });
14842 return Object.keys(reexports);
14843 };
14844 Module.prototype.getRenderedExports = function () {
14845 // only direct exports are counted here, not reexports at all
14846 var renderedExports = [];
14847 var removedExports = [];
14848 for (var exportName in this.exports) {
14849 var variable = this.getVariableForExportName(exportName);
14850 (variable && variable.included ? renderedExports : removedExports).push(exportName);
14851 }
14852 return { renderedExports: renderedExports, removedExports: removedExports };
14853 };
14854 Module.prototype.getVariableForExportName = function (name, isExportAllSearch) {
14855 if (name[0] === '*') {
14856 if (name.length === 1) {
14857 return this.getOrCreateNamespace();
14858 }
14859 else {
14860 // export * from 'external'
14861 var module = this.graph.moduleById.get(name.slice(1));
14862 return module.getVariableForExportName('*');
14863 }
14864 }
14865 // export { foo } from './other'
14866 var reexportDeclaration = this.reexports[name];
14867 if (reexportDeclaration) {
14868 var declaration = reexportDeclaration.module.getVariableForExportName(reexportDeclaration.localName);
14869 if (!declaration) {
14870 handleMissingExport(reexportDeclaration.localName, this, reexportDeclaration.module.id, reexportDeclaration.start);
14871 }
14872 return declaration;
14873 }
14874 var exportDeclaration = this.exports[name];
14875 if (exportDeclaration) {
14876 if (exportDeclaration === MISSING_EXPORT_SHIM_DESCRIPTION) {
14877 return this.exportShimVariable;
14878 }
14879 var name_1 = exportDeclaration.localName;
14880 return this.traceVariable(name_1) || this.graph.scope.findVariable(name_1);
14881 }
14882 if (name !== 'default') {
14883 for (var i = 0; i < this.exportAllModules.length; i += 1) {
14884 var module = this.exportAllModules[i];
14885 var declaration = module.getVariableForExportName(name, true);
14886 if (declaration)
14887 return declaration;
14888 }
14889 }
14890 // we don't want to create shims when we are just
14891 // probing export * modules for exports
14892 if (this.graph.shimMissingExports && !isExportAllSearch) {
14893 this.shimMissingExport(name);
14894 return this.exportShimVariable;
14895 }
14896 };
14897 Module.prototype.include = function () {
14898 if (this.ast.shouldBeIncluded())
14899 this.ast.include(false);
14900 };
14901 Module.prototype.includeAllExports = function () {
14902 if (!this.isExecuted) {
14903 this.graph.needsTreeshakingPass = true;
14904 visitStaticModuleDependencies(this, function (module) {
14905 if (module instanceof ExternalModule || module.isExecuted)
14906 return true;
14907 module.isExecuted = true;
14908 return false;
14909 });
14910 }
14911 for (var _i = 0, _a = this.getExports(); _i < _a.length; _i++) {
14912 var exportName = _a[_i];
14913 var variable = this.getVariableForExportName(exportName);
14914 variable.deoptimizePath(UNKNOWN_PATH);
14915 if (!variable.included) {
14916 variable.include();
14917 this.graph.needsTreeshakingPass = true;
14918 }
14919 }
14920 for (var _b = 0, _c = this.getReexports(); _b < _c.length; _b++) {
14921 var name = _c[_b];
14922 var variable = this.getVariableForExportName(name);
14923 if (variable.isExternal) {
14924 variable.reexported = variable.module.reexported = true;
14925 }
14926 else if (!variable.included) {
14927 variable.include();
14928 variable.deoptimizePath(UNKNOWN_PATH);
14929 this.graph.needsTreeshakingPass = true;
14930 }
14931 }
14932 };
14933 Module.prototype.includeAllInBundle = function () {
14934 this.ast.include(true);
14935 };
14936 Module.prototype.isIncluded = function () {
14937 return this.ast.included || (this.namespaceVariable && this.namespaceVariable.included);
14938 };
14939 Module.prototype.linkDependencies = function () {
14940 var _this = this;
14941 for (var _i = 0, _a = this.sources; _i < _a.length; _i++) {
14942 var source = _a[_i];
14943 var id = this.resolvedIds[source].id;
14944 if (id) {
14945 var module = this.graph.moduleById.get(id);
14946 this.dependencies.push(module);
14947 }
14948 }
14949 for (var _b = 0, _c = this.dynamicImports; _b < _c.length; _b++) {
14950 var resolution = _c[_b].resolution;
14951 if (resolution instanceof Module || resolution instanceof ExternalModule) {
14952 this.dynamicDependencies.push(resolution);
14953 }
14954 }
14955 this.addModulesToSpecifiers(this.importDescriptions);
14956 this.addModulesToSpecifiers(this.reexports);
14957 this.exportAllModules = this.exportAllSources.map(function (source) {
14958 var id = _this.resolvedIds[source].id;
14959 return _this.graph.moduleById.get(id);
14960 });
14961 };
14962 Module.prototype.render = function (options) {
14963 var magicString = this.magicString.clone();
14964 this.ast.render(magicString, options);
14965 this.usesTopLevelAwait = this.astContext.usesTopLevelAwait;
14966 return magicString;
14967 };
14968 Module.prototype.setSource = function (_a) {
14969 var _this = this;
14970 var code = _a.code, originalCode = _a.originalCode, originalSourcemap = _a.originalSourcemap, ast = _a.ast, sourcemapChain = _a.sourcemapChain, resolvedIds = _a.resolvedIds, transformDependencies = _a.transformDependencies, customTransformCache = _a.customTransformCache;
14971 this.code = code;
14972 this.originalCode = originalCode;
14973 this.originalSourcemap = originalSourcemap;
14974 this.sourcemapChain = sourcemapChain;
14975 this.transformDependencies = transformDependencies;
14976 this.customTransformCache = customTransformCache;
14977 timeStart('generate ast', 3);
14978 this.esTreeAst = ((ast || tryParse(this, this.graph.acornParser, this.graph.acornOptions)));
14979 markPureCallExpressions(this.comments, this.esTreeAst);
14980 timeEnd('generate ast', 3);
14981 this.resolvedIds = resolvedIds || Object.create(null);
14982 // By default, `id` is the file name. Custom resolvers and loaders
14983 // can change that, but it makes sense to use it for the source file name
14984 var fileName = this.id;
14985 this.magicString = new MagicString(code, {
14986 filename: this.excludeFromSourcemap ? null : fileName,
14987 indentExclusionRanges: []
14988 });
14989 this.removeExistingSourceMap();
14990 timeStart('analyse ast', 3);
14991 this.astContext = {
14992 addDynamicImport: this.addDynamicImport.bind(this),
14993 addExport: this.addExport.bind(this),
14994 addImport: this.addImport.bind(this),
14995 addImportMeta: this.addImportMeta.bind(this),
14996 annotations: this.graph.treeshake && this.graph.treeshakingOptions.annotations,
14997 code: code,
14998 deoptimizationTracker: this.graph.deoptimizationTracker,
14999 error: this.error.bind(this),
15000 fileName: fileName,
15001 getAssetFileName: this.graph.pluginDriver.getAssetFileName,
15002 getChunkFileName: this.graph.moduleLoader.getChunkFileName.bind(this.graph.moduleLoader),
15003 getExports: this.getExports.bind(this),
15004 getModuleExecIndex: function () { return _this.execIndex; },
15005 getModuleName: this.basename.bind(this),
15006 getReexports: this.getReexports.bind(this),
15007 importDescriptions: this.importDescriptions,
15008 includeDynamicImport: this.includeDynamicImport.bind(this),
15009 includeVariable: this.includeVariable.bind(this),
15010 isCrossChunkImport: function (importDescription) { return importDescription.module.chunk !== _this.chunk; },
15011 magicString: this.magicString,
15012 module: this,
15013 moduleContext: this.context,
15014 nodeConstructors: nodeConstructors,
15015 preserveModules: this.graph.preserveModules,
15016 propertyReadSideEffects: !this.graph.treeshake || this.graph.treeshakingOptions.propertyReadSideEffects,
15017 traceExport: this.getVariableForExportName.bind(this),
15018 traceVariable: this.traceVariable.bind(this),
15019 treeshake: this.graph.treeshake,
15020 usesTopLevelAwait: false,
15021 warn: this.warn.bind(this)
15022 };
15023 this.scope = new ModuleScope(this.graph.scope, this.astContext);
15024 this.ast = new Program$1(this.esTreeAst, { type: 'Module', context: this.astContext }, this.scope);
15025 timeEnd('analyse ast', 3);
15026 };
15027 Module.prototype.toJSON = function () {
15028 return {
15029 ast: this.esTreeAst,
15030 code: this.code,
15031 customTransformCache: this.customTransformCache,
15032 dependencies: this.dependencies.map(function (module) { return module.id; }),
15033 id: this.id,
15034 originalCode: this.originalCode,
15035 originalSourcemap: this.originalSourcemap,
15036 resolvedIds: this.resolvedIds,
15037 sourcemapChain: this.sourcemapChain,
15038 transformAssets: this.transformAssets,
15039 transformDependencies: this.transformDependencies
15040 };
15041 };
15042 Module.prototype.traceVariable = function (name) {
15043 if (name in this.scope.variables) {
15044 return this.scope.variables[name];
15045 }
15046 if (name in this.importDescriptions) {
15047 var importDeclaration = this.importDescriptions[name];
15048 var otherModule = importDeclaration.module;
15049 if (!otherModule.isExternal && importDeclaration.name === '*') {
15050 return otherModule.getOrCreateNamespace();
15051 }
15052 var declaration = otherModule.getVariableForExportName(importDeclaration.name);
15053 if (!declaration) {
15054 handleMissingExport(importDeclaration.name, this, otherModule.id, importDeclaration.start);
15055 }
15056 return declaration;
15057 }
15058 return null;
15059 };
15060 Module.prototype.warn = function (warning, pos) {
15061 if (pos !== undefined) {
15062 warning.pos = pos;
15063 var _a = locate(this.code, pos, { offsetLine: 1 }), line = _a.line, column = _a.column; // TODO trace sourcemaps, cf. error()
15064 warning.loc = { file: this.id, line: line, column: column };
15065 warning.frame = getCodeFrame(this.code, line, column);
15066 }
15067 warning.id = this.id;
15068 this.graph.warn(warning);
15069 };
15070 Module.prototype.addDynamicImport = function (node) {
15071 this.dynamicImports.push({ node: node, resolution: undefined });
15072 };
15073 Module.prototype.addExport = function (node) {
15074 var source = node.source && node.source.value;
15075 // export { name } from './other'
15076 if (source) {
15077 if (this.sources.indexOf(source) === -1)
15078 this.sources.push(source);
15079 if (node.type === ExportAllDeclaration) {
15080 // Store `export * from '...'` statements in an array of delegates.
15081 // When an unknown import is encountered, we see if one of them can satisfy it.
15082 this.exportAllSources.push(source);
15083 }
15084 else {
15085 for (var _i = 0, _a = node.specifiers; _i < _a.length; _i++) {
15086 var specifier = _a[_i];
15087 var name = specifier.exported.name;
15088 if (this.exports[name] || this.reexports[name]) {
15089 this.error({
15090 code: 'DUPLICATE_EXPORT',
15091 message: "A module cannot have multiple exports with the same name ('" + name + "')"
15092 }, specifier.start);
15093 }
15094 this.reexports[name] = {
15095 localName: specifier.local.name,
15096 module: null,
15097 source: source,
15098 start: specifier.start
15099 };
15100 }
15101 }
15102 }
15103 else if (isExportDefaultDeclaration(node)) {
15104 // export default function foo () {}
15105 // export default foo;
15106 // export default 42;
15107 if (this.exports.default) {
15108 this.error({
15109 code: 'DUPLICATE_EXPORT',
15110 message: "A module can only have one default export"
15111 }, node.start);
15112 }
15113 this.exports.default = {
15114 identifier: node.variable.getOriginalVariableName(),
15115 localName: 'default'
15116 };
15117 }
15118 else if (node.declaration) {
15119 // export var { foo, bar } = ...
15120 // export var foo = 42;
15121 // export var a = 1, b = 2, c = 3;
15122 // export function foo () {}
15123 var declaration = node.declaration;
15124 if (declaration.type === VariableDeclaration) {
15125 for (var _b = 0, _c = declaration.declarations; _b < _c.length; _b++) {
15126 var decl = _c[_b];
15127 for (var _d = 0, _e = extractAssignedNames(decl.id); _d < _e.length; _d++) {
15128 var localName = _e[_d];
15129 this.exports[localName] = { localName: localName };
15130 }
15131 }
15132 }
15133 else {
15134 // export function foo () {}
15135 var localName = declaration.id.name;
15136 this.exports[localName] = { localName: localName };
15137 }
15138 }
15139 else {
15140 // export { foo, bar, baz }
15141 for (var _f = 0, _g = node.specifiers; _f < _g.length; _f++) {
15142 var specifier = _g[_f];
15143 var localName = specifier.local.name;
15144 var exportedName = specifier.exported.name;
15145 if (this.exports[exportedName] || this.reexports[exportedName]) {
15146 this.error({
15147 code: 'DUPLICATE_EXPORT',
15148 message: "A module cannot have multiple exports with the same name ('" + exportedName + "')"
15149 }, specifier.start);
15150 }
15151 this.exports[exportedName] = { localName: localName };
15152 }
15153 }
15154 };
15155 Module.prototype.addImport = function (node) {
15156 var source = node.source.value;
15157 if (this.sources.indexOf(source) === -1)
15158 this.sources.push(source);
15159 for (var _i = 0, _a = node.specifiers; _i < _a.length; _i++) {
15160 var specifier = _a[_i];
15161 var localName = specifier.local.name;
15162 if (this.importDescriptions[localName]) {
15163 this.error({
15164 code: 'DUPLICATE_IMPORT',
15165 message: "Duplicated import '" + localName + "'"
15166 }, specifier.start);
15167 }
15168 var isDefault = specifier.type === ImportDefaultSpecifier;
15169 var isNamespace = specifier.type === ImportNamespaceSpecifier;
15170 var name = isDefault
15171 ? 'default'
15172 : isNamespace
15173 ? '*'
15174 : specifier.imported.name;
15175 this.importDescriptions[localName] = { source: source, start: specifier.start, name: name, module: null };
15176 }
15177 };
15178 Module.prototype.addImportMeta = function (node) {
15179 this.importMetas.push(node);
15180 };
15181 Module.prototype.addModulesToSpecifiers = function (specifiers) {
15182 for (var _i = 0, _a = Object.keys(specifiers); _i < _a.length; _i++) {
15183 var name = _a[_i];
15184 var specifier = specifiers[name];
15185 var id = this.resolvedIds[specifier.source].id;
15186 specifier.module = this.graph.moduleById.get(id);
15187 }
15188 };
15189 Module.prototype.includeDynamicImport = function (node) {
15190 var resolution = this.dynamicImports.find(function (dynamicImport) { return dynamicImport.node === node; })
15191 .resolution;
15192 if (resolution instanceof Module) {
15193 resolution.dynamicallyImportedBy.push(this);
15194 resolution.includeAllExports();
15195 }
15196 };
15197 Module.prototype.includeVariable = function (variable) {
15198 if (!variable.included) {
15199 variable.include();
15200 this.graph.needsTreeshakingPass = true;
15201 }
15202 if (variable.module && variable.module !== this) {
15203 this.imports.add(variable);
15204 }
15205 };
15206 Module.prototype.removeExistingSourceMap = function () {
15207 for (var _i = 0, _a = this.comments; _i < _a.length; _i++) {
15208 var comment = _a[_i];
15209 if (!comment.block && SOURCEMAPPING_URL_RE.test(comment.text)) {
15210 this.magicString.remove(comment.start, comment.end);
15211 }
15212 }
15213 };
15214 Module.prototype.shimMissingExport = function (name) {
15215 if (!this.exports[name]) {
15216 this.graph.warn({
15217 code: 'SHIMMED_EXPORT',
15218 exporter: relativeId(this.id),
15219 exportName: name,
15220 message: "Missing export \"" + name + "\" has been shimmed in module " + relativeId(this.id) + "."
15221 });
15222 this.exports[name] = MISSING_EXPORT_SHIM_DESCRIPTION;
15223 }
15224 };
15225 return Module;
15226}());
15227
15228var Source = /** @class */ (function () {
15229 function Source(filename, content) {
15230 this.isOriginal = true;
15231 this.filename = filename;
15232 this.content = content;
15233 }
15234 Source.prototype.traceSegment = function (line, column, name) {
15235 return { line: line, column: column, name: name, source: this };
15236 };
15237 return Source;
15238}());
15239var Link = /** @class */ (function () {
15240 function Link(map, sources) {
15241 this.sources = sources;
15242 this.names = map.names;
15243 this.mappings = map.mappings;
15244 }
15245 Link.prototype.traceMappings = function () {
15246 var sources = [];
15247 var sourcesContent = [];
15248 var names = [];
15249 var mappings = [];
15250 for (var _i = 0, _a = this.mappings; _i < _a.length; _i++) {
15251 var line = _a[_i];
15252 var tracedLine = [];
15253 for (var _b = 0, line_1 = line; _b < line_1.length; _b++) {
15254 var segment = line_1[_b];
15255 var source = this.sources[segment[1]];
15256 if (!source)
15257 continue;
15258 var traced = source.traceSegment(segment[2], segment[3], this.names[segment[4]]);
15259 if (traced) {
15260 // newer sources are more likely to be used, so search backwards.
15261 var sourceIndex = sources.lastIndexOf(traced.source.filename);
15262 if (sourceIndex === -1) {
15263 sourceIndex = sources.length;
15264 sources.push(traced.source.filename);
15265 sourcesContent[sourceIndex] = traced.source.content;
15266 }
15267 else if (sourcesContent[sourceIndex] == null) {
15268 sourcesContent[sourceIndex] = traced.source.content;
15269 }
15270 else if (traced.source.content != null &&
15271 sourcesContent[sourceIndex] !== traced.source.content) {
15272 error({
15273 message: "Multiple conflicting contents for sourcemap source " + traced.source.filename
15274 });
15275 }
15276 var tracedSegment = [
15277 segment[0],
15278 sourceIndex,
15279 traced.line,
15280 traced.column
15281 ];
15282 if (traced.name) {
15283 var nameIndex = names.indexOf(traced.name);
15284 if (nameIndex === -1) {
15285 nameIndex = names.length;
15286 names.push(traced.name);
15287 }
15288 tracedSegment[4] = nameIndex;
15289 }
15290 tracedLine.push(tracedSegment);
15291 }
15292 }
15293 mappings.push(tracedLine);
15294 }
15295 return { sources: sources, sourcesContent: sourcesContent, names: names, mappings: mappings };
15296 };
15297 Link.prototype.traceSegment = function (line, column, name) {
15298 var segments = this.mappings[line];
15299 if (!segments)
15300 return null;
15301 // binary search through segments for the given column
15302 var i = 0;
15303 var j = segments.length - 1;
15304 while (i <= j) {
15305 var m = (i + j) >> 1;
15306 var segment = segments[m];
15307 if (segment[0] === column) {
15308 var source = this.sources[segment[1]];
15309 if (!source)
15310 return null;
15311 return source.traceSegment(segment[2], segment[3], this.names[segment[4]] || name);
15312 }
15313 if (segment[0] > column) {
15314 j = m - 1;
15315 }
15316 else {
15317 i = m + 1;
15318 }
15319 }
15320 return null;
15321 };
15322 return Link;
15323}());
15324// TODO TypeScript: Fix <any> typecasts
15325function collapseSourcemaps(bundle, file, map, modules, bundleSourcemapChain, excludeContent) {
15326 function linkMap(source, map) {
15327 if (map.missing) {
15328 bundle.graph.warn({
15329 code: 'SOURCEMAP_BROKEN',
15330 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",
15331 plugin: map.plugin,
15332 url: "https://rollupjs.org/guide/en#warning-sourcemap-is-likely-to-be-incorrect"
15333 });
15334 map = {
15335 mappings: '',
15336 names: []
15337 };
15338 }
15339 return new Link(map, [source]);
15340 }
15341 var moduleSources = modules
15342 .filter(function (module) { return !module.excludeFromSourcemap; })
15343 .map(function (module) {
15344 var sourcemapChain = module.sourcemapChain;
15345 var source;
15346 var originalSourcemap = module.originalSourcemap;
15347 if (!originalSourcemap) {
15348 source = new Source(module.id, module.originalCode);
15349 }
15350 else {
15351 var sources_1 = originalSourcemap.sources;
15352 var sourcesContent_1 = originalSourcemap.sourcesContent || [];
15353 if (sources_1 == null || (sources_1.length <= 1 && sources_1[0] == null)) {
15354 source = new Source(module.id, sourcesContent_1[0]);
15355 sourcemapChain = [originalSourcemap].concat(sourcemapChain);
15356 }
15357 else {
15358 // TODO indiscriminately treating IDs and sources as normal paths is probably bad.
15359 var directory_1 = dirname(module.id) || '.';
15360 var sourceRoot_1 = originalSourcemap.sourceRoot || '.';
15361 var baseSources = sources_1.map(function (source, i) { return new Source(resolve$1(directory_1, sourceRoot_1, source), sourcesContent_1[i]); });
15362 source = new Link(originalSourcemap, baseSources);
15363 }
15364 }
15365 source = sourcemapChain.reduce(linkMap, source);
15366 return source;
15367 });
15368 var source = new Link(map, moduleSources);
15369 source = bundleSourcemapChain.reduce(linkMap, source);
15370 var _a = source.traceMappings(), sources = _a.sources, sourcesContent = _a.sourcesContent, names = _a.names, mappings = _a.mappings;
15371 if (file) {
15372 var directory_2 = dirname(file);
15373 sources = sources.map(function (source) { return relative(directory_2, source); });
15374 file = basename(file);
15375 }
15376 sourcesContent = excludeContent ? null : sourcesContent;
15377 return new SourceMap({ file: file, sources: sources, sourcesContent: sourcesContent, names: names, mappings: mappings });
15378}
15379
15380var _a;
15381var RESERVED_NAMES = Object.assign(Object.create(null), {
15382 await: true,
15383 break: true,
15384 case: true,
15385 catch: true,
15386 class: true,
15387 const: true,
15388 continue: true,
15389 debugger: true,
15390 default: true,
15391 delete: true,
15392 do: true,
15393 else: true,
15394 enum: true,
15395 eval: true,
15396 export: true,
15397 extends: true,
15398 finally: true,
15399 for: true,
15400 function: true,
15401 if: true,
15402 implements: true,
15403 import: true,
15404 in: true,
15405 instanceof: true,
15406 interface: true,
15407 let: true,
15408 new: true,
15409 null: true,
15410 package: true,
15411 private: true,
15412 protected: true,
15413 public: true,
15414 return: true,
15415 static: true,
15416 super: true,
15417 switch: true,
15418 throw: true,
15419 try: true,
15420 typeof: true,
15421 undefined: true,
15422 var: true,
15423 void: true,
15424 while: true,
15425 with: true,
15426 yield: true
15427});
15428var NONE = {};
15429var EXPORTS = { exports: true };
15430var RESERVED_NAMES_BY_FORMAT = {
15431 amd: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES },
15432 cjs: {
15433 forbiddenNames: RESERVED_NAMES,
15434 formatGlobals: (_a = { exports: true, module: true }, _a[INTEROP_DEFAULT_VARIABLE] = true, _a)
15435 },
15436 es: { formatGlobals: NONE, forbiddenNames: RESERVED_NAMES },
15437 iife: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES },
15438 system: {
15439 forbiddenNames: Object.assign(Object.create(null), RESERVED_NAMES, EXPORTS),
15440 formatGlobals: NONE
15441 },
15442 umd: { formatGlobals: EXPORTS, forbiddenNames: RESERVED_NAMES }
15443};
15444
15445var DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT = {
15446 amd: deconflictImportsOther,
15447 cjs: deconflictImportsOther,
15448 es: deconflictImportsEsm,
15449 iife: deconflictImportsOther,
15450 system: deconflictImportsEsm,
15451 umd: deconflictImportsOther
15452};
15453function deconflictChunk(modules, dependencies, imports, usedNames, format, interop, preserveModules) {
15454 var _a = RESERVED_NAMES_BY_FORMAT[format], forbiddenNames = _a.forbiddenNames, formatGlobals = _a.formatGlobals;
15455 Object.assign(usedNames, forbiddenNames);
15456 Object.assign(usedNames, formatGlobals);
15457 addUsedGlobalNames(usedNames, modules);
15458 deconflictTopLevelVariables(usedNames, modules);
15459 DECONFLICT_IMPORTED_VARIABLES_BY_FORMAT[format](usedNames, imports, dependencies, interop, preserveModules);
15460 for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
15461 var module = modules_1[_i];
15462 module.scope.deconflict(forbiddenNames);
15463 }
15464}
15465function addUsedGlobalNames(usedNames, modules) {
15466 var accessedGlobals = Object.assign.apply(Object, [{}].concat(modules.map(function (module) { return module.scope.accessedOutsideVariables; })));
15467 for (var _i = 0, _a = Object.keys(accessedGlobals); _i < _a.length; _i++) {
15468 var name = _a[_i];
15469 var variable = accessedGlobals[name];
15470 if (variable.included) {
15471 usedNames[name] = true;
15472 }
15473 }
15474}
15475function deconflictImportsEsm(usedNames, imports, _dependencies, interop) {
15476 for (var _i = 0, _a = Array.from(imports); _i < _a.length; _i++) {
15477 var variable = _a[_i];
15478 var module = variable.module;
15479 var name = variable.name;
15480 var proposedName = void 0;
15481 if (module instanceof ExternalModule && (name === '*' || name === 'default')) {
15482 if (name === 'default' && interop && module.exportsNamespace) {
15483 proposedName = module.variableName + '__default';
15484 }
15485 else {
15486 proposedName = module.variableName;
15487 }
15488 }
15489 else {
15490 proposedName = name;
15491 }
15492 variable.setRenderNames(null, getSafeName(proposedName, usedNames));
15493 }
15494}
15495function deconflictImportsOther(usedNames, imports, dependencies, interop, preserveModules) {
15496 for (var _i = 0, dependencies_1 = dependencies; _i < dependencies_1.length; _i++) {
15497 var chunkOrExternalModule = dependencies_1[_i];
15498 chunkOrExternalModule.variableName = getSafeName(chunkOrExternalModule.variableName, usedNames);
15499 }
15500 for (var _a = 0, _b = Array.from(imports); _a < _b.length; _a++) {
15501 var variable = _b[_a];
15502 var module = variable.module;
15503 if (module instanceof ExternalModule) {
15504 var name = variable.name;
15505 if (name === 'default' && interop && (module.exportsNamespace || module.exportsNames)) {
15506 variable.setRenderNames(null, module.variableName + '__default');
15507 }
15508 else if (name === '*' || name === 'default') {
15509 variable.setRenderNames(null, module.variableName);
15510 }
15511 else {
15512 variable.setRenderNames(module.variableName, null);
15513 }
15514 }
15515 else {
15516 var chunk = module.chunk;
15517 if (chunk.exportMode === 'default' || (preserveModules && variable.isNamespace)) {
15518 variable.setRenderNames(null, chunk.variableName);
15519 }
15520 else {
15521 variable.setRenderNames(chunk.variableName, module.chunk.getVariableExportName(variable));
15522 }
15523 }
15524 }
15525}
15526function deconflictTopLevelVariables(usedNames, modules) {
15527 for (var _i = 0, modules_2 = modules; _i < modules_2.length; _i++) {
15528 var module = modules_2[_i];
15529 var moduleVariables = module.scope.variables;
15530 for (var _a = 0, _b = Object.keys(moduleVariables); _a < _b.length; _a++) {
15531 var name = _b[_a];
15532 var variable = moduleVariables[name];
15533 if (variable.included &&
15534 // this will only happen for exports in some formats
15535 !(variable.renderBaseName ||
15536 (variable instanceof ExportDefaultVariable && variable.referencesOriginal()))) {
15537 variable.setRenderNames(null, getSafeName(variable.name, usedNames));
15538 }
15539 }
15540 var namespace = module.getOrCreateNamespace();
15541 if (namespace.included) {
15542 namespace.setRenderNames(null, getSafeName(namespace.name, usedNames));
15543 }
15544 }
15545}
15546
15547var compareExecIndex = function (unitA, unitB) {
15548 return unitA.execIndex > unitB.execIndex ? 1 : -1;
15549};
15550function sortByExecutionOrder(units) {
15551 units.sort(compareExecIndex);
15552}
15553function analyseModuleExecution(entryModules) {
15554 var nextExecIndex = 0;
15555 var inStaticGraph = true;
15556 var cyclePaths = [];
15557 var analysedModules = {};
15558 var orderedModules = [];
15559 var dynamicImports = [];
15560 var parents = {};
15561 var analyseModule = function (module) {
15562 if (analysedModules[module.id])
15563 return;
15564 if (module instanceof ExternalModule) {
15565 module.execIndex = nextExecIndex++;
15566 analysedModules[module.id] = true;
15567 return;
15568 }
15569 if (inStaticGraph) {
15570 module.isExecuted = true;
15571 }
15572 for (var _i = 0, _a = module.dependencies; _i < _a.length; _i++) {
15573 var dependency = _a[_i];
15574 if (dependency.id in parents) {
15575 if (!analysedModules[dependency.id]) {
15576 cyclePaths.push(getCyclePath(dependency.id, module.id, parents));
15577 }
15578 continue;
15579 }
15580 parents[dependency.id] = module.id;
15581 analyseModule(dependency);
15582 }
15583 for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
15584 var resolution = _c[_b].resolution;
15585 if (resolution instanceof Module && dynamicImports.indexOf(resolution) === -1) {
15586 dynamicImports.push(resolution);
15587 }
15588 }
15589 module.execIndex = nextExecIndex++;
15590 analysedModules[module.id] = true;
15591 orderedModules.push(module);
15592 };
15593 for (var _i = 0, entryModules_1 = entryModules; _i < entryModules_1.length; _i++) {
15594 var curEntry = entryModules_1[_i];
15595 curEntry.isEntryPoint = true;
15596 if (!parents[curEntry.id]) {
15597 parents[curEntry.id] = null;
15598 analyseModule(curEntry);
15599 }
15600 }
15601 inStaticGraph = false;
15602 for (var _a = 0, dynamicImports_1 = dynamicImports; _a < dynamicImports_1.length; _a++) {
15603 var curEntry = dynamicImports_1[_a];
15604 if (!parents[curEntry.id]) {
15605 parents[curEntry.id] = null;
15606 analyseModule(curEntry);
15607 }
15608 }
15609 return { orderedModules: orderedModules, cyclePaths: cyclePaths };
15610}
15611function getCyclePath(id, parentId, parents) {
15612 var path = [relativeId(id)];
15613 var curId = parentId;
15614 while (curId !== id) {
15615 path.push(relativeId(curId));
15616 curId = parents[curId];
15617 if (!curId)
15618 break;
15619 }
15620 path.push(path[0]);
15621 path.reverse();
15622 return path;
15623}
15624
15625function guessIndentString(code) {
15626 var lines = code.split('\n');
15627 var tabbed = lines.filter(function (line) { return /^\t+/.test(line); });
15628 var spaced = lines.filter(function (line) { return /^ {2,}/.test(line); });
15629 if (tabbed.length === 0 && spaced.length === 0) {
15630 return null;
15631 }
15632 // More lines tabbed than spaced? Assume tabs, and
15633 // default to tabs in the case of a tie (or nothing
15634 // to go on)
15635 if (tabbed.length >= spaced.length) {
15636 return '\t';
15637 }
15638 // Otherwise, we need to guess the multiple
15639 var min = spaced.reduce(function (previous, current) {
15640 var numSpaces = /^ +/.exec(current)[0].length;
15641 return Math.min(numSpaces, previous);
15642 }, Infinity);
15643 return new Array(min + 1).join(' ');
15644}
15645function getIndentString(modules, options) {
15646 if (options.indent !== true)
15647 return options.indent || '';
15648 for (var i = 0; i < modules.length; i++) {
15649 var indent = guessIndentString(modules[i].originalCode);
15650 if (indent !== null)
15651 return indent;
15652 }
15653 return '\t';
15654}
15655
15656function renderChunk(_a) {
15657 var graph = _a.graph, chunk = _a.chunk, renderChunk = _a.renderChunk, code = _a.code, sourcemapChain = _a.sourcemapChain, options = _a.options;
15658 var renderChunkReducer = function (code, result, plugin) {
15659 if (result == null)
15660 return code;
15661 if (typeof result === 'string')
15662 result = {
15663 code: result,
15664 map: undefined
15665 };
15666 var map = typeof result.map === 'string' ? JSON.parse(result.map) : result.map;
15667 if (map && typeof map.mappings === 'string')
15668 map.mappings = decode(map.mappings);
15669 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
15670 if (map !== null)
15671 sourcemapChain.push(map || { missing: true, plugin: plugin.name });
15672 return result.code;
15673 };
15674 var inTransformBundle = false;
15675 var inRenderChunk = true;
15676 return graph.pluginDriver
15677 .hookReduceArg0('renderChunk', [code, renderChunk, options], renderChunkReducer)
15678 .then(function (code) {
15679 inRenderChunk = false;
15680 return graph.pluginDriver.hookReduceArg0('transformChunk', [code, options, chunk], renderChunkReducer);
15681 })
15682 .then(function (code) {
15683 inTransformBundle = true;
15684 return graph.pluginDriver.hookReduceArg0('transformBundle', [code, options, chunk], renderChunkReducer);
15685 })
15686 .catch(function (err) {
15687 if (inRenderChunk)
15688 throw err;
15689 error(err, {
15690 code: inTransformBundle ? 'BAD_BUNDLE_TRANSFORMER' : 'BAD_CHUNK_TRANSFORMER',
15691 message: "Error transforming " + ((inTransformBundle ? 'bundle' : 'chunk') +
15692 (err.plugin ? " with '" + err.plugin + "' plugin" : '')) + ": " + err.message,
15693 plugin: err.plugin
15694 });
15695 });
15696}
15697
15698function renderNamePattern(pattern, patternName, getReplacement) {
15699 if (!isPlainName(pattern))
15700 error({
15701 code: 'INVALID_PATTERN',
15702 message: "Invalid output pattern \"" + pattern + "\" for " + patternName + ", cannot be an absolute or relative URL or path."
15703 });
15704 return pattern.replace(/\[(\w+)\]/g, function (_match, type) {
15705 var replacement = getReplacement(type);
15706 if (replacement === undefined)
15707 error({
15708 code: 'INVALID_PATTERN_REPLACEMENT',
15709 message: "\"" + type + "\" is not a valid substitution name in output option " + patternName + " pattern."
15710 });
15711 if (!isPlainName(replacement))
15712 error({
15713 code: 'INVALID_PATTERN_REPLACEMENT',
15714 message: "Invalid replacement \"" + replacement + "\" for \"" + type + "\" in " + patternName + " pattern, must be a plain path name."
15715 });
15716 return replacement;
15717 });
15718}
15719function makeUnique(name, existingNames) {
15720 if (name in existingNames === false)
15721 return name;
15722 var ext = extname(name);
15723 name = name.substr(0, name.length - ext.length);
15724 var uniqueName, uniqueIndex = 1;
15725 while (existingNames[(uniqueName = name + ++uniqueIndex + ext)])
15726 ;
15727 return uniqueName;
15728}
15729
15730function sanitizeFileName(name) {
15731 return name.replace(/[\0]/g, '_');
15732}
15733
15734function getGlobalName(module, globals, graph, hasExports) {
15735 var globalName;
15736 if (typeof globals === 'function') {
15737 globalName = globals(module.id);
15738 }
15739 else if (globals) {
15740 globalName = globals[module.id];
15741 }
15742 if (globalName) {
15743 return globalName;
15744 }
15745 if (hasExports) {
15746 graph.warn({
15747 code: 'MISSING_GLOBAL_NAME',
15748 guess: module.variableName,
15749 message: "No name was provided for external module '" + module.id + "' in output.globals \u2013 guessing '" + module.variableName + "'",
15750 source: module.id
15751 });
15752 return module.variableName;
15753 }
15754}
15755function isChunkRendered(chunk) {
15756 return !chunk.isEmpty || chunk.entryModules.length > 0 || chunk.manualChunkAlias !== null;
15757}
15758var Chunk$1 = /** @class */ (function () {
15759 function Chunk(graph, orderedModules) {
15760 this.entryModules = [];
15761 this.exportMode = 'named';
15762 this.facadeModule = null;
15763 this.hasDynamicImport = false;
15764 this.id = undefined;
15765 this.indentString = undefined;
15766 this.manualChunkAlias = null;
15767 this.usedModules = undefined;
15768 this.dependencies = undefined;
15769 this.dynamicDependencies = undefined;
15770 this.exportNames = Object.create(null);
15771 this.exports = new Set();
15772 this.imports = new Set();
15773 this.needsExportsShim = false;
15774 this.renderedDeclarations = undefined;
15775 this.renderedHash = undefined;
15776 this.renderedModuleSources = undefined;
15777 this.renderedSource = null;
15778 this.renderedSourceLength = undefined;
15779 this.sortedExportNames = null;
15780 this.graph = graph;
15781 this.orderedModules = orderedModules;
15782 this.execIndex = orderedModules.length > 0 ? orderedModules[0].execIndex : Infinity;
15783 this.isEmpty = true;
15784 for (var _i = 0, orderedModules_1 = orderedModules; _i < orderedModules_1.length; _i++) {
15785 var module = orderedModules_1[_i];
15786 if (this.isEmpty && module.isIncluded()) {
15787 this.isEmpty = false;
15788 }
15789 if (module.manualChunkAlias) {
15790 this.manualChunkAlias = module.manualChunkAlias;
15791 }
15792 module.chunk = this;
15793 if (module.isEntryPoint ||
15794 module.dynamicallyImportedBy.some(function (module) { return orderedModules.indexOf(module) === -1; })) {
15795 this.entryModules.push(module);
15796 }
15797 }
15798 var entryModule = this.entryModules[0];
15799 if (entryModule) {
15800 this.variableName = makeLegal(basename(entryModule.chunkAlias || entryModule.manualChunkAlias || getAliasName(entryModule.id)));
15801 }
15802 else {
15803 this.variableName = '__chunk_' + ++graph.curChunkIndex;
15804 }
15805 }
15806 Chunk.prototype.generateEntryExportsOrMarkAsTainted = function () {
15807 var _this = this;
15808 var exportVariableMaps = this.entryModules.map(function (module) { return ({
15809 map: _this.getVariableExportNamesForModule(module),
15810 module: module
15811 }); });
15812 for (var _i = 0, exportVariableMaps_1 = exportVariableMaps; _i < exportVariableMaps_1.length; _i++) {
15813 var map = exportVariableMaps_1[_i].map;
15814 for (var _a = 0, _b = Array.from(map.keys()); _a < _b.length; _a++) {
15815 var exposedVariable = _b[_a];
15816 this.exports.add(exposedVariable);
15817 }
15818 }
15819 var exposedVariables = Array.from(this.exports);
15820 checkNextEntryModule: for (var _c = 0, exportVariableMaps_2 = exportVariableMaps; _c < exportVariableMaps_2.length; _c++) {
15821 var _d = exportVariableMaps_2[_c], map = _d.map, module = _d.module;
15822 if (!this.graph.preserveModules) {
15823 if (this.manualChunkAlias &&
15824 module.chunkAlias &&
15825 this.manualChunkAlias !== module.chunkAlias) {
15826 continue checkNextEntryModule;
15827 }
15828 for (var _e = 0, exposedVariables_1 = exposedVariables; _e < exposedVariables_1.length; _e++) {
15829 var exposedVariable = exposedVariables_1[_e];
15830 if (!map.has(exposedVariable)) {
15831 continue checkNextEntryModule;
15832 }
15833 }
15834 }
15835 this.facadeModule = module;
15836 for (var _f = 0, _g = Array.from(map); _f < _g.length; _f++) {
15837 var _h = _g[_f], variable = _h[0], exportNames = _h[1];
15838 for (var _j = 0, exportNames_1 = exportNames; _j < exportNames_1.length; _j++) {
15839 var exportName = exportNames_1[_j];
15840 this.exportNames[exportName] = variable;
15841 }
15842 }
15843 return;
15844 }
15845 };
15846 Chunk.prototype.generateId = function (pattern, patternName, addons, options, existingNames) {
15847 var _this = this;
15848 this.id = makeUnique(renderNamePattern(pattern, patternName, function (type) {
15849 switch (type) {
15850 case 'format':
15851 return options.format === 'es' ? 'esm' : options.format;
15852 case 'hash':
15853 return _this.computeContentHashWithDependencies(addons, options);
15854 case 'name':
15855 return _this.getChunkName();
15856 }
15857 }), existingNames);
15858 };
15859 Chunk.prototype.generateIdPreserveModules = function (preserveModulesRelativeDir, existingNames) {
15860 var sanitizedId = sanitizeFileName(this.orderedModules[0].id);
15861 this.id = makeUnique(normalize(isAbsolute(this.orderedModules[0].id)
15862 ? relative(preserveModulesRelativeDir, sanitizedId)
15863 : '_virtual/' + basename(sanitizedId)), existingNames);
15864 };
15865 Chunk.prototype.generateInternalExports = function (options) {
15866 if (this.facadeModule !== null)
15867 return;
15868 var mangle = options.format === 'system' || options.format === 'es' || options.compact;
15869 var i = 0, safeExportName;
15870 this.exportNames = Object.create(null);
15871 this.sortedExportNames = null;
15872 var exportedVariables = Array.from(this.exports);
15873 if (mangle) {
15874 for (var _i = 0, exportedVariables_1 = exportedVariables; _i < exportedVariables_1.length; _i++) {
15875 var variable = exportedVariables_1[_i];
15876 do {
15877 safeExportName = toBase64(++i);
15878 // skip past leading number identifiers
15879 if (safeExportName.charCodeAt(0) === 49 /* '1' */) {
15880 i += 9 * Math.pow(64, (safeExportName.length - 1));
15881 safeExportName = toBase64(i);
15882 }
15883 } while (RESERVED_NAMES[safeExportName]);
15884 this.exportNames[safeExportName] = variable;
15885 }
15886 }
15887 else {
15888 for (var _a = 0, exportedVariables_2 = exportedVariables; _a < exportedVariables_2.length; _a++) {
15889 var variable = exportedVariables_2[_a];
15890 i = 0;
15891 safeExportName = variable.name;
15892 while (this.exportNames[safeExportName]) {
15893 safeExportName = variable.name + '$' + ++i;
15894 }
15895 this.exportNames[safeExportName] = variable;
15896 }
15897 }
15898 };
15899 Chunk.prototype.getChunkName = function () {
15900 return this.chunkName || (this.chunkName = this.computeChunkName());
15901 };
15902 Chunk.prototype.getDynamicImportIds = function () {
15903 return this.dynamicDependencies.map(function (chunk) { return chunk.id; }).filter(Boolean);
15904 };
15905 Chunk.prototype.getExportNames = function () {
15906 return (this.sortedExportNames || (this.sortedExportNames = Object.keys(this.exportNames).sort()));
15907 };
15908 Chunk.prototype.getImportIds = function () {
15909 return this.dependencies.map(function (chunk) { return chunk.id; });
15910 };
15911 Chunk.prototype.getRenderedHash = function () {
15912 var _this = this;
15913 if (this.renderedHash)
15914 return this.renderedHash;
15915 if (!this.renderedSource)
15916 return '';
15917 var hash = _256();
15918 hash.update(this.renderedSource.toString());
15919 hash.update(this.getExportNames()
15920 .map(function (exportName) {
15921 var variable = _this.exportNames[exportName];
15922 return relativeId(variable.module.id).replace(/\\/g, '/') + ":" + variable.name + ":" + exportName;
15923 })
15924 .join(','));
15925 return (this.renderedHash = hash.digest('hex'));
15926 };
15927 Chunk.prototype.getRenderedSourceLength = function () {
15928 if (this.renderedSourceLength !== undefined)
15929 return this.renderedSourceLength;
15930 return (this.renderedSourceLength = this.renderedSource.length());
15931 };
15932 Chunk.prototype.getVariableExportName = function (variable) {
15933 if (this.graph.preserveModules && variable instanceof NamespaceVariable) {
15934 return '*';
15935 }
15936 for (var _i = 0, _a = Object.keys(this.exportNames); _i < _a.length; _i++) {
15937 var exportName = _a[_i];
15938 if (this.exportNames[exportName] === variable)
15939 return exportName;
15940 }
15941 };
15942 Chunk.prototype.link = function () {
15943 var dependencies = new Set();
15944 var dynamicDependencies = new Set();
15945 for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
15946 var module = _a[_i];
15947 this.addChunksFromDependencies(module.dependencies, dependencies);
15948 this.addChunksFromDependencies(module.dynamicDependencies, dynamicDependencies);
15949 this.setUpModuleImports(module);
15950 }
15951 this.dependencies = Array.from(dependencies);
15952 this.dynamicDependencies = Array.from(dynamicDependencies);
15953 };
15954 /*
15955 * Performs a full merge of another chunk into this chunk
15956 * chunkList allows updating references in other chunks for the merged chunk to this chunk
15957 * A new facade will be added to chunkList if tainting exports of either as an entry point
15958 */
15959 Chunk.prototype.merge = function (chunk, chunkList, options, inputBase) {
15960 var _this = this;
15961 if (this.facadeModule !== null || chunk.facadeModule !== null)
15962 throw new Error('Internal error: Code splitting chunk merges not supported for facades');
15963 for (var _i = 0, _a = chunk.orderedModules; _i < _a.length; _i++) {
15964 var module = _a[_i];
15965 module.chunk = this;
15966 this.orderedModules.push(module);
15967 }
15968 for (var _b = 0, _c = Array.from(chunk.imports); _b < _c.length; _b++) {
15969 var variable = _c[_b];
15970 if (!this.imports.has(variable) && variable.module.chunk !== this) {
15971 this.imports.add(variable);
15972 }
15973 }
15974 // NB detect when exported variables are orphaned by the merge itself
15975 // (involves reverse tracing dependents)
15976 for (var _d = 0, _e = Array.from(chunk.exports); _d < _e.length; _d++) {
15977 var variable = _e[_d];
15978 if (!this.exports.has(variable)) {
15979 this.exports.add(variable);
15980 }
15981 }
15982 var thisOldExportNames = this.exportNames;
15983 // regenerate internal names
15984 this.generateInternalExports(options);
15985 var updateRenderedDeclaration = function (dep, oldExportNames) {
15986 if (dep.imports) {
15987 for (var _i = 0, _a = dep.imports; _i < _a.length; _i++) {
15988 var impt = _a[_i];
15989 impt.imported = _this.getVariableExportName(oldExportNames[impt.imported]);
15990 }
15991 }
15992 if (dep.reexports) {
15993 for (var _b = 0, _c = dep.reexports; _b < _c.length; _b++) {
15994 var reexport = _c[_b];
15995 reexport.imported = _this.getVariableExportName(oldExportNames[reexport.imported]);
15996 }
15997 }
15998 };
15999 var mergeRenderedDeclaration = function (into, from) {
16000 if (from.imports) {
16001 if (!into.imports) {
16002 into.imports = from.imports;
16003 }
16004 else {
16005 into.imports = into.imports.concat(from.imports);
16006 }
16007 }
16008 if (from.reexports) {
16009 if (!into.reexports) {
16010 into.reexports = from.reexports;
16011 }
16012 else {
16013 into.reexports = into.reexports.concat(from.reexports);
16014 }
16015 }
16016 if (!into.exportsNames && from.exportsNames) {
16017 into.exportsNames = true;
16018 }
16019 if (!into.exportsDefault && from.exportsDefault) {
16020 into.exportsDefault = true;
16021 }
16022 into.name = _this.variableName;
16023 };
16024 // go through the other chunks and update their dependencies
16025 // also update their import and reexport names in the process
16026 for (var _f = 0, chunkList_1 = chunkList; _f < chunkList_1.length; _f++) {
16027 var c = chunkList_1[_f];
16028 var includedDeclaration = void 0;
16029 for (var i = 0; i < c.dependencies.length; i++) {
16030 var dep = c.dependencies[i];
16031 if ((dep === chunk || dep === this) && includedDeclaration) {
16032 var duplicateDeclaration = c.renderedDeclarations.dependencies[i];
16033 updateRenderedDeclaration(duplicateDeclaration, dep === chunk ? chunk.exportNames : thisOldExportNames);
16034 mergeRenderedDeclaration(includedDeclaration, duplicateDeclaration);
16035 c.renderedDeclarations.dependencies.splice(i, 1);
16036 c.dependencies.splice(i--, 1);
16037 }
16038 else if (dep === chunk) {
16039 c.dependencies[i] = this;
16040 includedDeclaration = c.renderedDeclarations.dependencies[i];
16041 updateRenderedDeclaration(includedDeclaration, chunk.exportNames);
16042 }
16043 else if (dep === this) {
16044 includedDeclaration = c.renderedDeclarations.dependencies[i];
16045 updateRenderedDeclaration(includedDeclaration, thisOldExportNames);
16046 }
16047 }
16048 }
16049 // re-render the merged chunk
16050 this.preRender(options, inputBase);
16051 };
16052 // prerender allows chunk hashes and names to be generated before finalizing
16053 Chunk.prototype.preRender = function (options, inputBase) {
16054 timeStart('render modules', 3);
16055 var magicString = new Bundle({ separator: options.compact ? '' : '\n\n' });
16056 this.usedModules = [];
16057 this.indentString = options.compact ? '' : getIndentString(this.orderedModules, options);
16058 var n = options.compact ? '' : '\n';
16059 var _ = options.compact ? '' : ' ';
16060 var renderOptions = {
16061 compact: options.compact,
16062 dynamicImportFunction: options.dynamicImportFunction,
16063 format: options.format,
16064 freeze: options.freeze !== false,
16065 indent: this.indentString,
16066 namespaceToStringTag: options.namespaceToStringTag === true,
16067 varOrConst: options.preferConst ? 'const' : 'var'
16068 };
16069 // Make sure the direct dependencies of a chunk are present to maintain execution order
16070 for (var _i = 0, _a = Array.from(this.imports); _i < _a.length; _i++) {
16071 var module = _a[_i].module;
16072 var chunkOrExternal = module instanceof Module ? module.chunk : module;
16073 if (this.dependencies.indexOf(chunkOrExternal) === -1) {
16074 this.dependencies.push(chunkOrExternal);
16075 }
16076 }
16077 // for static and dynamic entry points, inline the execution list to avoid loading latency
16078 if (!this.graph.preserveModules && this.facadeModule !== null) {
16079 for (var _b = 0, _c = this.dependencies; _b < _c.length; _b++) {
16080 var dep = _c[_b];
16081 if (dep instanceof Chunk)
16082 this.inlineChunkDependencies(dep, true);
16083 }
16084 }
16085 // prune empty dependency chunks, inlining their side-effect dependencies
16086 for (var i = 0; i < this.dependencies.length; i++) {
16087 var dep = this.dependencies[i];
16088 if (dep instanceof Chunk && dep.isEmpty) {
16089 this.dependencies.splice(i--, 1);
16090 this.inlineChunkDependencies(dep, false);
16091 }
16092 }
16093 sortByExecutionOrder(this.dependencies);
16094 this.setIdentifierRenderResolutions(options);
16095 this.prepareDynamicImports();
16096 var hoistedSource = '';
16097 this.renderedModules = Object.create(null);
16098 this.renderedModuleSources = [];
16099 for (var i = 0; i < this.orderedModules.length; i++) {
16100 var module = this.orderedModules[i];
16101 var source = module.render(renderOptions);
16102 source.trim();
16103 if (options.compact && source.lastLine().indexOf('//') !== -1)
16104 source.append('\n');
16105 this.renderedModuleSources.push(source);
16106 var _d = module.getRenderedExports(), renderedExports = _d.renderedExports, removedExports = _d.removedExports;
16107 this.renderedModules[module.id] = {
16108 originalLength: module.originalCode.length,
16109 removedExports: removedExports,
16110 renderedExports: renderedExports,
16111 renderedLength: source.length()
16112 };
16113 var namespace = module.getOrCreateNamespace();
16114 if (namespace.included || !source.isEmpty()) {
16115 magicString.addSource(source);
16116 this.usedModules.push(module);
16117 if (namespace.included && !this.graph.preserveModules) {
16118 var rendered = namespace.renderBlock(renderOptions);
16119 if (namespace.renderFirst())
16120 hoistedSource += n + rendered;
16121 else
16122 magicString.addSource(new MagicString(rendered));
16123 }
16124 }
16125 }
16126 if (hoistedSource)
16127 magicString.prepend(hoistedSource + n + n);
16128 if (this.needsExportsShim) {
16129 magicString.prepend("" + n + renderOptions.varOrConst + " " + MISSING_EXPORT_SHIM_VARIABLE + _ + "=" + _ + "void 0;" + n + n);
16130 }
16131 if (options.compact) {
16132 this.renderedSource = magicString;
16133 }
16134 else {
16135 this.renderedSource = magicString.trim();
16136 }
16137 this.renderedSourceLength = undefined;
16138 this.renderedHash = undefined;
16139 if (this.getExportNames().length === 0 && this.getImportIds().length === 0 && this.isEmpty) {
16140 this.graph.warn({
16141 code: 'EMPTY_BUNDLE',
16142 message: 'Generated an empty bundle'
16143 });
16144 }
16145 this.setExternalRenderPaths(options, inputBase);
16146 this.renderedDeclarations = {
16147 dependencies: this.getChunkDependencyDeclarations(options),
16148 exports: this.exportMode === 'none' ? [] : this.getChunkExportDeclarations()
16149 };
16150 timeEnd('render modules', 3);
16151 };
16152 Chunk.prototype.render = function (options, addons, outputChunk) {
16153 var _this = this;
16154 timeStart('render format', 3);
16155 if (!this.renderedSource)
16156 throw new Error('Internal error: Chunk render called before preRender');
16157 var finalise = finalisers[options.format];
16158 if (!finalise) {
16159 error({
16160 code: 'INVALID_OPTION',
16161 message: "Invalid format: " + options.format + " - valid options are " + Object.keys(finalisers).join(', ') + "."
16162 });
16163 }
16164 if (options.dynamicImportFunction && options.format !== 'es') {
16165 this.graph.warn({
16166 code: 'INVALID_OPTION',
16167 message: '"output.dynamicImportFunction" is ignored for formats other than "esm".'
16168 });
16169 }
16170 // populate ids in the rendered declarations only here
16171 // as chunk ids known only after prerender
16172 for (var i = 0; i < this.dependencies.length; i++) {
16173 var dep = this.dependencies[i];
16174 if (dep instanceof ExternalModule && !dep.renormalizeRenderPath)
16175 continue;
16176 var renderedDependency = this.renderedDeclarations.dependencies[i];
16177 var depId = dep instanceof ExternalModule ? renderedDependency.id : dep.id;
16178 var relPath = this.id ? normalize(relative(dirname(this.id), depId)) : depId;
16179 if (!relPath.startsWith('../'))
16180 relPath = './' + relPath;
16181 if (dep instanceof Chunk)
16182 renderedDependency.namedExportsMode = dep.exportMode !== 'default';
16183 renderedDependency.id = relPath;
16184 }
16185 this.finaliseDynamicImports(options.format);
16186 var needsAmdModule = this.finaliseImportMetas(options);
16187 var hasExports = this.renderedDeclarations.exports.length !== 0 ||
16188 this.renderedDeclarations.dependencies.some(function (dep) { return dep.reexports && dep.reexports.length !== 0; });
16189 var usesTopLevelAwait = this.orderedModules.some(function (module) { return module.usesTopLevelAwait; });
16190 if (usesTopLevelAwait && options.format !== 'es' && options.format !== 'system') {
16191 error({
16192 code: 'INVALID_TLA_FORMAT',
16193 message: "Module format " + options.format + " does not support top-level await. Use the \"es\" or \"system\" output formats rather."
16194 });
16195 }
16196 var magicString = finalise(this.renderedSource, {
16197 dependencies: this.renderedDeclarations.dependencies,
16198 dynamicImport: this.hasDynamicImport,
16199 exports: this.renderedDeclarations.exports,
16200 hasExports: hasExports,
16201 indentString: this.indentString,
16202 intro: addons.intro,
16203 isEntryModuleFacade: this.facadeModule !== null && this.facadeModule.isEntryPoint,
16204 namedExportsMode: this.exportMode !== 'default',
16205 needsAmdModule: needsAmdModule,
16206 outro: addons.outro,
16207 usesTopLevelAwait: usesTopLevelAwait,
16208 varOrConst: options.preferConst ? 'const' : 'var',
16209 warn: this.graph.warn.bind(this.graph)
16210 }, options);
16211 if (addons.banner)
16212 magicString.prepend(addons.banner);
16213 if (addons.footer)
16214 magicString.append(addons.footer);
16215 var prevCode = magicString.toString();
16216 timeEnd('render format', 3);
16217 var map = null;
16218 var chunkSourcemapChain = [];
16219 return renderChunk({
16220 chunk: this,
16221 code: prevCode,
16222 graph: this.graph,
16223 options: options,
16224 renderChunk: outputChunk,
16225 sourcemapChain: chunkSourcemapChain
16226 }).then(function (code) {
16227 if (options.sourcemap) {
16228 timeStart('sourcemap', 3);
16229 var file = void 0;
16230 if (options.file)
16231 file = resolve$1(options.sourcemapFile || options.file);
16232 else if (options.dir)
16233 file = resolve$1(options.dir, _this.id);
16234 else
16235 file = resolve$1(_this.id);
16236 if (_this.graph.pluginDriver.hasLoadersOrTransforms) {
16237 var decodedMap = magicString.generateDecodedMap({});
16238 map = collapseSourcemaps(_this, file, decodedMap, _this.usedModules, chunkSourcemapChain, options.sourcemapExcludeSources);
16239 }
16240 else {
16241 map = magicString.generateMap({ file: file, includeContent: !options.sourcemapExcludeSources });
16242 }
16243 map.sources = map.sources.map(function (sourcePath) {
16244 return normalize(options.sourcemapPathTransform ? options.sourcemapPathTransform(sourcePath) : sourcePath);
16245 });
16246 timeEnd('sourcemap', 3);
16247 }
16248 if (options.compact !== true && code[code.length - 1] !== '\n')
16249 code += '\n';
16250 return { code: code, map: map };
16251 });
16252 };
16253 Chunk.prototype.turnIntoFacade = function (facadedModule) {
16254 this.dependencies = [facadedModule.chunk];
16255 this.dynamicDependencies = [];
16256 this.facadeModule = facadedModule;
16257 facadedModule.facadeChunk = this;
16258 for (var _i = 0, _a = facadedModule.getAllExports(); _i < _a.length; _i++) {
16259 var exportName = _a[_i];
16260 var tracedVariable = facadedModule.getVariableForExportName(exportName);
16261 this.exports.add(tracedVariable);
16262 this.exportNames[exportName] = tracedVariable;
16263 }
16264 };
16265 Chunk.prototype.visitDependencies = function (handleDependency) {
16266 var toBeVisited = [this];
16267 var visited = new Set();
16268 for (var _i = 0, toBeVisited_1 = toBeVisited; _i < toBeVisited_1.length; _i++) {
16269 var current = toBeVisited_1[_i];
16270 handleDependency(current);
16271 if (current instanceof ExternalModule)
16272 continue;
16273 for (var _a = 0, _b = current.dependencies.concat(current.dynamicDependencies); _a < _b.length; _a++) {
16274 var dependency = _b[_a];
16275 if (!visited.has(dependency)) {
16276 visited.add(dependency);
16277 toBeVisited.push(dependency);
16278 }
16279 }
16280 }
16281 };
16282 Chunk.prototype.visitStaticDependenciesUntilCondition = function (isConditionSatisfied) {
16283 var seen = new Set();
16284 function visitDep(dep) {
16285 if (seen.has(dep))
16286 return;
16287 seen.add(dep);
16288 if (dep instanceof Chunk) {
16289 for (var _i = 0, _a = dep.dependencies; _i < _a.length; _i++) {
16290 var subDep = _a[_i];
16291 if (visitDep(subDep))
16292 return true;
16293 }
16294 }
16295 return isConditionSatisfied(dep) === true;
16296 }
16297 return visitDep(this);
16298 };
16299 Chunk.prototype.addChunksFromDependencies = function (moduleDependencies, chunkDependencies) {
16300 for (var _i = 0, moduleDependencies_1 = moduleDependencies; _i < moduleDependencies_1.length; _i++) {
16301 var depModule = moduleDependencies_1[_i];
16302 if (depModule.chunk === this) {
16303 continue;
16304 }
16305 var dependency = void 0;
16306 if (depModule instanceof Module) {
16307 dependency = depModule.chunk;
16308 }
16309 else {
16310 if (!depModule.used && this.graph.isPureExternalModule(depModule.id)) {
16311 continue;
16312 }
16313 dependency = depModule;
16314 }
16315 chunkDependencies.add(dependency);
16316 }
16317 };
16318 Chunk.prototype.computeChunkName = function () {
16319 if (this.manualChunkAlias) {
16320 return sanitizeFileName(this.manualChunkAlias);
16321 }
16322 if (this.facadeModule !== null) {
16323 return sanitizeFileName(this.facadeModule.chunkAlias || getAliasName(this.facadeModule.id));
16324 }
16325 for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
16326 var module = _a[_i];
16327 if (module.chunkAlias)
16328 return sanitizeFileName(module.chunkAlias);
16329 }
16330 return 'chunk';
16331 };
16332 Chunk.prototype.computeContentHashWithDependencies = function (addons, options) {
16333 var hash = _256();
16334 hash.update([addons.intro, addons.outro, addons.banner, addons.footer].map(function (addon) { return addon || ''; }).join(':'));
16335 hash.update(options.format);
16336 this.visitDependencies(function (dep) {
16337 if (dep instanceof ExternalModule)
16338 hash.update(':' + dep.renderPath);
16339 else
16340 hash.update(dep.getRenderedHash());
16341 });
16342 return hash.digest('hex').substr(0, 8);
16343 };
16344 Chunk.prototype.finaliseDynamicImports = function (format) {
16345 for (var i = 0; i < this.orderedModules.length; i++) {
16346 var module = this.orderedModules[i];
16347 var code = this.renderedModuleSources[i];
16348 for (var _i = 0, _a = module.dynamicImports; _i < _a.length; _i++) {
16349 var _b = _a[_i], node = _b.node, resolution = _b.resolution;
16350 if (!resolution)
16351 continue;
16352 if (resolution instanceof Module) {
16353 if (resolution.chunk !== this && isChunkRendered(resolution.chunk)) {
16354 var resolutionChunk = resolution.facadeChunk || resolution.chunk;
16355 var relPath = normalize(relative(dirname(this.id), resolutionChunk.id));
16356 if (!relPath.startsWith('../'))
16357 relPath = './' + relPath;
16358 node.renderFinalResolution(code, "'" + relPath + "'", format);
16359 }
16360 }
16361 else if (resolution instanceof ExternalModule) {
16362 var resolutionId = resolution.id;
16363 if (resolution.renormalizeRenderPath) {
16364 resolutionId = normalize(relative(dirname(this.id), resolution.renderPath));
16365 if (!resolutionId.startsWith('../'))
16366 resolutionId = './' + resolutionId;
16367 }
16368 node.renderFinalResolution(code, "'" + resolutionId + "'", format);
16369 }
16370 else {
16371 node.renderFinalResolution(code, resolution, format);
16372 }
16373 }
16374 }
16375 };
16376 Chunk.prototype.finaliseImportMetas = function (options) {
16377 var needsAmdModule = false;
16378 for (var i = 0; i < this.orderedModules.length; i++) {
16379 var module = this.orderedModules[i];
16380 var code = this.renderedModuleSources[i];
16381 for (var _i = 0, _a = module.importMetas; _i < _a.length; _i++) {
16382 var importMeta = _a[_i];
16383 if (importMeta.renderFinalMechanism(code, this.id, options.format, this.graph.pluginDriver)) {
16384 needsAmdModule = true;
16385 }
16386 }
16387 }
16388 return needsAmdModule;
16389 };
16390 Chunk.prototype.getChunkDependencyDeclarations = function (options) {
16391 var reexportDeclarations = new Map();
16392 for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
16393 var exportName = _a[_i];
16394 var exportModule = void 0;
16395 var importName = void 0;
16396 var needsLiveBinding = false;
16397 if (exportName[0] === '*') {
16398 exportModule = this.graph.moduleById.get(exportName.substr(1));
16399 importName = exportName = '*';
16400 }
16401 else {
16402 var variable = this.exportNames[exportName];
16403 var module = variable.module;
16404 // skip local exports
16405 if (!module || module.chunk === this)
16406 continue;
16407 if (module instanceof Module) {
16408 exportModule = module.chunk;
16409 importName = module.chunk.getVariableExportName(variable);
16410 needsLiveBinding = variable.isReassigned;
16411 }
16412 else {
16413 exportModule = module;
16414 importName = variable.name;
16415 needsLiveBinding = true;
16416 }
16417 }
16418 var exportDeclaration = reexportDeclarations.get(exportModule);
16419 if (!exportDeclaration)
16420 reexportDeclarations.set(exportModule, (exportDeclaration = []));
16421 exportDeclaration.push({ imported: importName, reexported: exportName, needsLiveBinding: needsLiveBinding });
16422 }
16423 var importsAsArray = Array.from(this.imports);
16424 var renderedImports = new Set();
16425 var dependencies = [];
16426 for (var _b = 0, _c = this.dependencies; _b < _c.length; _b++) {
16427 var dep = _c[_b];
16428 var imports = [];
16429 for (var _d = 0, importsAsArray_1 = importsAsArray; _d < importsAsArray_1.length; _d++) {
16430 var variable = importsAsArray_1[_d];
16431 var renderedVariable = variable instanceof ExportDefaultVariable && variable.referencesOriginal()
16432 ? variable.getOriginalVariable()
16433 : variable;
16434 if ((variable.module instanceof Module
16435 ? variable.module.chunk === dep
16436 : variable.module === dep) &&
16437 !renderedImports.has(renderedVariable)) {
16438 renderedImports.add(renderedVariable);
16439 var local = variable.getName();
16440 var imported = variable.module instanceof ExternalModule
16441 ? variable.name
16442 : variable.module.chunk.getVariableExportName(variable);
16443 imports.push({ local: local, imported: imported });
16444 }
16445 }
16446 var reexports = reexportDeclarations.get(dep);
16447 var exportsNames = void 0, exportsDefault = void 0;
16448 var namedExportsMode = true;
16449 if (dep instanceof ExternalModule) {
16450 exportsNames = dep.exportsNames || dep.exportsNamespace;
16451 exportsDefault = 'default' in dep.declarations;
16452 }
16453 else {
16454 exportsNames = true;
16455 // we don't want any interop patterns to trigger
16456 exportsDefault = false;
16457 namedExportsMode = dep.exportMode !== 'default';
16458 }
16459 var id = void 0;
16460 var globalName = void 0;
16461 if (dep instanceof ExternalModule) {
16462 id = dep.renderPath;
16463 if (options.format === 'umd' || options.format === 'iife') {
16464 globalName = getGlobalName(dep, options.globals, this.graph, exportsNames || exportsDefault);
16465 }
16466 }
16467 dependencies.push({
16468 exportsDefault: exportsDefault,
16469 exportsNames: exportsNames,
16470 globalName: globalName,
16471 id: id,
16472 imports: imports.length > 0 ? imports : null,
16473 isChunk: !dep.isExternal,
16474 name: dep.variableName,
16475 namedExportsMode: namedExportsMode,
16476 reexports: reexports
16477 });
16478 }
16479 return dependencies;
16480 };
16481 Chunk.prototype.getChunkExportDeclarations = function () {
16482 var exports = [];
16483 var _loop_1 = function (exportName) {
16484 if (exportName[0] === '*')
16485 return "continue";
16486 var variable = this_1.exportNames[exportName];
16487 var module = variable.module;
16488 if (module && module.chunk !== this_1)
16489 return "continue";
16490 var hoisted = false;
16491 var uninitialized = false;
16492 if (variable instanceof LocalVariable) {
16493 if (variable.init === UNDEFINED_EXPRESSION) {
16494 uninitialized = true;
16495 }
16496 variable.declarations.forEach(function (decl) {
16497 if (decl.type === ExportDefaultDeclaration) {
16498 if (decl.declaration.type === FunctionDeclaration)
16499 hoisted = true;
16500 }
16501 else if (decl.parent.type === FunctionDeclaration) {
16502 hoisted = true;
16503 }
16504 });
16505 }
16506 else if (variable instanceof GlobalVariable) {
16507 hoisted = true;
16508 }
16509 var localName = variable.getName();
16510 exports.push({
16511 exported: exportName === '*' ? localName : exportName,
16512 hoisted: hoisted,
16513 local: localName,
16514 uninitialized: uninitialized
16515 });
16516 };
16517 var this_1 = this;
16518 for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
16519 var exportName = _a[_i];
16520 _loop_1(exportName);
16521 }
16522 return exports;
16523 };
16524 Chunk.prototype.getVariableExportNamesForModule = function (module) {
16525 var exportNamesByVariable = new Map();
16526 for (var _i = 0, _a = module.getAllExports(); _i < _a.length; _i++) {
16527 var exportName = _a[_i];
16528 var tracedVariable = module.getVariableForExportName(exportName);
16529 if (!tracedVariable || !(tracedVariable.included || tracedVariable.isExternal)) {
16530 continue;
16531 }
16532 var existingExportNames = exportNamesByVariable.get(tracedVariable);
16533 if (existingExportNames) {
16534 existingExportNames.push(exportName);
16535 }
16536 else {
16537 exportNamesByVariable.set(tracedVariable, [exportName]);
16538 }
16539 var exportingModule = tracedVariable.module;
16540 if (exportingModule && exportingModule.chunk && exportingModule.chunk !== this) {
16541 exportingModule.chunk.exports.add(tracedVariable);
16542 }
16543 }
16544 return exportNamesByVariable;
16545 };
16546 Chunk.prototype.inlineChunkDependencies = function (chunk, deep) {
16547 for (var _i = 0, _a = chunk.dependencies; _i < _a.length; _i++) {
16548 var dep = _a[_i];
16549 if (dep instanceof ExternalModule) {
16550 if (this.dependencies.indexOf(dep) === -1)
16551 this.dependencies.push(dep);
16552 }
16553 else {
16554 if (dep === this || this.dependencies.indexOf(dep) !== -1)
16555 continue;
16556 if (!dep.isEmpty)
16557 this.dependencies.push(dep);
16558 if (deep)
16559 this.inlineChunkDependencies(dep, true);
16560 }
16561 }
16562 };
16563 Chunk.prototype.prepareDynamicImports = function () {
16564 for (var _i = 0, _a = this.orderedModules; _i < _a.length; _i++) {
16565 var module = _a[_i];
16566 for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
16567 var _d = _c[_b], node = _d.node, resolution = _d.resolution;
16568 if (!resolution)
16569 continue;
16570 if (resolution instanceof Module) {
16571 if (resolution.chunk === this) {
16572 var namespace = resolution.getOrCreateNamespace();
16573 node.setResolution(false, namespace.getName());
16574 }
16575 else {
16576 node.setResolution(false);
16577 }
16578 }
16579 else if (resolution instanceof ExternalModule) {
16580 node.setResolution(false);
16581 }
16582 else {
16583 node.setResolution(false);
16584 }
16585 }
16586 }
16587 };
16588 Chunk.prototype.setExternalRenderPaths = function (options, inputBase) {
16589 for (var _i = 0, _a = this.dependencies.concat(this.dynamicDependencies); _i < _a.length; _i++) {
16590 var dependency = _a[_i];
16591 if (dependency instanceof ExternalModule) {
16592 dependency.setRenderPath(options, inputBase);
16593 }
16594 }
16595 };
16596 Chunk.prototype.setIdentifierRenderResolutions = function (options) {
16597 for (var _i = 0, _a = this.getExportNames(); _i < _a.length; _i++) {
16598 var exportName = _a[_i];
16599 var exportVariable = this.exportNames[exportName];
16600 if (exportVariable) {
16601 if (exportVariable instanceof ExportShimVariable) {
16602 this.needsExportsShim = true;
16603 }
16604 exportVariable.exportName = exportName;
16605 if (options.format !== 'es' &&
16606 options.format !== 'system' &&
16607 exportVariable.isReassigned &&
16608 !exportVariable.isId &&
16609 (!isExportDefaultVariable(exportVariable) || !exportVariable.hasId)) {
16610 exportVariable.setRenderNames('exports', exportName);
16611 }
16612 else {
16613 exportVariable.setRenderNames(null, null);
16614 }
16615 }
16616 }
16617 var usedNames = Object.create(null);
16618 if (this.needsExportsShim) {
16619 usedNames[MISSING_EXPORT_SHIM_VARIABLE] = true;
16620 }
16621 deconflictChunk(this.orderedModules, this.dependencies, this.imports, usedNames, options.format, options.interop !== false, this.graph.preserveModules);
16622 };
16623 Chunk.prototype.setUpModuleImports = function (module) {
16624 for (var _i = 0, _a = Array.from(module.imports); _i < _a.length; _i++) {
16625 var variable = _a[_i];
16626 if (variable.module.chunk !== this) {
16627 this.imports.add(variable);
16628 if (variable.module instanceof Module) {
16629 variable.module.chunk.exports.add(variable);
16630 }
16631 }
16632 }
16633 if (module.getOrCreateNamespace().included) {
16634 for (var _b = 0, _c = Object.keys(module.reexports); _b < _c.length; _b++) {
16635 var reexportName = _c[_b];
16636 var reexport = module.reexports[reexportName];
16637 var variable = reexport.module.getVariableForExportName(reexport.localName);
16638 if (variable.module.chunk !== this) {
16639 this.imports.add(variable);
16640 if (variable.module instanceof Module) {
16641 variable.module.chunk.exports.add(variable);
16642 }
16643 }
16644 }
16645 }
16646 for (var _d = 0, _e = module.dynamicImports; _d < _e.length; _d++) {
16647 var _f = _e[_d], node = _f.node, resolution = _f.resolution;
16648 if (node.included) {
16649 this.hasDynamicImport = true;
16650 if (resolution instanceof Module && resolution.chunk === this)
16651 resolution.getOrCreateNamespace().include();
16652 }
16653 }
16654 };
16655 return Chunk;
16656}());
16657
16658/*
16659 * Given a chunk list, perform optimizations on that chunk list
16660 * to reduce the mumber of chunks. Mutates the chunks array.
16661 *
16662 * Manual chunks (with chunk.chunkAlias already set) are preserved
16663 * Entry points are carefully preserved as well
16664 *
16665 */
16666function optimizeChunks(chunks, options, CHUNK_GROUPING_SIZE, inputBase) {
16667 var _loop_1 = function (chunkIndex) {
16668 var mainChunk = chunks[chunkIndex];
16669 var execGroup = [];
16670 mainChunk.visitStaticDependenciesUntilCondition(function (dep) {
16671 if (dep instanceof Chunk$1) {
16672 execGroup.push(dep);
16673 }
16674 });
16675 if (execGroup.length < 2) {
16676 return out_chunkIndex_1 = chunkIndex, "continue";
16677 }
16678 var execGroupIndex = 1;
16679 var seekingFirstMergeCandidate = true;
16680 var lastChunk, chunk = execGroup[0], nextChunk = execGroup[1];
16681 var isMergeCandidate = function (chunk) {
16682 if (chunk.facadeModule !== null || chunk.manualChunkAlias !== null) {
16683 return false;
16684 }
16685 if (!nextChunk || nextChunk.facadeModule !== null) {
16686 return false;
16687 }
16688 if (chunk.getRenderedSourceLength() > CHUNK_GROUPING_SIZE) {
16689 return false;
16690 }
16691 // if (!chunk.isPure()) continue;
16692 return true;
16693 };
16694 var _loop_2 = function () {
16695 if (seekingFirstMergeCandidate) {
16696 if (isMergeCandidate(chunk)) {
16697 seekingFirstMergeCandidate = false;
16698 }
16699 return "continue";
16700 }
16701 var remainingSize = CHUNK_GROUPING_SIZE - lastChunk.getRenderedSourceLength() - chunk.getRenderedSourceLength();
16702 if (remainingSize <= 0) {
16703 if (!isMergeCandidate(chunk)) {
16704 seekingFirstMergeCandidate = true;
16705 }
16706 return "continue";
16707 }
16708 // if (!chunk.isPure()) continue;
16709 var chunkDependencies = new Set();
16710 chunk.visitStaticDependenciesUntilCondition(function (dep) { return chunkDependencies.add(dep); });
16711 var ignoreSizeChunks = new Set([chunk, lastChunk]);
16712 if (lastChunk.visitStaticDependenciesUntilCondition(function (dep) {
16713 if (dep === chunk || dep === lastChunk) {
16714 return false;
16715 }
16716 if (chunkDependencies.has(dep)) {
16717 return false;
16718 }
16719 if (dep instanceof ExternalModule) {
16720 return true;
16721 }
16722 remainingSize -= dep.getRenderedSourceLength();
16723 if (remainingSize <= 0) {
16724 return true;
16725 }
16726 ignoreSizeChunks.add(dep);
16727 })) {
16728 if (!isMergeCandidate(chunk)) {
16729 seekingFirstMergeCandidate = true;
16730 }
16731 return "continue";
16732 }
16733 if (chunk.visitStaticDependenciesUntilCondition(function (dep) {
16734 if (ignoreSizeChunks.has(dep)) {
16735 return false;
16736 }
16737 if (dep instanceof ExternalModule) {
16738 return true;
16739 }
16740 remainingSize -= dep.getRenderedSourceLength();
16741 if (remainingSize <= 0) {
16742 return true;
16743 }
16744 })) {
16745 if (!isMergeCandidate(chunk)) {
16746 seekingFirstMergeCandidate = true;
16747 }
16748 return "continue";
16749 }
16750 // within the size limit -> merge!
16751 var optimizedChunkIndex = chunks.indexOf(chunk);
16752 if (optimizedChunkIndex <= chunkIndex)
16753 chunkIndex--;
16754 chunks.splice(optimizedChunkIndex, 1);
16755 lastChunk.merge(chunk, chunks, options, inputBase);
16756 execGroup.splice(--execGroupIndex, 1);
16757 chunk = lastChunk;
16758 // keep going to see if we can merge this with the next again
16759 if (nextChunk && !isMergeCandidate(nextChunk)) {
16760 seekingFirstMergeCandidate = true;
16761 }
16762 };
16763 do {
16764 _loop_2();
16765 } while (((lastChunk = chunk), (chunk = nextChunk), (nextChunk = execGroup[++execGroupIndex]), chunk));
16766 out_chunkIndex_1 = chunkIndex;
16767 };
16768 var out_chunkIndex_1;
16769 for (var chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
16770 _loop_1(chunkIndex);
16771 chunkIndex = out_chunkIndex_1;
16772 }
16773 return chunks;
16774}
16775
16776const tt = acorn__default.tokTypes;
16777const isIdentifierStart = acorn__default.isIdentifierStart;
16778
16779var acornBigint = function(Parser) {
16780 return class extends Parser {
16781 parseLiteral(value) {
16782 const node = super.parseLiteral(value);
16783 if (node.raw.charCodeAt(node.raw.length - 1) == 110) node.bigint = this.getNumberInput(node.start, node.end);
16784 return node
16785 }
16786
16787 readRadixNumber(radix) {
16788 let start = this.pos;
16789 this.pos += 2; // 0x
16790 let val = this.readInt(radix);
16791 if (val === null) this.raise(this.start + 2, `Expected number in radix ${radix}`);
16792 if (this.input.charCodeAt(this.pos) == 110) {
16793 let str = this.getNumberInput(start, this.pos);
16794 val = typeof BigInt !== "undefined" ? BigInt(str) : null;
16795 ++this.pos;
16796 } else if (isIdentifierStart(this.fullCharCodeAtPos())) this.raise(this.pos, "Identifier directly after number");
16797 return this.finishToken(tt.num, val)
16798 }
16799
16800 readNumber(startsWithDot) {
16801 let start = this.pos;
16802
16803 // Not an int
16804 if (startsWithDot) return super.readNumber(startsWithDot)
16805
16806 // Legacy octal
16807 if (this.input.charCodeAt(start) === 48 && this.input.charCodeAt(start + 1) !== 110) {
16808 return super.readNumber(startsWithDot)
16809 }
16810
16811 if (this.readInt(10) === null) this.raise(start, "Invalid number");
16812
16813 // Not a BigInt, reset and parse again
16814 if (this.input.charCodeAt(this.pos) != 110) {
16815 this.pos = start;
16816 return super.readNumber(startsWithDot)
16817 }
16818
16819 let str = this.getNumberInput(start, this.pos);
16820 let val = typeof BigInt !== "undefined" ? BigInt(str) : null;
16821 ++this.pos;
16822 return this.finishToken(tt.num, val)
16823 }
16824
16825 // This is basically a hook for acorn-numeric-separator
16826 getNumberInput(start, end) {
16827 if (super.getNumberInput) return super.getNumberInput(start, end)
16828 return this.input.slice(start, end)
16829 }
16830 }
16831};
16832
16833/* eslint-disable no-underscore-dangle */
16834
16835const DynamicImportKey = 'Import';
16836
16837// NOTE: This allows `yield import()` to parse correctly.
16838tokTypes._import.startsExpr = true;
16839
16840function parseDynamicImport() {
16841 const node = this.startNode();
16842 this.next();
16843 if (this.type !== tokTypes.parenL) {
16844 this.unexpected();
16845 }
16846 return this.finishNode(node, DynamicImportKey);
16847}
16848
16849function parenAfter() {
16850 return /^(\s|\/\/.*|\/\*[^]*?\*\/)*\(/.test(this.input.slice(this.pos));
16851}
16852
16853function dynamicImport(Parser) {
16854 return class extends Parser {
16855 parseStatement(context, topLevel, exports) {
16856 if (this.type === tokTypes._import && parenAfter.call(this)) {
16857 return this.parseExpressionStatement(this.startNode(), this.parseExpression());
16858 }
16859 return super.parseStatement(context, topLevel, exports);
16860 }
16861
16862 parseExprAtom(refDestructuringErrors) {
16863 if (this.type === tokTypes._import) {
16864 return parseDynamicImport.call(this);
16865 }
16866 return super.parseExprAtom(refDestructuringErrors);
16867 }
16868 };
16869}
16870
16871const tt$1 = acorn__default.tokTypes;
16872
16873const skipWhiteSpace = /(?:\s|\/\/.*|\/\*[^]*?\*\/)*/g;
16874
16875const nextTokenIsDot = parser => {
16876 skipWhiteSpace.lastIndex = parser.pos;
16877 let skip = skipWhiteSpace.exec(parser.input);
16878 let next = parser.pos + skip[0].length;
16879 return parser.input.slice(next, next + 1) === "."
16880};
16881
16882var acornImportMeta = function(Parser) {
16883 return class extends Parser {
16884 parseExprAtom(refDestructuringErrors) {
16885 if (this.type !== tt$1._import || !nextTokenIsDot(this)) return super.parseExprAtom(refDestructuringErrors)
16886
16887 if (!this.options.allowImportExportEverywhere && !this.inModule) {
16888 this.raise(this.start, "'import' and 'export' may appear only with 'sourceType: module'");
16889 }
16890
16891 let node = this.startNode();
16892 node.meta = this.parseIdent(true);
16893 this.expect(tt$1.dot);
16894 node.property = this.parseIdent(true);
16895 if (node.property.name !== "meta") {
16896 this.raiseRecoverable(node.property.start, "The only valid meta property for import is import.meta");
16897 }
16898 if (this.containsEsc) {
16899 this.raiseRecoverable(node.property.start, "\"meta\" in import.meta must not contain escape sequences");
16900 }
16901 return this.finishNode(node, "MetaProperty")
16902 }
16903
16904 parseStatement(context, topLevel, exports) {
16905 if (this.type !== tt$1._import || !nextTokenIsDot(this)) {
16906 return super.parseStatement(context, topLevel, exports)
16907 }
16908
16909 let node = this.startNode();
16910 let expr = this.parseExpression();
16911 return this.parseExpressionStatement(node, expr)
16912 }
16913 }
16914};
16915
16916var UndefinedVariable = /** @class */ (function (_super) {
16917 __extends(UndefinedVariable, _super);
16918 function UndefinedVariable() {
16919 return _super.call(this, 'undefined') || this;
16920 }
16921 UndefinedVariable.prototype.getLiteralValueAtPath = function () {
16922 return undefined;
16923 };
16924 return UndefinedVariable;
16925}(Variable));
16926
16927var GlobalScope = /** @class */ (function (_super) {
16928 __extends(GlobalScope, _super);
16929 function GlobalScope() {
16930 var _this = _super.call(this) || this;
16931 _this.variables.undefined = new UndefinedVariable();
16932 return _this;
16933 }
16934 GlobalScope.prototype.findVariable = function (name) {
16935 if (!this.variables[name])
16936 return (this.variables[name] = new GlobalVariable(name));
16937 return this.variables[name];
16938 };
16939 return GlobalScope;
16940}(Scope));
16941
16942var getNewTrackedPaths = function () { return ({
16943 paths: Object.create(null),
16944 tracked: false,
16945 unknownPath: null
16946}); };
16947var EntityPathTracker = /** @class */ (function () {
16948 function EntityPathTracker() {
16949 this.entityPaths = new Map();
16950 }
16951 EntityPathTracker.prototype.track = function (entity, path) {
16952 var trackedPaths = this.entityPaths.get(entity);
16953 if (!trackedPaths) {
16954 trackedPaths = getNewTrackedPaths();
16955 this.entityPaths.set(entity, trackedPaths);
16956 }
16957 var pathIndex = 0, trackedSubPaths;
16958 while (pathIndex < path.length) {
16959 var key = path[pathIndex];
16960 if (typeof key === 'string') {
16961 trackedSubPaths = trackedPaths.paths[key];
16962 if (!trackedSubPaths) {
16963 trackedSubPaths = getNewTrackedPaths();
16964 trackedPaths.paths[key] = trackedSubPaths;
16965 }
16966 }
16967 else {
16968 trackedSubPaths = trackedPaths.unknownPath;
16969 if (!trackedSubPaths) {
16970 trackedSubPaths = getNewTrackedPaths();
16971 trackedPaths.unknownPath = trackedSubPaths;
16972 }
16973 }
16974 trackedPaths = trackedSubPaths;
16975 pathIndex++;
16976 }
16977 var found = trackedPaths.tracked;
16978 trackedPaths.tracked = true;
16979 return found;
16980 };
16981 return EntityPathTracker;
16982}());
16983
16984function addWithNewReferenceId(item, idMap, hashBase) {
16985 var referenceId;
16986 do {
16987 var hash = _256();
16988 if (referenceId) {
16989 hash.update(referenceId);
16990 }
16991 else {
16992 hash.update(hashBase);
16993 }
16994 referenceId = hash.digest('hex').substr(0, 8);
16995 } while (idMap.has(referenceId));
16996 idMap.set(referenceId, item);
16997 return referenceId;
16998}
16999
17000function getAssetFileName(asset, existingNames, assetFileNames) {
17001 if (asset.source === undefined)
17002 error(errNoAssetSourceSet(asset));
17003 if (asset.fileName)
17004 return asset.fileName;
17005 return makeUnique(renderNamePattern(assetFileNames, 'assetFileNames', function (name) {
17006 switch (name) {
17007 case 'hash':
17008 var hash = _256();
17009 hash.update(name);
17010 hash.update(':');
17011 hash.update(asset.source);
17012 return hash.digest('hex').substr(0, 8);
17013 case 'name':
17014 return asset.name.substr(0, asset.name.length - extname(asset.name).length);
17015 case 'extname':
17016 return extname(asset.name);
17017 case 'ext':
17018 return extname(asset.name).substr(1);
17019 }
17020 }), existingNames);
17021}
17022function createAssetPluginHooks(assetsByReferenceId, outputBundle, assetFileNames) {
17023 return {
17024 emitAsset: function (name, source) {
17025 if (typeof name !== 'string' || !isPlainName(name))
17026 error(errInvalidAssetName(name));
17027 var asset = { name: name, source: source, fileName: undefined };
17028 if (outputBundle && source !== undefined)
17029 finaliseAsset(asset, outputBundle, assetFileNames);
17030 return addWithNewReferenceId(asset, assetsByReferenceId, name);
17031 },
17032 setAssetSource: function (assetReferenceId, source) {
17033 var asset = assetsByReferenceId.get(assetReferenceId);
17034 if (!asset)
17035 error(errAssetReferenceIdNotFoundForSetSource(assetReferenceId));
17036 if (asset.source !== undefined)
17037 error(errAssetSourceAlreadySet(asset));
17038 if (typeof source !== 'string' && !source)
17039 error(errAssetSourceMissingForSetSource(asset));
17040 asset.source = source;
17041 if (outputBundle)
17042 finaliseAsset(asset, outputBundle, assetFileNames);
17043 },
17044 getAssetFileName: function (assetReferenceId) {
17045 var asset = assetsByReferenceId.get(assetReferenceId);
17046 if (!asset)
17047 error(errAssetReferenceIdNotFoundForFilename(assetReferenceId));
17048 if (asset.fileName === undefined)
17049 error(errAssetNotFinalisedForFileName(asset));
17050 return asset.fileName;
17051 }
17052 };
17053}
17054function finaliseAsset(asset, outputBundle, assetFileNames) {
17055 var fileName = getAssetFileName(asset, outputBundle, assetFileNames);
17056 asset.fileName = fileName;
17057 outputBundle[fileName] = {
17058 fileName: fileName,
17059 isAsset: true,
17060 source: asset.source
17061 };
17062}
17063function createTransformEmitAsset(assetsByReferenceId, emitAsset) {
17064 var assets = [];
17065 return {
17066 assets: assets,
17067 emitAsset: function (name, source) {
17068 var assetReferenceId = emitAsset(name, source);
17069 var asset = assetsByReferenceId.get(assetReferenceId);
17070 assets.push({
17071 fileName: undefined,
17072 name: asset.name,
17073 source: asset.source
17074 });
17075 return assetReferenceId;
17076 }
17077 };
17078}
17079
17080var BuildPhase;
17081(function (BuildPhase) {
17082 BuildPhase[BuildPhase["LOAD_AND_PARSE"] = 0] = "LOAD_AND_PARSE";
17083 BuildPhase[BuildPhase["ANALYSE"] = 1] = "ANALYSE";
17084 BuildPhase[BuildPhase["GENERATE"] = 2] = "GENERATE";
17085})(BuildPhase || (BuildPhase = {}));
17086
17087function mkdirpath(path) {
17088 var dir = dirname(path);
17089 try {
17090 readdirSync(dir);
17091 }
17092 catch (err) {
17093 mkdirpath(dir);
17094 try {
17095 mkdirSync(dir);
17096 }
17097 catch (err2) {
17098 if (err2.code !== 'EEXIST') {
17099 throw err2;
17100 }
17101 }
17102 }
17103}
17104function writeFile(dest, data) {
17105 return new Promise(function (fulfil, reject) {
17106 mkdirpath(dest);
17107 writeFile$1(dest, data, function (err) {
17108 if (err) {
17109 reject(err);
17110 }
17111 else {
17112 fulfil();
17113 }
17114 });
17115 });
17116}
17117
17118function getRollupDefaultPlugin(preserveSymlinks) {
17119 return {
17120 name: 'Rollup Core',
17121 resolveId: createResolveId(preserveSymlinks),
17122 load: function (id) {
17123 return readFileSync(id, 'utf-8');
17124 },
17125 resolveFileUrl: function (_a) {
17126 var relativePath = _a.relativePath, format = _a.format;
17127 return relativeUrlMechanisms[format](relativePath);
17128 },
17129 resolveImportMeta: function (prop, _a) {
17130 var chunkId = _a.chunkId, format = _a.format;
17131 var mechanism = importMetaMechanisms[format] && importMetaMechanisms[format](prop, chunkId);
17132 if (mechanism) {
17133 return mechanism;
17134 }
17135 }
17136 };
17137}
17138function findFile(file, preserveSymlinks) {
17139 try {
17140 var stats = lstatSync(file);
17141 if (!preserveSymlinks && stats.isSymbolicLink())
17142 return findFile(realpathSync(file), preserveSymlinks);
17143 if ((preserveSymlinks && stats.isSymbolicLink()) || stats.isFile()) {
17144 // check case
17145 var name = basename(file);
17146 var files = readdirSync(dirname(file));
17147 if (files.indexOf(name) !== -1)
17148 return file;
17149 }
17150 }
17151 catch (err) {
17152 // suppress
17153 }
17154}
17155function addJsExtensionIfNecessary(file, preserveSymlinks) {
17156 var found = findFile(file, preserveSymlinks);
17157 if (found)
17158 return found;
17159 found = findFile(file + '.mjs', preserveSymlinks);
17160 if (found)
17161 return found;
17162 found = findFile(file + '.js', preserveSymlinks);
17163 return found;
17164}
17165function createResolveId(preserveSymlinks) {
17166 return function (source, importer) {
17167 if (typeof process === 'undefined') {
17168 error({
17169 code: 'MISSING_PROCESS',
17170 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",
17171 url: 'https://rollupjs.org/guide/en#a-simple-example'
17172 });
17173 }
17174 // external modules (non-entry modules that start with neither '.' or '/')
17175 // are skipped at this stage.
17176 if (importer !== undefined && !isAbsolute(source) && source[0] !== '.')
17177 return null;
17178 // `resolve` processes paths from right to left, prepending them until an
17179 // absolute path is created. Absolute importees therefore shortcircuit the
17180 // resolve call and require no special handing on our part.
17181 // See https://nodejs.org/api/path.html#path_path_resolve_paths
17182 return addJsExtensionIfNecessary(resolve$1(importer ? dirname(importer) : resolve$1(), source), preserveSymlinks);
17183 };
17184}
17185var getResolveUrl = function (path, URL) {
17186 if (URL === void 0) { URL = 'URL'; }
17187 return "new " + URL + "(" + path + ").href";
17188};
17189var getUrlFromDocument = function (chunkId) {
17190 return "(document.currentScript && document.currentScript.src || new URL('" + chunkId + "', document.baseURI).href)";
17191};
17192var getGenericImportMetaMechanism = function (getUrl) { return function (prop, chunkId) {
17193 var urlMechanism = getUrl(chunkId);
17194 return prop === null ? "({ url: " + urlMechanism + " })" : prop === 'url' ? urlMechanism : 'undefined';
17195}; };
17196var importMetaMechanisms = {
17197 amd: getGenericImportMetaMechanism(function () { return getResolveUrl("module.uri, document.baseURI"); }),
17198 cjs: getGenericImportMetaMechanism(function (chunkId) {
17199 return "(typeof document === 'undefined' ? " + getResolveUrl("'file:' + __filename", "(require('u' + 'rl').URL)") + " : " + getUrlFromDocument(chunkId) + ")";
17200 }),
17201 iife: getGenericImportMetaMechanism(function (chunkId) { return getUrlFromDocument(chunkId); }),
17202 system: function (prop) { return (prop === null ? "module.meta" : "module.meta." + prop); },
17203 umd: getGenericImportMetaMechanism(function (chunkId) {
17204 return "(typeof document === 'undefined' ? " + getResolveUrl("'file:' + __filename", "(require('u' + 'rl').URL)") + " : " + getUrlFromDocument(chunkId) + ")";
17205 })
17206};
17207var getRelativeUrlFromDocument = function (relativePath) {
17208 return getResolveUrl("(document.currentScript && document.currentScript.src || document.baseURI) + '/../" + relativePath + "'");
17209};
17210var relativeUrlMechanisms = {
17211 amd: function (relativePath) { return getResolveUrl("module.uri + '/../" + relativePath + "', document.baseURI"); },
17212 cjs: function (relativePath) {
17213 return "(typeof document === 'undefined' ? " + getResolveUrl("'file:' + __dirname + '/" + relativePath + "'", "(require('u' + 'rl').URL)") + " : " + getRelativeUrlFromDocument(relativePath) + ")";
17214 },
17215 es: function (relativePath) { return getResolveUrl("'" + relativePath + "', import.meta.url"); },
17216 iife: function (relativePath) { return getRelativeUrlFromDocument(relativePath); },
17217 system: function (relativePath) { return getResolveUrl("'" + relativePath + "', module.meta.url"); },
17218 umd: function (relativePath) {
17219 return "(typeof document === 'undefined' ? " + getResolveUrl("'file:' + __dirname + '/" + relativePath + "'", "(require('u' + 'rl').URL)") + " : " + getRelativeUrlFromDocument(relativePath) + ")";
17220 }
17221};
17222
17223var deprecatedHookNames = {
17224 ongenerate: 'generateBundle',
17225 onwrite: 'generateBundle',
17226 transformBundle: 'renderChunk',
17227 transformChunk: 'renderChunk'
17228};
17229function createPluginDriver(graph, options, pluginCache, watcher) {
17230 var plugins = (options.plugins || []).concat([getRollupDefaultPlugin(options.preserveSymlinks)]);
17231 var _a = createAssetPluginHooks(graph.assetsById), emitAsset = _a.emitAsset, getAssetFileName = _a.getAssetFileName, setAssetSource = _a.setAssetSource;
17232 var existingPluginKeys = {};
17233 var hasLoadersOrTransforms = false;
17234 var pluginContexts = plugins.map(function (plugin, pidx) {
17235 var cacheable = true;
17236 if (typeof plugin.cacheKey !== 'string') {
17237 if (typeof plugin.name !== 'string' || existingPluginKeys[plugin.name]) {
17238 cacheable = false;
17239 }
17240 else {
17241 existingPluginKeys[plugin.name] = true;
17242 }
17243 }
17244 if (!hasLoadersOrTransforms &&
17245 (plugin.load || plugin.transform || plugin.transformBundle || plugin.transformChunk))
17246 hasLoadersOrTransforms = true;
17247 var cacheInstance;
17248 if (!pluginCache) {
17249 cacheInstance = noCache;
17250 }
17251 else if (cacheable) {
17252 var cacheKey = plugin.cacheKey || plugin.name;
17253 cacheInstance = createPluginCache(pluginCache[cacheKey] || (pluginCache[cacheKey] = Object.create(null)));
17254 }
17255 else {
17256 cacheInstance = uncacheablePlugin(plugin.name);
17257 }
17258 var watcherDeprecationWarningShown = false;
17259 function deprecatedWatchListener(event, handler) {
17260 if (!watcherDeprecationWarningShown) {
17261 context.warn({
17262 code: 'PLUGIN_WATCHER_DEPRECATED',
17263 message: "this.watcher usage is deprecated in plugins. Use the watchChange plugin hook and this.addWatchFile() instead."
17264 });
17265 watcherDeprecationWarningShown = true;
17266 }
17267 return watcher.on(event, handler);
17268 }
17269 var context = {
17270 addWatchFile: function (id) {
17271 if (graph.phase >= BuildPhase.GENERATE)
17272 this.error(errInvalidRollupPhaseForAddWatchFile());
17273 graph.watchFiles[id] = true;
17274 },
17275 cache: cacheInstance,
17276 emitAsset: emitAsset,
17277 emitChunk: function (id, options) {
17278 if (graph.phase > BuildPhase.LOAD_AND_PARSE)
17279 this.error(errInvalidRollupPhaseForEmitChunk());
17280 return graph.moduleLoader.addEntryModuleAndGetReferenceId({
17281 alias: (options && options.name) || null,
17282 unresolvedId: id
17283 });
17284 },
17285 error: function (err) {
17286 if (typeof err === 'string')
17287 err = { message: err };
17288 if (err.code)
17289 err.pluginCode = err.code;
17290 err.code = 'PLUGIN_ERROR';
17291 err.plugin = plugin.name || "Plugin at position " + (pidx + 1);
17292 error(err);
17293 },
17294 isExternal: function (id, parentId, isResolved) {
17295 if (isResolved === void 0) { isResolved = false; }
17296 return graph.moduleLoader.isExternal(id, parentId, isResolved);
17297 },
17298 getAssetFileName: getAssetFileName,
17299 getChunkFileName: function (chunkReferenceId) {
17300 return graph.moduleLoader.getChunkFileName(chunkReferenceId);
17301 },
17302 getModuleInfo: function (moduleId) {
17303 var foundModule = graph.moduleById.get(moduleId);
17304 if (foundModule == null) {
17305 throw new Error("Unable to find module " + moduleId);
17306 }
17307 return {
17308 id: foundModule.id,
17309 importedIds: foundModule.isExternal
17310 ? []
17311 : foundModule.sources.map(function (id) { return foundModule.resolvedIds[id].id; }),
17312 isExternal: !!foundModule.isExternal
17313 };
17314 },
17315 meta: {
17316 rollupVersion: version
17317 },
17318 moduleIds: graph.moduleById.keys(),
17319 parse: graph.contextParse,
17320 resolveId: function (source, importer) {
17321 return graph.moduleLoader
17322 .resolveId(source, importer)
17323 .then(function (resolveId) { return resolveId && resolveId.id; });
17324 },
17325 resolve: function (source, importer) {
17326 return graph.moduleLoader.resolveId(source, importer);
17327 },
17328 setAssetSource: setAssetSource,
17329 warn: function (warning) {
17330 if (typeof warning === 'string')
17331 warning = { message: warning };
17332 if (warning.code)
17333 warning.pluginCode = warning.code;
17334 warning.code = 'PLUGIN_WARNING';
17335 warning.plugin = plugin.name || "Plugin at position " + (pidx + 1);
17336 graph.warn(warning);
17337 },
17338 watcher: watcher
17339 ? __assign({}, watcher, { addListener: deprecatedWatchListener, on: deprecatedWatchListener })
17340 : undefined
17341 };
17342 return context;
17343 });
17344 function runHookSync(hookName, args, pluginIndex, permitValues, hookContext) {
17345 if (permitValues === void 0) { permitValues = false; }
17346 var plugin = plugins[pluginIndex];
17347 var context = pluginContexts[pluginIndex];
17348 var hook = plugin[hookName];
17349 if (!hook)
17350 return;
17351 var deprecatedHookNewName = deprecatedHookNames[hookName];
17352 if (deprecatedHookNewName)
17353 context.warn(hookDeprecationWarning(hookName, deprecatedHookNewName, plugin, pluginIndex));
17354 if (hookContext) {
17355 context = hookContext(context, plugin);
17356 if (!context || context === pluginContexts[pluginIndex])
17357 throw new Error('Internal Rollup error: hookContext must return a new context object.');
17358 }
17359 try {
17360 // permit values allows values to be returned instead of a functional hook
17361 if (typeof hook !== 'function') {
17362 if (permitValues)
17363 return hook;
17364 error({
17365 code: 'INVALID_PLUGIN_HOOK',
17366 message: "Error running plugin hook " + hookName + " for " + (plugin.name ||
17367 "Plugin at position " + (pluginIndex + 1)) + ", expected a function hook."
17368 });
17369 }
17370 return hook.apply(context, args);
17371 }
17372 catch (err) {
17373 if (typeof err === 'string')
17374 err = { message: err };
17375 if (err.code !== 'PLUGIN_ERROR') {
17376 if (err.code)
17377 err.pluginCode = err.code;
17378 err.code = 'PLUGIN_ERROR';
17379 }
17380 err.plugin = plugin.name || "Plugin at position " + (pluginIndex + 1);
17381 err.hook = hookName;
17382 error(err);
17383 }
17384 }
17385 function runHook(hookName, args, pluginIndex, permitValues, hookContext) {
17386 if (permitValues === void 0) { permitValues = false; }
17387 var plugin = plugins[pluginIndex];
17388 var context = pluginContexts[pluginIndex];
17389 var hook = plugin[hookName];
17390 if (!hook)
17391 return;
17392 var deprecatedHookNewName = deprecatedHookNames[hookName];
17393 if (deprecatedHookNewName)
17394 context.warn(hookDeprecationWarning(hookName, deprecatedHookNewName, plugin, pluginIndex));
17395 if (hookContext) {
17396 context = hookContext(context, plugin);
17397 if (!context || context === pluginContexts[pluginIndex])
17398 throw new Error('Internal Rollup error: hookContext must return a new context object.');
17399 }
17400 return Promise.resolve()
17401 .then(function () {
17402 // permit values allows values to be returned instead of a functional hook
17403 if (typeof hook !== 'function') {
17404 if (permitValues)
17405 return hook;
17406 error({
17407 code: 'INVALID_PLUGIN_HOOK',
17408 message: "Error running plugin hook " + hookName + " for " + (plugin.name ||
17409 "Plugin at position " + (pluginIndex + 1)) + ", expected a function hook."
17410 });
17411 }
17412 return hook.apply(context, args);
17413 })
17414 .catch(function (err) {
17415 if (typeof err === 'string')
17416 err = { message: err };
17417 if (err.code !== 'PLUGIN_ERROR') {
17418 if (err.code)
17419 err.pluginCode = err.code;
17420 err.code = 'PLUGIN_ERROR';
17421 }
17422 err.plugin = plugin.name || "Plugin at position " + (pluginIndex + 1);
17423 err.hook = hookName;
17424 error(err);
17425 });
17426 }
17427 var pluginDriver = {
17428 emitAsset: emitAsset,
17429 getAssetFileName: getAssetFileName,
17430 hasLoadersOrTransforms: hasLoadersOrTransforms,
17431 // chains, ignores returns
17432 hookSeq: function (name, args, hookContext) {
17433 var promise = Promise.resolve();
17434 var _loop_1 = function (i) {
17435 promise = promise.then(function () { return runHook(name, args, i, false, hookContext); });
17436 };
17437 for (var i = 0; i < plugins.length; i++) {
17438 _loop_1(i);
17439 }
17440 return promise;
17441 },
17442 // chains, ignores returns
17443 hookSeqSync: function (name, args, hookContext) {
17444 for (var i = 0; i < plugins.length; i++)
17445 runHookSync(name, args, i, false, hookContext);
17446 },
17447 // chains, first non-null result stops and returns
17448 hookFirst: function (name, args, hookContext) {
17449 var promise = Promise.resolve();
17450 var _loop_2 = function (i) {
17451 promise = promise.then(function (result) {
17452 if (result != null)
17453 return result;
17454 return runHook(name, args, i, false, hookContext);
17455 });
17456 };
17457 for (var i = 0; i < plugins.length; i++) {
17458 _loop_2(i);
17459 }
17460 return promise;
17461 },
17462 // chains synchronously, first non-null result stops and returns
17463 hookFirstSync: function (name, args, hookContext) {
17464 for (var i = 0; i < plugins.length; i++) {
17465 var result = runHookSync(name, args, i, false, hookContext);
17466 if (result != null)
17467 return result;
17468 }
17469 return null;
17470 },
17471 // parallel, ignores returns
17472 hookParallel: function (name, args, hookContext) {
17473 var promises = [];
17474 for (var i = 0; i < plugins.length; i++) {
17475 var hookPromise = runHook(name, args, i, false, hookContext);
17476 if (!hookPromise)
17477 continue;
17478 promises.push(hookPromise);
17479 }
17480 return Promise.all(promises).then(function () { });
17481 },
17482 // chains, reduces returns of type R, to type T, handling the reduced value as the first hook argument
17483 hookReduceArg0: function (name, _a, reduce, hookContext) {
17484 var arg0 = _a[0], args = _a.slice(1);
17485 var promise = Promise.resolve(arg0);
17486 var _loop_3 = function (i) {
17487 promise = promise.then(function (arg0) {
17488 var hookPromise = runHook(name, [arg0].concat(args), i, false, hookContext);
17489 if (!hookPromise)
17490 return arg0;
17491 return hookPromise.then(function (result) {
17492 return reduce.call(pluginContexts[i], arg0, result, plugins[i]);
17493 });
17494 });
17495 };
17496 for (var i = 0; i < plugins.length; i++) {
17497 _loop_3(i);
17498 }
17499 return promise;
17500 },
17501 // chains synchronously, reduces returns of type R, to type T, handling the reduced value as the first hook argument
17502 hookReduceArg0Sync: function (name, _a, reduce, hookContext) {
17503 var arg0 = _a[0], args = _a.slice(1);
17504 for (var i = 0; i < plugins.length; i++) {
17505 var result = runHookSync(name, [arg0].concat(args), i, false, hookContext);
17506 arg0 = reduce.call(pluginContexts[i], arg0, result, plugins[i]);
17507 }
17508 return arg0;
17509 },
17510 // chains, reduces returns of type R, to type T, handling the reduced value separately. permits hooks as values.
17511 hookReduceValue: function (name, initial, args, reduce, hookContext) {
17512 var promise = Promise.resolve(initial);
17513 var _loop_4 = function (i) {
17514 promise = promise.then(function (value) {
17515 var hookPromise = runHook(name, args, i, true, hookContext);
17516 if (!hookPromise)
17517 return value;
17518 return hookPromise.then(function (result) {
17519 return reduce.call(pluginContexts[i], value, result, plugins[i]);
17520 });
17521 });
17522 };
17523 for (var i = 0; i < plugins.length; i++) {
17524 _loop_4(i);
17525 }
17526 return promise;
17527 }
17528 };
17529 return pluginDriver;
17530}
17531function createPluginCache(cache) {
17532 return {
17533 has: function (id) {
17534 var item = cache[id];
17535 if (!item)
17536 return false;
17537 item[0] = 0;
17538 return true;
17539 },
17540 get: function (id) {
17541 var item = cache[id];
17542 if (!item)
17543 return undefined;
17544 item[0] = 0;
17545 return item[1];
17546 },
17547 set: function (id, value) {
17548 cache[id] = [0, value];
17549 },
17550 delete: function (id) {
17551 return delete cache[id];
17552 }
17553 };
17554}
17555function trackPluginCache(pluginCache) {
17556 var result = { used: false, cache: undefined };
17557 result.cache = {
17558 has: function (id) {
17559 result.used = true;
17560 return pluginCache.has(id);
17561 },
17562 get: function (id) {
17563 result.used = true;
17564 return pluginCache.get(id);
17565 },
17566 set: function (id, value) {
17567 result.used = true;
17568 return pluginCache.set(id, value);
17569 },
17570 delete: function (id) {
17571 result.used = true;
17572 return pluginCache.delete(id);
17573 }
17574 };
17575 return result;
17576}
17577var noCache = {
17578 has: function () {
17579 return false;
17580 },
17581 get: function () {
17582 return undefined;
17583 },
17584 set: function () { },
17585 delete: function () {
17586 return false;
17587 }
17588};
17589function uncacheablePluginError(pluginName) {
17590 if (!pluginName)
17591 error({
17592 code: 'ANONYMOUS_PLUGIN_CACHE',
17593 message: 'A plugin is trying to use the Rollup cache but is not declaring a plugin name or cacheKey.'
17594 });
17595 else
17596 error({
17597 code: 'DUPLICATE_PLUGIN_NAME',
17598 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)."
17599 });
17600}
17601var uncacheablePlugin = function (pluginName) { return ({
17602 has: function () {
17603 uncacheablePluginError(pluginName);
17604 return false;
17605 },
17606 get: function () {
17607 uncacheablePluginError(pluginName);
17608 return undefined;
17609 },
17610 set: function () {
17611 uncacheablePluginError(pluginName);
17612 },
17613 delete: function () {
17614 uncacheablePluginError(pluginName);
17615 return false;
17616 }
17617}); };
17618function hookDeprecationWarning(name, newName, plugin, pluginIndex) {
17619 return {
17620 code: name.toUpperCase() + '_HOOK_DEPRECATED',
17621 message: "The " + name + " hook used by plugin " + (plugin.name ||
17622 "at position " + (pluginIndex + 1)) + " is deprecated. The " + newName + " hook should be used instead."
17623 };
17624}
17625
17626function transform(graph, source, module) {
17627 var id = module.id;
17628 var sourcemapChain = [];
17629 var originalSourcemap = typeof source.map === 'string' ? JSON.parse(source.map) : source.map;
17630 if (originalSourcemap && typeof originalSourcemap.mappings === 'string')
17631 originalSourcemap.mappings = decode(originalSourcemap.mappings);
17632 var baseEmitAsset = graph.pluginDriver.emitAsset;
17633 var originalCode = source.code;
17634 var ast = source.ast;
17635 var transformDependencies;
17636 var assets;
17637 var customTransformCache = false;
17638 var trackedPluginCache;
17639 var curPlugin;
17640 var curSource = source.code;
17641 function transformReducer(code, result, plugin) {
17642 // track which plugins use the custom this.cache to opt-out of transform caching
17643 if (!customTransformCache && trackedPluginCache.used)
17644 customTransformCache = true;
17645 if (customTransformCache) {
17646 if (result && Array.isArray(result.dependencies)) {
17647 for (var _i = 0, _a = result.dependencies; _i < _a.length; _i++) {
17648 var dep = _a[_i];
17649 var depId = resolve$1(dirname(id), dep);
17650 if (!graph.watchFiles[depId])
17651 graph.watchFiles[depId] = true;
17652 }
17653 }
17654 }
17655 else {
17656 // assets emitted by transform are transformDependencies
17657 if (assets.length)
17658 module.transformAssets = assets;
17659 if (result && Array.isArray(result.dependencies)) {
17660 // not great, but a useful way to track this without assuming WeakMap
17661 if (!curPlugin.warnedTransformDependencies)
17662 this.warn({
17663 code: 'TRANSFORM_DEPENDENCIES_DEPRECATED',
17664 message: "Returning \"dependencies\" from plugin transform hook is deprecated for using this.addWatchFile() instead."
17665 });
17666 curPlugin.warnedTransformDependencies = true;
17667 if (!transformDependencies)
17668 transformDependencies = [];
17669 for (var _b = 0, _c = result.dependencies; _b < _c.length; _b++) {
17670 var dep = _c[_b];
17671 transformDependencies.push(resolve$1(dirname(id), dep));
17672 }
17673 }
17674 }
17675 if (result == null)
17676 return code;
17677 if (typeof result === 'string') {
17678 result = {
17679 ast: undefined,
17680 code: result,
17681 map: undefined
17682 };
17683 }
17684 else if (typeof result.map === 'string') {
17685 // `result.map` can only be a string if `result` isn't
17686 result.map = JSON.parse(result.map);
17687 }
17688 if (result.map && typeof result.map.mappings === 'string') {
17689 result.map.mappings = decode(result.map.mappings);
17690 }
17691 // strict null check allows 'null' maps to not be pushed to the chain, while 'undefined' gets the missing map warning
17692 if (result.map !== null) {
17693 sourcemapChain.push(result.map || { missing: true, plugin: plugin.name });
17694 }
17695 ast = result.ast;
17696 return result.code;
17697 }
17698 var setAssetSourceErr;
17699 return graph.pluginDriver
17700 .hookReduceArg0('transform', [curSource, id], transformReducer, function (pluginContext, plugin) {
17701 var _a;
17702 curPlugin = plugin;
17703 if (plugin.cacheKey)
17704 customTransformCache = true;
17705 else
17706 trackedPluginCache = trackPluginCache(pluginContext.cache);
17707 var emitAsset;
17708 (_a = createTransformEmitAsset(graph.assetsById, baseEmitAsset), assets = _a.assets, emitAsset = _a.emitAsset);
17709 return __assign({}, pluginContext, { cache: trackedPluginCache ? trackedPluginCache.cache : pluginContext.cache, warn: function (warning, pos) {
17710 if (typeof warning === 'string')
17711 warning = { message: warning };
17712 if (pos)
17713 augmentCodeLocation(warning, pos, curSource, id);
17714 warning.id = id;
17715 warning.hook = 'transform';
17716 pluginContext.warn(warning);
17717 },
17718 error: function (err, pos) {
17719 if (typeof err === 'string')
17720 err = { message: err };
17721 if (pos)
17722 augmentCodeLocation(err, pos, curSource, id);
17723 err.id = id;
17724 err.hook = 'transform';
17725 pluginContext.error(err);
17726 },
17727 emitAsset: emitAsset,
17728 addWatchFile: function (id) {
17729 if (!transformDependencies)
17730 transformDependencies = [];
17731 transformDependencies.push(id);
17732 pluginContext.addWatchFile(id);
17733 },
17734 setAssetSource: function (assetReferenceId, source) {
17735 pluginContext.setAssetSource(assetReferenceId, source);
17736 if (!customTransformCache && !setAssetSourceErr) {
17737 try {
17738 this.error({
17739 code: 'INVALID_SETASSETSOURCE',
17740 message: "setAssetSource cannot be called in transform for caching reasons. Use emitAsset with a source, or call setAssetSource in another hook."
17741 });
17742 }
17743 catch (err) {
17744 setAssetSourceErr = err;
17745 }
17746 }
17747 } });
17748 })
17749 .catch(function (err) {
17750 if (typeof err === 'string')
17751 err = { message: err };
17752 if (err.code !== 'PLUGIN_ERROR') {
17753 if (err.code)
17754 err.pluginCode = err.code;
17755 err.code = 'PLUGIN_ERROR';
17756 }
17757 err.id = id;
17758 error(err);
17759 })
17760 .then(function (code) {
17761 if (!customTransformCache && setAssetSourceErr)
17762 throw setAssetSourceErr;
17763 return {
17764 ast: ast,
17765 code: code,
17766 customTransformCache: customTransformCache,
17767 originalCode: originalCode,
17768 originalSourcemap: originalSourcemap,
17769 sourcemapChain: sourcemapChain,
17770 transformDependencies: transformDependencies
17771 };
17772 });
17773}
17774
17775function normalizeRelativeExternalId(importer, source) {
17776 return isRelative(source) ? resolve$1(importer, '..', source) : source;
17777}
17778var ModuleLoader = /** @class */ (function () {
17779 function ModuleLoader(graph, modulesById, pluginDriver, external, getManualChunk) {
17780 var _this = this;
17781 this.entriesByReferenceId = new Map();
17782 this.entryModules = [];
17783 this.latestLoadModulesPromise = Promise.resolve();
17784 this.manualChunkModules = {};
17785 this.loadEntryModule = function (_a) {
17786 var alias = _a.alias, unresolvedId = _a.unresolvedId;
17787 return _this.pluginDriver
17788 .hookFirst('resolveId', [unresolvedId, undefined])
17789 .then(function (resolveIdResult) {
17790 if (resolveIdResult === false ||
17791 (resolveIdResult && typeof resolveIdResult === 'object' && resolveIdResult.external)) {
17792 error(errEntryCannotBeExternal(unresolvedId));
17793 }
17794 var id = resolveIdResult && typeof resolveIdResult === 'object'
17795 ? resolveIdResult.id
17796 : resolveIdResult;
17797 if (typeof id === 'string') {
17798 return _this.fetchModule(id, undefined).then(function (module) {
17799 if (alias !== null) {
17800 if (module.chunkAlias !== null && module.chunkAlias !== alias) {
17801 error(errCannotAssignModuleToChunk(module.id, alias, module.chunkAlias));
17802 }
17803 module.chunkAlias = alias;
17804 }
17805 return module;
17806 });
17807 }
17808 error(errUnresolvedEntry(unresolvedId));
17809 });
17810 };
17811 this.graph = graph;
17812 this.modulesById = modulesById;
17813 this.pluginDriver = pluginDriver;
17814 if (typeof external === 'function') {
17815 this.isExternal = function (id, parentId, isResolved) {
17816 return !id.startsWith('\0') && external(id, parentId, isResolved);
17817 };
17818 }
17819 else {
17820 var ids_1 = new Set(Array.isArray(external) ? external : external ? [external] : []);
17821 this.isExternal = function (id) { return ids_1.has(id); };
17822 }
17823 this.getManualChunk = typeof getManualChunk === 'function' ? getManualChunk : function () { return null; };
17824 }
17825 ModuleLoader.prototype.addEntryModuleAndGetReferenceId = function (unresolvedEntryModule) {
17826 var entryRecord = {
17827 module: null,
17828 name: unresolvedEntryModule.unresolvedId
17829 };
17830 var referenceId = addWithNewReferenceId(entryRecord, this.entriesByReferenceId, unresolvedEntryModule.unresolvedId);
17831 this.addEntryModules([unresolvedEntryModule], false)
17832 .then(function (_a) {
17833 var module = _a.newEntryModules[0];
17834 entryRecord.module = module;
17835 })
17836 .catch(function () {
17837 // Avoid unhandled Promise rejection as the error will be thrown later
17838 // once module loading has finished
17839 });
17840 return referenceId;
17841 };
17842 ModuleLoader.prototype.addEntryModules = function (unresolvedEntryModules, isUserDefined) {
17843 var _this = this;
17844 var loadNewEntryModulesPromise = Promise.all(unresolvedEntryModules.map(this.loadEntryModule)).then(function (entryModules) {
17845 var _loop_1 = function (entryModule) {
17846 entryModule.isUserDefinedEntryPoint = entryModule.isUserDefinedEntryPoint || isUserDefined;
17847 var existingEntryModule = _this.entryModules.find(function (module) { return module.id === entryModule.id; });
17848 if (!existingEntryModule) {
17849 _this.entryModules.push(entryModule);
17850 }
17851 };
17852 for (var _i = 0, entryModules_1 = entryModules; _i < entryModules_1.length; _i++) {
17853 var entryModule = entryModules_1[_i];
17854 _loop_1(entryModule);
17855 }
17856 return entryModules;
17857 });
17858 return this.awaitLoadModulesPromise(loadNewEntryModulesPromise).then(function (newEntryModules) { return ({
17859 entryModules: _this.entryModules,
17860 manualChunkModulesByAlias: _this.manualChunkModules,
17861 newEntryModules: newEntryModules
17862 }); });
17863 };
17864 ModuleLoader.prototype.addManualChunks = function (manualChunks) {
17865 var _this = this;
17866 var unresolvedManualChunks = [];
17867 for (var _i = 0, _a = Object.keys(manualChunks); _i < _a.length; _i++) {
17868 var alias = _a[_i];
17869 var manualChunkIds = manualChunks[alias];
17870 for (var _b = 0, manualChunkIds_1 = manualChunkIds; _b < manualChunkIds_1.length; _b++) {
17871 var unresolvedId = manualChunkIds_1[_b];
17872 unresolvedManualChunks.push({ alias: null, unresolvedId: unresolvedId, manualChunkAlias: alias });
17873 }
17874 }
17875 var loadNewManualChunkModulesPromise = Promise.all(unresolvedManualChunks.map(this.loadEntryModule)).then(function (manualChunkModules) {
17876 for (var index = 0; index < manualChunkModules.length; index++) {
17877 _this.addToManualChunk(unresolvedManualChunks[index].manualChunkAlias, manualChunkModules[index]);
17878 }
17879 });
17880 return this.awaitLoadModulesPromise(loadNewManualChunkModulesPromise);
17881 };
17882 ModuleLoader.prototype.getChunkFileName = function (referenceId) {
17883 var entryRecord = this.entriesByReferenceId.get(referenceId);
17884 if (!entryRecord)
17885 error(errChunkReferenceIdNotFoundForFilename(referenceId));
17886 var fileName = entryRecord.module &&
17887 (entryRecord.module.facadeChunk
17888 ? entryRecord.module.facadeChunk.id
17889 : entryRecord.module.chunk.id);
17890 if (!fileName)
17891 error(errChunkNotGeneratedForFileName(entryRecord));
17892 return fileName;
17893 };
17894 ModuleLoader.prototype.resolveId = function (source, importer) {
17895 var _this = this;
17896 return Promise.resolve(this.isExternal(source, importer, false)
17897 ? { id: source, external: true }
17898 : this.pluginDriver.hookFirst('resolveId', [source, importer])).then(function (result) { return _this.normalizeResolveIdResult(result, importer, source); });
17899 };
17900 ModuleLoader.prototype.addToManualChunk = function (alias, module) {
17901 if (module.manualChunkAlias !== null && module.manualChunkAlias !== alias) {
17902 error(errCannotAssignModuleToChunk(module.id, alias, module.manualChunkAlias));
17903 }
17904 module.manualChunkAlias = alias;
17905 if (!this.manualChunkModules[alias]) {
17906 this.manualChunkModules[alias] = [];
17907 }
17908 this.manualChunkModules[alias].push(module);
17909 };
17910 ModuleLoader.prototype.awaitLoadModulesPromise = function (loadNewModulesPromise) {
17911 var _this = this;
17912 this.latestLoadModulesPromise = Promise.all([
17913 loadNewModulesPromise,
17914 this.latestLoadModulesPromise
17915 ]);
17916 var getCombinedPromise = function () {
17917 var startingPromise = _this.latestLoadModulesPromise;
17918 return startingPromise.then(function () {
17919 if (_this.latestLoadModulesPromise !== startingPromise) {
17920 return getCombinedPromise();
17921 }
17922 });
17923 };
17924 return getCombinedPromise().then(function () { return loadNewModulesPromise; });
17925 };
17926 ModuleLoader.prototype.fetchAllDependencies = function (module) {
17927 var _this = this;
17928 var fetchDynamicImportsPromise = Promise.all(module.getDynamicImportExpressions().map(function (specifier, index) {
17929 return _this.resolveDynamicImport(specifier, module.id).then(function (resolvedId) {
17930 if (resolvedId === null)
17931 return;
17932 var dynamicImport = module.dynamicImports[index];
17933 if (typeof resolvedId === 'string') {
17934 dynamicImport.resolution = resolvedId;
17935 return;
17936 }
17937 return _this.fetchResolvedDependency(relativeId(resolvedId.id), module.id, resolvedId).then(function (module) {
17938 dynamicImport.resolution = module;
17939 });
17940 });
17941 }));
17942 fetchDynamicImportsPromise.catch(function () { });
17943 return Promise.all(module.sources.map(function (source) { return _this.resolveAndFetchDependency(module, source); })).then(function () { return fetchDynamicImportsPromise; });
17944 };
17945 ModuleLoader.prototype.fetchModule = function (id, importer) {
17946 var _this = this;
17947 var existingModule = this.modulesById.get(id);
17948 if (existingModule) {
17949 if (existingModule.isExternal)
17950 throw new Error("Cannot fetch external module " + id);
17951 return Promise.resolve(existingModule);
17952 }
17953 var module = new Module(this.graph, id);
17954 this.modulesById.set(id, module);
17955 var manualChunkAlias = this.getManualChunk(id);
17956 if (typeof manualChunkAlias === 'string') {
17957 this.addToManualChunk(manualChunkAlias, module);
17958 }
17959 timeStart('load modules', 3);
17960 return Promise.resolve(this.pluginDriver.hookFirst('load', [id]))
17961 .catch(function (err) {
17962 timeEnd('load modules', 3);
17963 var msg = "Could not load " + id;
17964 if (importer)
17965 msg += " (imported by " + importer + ")";
17966 msg += ": " + err.message;
17967 throw new Error(msg);
17968 })
17969 .then(function (source) {
17970 timeEnd('load modules', 3);
17971 if (typeof source === 'string')
17972 return source;
17973 if (source && typeof source === 'object' && typeof source.code === 'string')
17974 return source;
17975 error(errBadLoader(id));
17976 })
17977 .then(function (source) {
17978 var sourceDescription = typeof source === 'string'
17979 ? {
17980 ast: null,
17981 code: source
17982 }
17983 : source;
17984 var cachedModule = _this.graph.cachedModules.get(id);
17985 if (cachedModule &&
17986 !cachedModule.customTransformCache &&
17987 cachedModule.originalCode === sourceDescription.code) {
17988 // re-emit transform assets
17989 if (cachedModule.transformAssets) {
17990 for (var _i = 0, _a = cachedModule.transformAssets; _i < _a.length; _i++) {
17991 var asset = _a[_i];
17992 _this.pluginDriver.emitAsset(asset.name, asset.source);
17993 }
17994 }
17995 return cachedModule;
17996 }
17997 return transform(_this.graph, sourceDescription, module);
17998 })
17999 .then(function (source) {
18000 module.setSource(source);
18001 _this.modulesById.set(id, module);
18002 return _this.fetchAllDependencies(module).then(function () {
18003 for (var name in module.exports) {
18004 if (name !== 'default') {
18005 module.exportsAll[name] = module.id;
18006 }
18007 }
18008 module.exportAllSources.forEach(function (source) {
18009 var id = module.resolvedIds[source].id;
18010 var exportAllModule = _this.modulesById.get(id);
18011 if (exportAllModule instanceof ExternalModule)
18012 return;
18013 for (var name in exportAllModule.exportsAll) {
18014 if (name in module.exportsAll) {
18015 _this.graph.warn(errNamespaceConflict(name, module, exportAllModule));
18016 }
18017 else {
18018 module.exportsAll[name] = exportAllModule.exportsAll[name];
18019 }
18020 }
18021 });
18022 return module;
18023 });
18024 });
18025 };
18026 ModuleLoader.prototype.fetchResolvedDependency = function (source, importer, resolvedId) {
18027 if (resolvedId.external) {
18028 if (!this.modulesById.has(resolvedId.id)) {
18029 this.modulesById.set(resolvedId.id, new ExternalModule({ graph: this.graph, id: resolvedId.id }));
18030 }
18031 var externalModule = this.modulesById.get(resolvedId.id);
18032 if (externalModule instanceof ExternalModule === false) {
18033 error(errInternalIdCannotBeExternal(source, importer));
18034 }
18035 return Promise.resolve(externalModule);
18036 }
18037 else {
18038 return this.fetchModule(resolvedId.id, importer);
18039 }
18040 };
18041 ModuleLoader.prototype.handleMissingImports = function (resolvedId, source, importer) {
18042 if (resolvedId === null) {
18043 if (isRelative(source)) {
18044 error(errUnresolvedImport(source, importer));
18045 }
18046 this.graph.warn(errUnresolvedImportTreatedAsExternal(source, importer));
18047 return { id: source, external: true };
18048 }
18049 return resolvedId;
18050 };
18051 ModuleLoader.prototype.normalizeResolveIdResult = function (resolveIdResult, importer, source) {
18052 var id = '';
18053 var external = false;
18054 if (resolveIdResult) {
18055 if (typeof resolveIdResult === 'object') {
18056 id = resolveIdResult.id;
18057 if (resolveIdResult.external) {
18058 external = true;
18059 }
18060 }
18061 else {
18062 id = resolveIdResult;
18063 if (this.isExternal(id, importer, true)) {
18064 external = true;
18065 }
18066 }
18067 if (external) {
18068 id = normalizeRelativeExternalId(importer, id);
18069 }
18070 }
18071 else {
18072 id = normalizeRelativeExternalId(importer, source);
18073 if (resolveIdResult !== false && !this.isExternal(id, importer, true)) {
18074 return null;
18075 }
18076 external = true;
18077 }
18078 return { id: id, external: external };
18079 };
18080 ModuleLoader.prototype.resolveAndFetchDependency = function (module, source) {
18081 var _this = this;
18082 return Promise.resolve(module.resolvedIds[source] ||
18083 this.resolveId(source, module.id).then(function (resolvedId) {
18084 return _this.handleMissingImports(resolvedId, source, module.id);
18085 })).then(function (resolvedId) {
18086 module.resolvedIds[source] = resolvedId;
18087 return _this.fetchResolvedDependency(source, module.id, resolvedId);
18088 });
18089 };
18090 ModuleLoader.prototype.resolveDynamicImport = function (specifier, importer) {
18091 var _this = this;
18092 // TODO we only should expose the acorn AST here
18093 return this.pluginDriver
18094 .hookFirst('resolveDynamicImport', [specifier, importer])
18095 .then(function (resolution) {
18096 if (typeof specifier !== 'string') {
18097 if (typeof resolution === 'string') {
18098 return resolution;
18099 }
18100 if (!resolution) {
18101 return null;
18102 }
18103 return __assign({ external: false }, resolution);
18104 }
18105 if (resolution == null) {
18106 return _this.resolveId(specifier, importer).then(function (resolvedId) {
18107 return _this.handleMissingImports(resolvedId, specifier, importer);
18108 });
18109 }
18110 return _this.handleMissingImports(_this.normalizeResolveIdResult(resolution, importer, specifier), specifier, importer);
18111 });
18112 };
18113 return ModuleLoader;
18114}());
18115
18116var CHAR_CODE_A = 97;
18117var CHAR_CODE_0 = 48;
18118function intToHex(num) {
18119 if (num < 10)
18120 return String.fromCharCode(CHAR_CODE_0 + num);
18121 else
18122 return String.fromCharCode(CHAR_CODE_A + (num - 10));
18123}
18124function Uint8ArrayToHexString(buffer) {
18125 var str = '';
18126 // hex conversion - 2 chars per 8 bit component
18127 for (var i = 0; i < buffer.length; i++) {
18128 var num = buffer[i];
18129 // big endian conversion, but whatever
18130 str += intToHex(num >> 4);
18131 str += intToHex(num & 0xf);
18132 }
18133 return str;
18134}
18135function Uint8ArrayXor(to, from) {
18136 for (var i = 0; i < to.length; i++)
18137 to[i] = to[i] ^ from[i];
18138 return to;
18139}
18140function randomUint8Array(len) {
18141 var buffer = new Uint8Array(len);
18142 for (var i = 0; i < buffer.length; i++)
18143 buffer[i] = Math.random() * (2 << 8);
18144 return buffer;
18145}
18146
18147function assignChunkColouringHashes(entryModules, manualChunkModules) {
18148 var currentEntry, currentEntryHash;
18149 var modulesVisitedForCurrentEntry;
18150 var handledEntryPoints = new Set();
18151 var dynamicImports = [];
18152 var addCurrentEntryColourToModule = function (module) {
18153 if (currentEntry.manualChunkAlias) {
18154 module.manualChunkAlias = currentEntry.manualChunkAlias;
18155 module.entryPointsHash = currentEntryHash;
18156 }
18157 else {
18158 Uint8ArrayXor(module.entryPointsHash, currentEntryHash);
18159 }
18160 for (var _i = 0, _a = module.dependencies; _i < _a.length; _i++) {
18161 var dependency = _a[_i];
18162 if (dependency instanceof ExternalModule ||
18163 modulesVisitedForCurrentEntry.has(dependency.id)) {
18164 continue;
18165 }
18166 modulesVisitedForCurrentEntry.add(dependency.id);
18167 if (!handledEntryPoints.has(dependency.id) && !dependency.manualChunkAlias) {
18168 addCurrentEntryColourToModule(dependency);
18169 }
18170 }
18171 for (var _b = 0, _c = module.dynamicImports; _b < _c.length; _b++) {
18172 var resolution = _c[_b].resolution;
18173 if (resolution instanceof Module &&
18174 resolution.dynamicallyImportedBy.length > 0 &&
18175 !resolution.manualChunkAlias) {
18176 dynamicImports.push(resolution);
18177 }
18178 }
18179 };
18180 if (manualChunkModules) {
18181 for (var _i = 0, _a = Object.keys(manualChunkModules); _i < _a.length; _i++) {
18182 var chunkName = _a[_i];
18183 currentEntryHash = randomUint8Array(10);
18184 for (var _b = 0, _c = manualChunkModules[chunkName]; _b < _c.length; _b++) {
18185 currentEntry = _c[_b];
18186 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
18187 addCurrentEntryColourToModule(currentEntry);
18188 }
18189 }
18190 }
18191 for (var _d = 0, entryModules_1 = entryModules; _d < entryModules_1.length; _d++) {
18192 currentEntry = entryModules_1[_d];
18193 handledEntryPoints.add(currentEntry.id);
18194 currentEntryHash = randomUint8Array(10);
18195 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
18196 if (!currentEntry.manualChunkAlias) {
18197 addCurrentEntryColourToModule(currentEntry);
18198 }
18199 }
18200 for (var _e = 0, dynamicImports_1 = dynamicImports; _e < dynamicImports_1.length; _e++) {
18201 currentEntry = dynamicImports_1[_e];
18202 if (handledEntryPoints.has(currentEntry.id)) {
18203 continue;
18204 }
18205 handledEntryPoints.add(currentEntry.id);
18206 currentEntryHash = randomUint8Array(10);
18207 modulesVisitedForCurrentEntry = new Set(currentEntry.id);
18208 addCurrentEntryColourToModule(currentEntry);
18209 }
18210}
18211
18212function makeOnwarn() {
18213 var warned = Object.create(null);
18214 return function (warning) {
18215 var str = warning.toString();
18216 if (str in warned)
18217 return;
18218 console.error(str);
18219 warned[str] = true;
18220 };
18221}
18222function normalizeEntryModules(entryModules) {
18223 if (typeof entryModules === 'string') {
18224 return [{ alias: null, unresolvedId: entryModules }];
18225 }
18226 if (Array.isArray(entryModules)) {
18227 return entryModules.map(function (unresolvedId) { return ({ alias: null, unresolvedId: unresolvedId }); });
18228 }
18229 return Object.keys(entryModules).map(function (alias) { return ({
18230 alias: alias,
18231 unresolvedId: entryModules[alias]
18232 }); });
18233}
18234var Graph = /** @class */ (function () {
18235 function Graph(options, watcher) {
18236 var _this = this;
18237 var _a;
18238 this.assetsById = new Map();
18239 this.curChunkIndex = 0;
18240 this.moduleById = new Map();
18241 this.needsTreeshakingPass = false;
18242 this.phase = BuildPhase.LOAD_AND_PARSE;
18243 this.watchFiles = Object.create(null);
18244 this.externalModules = [];
18245 this.modules = [];
18246 this.curChunkIndex = 0;
18247 this.deoptimizationTracker = new EntityPathTracker();
18248 this.cachedModules = new Map();
18249 if (options.cache) {
18250 if (options.cache.modules)
18251 for (var _i = 0, _b = options.cache.modules; _i < _b.length; _i++) {
18252 var module = _b[_i];
18253 this.cachedModules.set(module.id, module);
18254 }
18255 }
18256 if (options.cache !== false) {
18257 this.pluginCache = (options.cache && options.cache.plugins) || Object.create(null);
18258 // increment access counter
18259 for (var name in this.pluginCache) {
18260 var cache = this.pluginCache[name];
18261 for (var _c = 0, _d = Object.keys(cache); _c < _d.length; _c++) {
18262 var key = _d[_c];
18263 cache[key][0]++;
18264 }
18265 }
18266 }
18267 this.preserveModules = options.preserveModules;
18268 this.cacheExpiry = options.experimentalCacheExpiry;
18269 this.treeshake = options.treeshake !== false;
18270 if (this.treeshake) {
18271 this.treeshakingOptions = options.treeshake
18272 ? {
18273 annotations: options.treeshake.annotations !== false,
18274 propertyReadSideEffects: options.treeshake.propertyReadSideEffects !== false,
18275 pureExternalModules: options.treeshake.pureExternalModules
18276 }
18277 : { propertyReadSideEffects: true, annotations: true, pureExternalModules: false };
18278 if (this.treeshakingOptions.pureExternalModules === true) {
18279 this.isPureExternalModule = function () { return true; };
18280 }
18281 else if (typeof this.treeshakingOptions.pureExternalModules === 'function') {
18282 this.isPureExternalModule = this.treeshakingOptions.pureExternalModules;
18283 }
18284 else if (Array.isArray(this.treeshakingOptions.pureExternalModules)) {
18285 var pureExternalModules_1 = new Set(this.treeshakingOptions.pureExternalModules);
18286 this.isPureExternalModule = function (id) { return pureExternalModules_1.has(id); };
18287 }
18288 else {
18289 this.isPureExternalModule = function () { return false; };
18290 }
18291 }
18292 else {
18293 this.isPureExternalModule = function () { return false; };
18294 }
18295 this.contextParse = function (code, options) {
18296 if (options === void 0) { options = {}; }
18297 return _this.acornParser.parse(code, __assign({}, defaultAcornOptions, options, _this.acornOptions));
18298 };
18299 this.pluginDriver = createPluginDriver(this, options, this.pluginCache, watcher);
18300 if (watcher) {
18301 var handleChange_1 = function (id) { return _this.pluginDriver.hookSeqSync('watchChange', [id]); };
18302 watcher.on('change', handleChange_1);
18303 watcher.once('restart', function () {
18304 watcher.removeListener('change', handleChange_1);
18305 });
18306 }
18307 this.shimMissingExports = options.shimMissingExports;
18308 this.scope = new GlobalScope();
18309 this.context = String(options.context);
18310 var optionsModuleContext = options.moduleContext;
18311 if (typeof optionsModuleContext === 'function') {
18312 this.getModuleContext = function (id) { return optionsModuleContext(id) || _this.context; };
18313 }
18314 else if (typeof optionsModuleContext === 'object') {
18315 var moduleContext_1 = new Map();
18316 for (var key in optionsModuleContext) {
18317 moduleContext_1.set(resolve$1(key), optionsModuleContext[key]);
18318 }
18319 this.getModuleContext = function (id) { return moduleContext_1.get(id) || _this.context; };
18320 }
18321 else {
18322 this.getModuleContext = function () { return _this.context; };
18323 }
18324 this.onwarn = options.onwarn || makeOnwarn();
18325 this.acornOptions = options.acorn || {};
18326 var acornPluginsToInject = [];
18327 acornPluginsToInject.push(dynamicImport);
18328 acornPluginsToInject.push(acornImportMeta);
18329 acornPluginsToInject.push(acornBigint);
18330 if (options.experimentalTopLevelAwait) {
18331 this.acornOptions.allowAwaitOutsideFunction = true;
18332 }
18333 var acornInjectPlugins = options.acornInjectPlugins;
18334 acornPluginsToInject.push.apply(acornPluginsToInject, (Array.isArray(acornInjectPlugins)
18335 ? acornInjectPlugins
18336 : acornInjectPlugins
18337 ? [acornInjectPlugins]
18338 : []));
18339 this.acornParser = (_a = Parser$1).extend.apply(_a, acornPluginsToInject);
18340 this.moduleLoader = new ModuleLoader(this, this.moduleById, this.pluginDriver, options.external, typeof options.manualChunks === 'function' && options.manualChunks);
18341 }
18342 Graph.prototype.build = function (entryModules, manualChunks, inlineDynamicImports) {
18343 // Phase 1 – discovery. We load the entry module and find which
18344 // modules it imports, and import those, until we have all
18345 // of the entry module's dependencies
18346 var _this = this;
18347 timeStart('parse modules', 2);
18348 return Promise.all([
18349 this.moduleLoader.addEntryModules(normalizeEntryModules(entryModules), true),
18350 manualChunks &&
18351 typeof manualChunks === 'object' &&
18352 this.moduleLoader.addManualChunks(manualChunks)
18353 ]).then(function (_a) {
18354 var _b = _a[0], entryModules = _b.entryModules, manualChunkModulesByAlias = _b.manualChunkModulesByAlias;
18355 if (entryModules.length === 0) {
18356 throw new Error('You must supply options.input to rollup');
18357 }
18358 for (var _i = 0, _c = Array.from(_this.moduleById.values()); _i < _c.length; _i++) {
18359 var module = _c[_i];
18360 if (module instanceof Module) {
18361 _this.modules.push(module);
18362 _this.watchFiles[module.id] = true;
18363 }
18364 else {
18365 _this.externalModules.push(module);
18366 }
18367 }
18368 timeEnd('parse modules', 2);
18369 _this.phase = BuildPhase.ANALYSE;
18370 // Phase 2 - linking. We populate the module dependency links and
18371 // determine the topological execution order for the bundle
18372 timeStart('analyse dependency graph', 2);
18373 _this.link(entryModules);
18374 timeEnd('analyse dependency graph', 2);
18375 // Phase 3 – marking. We include all statements that should be included
18376 timeStart('mark included statements', 2);
18377 if (inlineDynamicImports) {
18378 if (entryModules.length > 1) {
18379 throw new Error('Internal Error: can only inline dynamic imports for single-file builds.');
18380 }
18381 }
18382 for (var _d = 0, entryModules_1 = entryModules; _d < entryModules_1.length; _d++) {
18383 var module = entryModules_1[_d];
18384 module.includeAllExports();
18385 }
18386 _this.includeMarked(_this.modules);
18387 // check for unused external imports
18388 for (var _e = 0, _f = _this.externalModules; _e < _f.length; _e++) {
18389 var externalModule = _f[_e];
18390 externalModule.warnUnusedImports();
18391 }
18392 timeEnd('mark included statements', 2);
18393 // Phase 4 – we construct the chunks, working out the optimal chunking using
18394 // entry point graph colouring, before generating the import and export facades
18395 timeStart('generate chunks', 2);
18396 if (!_this.preserveModules && !inlineDynamicImports) {
18397 assignChunkColouringHashes(entryModules, manualChunkModulesByAlias);
18398 }
18399 // TODO: there is one special edge case unhandled here and that is that any module
18400 // exposed as an unresolvable export * (to a graph external export *,
18401 // either as a namespace import reexported or top-level export *)
18402 // should be made to be its own entry point module before chunking
18403 var chunks = [];
18404 if (_this.preserveModules) {
18405 for (var _g = 0, _h = _this.modules; _g < _h.length; _g++) {
18406 var module = _h[_g];
18407 var chunk = new Chunk$1(_this, [module]);
18408 if (module.isEntryPoint || !chunk.isEmpty) {
18409 chunk.entryModules = [module];
18410 }
18411 chunks.push(chunk);
18412 }
18413 }
18414 else {
18415 var chunkModules = {};
18416 for (var _j = 0, _k = _this.modules; _j < _k.length; _j++) {
18417 var module = _k[_j];
18418 var entryPointsHashStr = Uint8ArrayToHexString(module.entryPointsHash);
18419 var curChunk = chunkModules[entryPointsHashStr];
18420 if (curChunk) {
18421 curChunk.push(module);
18422 }
18423 else {
18424 chunkModules[entryPointsHashStr] = [module];
18425 }
18426 }
18427 for (var entryHashSum in chunkModules) {
18428 var chunkModulesOrdered = chunkModules[entryHashSum];
18429 sortByExecutionOrder(chunkModulesOrdered);
18430 var chunk = new Chunk$1(_this, chunkModulesOrdered);
18431 chunks.push(chunk);
18432 }
18433 }
18434 // for each chunk module, set up its imports to other
18435 // chunks, if those variables are included after treeshaking
18436 for (var _l = 0, chunks_1 = chunks; _l < chunks_1.length; _l++) {
18437 var chunk = chunks_1[_l];
18438 chunk.link();
18439 }
18440 // filter out empty dependencies
18441 chunks = chunks.filter(isChunkRendered);
18442 // then go over and ensure all entry chunks export their variables
18443 for (var _m = 0, chunks_2 = chunks; _m < chunks_2.length; _m++) {
18444 var chunk = chunks_2[_m];
18445 if (_this.preserveModules || chunk.entryModules.length > 0) {
18446 chunk.generateEntryExportsOrMarkAsTainted();
18447 }
18448 }
18449 // create entry point facades for entry module chunks that have tainted exports
18450 var facades = [];
18451 if (!_this.preserveModules) {
18452 for (var _o = 0, chunks_3 = chunks; _o < chunks_3.length; _o++) {
18453 var chunk = chunks_3[_o];
18454 for (var _p = 0, _q = chunk.entryModules; _p < _q.length; _p++) {
18455 var entryModule = _q[_p];
18456 if (chunk.facadeModule !== entryModule) {
18457 var entryPointFacade = new Chunk$1(_this, []);
18458 entryPointFacade.turnIntoFacade(entryModule);
18459 facades.push(entryPointFacade);
18460 }
18461 }
18462 }
18463 }
18464 timeEnd('generate chunks', 2);
18465 _this.phase = BuildPhase.GENERATE;
18466 return chunks.concat(facades);
18467 });
18468 };
18469 Graph.prototype.finaliseAssets = function (assetFileNames) {
18470 var outputBundle = Object.create(null);
18471 this.assetsById.forEach(function (asset) {
18472 if (asset.source !== undefined)
18473 finaliseAsset(asset, outputBundle, assetFileNames);
18474 });
18475 return outputBundle;
18476 };
18477 Graph.prototype.getCache = function () {
18478 // handle plugin cache eviction
18479 for (var name in this.pluginCache) {
18480 var cache = this.pluginCache[name];
18481 var allDeleted = true;
18482 for (var _i = 0, _a = Object.keys(cache); _i < _a.length; _i++) {
18483 var key = _a[_i];
18484 if (cache[key][0] >= this.cacheExpiry)
18485 delete cache[key];
18486 else
18487 allDeleted = false;
18488 }
18489 if (allDeleted)
18490 delete this.pluginCache[name];
18491 }
18492 return {
18493 modules: this.modules.map(function (module) { return module.toJSON(); }),
18494 plugins: this.pluginCache
18495 };
18496 };
18497 Graph.prototype.includeMarked = function (modules) {
18498 if (this.treeshake) {
18499 var treeshakingPass = 1;
18500 do {
18501 timeStart("treeshaking pass " + treeshakingPass, 3);
18502 this.needsTreeshakingPass = false;
18503 for (var _i = 0, modules_1 = modules; _i < modules_1.length; _i++) {
18504 var module = modules_1[_i];
18505 if (module.isExecuted)
18506 module.include();
18507 }
18508 timeEnd("treeshaking pass " + treeshakingPass++, 3);
18509 } while (this.needsTreeshakingPass);
18510 }
18511 else {
18512 // Necessary to properly replace namespace imports
18513 for (var _a = 0, modules_2 = modules; _a < modules_2.length; _a++) {
18514 var module = modules_2[_a];
18515 module.includeAllInBundle();
18516 }
18517 }
18518 };
18519 Graph.prototype.warn = function (warning) {
18520 warning.toString = function () {
18521 var str = '';
18522 if (warning.plugin)
18523 str += "(" + warning.plugin + " plugin) ";
18524 if (warning.loc)
18525 str += relativeId(warning.loc.file) + " (" + warning.loc.line + ":" + warning.loc.column + ") ";
18526 str += warning.message;
18527 return str;
18528 };
18529 this.onwarn(warning);
18530 };
18531 Graph.prototype.link = function (entryModules) {
18532 for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
18533 var module = _a[_i];
18534 module.linkDependencies();
18535 }
18536 var _b = analyseModuleExecution(entryModules), orderedModules = _b.orderedModules, cyclePaths = _b.cyclePaths;
18537 for (var _c = 0, cyclePaths_1 = cyclePaths; _c < cyclePaths_1.length; _c++) {
18538 var cyclePath = cyclePaths_1[_c];
18539 this.warn({
18540 code: 'CIRCULAR_DEPENDENCY',
18541 importer: cyclePath[0],
18542 message: "Circular dependency: " + cyclePath.join(' -> ')
18543 });
18544 }
18545 this.modules = orderedModules;
18546 for (var _d = 0, _e = this.modules; _d < _e.length; _d++) {
18547 var module = _e[_d];
18548 module.bindReferences();
18549 }
18550 this.warnForMissingExports();
18551 };
18552 Graph.prototype.warnForMissingExports = function () {
18553 for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
18554 var module = _a[_i];
18555 for (var _b = 0, _c = Object.keys(module.importDescriptions); _b < _c.length; _b++) {
18556 var importName = _c[_b];
18557 var importDescription = module.importDescriptions[importName];
18558 if (importDescription.name !== '*' &&
18559 !importDescription.module.getVariableForExportName(importDescription.name)) {
18560 module.warn({
18561 code: 'NON_EXISTENT_EXPORT',
18562 message: "Non-existent export '" + importDescription.name + "' is imported from " + relativeId(importDescription.module.id),
18563 name: importDescription.name,
18564 source: importDescription.module.id
18565 }, importDescription.start);
18566 }
18567 }
18568 }
18569 };
18570 return Graph;
18571}());
18572
18573function evalIfFn(strOrFn) {
18574 switch (typeof strOrFn) {
18575 case 'function':
18576 return strOrFn();
18577 case 'string':
18578 return strOrFn;
18579 default:
18580 return '';
18581 }
18582}
18583var concatSep = function (out, next) { return (next ? out + "\n" + next : out); };
18584var concatDblSep = function (out, next) { return (next ? out + "\n\n" + next : out); };
18585function createAddons(graph, options) {
18586 var pluginDriver = graph.pluginDriver;
18587 return Promise.all([
18588 pluginDriver.hookReduceValue('banner', evalIfFn(options.banner), [], concatSep),
18589 pluginDriver.hookReduceValue('footer', evalIfFn(options.footer), [], concatSep),
18590 pluginDriver.hookReduceValue('intro', evalIfFn(options.intro), [], concatDblSep),
18591 pluginDriver.hookReduceValue('outro', evalIfFn(options.outro), [], concatDblSep)
18592 ])
18593 .then(function (_a) {
18594 var banner = _a[0], footer = _a[1], intro = _a[2], outro = _a[3];
18595 if (intro)
18596 intro += '\n\n';
18597 if (outro)
18598 outro = "\n\n" + outro;
18599 if (banner.length)
18600 banner += '\n';
18601 if (footer.length)
18602 footer = '\n' + footer;
18603 return { intro: intro, outro: outro, banner: banner, footer: footer };
18604 })
18605 .catch(function (err) {
18606 error({
18607 code: 'ADDON_ERROR',
18608 message: "Could not retrieve " + err.hook + ". Check configuration of " + err.plugin + ".\n\tError Message: " + err.message
18609 });
18610 });
18611}
18612
18613function assignChunkIds(chunks, inputOptions, outputOptions, inputBase, addons) {
18614 var usedIds = {};
18615 var _a = chunks.reduce(function (_a, chunk) {
18616 var entryChunks = _a[0], otherChunks = _a[1];
18617 (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint
18618 ? entryChunks
18619 : otherChunks).push(chunk);
18620 return [entryChunks, otherChunks];
18621 }, [[], []]), entryChunks = _a[0], otherChunks = _a[1];
18622 // make sure entry chunk names take precedence with regard to deconflicting
18623 var chunksForNaming = entryChunks.concat(otherChunks);
18624 for (var i = 0; i < chunksForNaming.length; i++) {
18625 var chunk = chunksForNaming[i];
18626 if (outputOptions.file) {
18627 chunk.id = basename(outputOptions.file);
18628 }
18629 else if (inputOptions.preserveModules) {
18630 chunk.generateIdPreserveModules(inputBase, usedIds);
18631 }
18632 else {
18633 var pattern = void 0, patternName = void 0;
18634 if (chunk.facadeModule && chunk.facadeModule.isUserDefinedEntryPoint) {
18635 pattern = outputOptions.entryFileNames || '[name].js';
18636 patternName = 'output.entryFileNames';
18637 }
18638 else {
18639 pattern = outputOptions.chunkFileNames || '[name]-[hash].js';
18640 patternName = 'output.chunkFileNames';
18641 }
18642 chunk.generateId(pattern, patternName, addons, outputOptions, usedIds);
18643 }
18644 usedIds[chunk.id] = true;
18645 }
18646}
18647
18648// ported from https://github.com/substack/node-commondir
18649function commondir(files) {
18650 if (files.length === 0)
18651 return '/';
18652 if (files.length === 1)
18653 return dirname(files[0]);
18654 var commonSegments = files.slice(1).reduce(function (commonSegments, file) {
18655 var pathSegements = file.split(/\/+|\\+/);
18656 var i;
18657 for (i = 0; commonSegments[i] === pathSegements[i] &&
18658 i < Math.min(commonSegments.length, pathSegements.length); i++)
18659 ;
18660 return commonSegments.slice(0, i);
18661 }, files[0].split(/\/+|\\+/));
18662 // Windows correctly handles paths with forward-slashes
18663 return commonSegments.length > 1 ? commonSegments.join('/') : '/';
18664}
18665
18666function badExports(option, keys) {
18667 error({
18668 code: 'INVALID_EXPORT_OPTION',
18669 message: "'" + option + "' was specified for output.exports, but entry module has following exports: " + keys.join(', ')
18670 });
18671}
18672function getExportMode(chunk, _a) {
18673 var exportMode = _a.exports, name = _a.name, format = _a.format;
18674 var exportKeys = chunk.getExportNames();
18675 if (exportMode === 'default') {
18676 if (exportKeys.length !== 1 || exportKeys[0] !== 'default') {
18677 badExports('default', exportKeys);
18678 }
18679 }
18680 else if (exportMode === 'none' && exportKeys.length) {
18681 badExports('none', exportKeys);
18682 }
18683 if (!exportMode || exportMode === 'auto') {
18684 if (exportKeys.length === 0) {
18685 exportMode = 'none';
18686 }
18687 else if (exportKeys.length === 1 && exportKeys[0] === 'default') {
18688 exportMode = 'default';
18689 }
18690 else {
18691 if (chunk.facadeModule !== null &&
18692 chunk.facadeModule.isEntryPoint &&
18693 format !== 'es' &&
18694 exportKeys.indexOf('default') !== -1) {
18695 chunk.graph.warn({
18696 code: 'MIXED_EXPORTS',
18697 message: "Using named and default exports together. Consumers of your bundle will have to use " + (name ||
18698 'bundle') + "['default'] to access the default export, which may not be what you want. Use `output.exports: 'named'` to disable this warning",
18699 url: "https://rollupjs.org/guide/en#output-exports"
18700 });
18701 }
18702 exportMode = 'named';
18703 }
18704 }
18705 if (!/(?:default|named|none)/.test(exportMode)) {
18706 error({
18707 code: 'INVALID_EXPORT_OPTION',
18708 message: "output.exports must be 'default', 'named', 'none', 'auto', or left unspecified (defaults to 'auto')",
18709 url: "https://rollupjs.org/guide/en#output-exports"
18710 });
18711 }
18712 return exportMode;
18713}
18714
18715var createGetOption = function (config, command) { return function (name, defaultValue) {
18716 return command[name] !== undefined
18717 ? command[name]
18718 : config[name] !== undefined
18719 ? config[name]
18720 : defaultValue;
18721}; };
18722var normalizeObjectOptionValue = function (optionValue) {
18723 if (!optionValue) {
18724 return optionValue;
18725 }
18726 if (typeof optionValue !== 'object') {
18727 return {};
18728 }
18729 return optionValue;
18730};
18731var getObjectOption = function (config, command, name) {
18732 var commandOption = normalizeObjectOptionValue(command[name]);
18733 var configOption = normalizeObjectOptionValue(config[name]);
18734 if (commandOption !== undefined) {
18735 return commandOption && configOption ? __assign({}, configOption, commandOption) : commandOption;
18736 }
18737 return configOption;
18738};
18739var defaultOnWarn = function (warning) {
18740 if (typeof warning === 'string') {
18741 console.warn(warning);
18742 }
18743 else {
18744 console.warn(warning.message);
18745 }
18746};
18747var getOnWarn = function (config, command, defaultOnWarnHandler) {
18748 if (defaultOnWarnHandler === void 0) { defaultOnWarnHandler = defaultOnWarn; }
18749 return command.silent
18750 ? function () { }
18751 : config.onwarn
18752 ? function (warning) { return config.onwarn(warning, defaultOnWarnHandler); }
18753 : defaultOnWarnHandler;
18754};
18755// TODO Lukas manual chunks should receive the same treatment
18756var getExternal = function (config, command) {
18757 var configExternal = config.external;
18758 return typeof configExternal === 'function'
18759 ? function (id) {
18760 var rest = [];
18761 for (var _i = 1; _i < arguments.length; _i++) {
18762 rest[_i - 1] = arguments[_i];
18763 }
18764 return configExternal.apply(void 0, [id].concat(rest)) || command.external.indexOf(id) !== -1;
18765 }
18766 : (configExternal || []).concat(command.external);
18767};
18768var commandAliases = {
18769 c: 'config',
18770 d: 'dir',
18771 e: 'external',
18772 f: 'format',
18773 g: 'globals',
18774 h: 'help',
18775 i: 'input',
18776 m: 'sourcemap',
18777 n: 'name',
18778 o: 'file',
18779 v: 'version',
18780 w: 'watch'
18781};
18782function mergeOptions(_a) {
18783 var _b = _a.config, config = _b === void 0 ? {} : _b, _c = _a.command, rawCommandOptions = _c === void 0 ? {} : _c, defaultOnWarnHandler = _a.defaultOnWarnHandler;
18784 var command = getCommandOptions(rawCommandOptions);
18785 var inputOptions = getInputOptions(config, command, defaultOnWarnHandler);
18786 if (command.output) {
18787 Object.assign(command, command.output);
18788 }
18789 var output = config.output;
18790 var normalizedOutputOptions = Array.isArray(output) ? output : output ? [output] : [];
18791 if (normalizedOutputOptions.length === 0)
18792 normalizedOutputOptions.push({});
18793 var outputOptions = normalizedOutputOptions.map(function (singleOutputOptions) {
18794 return getOutputOptions(singleOutputOptions, command);
18795 });
18796 var unknownOptionErrors = [];
18797 var validInputOptions = Object.keys(inputOptions);
18798 addUnknownOptionErrors(unknownOptionErrors, Object.keys(config), validInputOptions, 'input option', /^output$/);
18799 var validOutputOptions = Object.keys(outputOptions[0]);
18800 addUnknownOptionErrors(unknownOptionErrors, outputOptions.reduce(function (allKeys, options) { return allKeys.concat(Object.keys(options)); }, []), validOutputOptions, 'output option');
18801 var validCliOutputOptions = validOutputOptions.filter(function (option) { return option !== 'sourcemapPathTransform'; });
18802 addUnknownOptionErrors(unknownOptionErrors, Object.keys(command), validInputOptions.concat(validCliOutputOptions, Object.keys(commandAliases), 'config', 'environment', 'silent'), 'CLI flag', /^_|output|(config.*)$/);
18803 return {
18804 inputOptions: inputOptions,
18805 optionError: unknownOptionErrors.length > 0 ? unknownOptionErrors.join('\n') : null,
18806 outputOptions: outputOptions
18807 };
18808}
18809function addUnknownOptionErrors(errors, options, validOptions, optionType, ignoredKeys) {
18810 if (ignoredKeys === void 0) { ignoredKeys = /$./; }
18811 var unknownOptions = options.filter(function (key) { return validOptions.indexOf(key) === -1 && !ignoredKeys.test(key); });
18812 if (unknownOptions.length > 0)
18813 errors.push("Unknown " + optionType + ": " + unknownOptions.join(', ') + ". Allowed options: " + validOptions.sort().join(', '));
18814}
18815function getCommandOptions(rawCommandOptions) {
18816 var command = __assign({}, rawCommandOptions);
18817 command.external = rawCommandOptions.external ? rawCommandOptions.external.split(',') : [];
18818 if (rawCommandOptions.globals) {
18819 command.globals = Object.create(null);
18820 rawCommandOptions.globals.split(',').forEach(function (str) {
18821 var names = str.split(':');
18822 command.globals[names[0]] = names[1];
18823 // Add missing Module IDs to external.
18824 if (command.external.indexOf(names[0]) === -1) {
18825 command.external.push(names[0]);
18826 }
18827 });
18828 }
18829 return command;
18830}
18831function getInputOptions(config, command, defaultOnWarnHandler) {
18832 if (command === void 0) { command = {}; }
18833 var getOption = createGetOption(config, command);
18834 var inputOptions = {
18835 acorn: config.acorn,
18836 acornInjectPlugins: config.acornInjectPlugins,
18837 cache: getOption('cache'),
18838 chunkGroupingSize: getOption('chunkGroupingSize', 5000),
18839 context: config.context,
18840 experimentalCacheExpiry: getOption('experimentalCacheExpiry', 10),
18841 experimentalOptimizeChunks: getOption('experimentalOptimizeChunks'),
18842 experimentalTopLevelAwait: getOption('experimentalTopLevelAwait'),
18843 external: getExternal(config, command),
18844 inlineDynamicImports: getOption('inlineDynamicImports', false),
18845 input: getOption('input', []),
18846 manualChunks: getOption('manualChunks'),
18847 moduleContext: config.moduleContext,
18848 onwarn: getOnWarn(config, command, defaultOnWarnHandler),
18849 perf: getOption('perf', false),
18850 plugins: config.plugins,
18851 preserveModules: getOption('preserveModules'),
18852 preserveSymlinks: getOption('preserveSymlinks'),
18853 shimMissingExports: getOption('shimMissingExports'),
18854 treeshake: getObjectOption(config, command, 'treeshake'),
18855 watch: config.watch
18856 };
18857 // support rollup({ cache: prevBuildObject })
18858 if (inputOptions.cache && inputOptions.cache.cache)
18859 inputOptions.cache = inputOptions.cache.cache;
18860 return inputOptions;
18861}
18862function getOutputOptions(config, command) {
18863 if (command === void 0) { command = {}; }
18864 var getOption = createGetOption(config, command);
18865 var format = getOption('format');
18866 // Handle format aliases
18867 switch (format) {
18868 case 'esm':
18869 case 'module':
18870 format = 'es';
18871 break;
18872 case 'commonjs':
18873 format = 'cjs';
18874 }
18875 return {
18876 amd: __assign({}, config.amd, command.amd),
18877 assetFileNames: getOption('assetFileNames'),
18878 banner: getOption('banner'),
18879 chunkFileNames: getOption('chunkFileNames'),
18880 compact: getOption('compact', false),
18881 dir: getOption('dir'),
18882 dynamicImportFunction: getOption('dynamicImportFunction'),
18883 entryFileNames: getOption('entryFileNames'),
18884 esModule: getOption('esModule', true),
18885 exports: getOption('exports'),
18886 extend: getOption('extend'),
18887 file: getOption('file'),
18888 footer: getOption('footer'),
18889 format: format === 'esm' ? 'es' : format,
18890 freeze: getOption('freeze', true),
18891 globals: getOption('globals'),
18892 indent: getOption('indent', true),
18893 interop: getOption('interop', true),
18894 intro: getOption('intro'),
18895 name: getOption('name'),
18896 namespaceToStringTag: getOption('namespaceToStringTag', false),
18897 noConflict: getOption('noConflict'),
18898 outro: getOption('outro'),
18899 paths: getOption('paths'),
18900 preferConst: getOption('preferConst'),
18901 sourcemap: getOption('sourcemap'),
18902 sourcemapExcludeSources: getOption('sourcemapExcludeSources'),
18903 sourcemapFile: getOption('sourcemapFile'),
18904 sourcemapPathTransform: getOption('sourcemapPathTransform'),
18905 strict: getOption('strict', true)
18906 };
18907}
18908
18909function checkOutputOptions(options) {
18910 if (options.format === 'es6') {
18911 error({
18912 message: 'The "es6" output format is deprecated – use "esm" instead',
18913 url: "https://rollupjs.org/guide/en#output-format"
18914 });
18915 }
18916 if (['amd', 'cjs', 'system', 'es', 'iife', 'umd'].indexOf(options.format) < 0) {
18917 error({
18918 message: "You must specify \"output.format\", which can be one of \"amd\", \"cjs\", \"system\", \"esm\", \"iife\" or \"umd\".",
18919 url: "https://rollupjs.org/guide/en#output-format"
18920 });
18921 }
18922}
18923function getAbsoluteEntryModulePaths(chunks) {
18924 var absoluteEntryModulePaths = [];
18925 for (var _i = 0, chunks_1 = chunks; _i < chunks_1.length; _i++) {
18926 var chunk = chunks_1[_i];
18927 for (var _a = 0, _b = chunk.entryModules; _a < _b.length; _a++) {
18928 var entryModule = _b[_a];
18929 if (isAbsolute(entryModule.id)) {
18930 absoluteEntryModulePaths.push(entryModule.id);
18931 }
18932 }
18933 }
18934 return absoluteEntryModulePaths;
18935}
18936var throwAsyncGenerateError = {
18937 get: function () {
18938 throw new Error("bundle.generate(...) now returns a Promise instead of a { code, map } object");
18939 }
18940};
18941function applyOptionHook(inputOptions, plugin) {
18942 if (plugin.options)
18943 return plugin.options.call({ meta: { rollupVersion: version } }, inputOptions) || inputOptions;
18944 return inputOptions;
18945}
18946function getInputOptions$1(rawInputOptions) {
18947 if (!rawInputOptions) {
18948 throw new Error('You must supply an options object to rollup');
18949 }
18950 var _a = mergeOptions({
18951 config: rawInputOptions
18952 }), inputOptions = _a.inputOptions, optionError = _a.optionError;
18953 if (optionError)
18954 inputOptions.onwarn({ message: optionError, code: 'UNKNOWN_OPTION' });
18955 var plugins = inputOptions.plugins;
18956 inputOptions.plugins = Array.isArray(plugins)
18957 ? plugins.filter(Boolean)
18958 : plugins
18959 ? [plugins]
18960 : [];
18961 inputOptions = inputOptions.plugins.reduce(applyOptionHook, inputOptions);
18962 if (inputOptions.inlineDynamicImports) {
18963 if (inputOptions.preserveModules)
18964 error({
18965 code: 'INVALID_OPTION',
18966 message: "\"preserveModules\" does not support the \"inlineDynamicImports\" option."
18967 });
18968 if (inputOptions.manualChunks)
18969 error({
18970 code: 'INVALID_OPTION',
18971 message: '"manualChunks" option is not supported for "inlineDynamicImports".'
18972 });
18973 if (inputOptions.experimentalOptimizeChunks)
18974 error({
18975 code: 'INVALID_OPTION',
18976 message: '"experimentalOptimizeChunks" option is not supported for "inlineDynamicImports".'
18977 });
18978 if ((inputOptions.input instanceof Array && inputOptions.input.length > 1) ||
18979 (typeof inputOptions.input === 'object' && Object.keys(inputOptions.input).length > 1))
18980 error({
18981 code: 'INVALID_OPTION',
18982 message: 'Multiple inputs are not supported for "inlineDynamicImports".'
18983 });
18984 }
18985 else if (inputOptions.preserveModules) {
18986 if (inputOptions.manualChunks)
18987 error({
18988 code: 'INVALID_OPTION',
18989 message: '"preserveModules" does not support the "manualChunks" option.'
18990 });
18991 if (inputOptions.experimentalOptimizeChunks)
18992 error({
18993 code: 'INVALID_OPTION',
18994 message: '"preserveModules" does not support the "experimentalOptimizeChunks" option.'
18995 });
18996 }
18997 return inputOptions;
18998}
18999var curWatcher;
19000function setWatcher(watcher) {
19001 curWatcher = watcher;
19002}
19003function rollup(rawInputOptions) {
19004 try {
19005 var inputOptions_1 = getInputOptions$1(rawInputOptions);
19006 initialiseTimers(inputOptions_1);
19007 var graph_1 = new Graph(inputOptions_1, curWatcher);
19008 curWatcher = undefined;
19009 // remove the cache option from the memory after graph creation (cache is not used anymore)
19010 var useCache_1 = rawInputOptions.cache !== false;
19011 delete inputOptions_1.cache;
19012 delete rawInputOptions.cache;
19013 timeStart('BUILD', 1);
19014 return graph_1.pluginDriver
19015 .hookParallel('buildStart', [inputOptions_1])
19016 .then(function () {
19017 return graph_1.build(inputOptions_1.input, inputOptions_1.manualChunks, inputOptions_1.inlineDynamicImports);
19018 })
19019 .then(function (chunks) { return graph_1.pluginDriver.hookParallel('buildEnd', []).then(function () { return chunks; }); }, function (err) {
19020 return graph_1.pluginDriver.hookParallel('buildEnd', [err]).then(function () {
19021 throw err;
19022 });
19023 })
19024 .then(function (chunks) {
19025 timeEnd('BUILD', 1);
19026 // ensure we only do one optimization pass per build
19027 var optimized = false;
19028 function getOutputOptions(rawOutputOptions) {
19029 return normalizeOutputOptions(inputOptions_1, rawOutputOptions, chunks.length > 1, graph_1.pluginDriver);
19030 }
19031 function generate(outputOptions, isWrite) {
19032 timeStart('GENERATE', 1);
19033 var assetFileNames = outputOptions.assetFileNames || 'assets/[name]-[hash][extname]';
19034 var outputBundle = graph_1.finaliseAssets(assetFileNames);
19035 var inputBase = commondir(getAbsoluteEntryModulePaths(chunks));
19036 return graph_1.pluginDriver
19037 .hookParallel('renderStart', [])
19038 .then(function () { return createAddons(graph_1, outputOptions); })
19039 .then(function (addons) {
19040 // pre-render all chunks
19041 for (var _i = 0, chunks_2 = chunks; _i < chunks_2.length; _i++) {
19042 var chunk = chunks_2[_i];
19043 if (!inputOptions_1.preserveModules)
19044 chunk.generateInternalExports(outputOptions);
19045 if (chunk.facadeModule && chunk.facadeModule.isEntryPoint)
19046 chunk.exportMode = getExportMode(chunk, outputOptions);
19047 }
19048 for (var _a = 0, chunks_3 = chunks; _a < chunks_3.length; _a++) {
19049 var chunk = chunks_3[_a];
19050 chunk.preRender(outputOptions, inputBase);
19051 }
19052 if (!optimized && inputOptions_1.experimentalOptimizeChunks) {
19053 optimizeChunks(chunks, outputOptions, inputOptions_1.chunkGroupingSize, inputBase);
19054 optimized = true;
19055 }
19056 assignChunkIds(chunks, inputOptions_1, outputOptions, inputBase, addons);
19057 var _loop_1 = function (i) {
19058 var chunk = chunks[i];
19059 var facadeModule = chunk.facadeModule;
19060 outputBundle[chunk.id] = {
19061 code: undefined,
19062 dynamicImports: chunk.getDynamicImportIds(),
19063 exports: chunk.getExportNames(),
19064 facadeModuleId: facadeModule && facadeModule.id,
19065 fileName: chunk.id,
19066 imports: chunk.getImportIds(),
19067 isDynamicEntry: facadeModule !== null && facadeModule.dynamicallyImportedBy.length > 0,
19068 isEntry: facadeModule !== null && facadeModule.isEntryPoint,
19069 map: undefined,
19070 modules: chunk.renderedModules,
19071 get name() {
19072 return chunk.getChunkName();
19073 }
19074 };
19075 };
19076 // assign to outputBundle
19077 for (var i = 0; i < chunks.length; i++) {
19078 _loop_1(i);
19079 }
19080 return Promise.all(chunks.map(function (chunk) {
19081 var outputChunk = outputBundle[chunk.id];
19082 return chunk.render(outputOptions, addons, outputChunk).then(function (rendered) {
19083 outputChunk.code = rendered.code;
19084 outputChunk.map = rendered.map;
19085 return graph_1.pluginDriver.hookParallel('ongenerate', [
19086 __assign({ bundle: outputChunk }, outputOptions),
19087 outputChunk
19088 ]);
19089 });
19090 })).then(function () { });
19091 })
19092 .catch(function (error) {
19093 return graph_1.pluginDriver.hookParallel('renderError', [error]).then(function () {
19094 throw error;
19095 });
19096 })
19097 .then(function () {
19098 // run generateBundle hook
19099 // assets emitted during generateBundle are unique to that specific generate call
19100 var assets = new Map(graph_1.assetsById);
19101 var generateAssetPluginHooks = createAssetPluginHooks(assets, outputBundle, assetFileNames);
19102 return graph_1.pluginDriver
19103 .hookSeq('generateBundle', [outputOptions, outputBundle, isWrite], function (context) { return (__assign({}, context, generateAssetPluginHooks)); })
19104 .then(function () {
19105 // throw errors for assets not finalised with a source
19106 assets.forEach(function (asset) {
19107 if (asset.fileName === undefined)
19108 finaliseAsset(asset, outputBundle, assetFileNames);
19109 });
19110 });
19111 })
19112 .then(function () {
19113 timeEnd('GENERATE', 1);
19114 return outputBundle;
19115 });
19116 }
19117 var cache = useCache_1 ? graph_1.getCache() : undefined;
19118 var result = {
19119 cache: cache,
19120 generate: (function (rawOutputOptions) {
19121 var promise = generate(getOutputOptions(rawOutputOptions), false).then(function (result) {
19122 return createOutput(result);
19123 });
19124 Object.defineProperty(promise, 'code', throwAsyncGenerateError);
19125 Object.defineProperty(promise, 'map', throwAsyncGenerateError);
19126 return promise;
19127 }),
19128 watchFiles: Object.keys(graph_1.watchFiles),
19129 write: (function (rawOutputOptions) {
19130 var outputOptions = getOutputOptions(rawOutputOptions);
19131 if (!outputOptions.dir && !outputOptions.file) {
19132 error({
19133 code: 'MISSING_OPTION',
19134 message: 'You must specify "output.file" or "output.dir" for the build.'
19135 });
19136 }
19137 return generate(outputOptions, true).then(function (bundle) {
19138 var chunkCnt = 0;
19139 for (var _i = 0, _a = Object.keys(bundle); _i < _a.length; _i++) {
19140 var fileName = _a[_i];
19141 var file = bundle[fileName];
19142 if (file.isAsset)
19143 continue;
19144 chunkCnt++;
19145 if (chunkCnt > 1)
19146 break;
19147 }
19148 if (chunkCnt > 1) {
19149 if (outputOptions.sourcemapFile)
19150 error({
19151 code: 'INVALID_OPTION',
19152 message: '"output.sourcemapFile" is only supported for single-file builds.'
19153 });
19154 if (typeof outputOptions.file === 'string')
19155 error({
19156 code: 'INVALID_OPTION',
19157 message: 'When building multiple chunks, the "output.dir" option must be used, not "output.file".' +
19158 (typeof inputOptions_1.input !== 'string' ||
19159 inputOptions_1.inlineDynamicImports === true
19160 ? ''
19161 : ' To inline dynamic imports, set the "inlineDynamicImports" option.')
19162 });
19163 }
19164 return Promise.all(Object.keys(bundle).map(function (chunkId) {
19165 return writeOutputFile(graph_1, result, bundle[chunkId], outputOptions);
19166 }))
19167 .then(function () { return graph_1.pluginDriver.hookParallel('writeBundle', [bundle]); })
19168 .then(function () { return createOutput(bundle); });
19169 });
19170 })
19171 };
19172 if (inputOptions_1.perf === true)
19173 result.getTimings = getTimings;
19174 return result;
19175 });
19176 }
19177 catch (err) {
19178 return Promise.reject(err);
19179 }
19180}
19181var SortingFileType;
19182(function (SortingFileType) {
19183 SortingFileType[SortingFileType["ENTRY_CHUNK"] = 0] = "ENTRY_CHUNK";
19184 SortingFileType[SortingFileType["SECONDARY_CHUNK"] = 1] = "SECONDARY_CHUNK";
19185 SortingFileType[SortingFileType["ASSET"] = 2] = "ASSET";
19186})(SortingFileType || (SortingFileType = {}));
19187function getSortingFileType(file) {
19188 if (file.isAsset) {
19189 return SortingFileType.ASSET;
19190 }
19191 if (file.isEntry) {
19192 return SortingFileType.ENTRY_CHUNK;
19193 }
19194 return SortingFileType.SECONDARY_CHUNK;
19195}
19196function createOutput(outputBundle) {
19197 return {
19198 output: Object.keys(outputBundle)
19199 .map(function (fileName) { return outputBundle[fileName]; })
19200 .sort(function (outputFileA, outputFileB) {
19201 var fileTypeA = getSortingFileType(outputFileA);
19202 var fileTypeB = getSortingFileType(outputFileB);
19203 if (fileTypeA === fileTypeB)
19204 return 0;
19205 return fileTypeA < fileTypeB ? -1 : 1;
19206 })
19207 };
19208}
19209function isOutputAsset(file) {
19210 return file.isAsset === true;
19211}
19212function writeOutputFile(graph, build, outputFile, outputOptions) {
19213 var fileName = resolve$1(outputOptions.dir || dirname(outputOptions.file), outputFile.fileName);
19214 var writeSourceMapPromise;
19215 var source;
19216 if (isOutputAsset(outputFile)) {
19217 source = outputFile.source;
19218 }
19219 else {
19220 source = outputFile.code;
19221 if (outputOptions.sourcemap && outputFile.map) {
19222 var url = void 0;
19223 if (outputOptions.sourcemap === 'inline') {
19224 url = outputFile.map.toUrl();
19225 }
19226 else {
19227 url = basename(outputFile.fileName) + ".map";
19228 writeSourceMapPromise = writeFile(fileName + ".map", outputFile.map.toString());
19229 }
19230 source += "//# " + SOURCEMAPPING_URL + "=" + url + "\n";
19231 }
19232 }
19233 return writeFile(fileName, source)
19234 .then(function () { return writeSourceMapPromise; })
19235 .then(function () {
19236 return !isOutputAsset(outputFile) &&
19237 graph.pluginDriver.hookSeq('onwrite', [
19238 __assign({ bundle: build }, outputOptions),
19239 outputFile
19240 ]);
19241 })
19242 .then(function () { });
19243}
19244function normalizeOutputOptions(inputOptions, rawOutputOptions, hasMultipleChunks, pluginDriver) {
19245 if (!rawOutputOptions) {
19246 throw new Error('You must supply an options object');
19247 }
19248 var mergedOptions = mergeOptions({
19249 config: {
19250 output: __assign({}, rawOutputOptions, rawOutputOptions.output, inputOptions.output)
19251 }
19252 });
19253 if (mergedOptions.optionError)
19254 throw new Error(mergedOptions.optionError);
19255 // now outputOptions is an array, but rollup.rollup API doesn't support arrays
19256 var mergedOutputOptions = mergedOptions.outputOptions[0];
19257 var outputOptionsReducer = function (outputOptions, result) {
19258 return result || outputOptions;
19259 };
19260 var outputOptions = pluginDriver.hookReduceArg0Sync('outputOptions', [mergedOutputOptions], outputOptionsReducer);
19261 checkOutputOptions(outputOptions);
19262 if (typeof outputOptions.file === 'string') {
19263 if (typeof outputOptions.dir === 'string')
19264 error({
19265 code: 'INVALID_OPTION',
19266 message: 'You must set either "output.file" for a single-file build or "output.dir" when generating multiple chunks.'
19267 });
19268 if (inputOptions.preserveModules) {
19269 error({
19270 code: 'INVALID_OPTION',
19271 message: 'You must set "output.dir" instead of "output.file" when using the "preserveModules" option.'
19272 });
19273 }
19274 if (typeof inputOptions.input === 'object' && !Array.isArray(inputOptions.input))
19275 error({
19276 code: 'INVALID_OPTION',
19277 message: 'You must set "output.dir" instead of "output.file" when providing named inputs.'
19278 });
19279 }
19280 if (hasMultipleChunks) {
19281 if (outputOptions.format === 'umd' || outputOptions.format === 'iife')
19282 error({
19283 code: 'INVALID_OPTION',
19284 message: 'UMD and IIFE output formats are not supported for code-splitting builds.'
19285 });
19286 if (typeof outputOptions.file === 'string')
19287 error({
19288 code: 'INVALID_OPTION',
19289 message: 'You must set "output.dir" instead of "output.file" when generating multiple chunks.'
19290 });
19291 }
19292 return outputOptions;
19293}
19294
19295var types = {
19296 ROOT : 0,
19297 GROUP : 1,
19298 POSITION : 2,
19299 SET : 3,
19300 RANGE : 4,
19301 REPETITION : 5,
19302 REFERENCE : 6,
19303 CHAR : 7,
19304};
19305
19306var INTS = function() {
19307 return [{ type: types.RANGE , from: 48, to: 57 }];
19308};
19309
19310var WORDS = function() {
19311 return [
19312 { type: types.CHAR, value: 95 },
19313 { type: types.RANGE, from: 97, to: 122 },
19314 { type: types.RANGE, from: 65, to: 90 }
19315 ].concat(INTS());
19316};
19317
19318var WHITESPACE$1 = function() {
19319 return [
19320 { type: types.CHAR, value: 9 },
19321 { type: types.CHAR, value: 10 },
19322 { type: types.CHAR, value: 11 },
19323 { type: types.CHAR, value: 12 },
19324 { type: types.CHAR, value: 13 },
19325 { type: types.CHAR, value: 32 },
19326 { type: types.CHAR, value: 160 },
19327 { type: types.CHAR, value: 5760 },
19328 { type: types.CHAR, value: 6158 },
19329 { type: types.CHAR, value: 8192 },
19330 { type: types.CHAR, value: 8193 },
19331 { type: types.CHAR, value: 8194 },
19332 { type: types.CHAR, value: 8195 },
19333 { type: types.CHAR, value: 8196 },
19334 { type: types.CHAR, value: 8197 },
19335 { type: types.CHAR, value: 8198 },
19336 { type: types.CHAR, value: 8199 },
19337 { type: types.CHAR, value: 8200 },
19338 { type: types.CHAR, value: 8201 },
19339 { type: types.CHAR, value: 8202 },
19340 { type: types.CHAR, value: 8232 },
19341 { type: types.CHAR, value: 8233 },
19342 { type: types.CHAR, value: 8239 },
19343 { type: types.CHAR, value: 8287 },
19344 { type: types.CHAR, value: 12288 },
19345 { type: types.CHAR, value: 65279 }
19346 ];
19347};
19348
19349var NOTANYCHAR = function() {
19350 return [
19351 { type: types.CHAR, value: 10 },
19352 { type: types.CHAR, value: 13 },
19353 { type: types.CHAR, value: 8232 },
19354 { type: types.CHAR, value: 8233 },
19355 ];
19356};
19357
19358// Predefined class objects.
19359var words = function() {
19360 return { type: types.SET, set: WORDS(), not: false };
19361};
19362
19363var notWords = function() {
19364 return { type: types.SET, set: WORDS(), not: true };
19365};
19366
19367var ints = function() {
19368 return { type: types.SET, set: INTS(), not: false };
19369};
19370
19371var notInts = function() {
19372 return { type: types.SET, set: INTS(), not: true };
19373};
19374
19375var whitespace = function() {
19376 return { type: types.SET, set: WHITESPACE$1(), not: false };
19377};
19378
19379var notWhitespace = function() {
19380 return { type: types.SET, set: WHITESPACE$1(), not: true };
19381};
19382
19383var anyChar = function() {
19384 return { type: types.SET, set: NOTANYCHAR(), not: true };
19385};
19386
19387var sets = {
19388 words: words,
19389 notWords: notWords,
19390 ints: ints,
19391 notInts: notInts,
19392 whitespace: whitespace,
19393 notWhitespace: notWhitespace,
19394 anyChar: anyChar
19395};
19396
19397var util = createCommonjsModule(function (module, exports) {
19398// All of these are private and only used by randexp.
19399// It's assumed that they will always be called with the correct input.
19400
19401var CTRL = '@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?';
19402var SLSH = { '0': 0, 't': 9, 'n': 10, 'v': 11, 'f': 12, 'r': 13 };
19403
19404/**
19405 * Finds character representations in str and convert all to
19406 * their respective characters
19407 *
19408 * @param {String} str
19409 * @return {String}
19410 */
19411exports.strToChars = function(str) {
19412 /* jshint maxlen: false */
19413 var chars_regex = /(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z\[\\\]\^?])|([0tnvfr]))/g;
19414 str = str.replace(chars_regex, function(s, b, lbs, a16, b16, c8, dctrl, eslsh) {
19415 if (lbs) {
19416 return s;
19417 }
19418
19419 var code = b ? 8 :
19420 a16 ? parseInt(a16, 16) :
19421 b16 ? parseInt(b16, 16) :
19422 c8 ? parseInt(c8, 8) :
19423 dctrl ? CTRL.indexOf(dctrl) :
19424 SLSH[eslsh];
19425
19426 var c = String.fromCharCode(code);
19427
19428 // Escape special regex characters.
19429 if (/[\[\]{}\^$.|?*+()]/.test(c)) {
19430 c = '\\' + c;
19431 }
19432
19433 return c;
19434 });
19435
19436 return str;
19437};
19438
19439
19440/**
19441 * turns class into tokens
19442 * reads str until it encounters a ] not preceeded by a \
19443 *
19444 * @param {String} str
19445 * @param {String} regexpStr
19446 * @return {Array.<Array.<Object>, Number>}
19447 */
19448exports.tokenizeClass = function(str, regexpStr) {
19449 /* jshint maxlen: false */
19450 var tokens = [];
19451 var regexp = /\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g;
19452 var rs, c;
19453
19454
19455 while ((rs = regexp.exec(str)) != null) {
19456 if (rs[1]) {
19457 tokens.push(sets.words());
19458
19459 } else if (rs[2]) {
19460 tokens.push(sets.ints());
19461
19462 } else if (rs[3]) {
19463 tokens.push(sets.whitespace());
19464
19465 } else if (rs[4]) {
19466 tokens.push(sets.notWords());
19467
19468 } else if (rs[5]) {
19469 tokens.push(sets.notInts());
19470
19471 } else if (rs[6]) {
19472 tokens.push(sets.notWhitespace());
19473
19474 } else if (rs[7]) {
19475 tokens.push({
19476 type: types.RANGE,
19477 from: (rs[8] || rs[9]).charCodeAt(0),
19478 to: rs[10].charCodeAt(0),
19479 });
19480
19481 } else if (c = rs[12]) {
19482 tokens.push({
19483 type: types.CHAR,
19484 value: c.charCodeAt(0),
19485 });
19486
19487 } else {
19488 return [tokens, regexp.lastIndex];
19489 }
19490 }
19491
19492 exports.error(regexpStr, 'Unterminated character class');
19493};
19494
19495
19496/**
19497 * Shortcut to throw errors.
19498 *
19499 * @param {String} regexp
19500 * @param {String} msg
19501 */
19502exports.error = function(regexp, msg) {
19503 throw new SyntaxError('Invalid regular expression: /' + regexp + '/: ' + msg);
19504};
19505});
19506
19507var wordBoundary = function() {
19508 return { type: types.POSITION, value: 'b' };
19509};
19510
19511var nonWordBoundary = function() {
19512 return { type: types.POSITION, value: 'B' };
19513};
19514
19515var begin = function() {
19516 return { type: types.POSITION, value: '^' };
19517};
19518
19519var end = function() {
19520 return { type: types.POSITION, value: '$' };
19521};
19522
19523var positions = {
19524 wordBoundary: wordBoundary,
19525 nonWordBoundary: nonWordBoundary,
19526 begin: begin,
19527 end: end
19528};
19529
19530var lib = function(regexpStr) {
19531 var i = 0, l, c,
19532 start = { type: types.ROOT, stack: []},
19533
19534 // Keep track of last clause/group and stack.
19535 lastGroup = start,
19536 last = start.stack,
19537 groupStack = [];
19538
19539
19540 var repeatErr = function(i) {
19541 util.error(regexpStr, 'Nothing to repeat at column ' + (i - 1));
19542 };
19543
19544 // Decode a few escaped characters.
19545 var str = util.strToChars(regexpStr);
19546 l = str.length;
19547
19548 // Iterate through each character in string.
19549 while (i < l) {
19550 c = str[i++];
19551
19552 switch (c) {
19553 // Handle escaped characters, inclues a few sets.
19554 case '\\':
19555 c = str[i++];
19556
19557 switch (c) {
19558 case 'b':
19559 last.push(positions.wordBoundary());
19560 break;
19561
19562 case 'B':
19563 last.push(positions.nonWordBoundary());
19564 break;
19565
19566 case 'w':
19567 last.push(sets.words());
19568 break;
19569
19570 case 'W':
19571 last.push(sets.notWords());
19572 break;
19573
19574 case 'd':
19575 last.push(sets.ints());
19576 break;
19577
19578 case 'D':
19579 last.push(sets.notInts());
19580 break;
19581
19582 case 's':
19583 last.push(sets.whitespace());
19584 break;
19585
19586 case 'S':
19587 last.push(sets.notWhitespace());
19588 break;
19589
19590 default:
19591 // Check if c is integer.
19592 // In which case it's a reference.
19593 if (/\d/.test(c)) {
19594 last.push({ type: types.REFERENCE, value: parseInt(c, 10) });
19595
19596 // Escaped character.
19597 } else {
19598 last.push({ type: types.CHAR, value: c.charCodeAt(0) });
19599 }
19600 }
19601
19602 break;
19603
19604
19605 // Positionals.
19606 case '^':
19607 last.push(positions.begin());
19608 break;
19609
19610 case '$':
19611 last.push(positions.end());
19612 break;
19613
19614
19615 // Handle custom sets.
19616 case '[':
19617 // Check if this class is 'anti' i.e. [^abc].
19618 var not;
19619 if (str[i] === '^') {
19620 not = true;
19621 i++;
19622 } else {
19623 not = false;
19624 }
19625
19626 // Get all the characters in class.
19627 var classTokens = util.tokenizeClass(str.slice(i), regexpStr);
19628
19629 // Increase index by length of class.
19630 i += classTokens[1];
19631 last.push({
19632 type: types.SET,
19633 set: classTokens[0],
19634 not: not,
19635 });
19636
19637 break;
19638
19639
19640 // Class of any character except \n.
19641 case '.':
19642 last.push(sets.anyChar());
19643 break;
19644
19645
19646 // Push group onto stack.
19647 case '(':
19648 // Create group.
19649 var group = {
19650 type: types.GROUP,
19651 stack: [],
19652 remember: true,
19653 };
19654
19655 c = str[i];
19656
19657 // If if this is a special kind of group.
19658 if (c === '?') {
19659 c = str[i + 1];
19660 i += 2;
19661
19662 // Match if followed by.
19663 if (c === '=') {
19664 group.followedBy = true;
19665
19666 // Match if not followed by.
19667 } else if (c === '!') {
19668 group.notFollowedBy = true;
19669
19670 } else if (c !== ':') {
19671 util.error(regexpStr,
19672 'Invalid group, character \'' + c +
19673 '\' after \'?\' at column ' + (i - 1));
19674 }
19675
19676 group.remember = false;
19677 }
19678
19679 // Insert subgroup into current group stack.
19680 last.push(group);
19681
19682 // Remember the current group for when the group closes.
19683 groupStack.push(lastGroup);
19684
19685 // Make this new group the current group.
19686 lastGroup = group;
19687 last = group.stack;
19688 break;
19689
19690
19691 // Pop group out of stack.
19692 case ')':
19693 if (groupStack.length === 0) {
19694 util.error(regexpStr, 'Unmatched ) at column ' + (i - 1));
19695 }
19696 lastGroup = groupStack.pop();
19697
19698 // Check if this group has a PIPE.
19699 // To get back the correct last stack.
19700 last = lastGroup.options ?
19701 lastGroup.options[lastGroup.options.length - 1] : lastGroup.stack;
19702 break;
19703
19704
19705 // Use pipe character to give more choices.
19706 case '|':
19707 // Create array where options are if this is the first PIPE
19708 // in this clause.
19709 if (!lastGroup.options) {
19710 lastGroup.options = [lastGroup.stack];
19711 delete lastGroup.stack;
19712 }
19713
19714 // Create a new stack and add to options for rest of clause.
19715 var stack = [];
19716 lastGroup.options.push(stack);
19717 last = stack;
19718 break;
19719
19720
19721 // Repetition.
19722 // For every repetition, remove last element from last stack
19723 // then insert back a RANGE object.
19724 // This design is chosen because there could be more than
19725 // one repetition symbols in a regex i.e. `a?+{2,3}`.
19726 case '{':
19727 var rs = /^(\d+)(,(\d+)?)?\}/.exec(str.slice(i)), min, max;
19728 if (rs !== null) {
19729 if (last.length === 0) {
19730 repeatErr(i);
19731 }
19732 min = parseInt(rs[1], 10);
19733 max = rs[2] ? rs[3] ? parseInt(rs[3], 10) : Infinity : min;
19734 i += rs[0].length;
19735
19736 last.push({
19737 type: types.REPETITION,
19738 min: min,
19739 max: max,
19740 value: last.pop(),
19741 });
19742 } else {
19743 last.push({
19744 type: types.CHAR,
19745 value: 123,
19746 });
19747 }
19748 break;
19749
19750 case '?':
19751 if (last.length === 0) {
19752 repeatErr(i);
19753 }
19754 last.push({
19755 type: types.REPETITION,
19756 min: 0,
19757 max: 1,
19758 value: last.pop(),
19759 });
19760 break;
19761
19762 case '+':
19763 if (last.length === 0) {
19764 repeatErr(i);
19765 }
19766 last.push({
19767 type: types.REPETITION,
19768 min: 1,
19769 max: Infinity,
19770 value: last.pop(),
19771 });
19772 break;
19773
19774 case '*':
19775 if (last.length === 0) {
19776 repeatErr(i);
19777 }
19778 last.push({
19779 type: types.REPETITION,
19780 min: 0,
19781 max: Infinity,
19782 value: last.pop(),
19783 });
19784 break;
19785
19786
19787 // Default is a character that is not `\[](){}?+*^$`.
19788 default:
19789 last.push({
19790 type: types.CHAR,
19791 value: c.charCodeAt(0),
19792 });
19793 }
19794
19795 }
19796
19797 // Check if any groups have not been closed.
19798 if (groupStack.length !== 0) {
19799 util.error(regexpStr, 'Unterminated group');
19800 }
19801
19802 return start;
19803};
19804
19805var types_1 = types;
19806lib.types = types_1;
19807
19808var types$1 = lib.types;
19809
19810var safeRegex = function (re, opts) {
19811 if (!opts) opts = {};
19812 var replimit = opts.limit === undefined ? 25 : opts.limit;
19813
19814 if (isRegExp(re)) re = re.source;
19815 else if (typeof re !== 'string') re = String(re);
19816
19817 try { re = lib(re); }
19818 catch (err) { return false }
19819
19820 var reps = 0;
19821 return (function walk (node, starHeight) {
19822 if (node.type === types$1.REPETITION) {
19823 starHeight ++;
19824 reps ++;
19825 if (starHeight > 1) return false;
19826 if (reps > replimit) return false;
19827 }
19828
19829 if (node.options) {
19830 for (var i = 0, len = node.options.length; i < len; i++) {
19831 var ok = walk({ stack: node.options[i] }, starHeight);
19832 if (!ok) return false;
19833 }
19834 }
19835 var stack = node.stack || (node.value && node.value.stack);
19836 if (!stack) return true;
19837
19838 for (var i = 0; i < stack.length; i++) {
19839 var ok = walk(stack[i], starHeight);
19840 if (!ok) return false;
19841 }
19842
19843 return true;
19844 })(re, 0);
19845};
19846
19847function isRegExp (x) {
19848 return {}.toString.call(x) === '[object RegExp]';
19849}
19850
19851/*!
19852 * isobject <https://github.com/jonschlinkert/isobject>
19853 *
19854 * Copyright (c) 2014-2017, Jon Schlinkert.
19855 * Released under the MIT License.
19856 */
19857
19858var isobject = function isObject(val) {
19859 return val != null && typeof val === 'object' && Array.isArray(val) === false;
19860};
19861
19862var toString$1 = Object.prototype.toString;
19863
19864var kindOf = function kindOf(val) {
19865 if (val === void 0) return 'undefined';
19866 if (val === null) return 'null';
19867
19868 var type = typeof val;
19869 if (type === 'boolean') return 'boolean';
19870 if (type === 'string') return 'string';
19871 if (type === 'number') return 'number';
19872 if (type === 'symbol') return 'symbol';
19873 if (type === 'function') {
19874 return isGeneratorFn(val) ? 'generatorfunction' : 'function';
19875 }
19876
19877 if (isArray(val)) return 'array';
19878 if (isBuffer(val)) return 'buffer';
19879 if (isArguments(val)) return 'arguments';
19880 if (isDate(val)) return 'date';
19881 if (isError(val)) return 'error';
19882 if (isRegexp(val)) return 'regexp';
19883
19884 switch (ctorName(val)) {
19885 case 'Symbol': return 'symbol';
19886 case 'Promise': return 'promise';
19887
19888 // Set, Map, WeakSet, WeakMap
19889 case 'WeakMap': return 'weakmap';
19890 case 'WeakSet': return 'weakset';
19891 case 'Map': return 'map';
19892 case 'Set': return 'set';
19893
19894 // 8-bit typed arrays
19895 case 'Int8Array': return 'int8array';
19896 case 'Uint8Array': return 'uint8array';
19897 case 'Uint8ClampedArray': return 'uint8clampedarray';
19898
19899 // 16-bit typed arrays
19900 case 'Int16Array': return 'int16array';
19901 case 'Uint16Array': return 'uint16array';
19902
19903 // 32-bit typed arrays
19904 case 'Int32Array': return 'int32array';
19905 case 'Uint32Array': return 'uint32array';
19906 case 'Float32Array': return 'float32array';
19907 case 'Float64Array': return 'float64array';
19908 }
19909
19910 if (isGeneratorObj(val)) {
19911 return 'generator';
19912 }
19913
19914 // Non-plain objects
19915 type = toString$1.call(val);
19916 switch (type) {
19917 case '[object Object]': return 'object';
19918 // iterators
19919 case '[object Map Iterator]': return 'mapiterator';
19920 case '[object Set Iterator]': return 'setiterator';
19921 case '[object String Iterator]': return 'stringiterator';
19922 case '[object Array Iterator]': return 'arrayiterator';
19923 }
19924
19925 // other
19926 return type.slice(8, -1).toLowerCase().replace(/\s/g, '');
19927};
19928
19929function ctorName(val) {
19930 return val.constructor ? val.constructor.name : null;
19931}
19932
19933function isArray(val) {
19934 if (Array.isArray) return Array.isArray(val);
19935 return val instanceof Array;
19936}
19937
19938function isError(val) {
19939 return val instanceof Error || (typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number');
19940}
19941
19942function isDate(val) {
19943 if (val instanceof Date) return true;
19944 return typeof val.toDateString === 'function'
19945 && typeof val.getDate === 'function'
19946 && typeof val.setDate === 'function';
19947}
19948
19949function isRegexp(val) {
19950 if (val instanceof RegExp) return true;
19951 return typeof val.flags === 'string'
19952 && typeof val.ignoreCase === 'boolean'
19953 && typeof val.multiline === 'boolean'
19954 && typeof val.global === 'boolean';
19955}
19956
19957function isGeneratorFn(name, val) {
19958 return ctorName(name) === 'GeneratorFunction';
19959}
19960
19961function isGeneratorObj(val) {
19962 return typeof val.throw === 'function'
19963 && typeof val.return === 'function'
19964 && typeof val.next === 'function';
19965}
19966
19967function isArguments(val) {
19968 try {
19969 if (typeof val.length === 'number' && typeof val.callee === 'function') {
19970 return true;
19971 }
19972 } catch (err) {
19973 if (err.message.indexOf('callee') !== -1) {
19974 return true;
19975 }
19976 }
19977 return false;
19978}
19979
19980/**
19981 * If you need to support Safari 5-7 (8-10 yr-old browser),
19982 * take a look at https://github.com/feross/is-buffer
19983 */
19984
19985function isBuffer(val) {
19986 if (val.constructor && typeof val.constructor.isBuffer === 'function') {
19987 return val.constructor.isBuffer(val);
19988 }
19989 return false;
19990}
19991
19992// accessor descriptor properties
19993var accessor = {
19994 get: 'function',
19995 set: 'function',
19996 configurable: 'boolean',
19997 enumerable: 'boolean'
19998};
19999
20000function isAccessorDescriptor(obj, prop) {
20001 if (typeof prop === 'string') {
20002 var val = Object.getOwnPropertyDescriptor(obj, prop);
20003 return typeof val !== 'undefined';
20004 }
20005
20006 if (kindOf(obj) !== 'object') {
20007 return false;
20008 }
20009
20010 if (has$1(obj, 'value') || has$1(obj, 'writable')) {
20011 return false;
20012 }
20013
20014 if (!has$1(obj, 'get') || typeof obj.get !== 'function') {
20015 return false;
20016 }
20017
20018 // tldr: it's valid to have "set" be undefined
20019 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
20020 // was used to get the value, and only `get` was defined by the user
20021 if (has$1(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
20022 return false;
20023 }
20024
20025 for (var key in obj) {
20026 if (!accessor.hasOwnProperty(key)) {
20027 continue;
20028 }
20029
20030 if (kindOf(obj[key]) === accessor[key]) {
20031 continue;
20032 }
20033
20034 if (typeof obj[key] !== 'undefined') {
20035 return false;
20036 }
20037 }
20038 return true;
20039}
20040
20041function has$1(obj, key) {
20042 return {}.hasOwnProperty.call(obj, key);
20043}
20044
20045/**
20046 * Expose `isAccessorDescriptor`
20047 */
20048
20049var isAccessorDescriptor_1 = isAccessorDescriptor;
20050
20051var isDataDescriptor = function isDataDescriptor(obj, prop) {
20052 // data descriptor properties
20053 var data = {
20054 configurable: 'boolean',
20055 enumerable: 'boolean',
20056 writable: 'boolean'
20057 };
20058
20059 if (kindOf(obj) !== 'object') {
20060 return false;
20061 }
20062
20063 if (typeof prop === 'string') {
20064 var val = Object.getOwnPropertyDescriptor(obj, prop);
20065 return typeof val !== 'undefined';
20066 }
20067
20068 if (!('value' in obj) && !('writable' in obj)) {
20069 return false;
20070 }
20071
20072 for (var key in obj) {
20073 if (key === 'value') continue;
20074
20075 if (!data.hasOwnProperty(key)) {
20076 continue;
20077 }
20078
20079 if (kindOf(obj[key]) === data[key]) {
20080 continue;
20081 }
20082
20083 if (typeof obj[key] !== 'undefined') {
20084 return false;
20085 }
20086 }
20087 return true;
20088};
20089
20090var isDescriptor = function isDescriptor(obj, key) {
20091 if (kindOf(obj) !== 'object') {
20092 return false;
20093 }
20094 if ('get' in obj) {
20095 return isAccessorDescriptor_1(obj, key);
20096 }
20097 return isDataDescriptor(obj, key);
20098};
20099
20100var define = (typeof Reflect !== 'undefined' && Reflect.defineProperty)
20101 ? Reflect.defineProperty
20102 : Object.defineProperty;
20103
20104var defineProperty = function defineProperty(obj, key, val) {
20105 if (!isobject(obj) && typeof obj !== 'function' && !Array.isArray(obj)) {
20106 throw new TypeError('expected an object, function, or array');
20107 }
20108
20109 if (typeof key !== 'string') {
20110 throw new TypeError('expected "key" to be a string');
20111 }
20112
20113 if (isDescriptor(val)) {
20114 define(obj, key, val);
20115 return obj;
20116 }
20117
20118 define(obj, key, {
20119 configurable: true,
20120 enumerable: false,
20121 writable: true,
20122 value: val
20123 });
20124
20125 return obj;
20126};
20127
20128function isObjectObject(o) {
20129 return isobject(o) === true
20130 && Object.prototype.toString.call(o) === '[object Object]';
20131}
20132
20133var isPlainObject = function isPlainObject(o) {
20134 var ctor,prot;
20135
20136 if (isObjectObject(o) === false) return false;
20137
20138 // If has modified constructor
20139 ctor = o.constructor;
20140 if (typeof ctor !== 'function') return false;
20141
20142 // If has modified prototype
20143 prot = ctor.prototype;
20144 if (isObjectObject(prot) === false) return false;
20145
20146 // If constructor does not have an Object-specific method
20147 if (prot.hasOwnProperty('isPrototypeOf') === false) {
20148 return false;
20149 }
20150
20151 // Most likely a plain Object
20152 return true;
20153};
20154
20155var isExtendable = function isExtendable(val) {
20156 return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);
20157};
20158
20159/*!
20160 * assign-symbols <https://github.com/jonschlinkert/assign-symbols>
20161 *
20162 * Copyright (c) 2015, Jon Schlinkert.
20163 * Licensed under the MIT License.
20164 */
20165
20166var assignSymbols = function(receiver, objects) {
20167 if (receiver === null || typeof receiver === 'undefined') {
20168 throw new TypeError('expected first argument to be an object.');
20169 }
20170
20171 if (typeof objects === 'undefined' || typeof Symbol === 'undefined') {
20172 return receiver;
20173 }
20174
20175 if (typeof Object.getOwnPropertySymbols !== 'function') {
20176 return receiver;
20177 }
20178
20179 var isEnumerable = Object.prototype.propertyIsEnumerable;
20180 var target = Object(receiver);
20181 var len = arguments.length, i = 0;
20182
20183 while (++i < len) {
20184 var provider = Object(arguments[i]);
20185 var names = Object.getOwnPropertySymbols(provider);
20186
20187 for (var j = 0; j < names.length; j++) {
20188 var key = names[j];
20189
20190 if (isEnumerable.call(provider, key)) {
20191 target[key] = provider[key];
20192 }
20193 }
20194 }
20195 return target;
20196};
20197
20198var extendShallow = Object.assign || function(obj/*, objects*/) {
20199 if (obj === null || typeof obj === 'undefined') {
20200 throw new TypeError('Cannot convert undefined or null to object');
20201 }
20202 if (!isObject$1(obj)) {
20203 obj = {};
20204 }
20205 for (var i = 1; i < arguments.length; i++) {
20206 var val = arguments[i];
20207 if (isString(val)) {
20208 val = toObject$1(val);
20209 }
20210 if (isObject$1(val)) {
20211 assign(obj, val);
20212 assignSymbols(obj, val);
20213 }
20214 }
20215 return obj;
20216};
20217
20218function assign(a, b) {
20219 for (var key in b) {
20220 if (hasOwn(b, key)) {
20221 a[key] = b[key];
20222 }
20223 }
20224}
20225
20226function isString(val) {
20227 return (val && typeof val === 'string');
20228}
20229
20230function toObject$1(str) {
20231 var obj = {};
20232 for (var i in str) {
20233 obj[i] = str[i];
20234 }
20235 return obj;
20236}
20237
20238function isObject$1(val) {
20239 return (val && typeof val === 'object') || isExtendable(val);
20240}
20241
20242/**
20243 * Returns true if the given `key` is an own property of `obj`.
20244 */
20245
20246function hasOwn(obj, key) {
20247 return Object.prototype.hasOwnProperty.call(obj, key);
20248}
20249
20250/**
20251 * The main export is a function that takes a `pattern` string and an `options` object.
20252 *
20253 * ```js
20254 & var not = require('regex-not');
20255 & console.log(not('foo'));
20256 & //=> /^(?:(?!^(?:foo)$).)*$/
20257 * ```
20258 *
20259 * @param {String} `pattern`
20260 * @param {Object} `options`
20261 * @return {RegExp} Converts the given `pattern` to a regex using the specified `options`.
20262 * @api public
20263 */
20264
20265function toRegex(pattern, options) {
20266 return new RegExp(toRegex.create(pattern, options));
20267}
20268
20269/**
20270 * Create a regex-compatible string from the given `pattern` and `options`.
20271 *
20272 * ```js
20273 & var not = require('regex-not');
20274 & console.log(not.create('foo'));
20275 & //=> '^(?:(?!^(?:foo)$).)*$'
20276 * ```
20277 * @param {String} `pattern`
20278 * @param {Object} `options`
20279 * @return {String}
20280 * @api public
20281 */
20282
20283toRegex.create = function(pattern, options) {
20284 if (typeof pattern !== 'string') {
20285 throw new TypeError('expected a string');
20286 }
20287
20288 var opts = extendShallow({}, options);
20289 if (opts.contains === true) {
20290 opts.strictNegate = false;
20291 }
20292
20293 var open = opts.strictOpen !== false ? '^' : '';
20294 var close = opts.strictClose !== false ? '$' : '';
20295 var endChar = opts.endChar ? opts.endChar : '+';
20296 var str = pattern;
20297
20298 if (opts.strictNegate === false) {
20299 str = '(?:(?!(?:' + pattern + ')).)' + endChar;
20300 } else {
20301 str = '(?:(?!^(?:' + pattern + ')$).)' + endChar;
20302 }
20303
20304 var res = open + str + close;
20305 if (opts.safe === true && safeRegex(res) === false) {
20306 throw new Error('potentially unsafe regular expression: ' + res);
20307 }
20308
20309 return res;
20310};
20311
20312/**
20313 * Expose `toRegex`
20314 */
20315
20316var regexNot = toRegex;
20317
20318var MAX_LENGTH = 1024 * 64;
20319
20320/**
20321 * Session cache
20322 */
20323
20324var cache = {};
20325
20326/**
20327 * Create a regular expression from the given `pattern` string.
20328 *
20329 * @param {String|RegExp} `pattern` Pattern can be a string or regular expression.
20330 * @param {Object} `options`
20331 * @return {RegExp}
20332 * @api public
20333 */
20334
20335var toRegex$1 = function(patterns, options) {
20336 if (!Array.isArray(patterns)) {
20337 return makeRe(patterns, options);
20338 }
20339 return makeRe(patterns.join('|'), options);
20340};
20341
20342/**
20343 * Create a regular expression from the given `pattern` string.
20344 *
20345 * @param {String|RegExp} `pattern` Pattern can be a string or regular expression.
20346 * @param {Object} `options`
20347 * @return {RegExp}
20348 * @api public
20349 */
20350
20351function makeRe(pattern, options) {
20352 if (pattern instanceof RegExp) {
20353 return pattern;
20354 }
20355
20356 if (typeof pattern !== 'string') {
20357 throw new TypeError('expected a string');
20358 }
20359
20360 if (pattern.length > MAX_LENGTH) {
20361 throw new Error('expected pattern to be less than ' + MAX_LENGTH + ' characters');
20362 }
20363
20364 var key = pattern;
20365 // do this before shallow cloning options, it's a lot faster
20366 if (!options || (options && options.cache !== false)) {
20367 key = createKey(pattern, options);
20368
20369 if (cache.hasOwnProperty(key)) {
20370 return cache[key];
20371 }
20372 }
20373
20374 var opts = extendShallow({}, options);
20375 if (opts.contains === true) {
20376 if (opts.negate === true) {
20377 opts.strictNegate = false;
20378 } else {
20379 opts.strict = false;
20380 }
20381 }
20382
20383 if (opts.strict === false) {
20384 opts.strictOpen = false;
20385 opts.strictClose = false;
20386 }
20387
20388 var open = opts.strictOpen !== false ? '^' : '';
20389 var close = opts.strictClose !== false ? '$' : '';
20390 var flags = opts.flags || '';
20391 var regex;
20392
20393 if (opts.nocase === true && !/i/.test(flags)) {
20394 flags += 'i';
20395 }
20396
20397 try {
20398 if (opts.negate || typeof opts.strictNegate === 'boolean') {
20399 pattern = regexNot.create(pattern, opts);
20400 }
20401
20402 var str = open + '(?:' + pattern + ')' + close;
20403 regex = new RegExp(str, flags);
20404
20405 if (opts.safe === true && safeRegex(regex) === false) {
20406 throw new Error('potentially unsafe regular expression: ' + regex.source);
20407 }
20408
20409 } catch (err) {
20410 if (opts.strictErrors === true || opts.safe === true) {
20411 err.key = key;
20412 err.pattern = pattern;
20413 err.originalOptions = options;
20414 err.createdOptions = opts;
20415 throw err;
20416 }
20417
20418 try {
20419 regex = new RegExp('^' + pattern.replace(/(\W)/g, '\\$1') + '$');
20420 } catch (err) {
20421 regex = /.^/; //<= match nothing
20422 }
20423 }
20424
20425 if (opts.cache !== false) {
20426 memoize(regex, key, pattern, opts);
20427 }
20428 return regex;
20429}
20430
20431/**
20432 * Memoize generated regex. This can result in dramatic speed improvements
20433 * and simplify debugging by adding options and pattern to the regex. It can be
20434 * disabled by passing setting `options.cache` to false.
20435 */
20436
20437function memoize(regex, key, pattern, options) {
20438 defineProperty(regex, 'cached', true);
20439 defineProperty(regex, 'pattern', pattern);
20440 defineProperty(regex, 'options', options);
20441 defineProperty(regex, 'key', key);
20442 cache[key] = regex;
20443}
20444
20445/**
20446 * Create the key to use for memoization. The key is generated
20447 * by iterating over the options and concatenating key-value pairs
20448 * to the pattern string.
20449 */
20450
20451function createKey(pattern, options) {
20452 if (!options) return pattern;
20453 var key = pattern;
20454 for (var prop in options) {
20455 if (options.hasOwnProperty(prop)) {
20456 key += ';' + prop + '=' + String(options[prop]);
20457 }
20458 }
20459 return key;
20460}
20461
20462/**
20463 * Expose `makeRe`
20464 */
20465
20466var makeRe_1 = makeRe;
20467toRegex$1.makeRe = makeRe_1;
20468
20469var arrayUnique = createCommonjsModule(function (module) {
20470
20471module.exports = function unique(arr) {
20472 if (!Array.isArray(arr)) {
20473 throw new TypeError('array-unique expects an array.');
20474 }
20475
20476 var len = arr.length;
20477 var i = -1;
20478
20479 while (i++ < len) {
20480 var j = i + 1;
20481
20482 for (; j < arr.length; ++j) {
20483 if (arr[i] === arr[j]) {
20484 arr.splice(j--, 1);
20485 }
20486 }
20487 }
20488 return arr;
20489};
20490
20491module.exports.immutable = function uniqueImmutable(arr) {
20492 if (!Array.isArray(arr)) {
20493 throw new TypeError('array-unique expects an array.');
20494 }
20495
20496 var arrLen = arr.length;
20497 var newArr = new Array(arrLen);
20498
20499 for (var i = 0; i < arrLen; i++) {
20500 newArr[i] = arr[i];
20501 }
20502
20503 return module.exports(newArr);
20504};
20505});
20506
20507/*!
20508 * is-extendable <https://github.com/jonschlinkert/is-extendable>
20509 *
20510 * Copyright (c) 2015, Jon Schlinkert.
20511 * Licensed under the MIT License.
20512 */
20513
20514var isExtendable$1 = function isExtendable(val) {
20515 return typeof val !== 'undefined' && val !== null
20516 && (typeof val === 'object' || typeof val === 'function');
20517};
20518
20519var extendShallow$1 = function extend(o/*, objects*/) {
20520 if (!isExtendable$1(o)) { o = {}; }
20521
20522 var len = arguments.length;
20523 for (var i = 1; i < len; i++) {
20524 var obj = arguments[i];
20525
20526 if (isExtendable$1(obj)) {
20527 assign$1(o, obj);
20528 }
20529 }
20530 return o;
20531};
20532
20533function assign$1(a, b) {
20534 for (var key in b) {
20535 if (hasOwn$1(b, key)) {
20536 a[key] = b[key];
20537 }
20538 }
20539}
20540
20541/**
20542 * Returns true if the given `key` is an own property of `obj`.
20543 */
20544
20545function hasOwn$1(obj, key) {
20546 return Object.prototype.hasOwnProperty.call(obj, key);
20547}
20548
20549var splitString = function(str, options, fn) {
20550 if (typeof str !== 'string') {
20551 throw new TypeError('expected a string');
20552 }
20553
20554 if (typeof options === 'function') {
20555 fn = options;
20556 options = null;
20557 }
20558
20559 // allow separator to be defined as a string
20560 if (typeof options === 'string') {
20561 options = { sep: options };
20562 }
20563
20564 var opts = extendShallow({sep: '.'}, options);
20565 var quotes = opts.quotes || ['"', "'", '`'];
20566 var brackets;
20567
20568 if (opts.brackets === true) {
20569 brackets = {
20570 '<': '>',
20571 '(': ')',
20572 '[': ']',
20573 '{': '}'
20574 };
20575 } else if (opts.brackets) {
20576 brackets = opts.brackets;
20577 }
20578
20579 var tokens = [];
20580 var stack = [];
20581 var arr = [''];
20582 var sep = opts.sep;
20583 var len = str.length;
20584 var idx = -1;
20585 var closeIdx;
20586
20587 function expected() {
20588 if (brackets && stack.length) {
20589 return brackets[stack[stack.length - 1]];
20590 }
20591 }
20592
20593 while (++idx < len) {
20594 var ch = str[idx];
20595 var next = str[idx + 1];
20596 var tok = { val: ch, idx: idx, arr: arr, str: str };
20597 tokens.push(tok);
20598
20599 if (ch === '\\') {
20600 tok.val = keepEscaping(opts, str, idx) === true ? (ch + next) : next;
20601 tok.escaped = true;
20602 if (typeof fn === 'function') {
20603 fn(tok);
20604 }
20605 arr[arr.length - 1] += tok.val;
20606 idx++;
20607 continue;
20608 }
20609
20610 if (brackets && brackets[ch]) {
20611 stack.push(ch);
20612 var e = expected();
20613 var i = idx + 1;
20614
20615 if (str.indexOf(e, i + 1) !== -1) {
20616 while (stack.length && i < len) {
20617 var s = str[++i];
20618 if (s === '\\') {
20619 s++;
20620 continue;
20621 }
20622
20623 if (quotes.indexOf(s) !== -1) {
20624 i = getClosingQuote(str, s, i + 1);
20625 continue;
20626 }
20627
20628 e = expected();
20629 if (stack.length && str.indexOf(e, i + 1) === -1) {
20630 break;
20631 }
20632
20633 if (brackets[s]) {
20634 stack.push(s);
20635 continue;
20636 }
20637
20638 if (e === s) {
20639 stack.pop();
20640 }
20641 }
20642 }
20643
20644 closeIdx = i;
20645 if (closeIdx === -1) {
20646 arr[arr.length - 1] += ch;
20647 continue;
20648 }
20649
20650 ch = str.slice(idx, closeIdx + 1);
20651 tok.val = ch;
20652 tok.idx = idx = closeIdx;
20653 }
20654
20655 if (quotes.indexOf(ch) !== -1) {
20656 closeIdx = getClosingQuote(str, ch, idx + 1);
20657 if (closeIdx === -1) {
20658 arr[arr.length - 1] += ch;
20659 continue;
20660 }
20661
20662 if (keepQuotes(ch, opts) === true) {
20663 ch = str.slice(idx, closeIdx + 1);
20664 } else {
20665 ch = str.slice(idx + 1, closeIdx);
20666 }
20667
20668 tok.val = ch;
20669 tok.idx = idx = closeIdx;
20670 }
20671
20672 if (typeof fn === 'function') {
20673 fn(tok, tokens);
20674 ch = tok.val;
20675 idx = tok.idx;
20676 }
20677
20678 if (tok.val === sep && tok.split !== false) {
20679 arr.push('');
20680 continue;
20681 }
20682
20683 arr[arr.length - 1] += tok.val;
20684 }
20685
20686 return arr;
20687};
20688
20689function getClosingQuote(str, ch, i, brackets) {
20690 var idx = str.indexOf(ch, i);
20691 if (str.charAt(idx - 1) === '\\') {
20692 return getClosingQuote(str, ch, idx + 1);
20693 }
20694 return idx;
20695}
20696
20697function keepQuotes(ch, opts) {
20698 if (opts.keepDoubleQuotes === true && ch === '"') return true;
20699 if (opts.keepSingleQuotes === true && ch === "'") return true;
20700 return opts.keepQuotes;
20701}
20702
20703function keepEscaping(opts, str, idx) {
20704 if (typeof opts.keepEscaping === 'function') {
20705 return opts.keepEscaping(str, idx);
20706 }
20707 return opts.keepEscaping === true || str[idx + 1] === '\\';
20708}
20709
20710/*!
20711 * arr-flatten <https://github.com/jonschlinkert/arr-flatten>
20712 *
20713 * Copyright (c) 2014-2017, Jon Schlinkert.
20714 * Released under the MIT License.
20715 */
20716
20717var arrFlatten = function (arr) {
20718 return flat(arr, []);
20719};
20720
20721function flat(arr, res) {
20722 var i = 0, cur;
20723 var len = arr.length;
20724 for (; i < len; i++) {
20725 cur = arr[i];
20726 Array.isArray(cur) ? flat(cur, res) : res.push(cur);
20727 }
20728 return res;
20729}
20730
20731/*!
20732 * Determine if an object is a Buffer
20733 *
20734 * @author Feross Aboukhadijeh <https://feross.org>
20735 * @license MIT
20736 */
20737
20738// The _isBuffer check is for Safari 5-7 support, because it's missing
20739// Object.prototype.constructor. Remove this eventually
20740var isBuffer_1 = function (obj) {
20741 return obj != null && (isBuffer$1(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
20742};
20743
20744function isBuffer$1 (obj) {
20745 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
20746}
20747
20748// For Node v0.10 support. Remove this eventually.
20749function isSlowBuffer (obj) {
20750 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer$1(obj.slice(0, 0))
20751}
20752
20753var toString$2 = Object.prototype.toString;
20754
20755/**
20756 * Get the native `typeof` a value.
20757 *
20758 * @param {*} `val`
20759 * @return {*} Native javascript type
20760 */
20761
20762var kindOf$1 = function kindOf(val) {
20763 // primitivies
20764 if (typeof val === 'undefined') {
20765 return 'undefined';
20766 }
20767 if (val === null) {
20768 return 'null';
20769 }
20770 if (val === true || val === false || val instanceof Boolean) {
20771 return 'boolean';
20772 }
20773 if (typeof val === 'string' || val instanceof String) {
20774 return 'string';
20775 }
20776 if (typeof val === 'number' || val instanceof Number) {
20777 return 'number';
20778 }
20779
20780 // functions
20781 if (typeof val === 'function' || val instanceof Function) {
20782 return 'function';
20783 }
20784
20785 // array
20786 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
20787 return 'array';
20788 }
20789
20790 // check for instances of RegExp and Date before calling `toString`
20791 if (val instanceof RegExp) {
20792 return 'regexp';
20793 }
20794 if (val instanceof Date) {
20795 return 'date';
20796 }
20797
20798 // other objects
20799 var type = toString$2.call(val);
20800
20801 if (type === '[object RegExp]') {
20802 return 'regexp';
20803 }
20804 if (type === '[object Date]') {
20805 return 'date';
20806 }
20807 if (type === '[object Arguments]') {
20808 return 'arguments';
20809 }
20810 if (type === '[object Error]') {
20811 return 'error';
20812 }
20813
20814 // buffer
20815 if (isBuffer_1(val)) {
20816 return 'buffer';
20817 }
20818
20819 // es6: Map, WeakMap, Set, WeakSet
20820 if (type === '[object Set]') {
20821 return 'set';
20822 }
20823 if (type === '[object WeakSet]') {
20824 return 'weakset';
20825 }
20826 if (type === '[object Map]') {
20827 return 'map';
20828 }
20829 if (type === '[object WeakMap]') {
20830 return 'weakmap';
20831 }
20832 if (type === '[object Symbol]') {
20833 return 'symbol';
20834 }
20835
20836 // typed arrays
20837 if (type === '[object Int8Array]') {
20838 return 'int8array';
20839 }
20840 if (type === '[object Uint8Array]') {
20841 return 'uint8array';
20842 }
20843 if (type === '[object Uint8ClampedArray]') {
20844 return 'uint8clampedarray';
20845 }
20846 if (type === '[object Int16Array]') {
20847 return 'int16array';
20848 }
20849 if (type === '[object Uint16Array]') {
20850 return 'uint16array';
20851 }
20852 if (type === '[object Int32Array]') {
20853 return 'int32array';
20854 }
20855 if (type === '[object Uint32Array]') {
20856 return 'uint32array';
20857 }
20858 if (type === '[object Float32Array]') {
20859 return 'float32array';
20860 }
20861 if (type === '[object Float64Array]') {
20862 return 'float64array';
20863 }
20864
20865 // must be a plain object
20866 return 'object';
20867};
20868
20869var isNumber = function isNumber(num) {
20870 var type = kindOf$1(num);
20871
20872 if (type === 'string') {
20873 if (!num.trim()) return false;
20874 } else if (type !== 'number') {
20875 return false;
20876 }
20877
20878 return (num - num + 1) >= 0;
20879};
20880
20881var extendShallow$2 = function extend(o/*, objects*/) {
20882 if (!isExtendable$1(o)) { o = {}; }
20883
20884 var len = arguments.length;
20885 for (var i = 1; i < len; i++) {
20886 var obj = arguments[i];
20887
20888 if (isExtendable$1(obj)) {
20889 assign$2(o, obj);
20890 }
20891 }
20892 return o;
20893};
20894
20895function assign$2(a, b) {
20896 for (var key in b) {
20897 if (hasOwn$2(b, key)) {
20898 a[key] = b[key];
20899 }
20900 }
20901}
20902
20903/**
20904 * Returns true if the given `key` is an own property of `obj`.
20905 */
20906
20907function hasOwn$2(obj, key) {
20908 return Object.prototype.hasOwnProperty.call(obj, key);
20909}
20910
20911/*!
20912 * repeat-string <https://github.com/jonschlinkert/repeat-string>
20913 *
20914 * Copyright (c) 2014-2015, Jon Schlinkert.
20915 * Licensed under the MIT License.
20916 */
20917
20918/**
20919 * Results cache
20920 */
20921
20922var res = '';
20923var cache$1;
20924
20925/**
20926 * Expose `repeat`
20927 */
20928
20929var repeatString = repeat;
20930
20931/**
20932 * Repeat the given `string` the specified `number`
20933 * of times.
20934 *
20935 * **Example:**
20936 *
20937 * ```js
20938 * var repeat = require('repeat-string');
20939 * repeat('A', 5);
20940 * //=> AAAAA
20941 * ```
20942 *
20943 * @param {String} `string` The string to repeat
20944 * @param {Number} `number` The number of times to repeat the string
20945 * @return {String} Repeated string
20946 * @api public
20947 */
20948
20949function repeat(str, num) {
20950 if (typeof str !== 'string') {
20951 throw new TypeError('expected a string');
20952 }
20953
20954 // cover common, quick use cases
20955 if (num === 1) return str;
20956 if (num === 2) return str + str;
20957
20958 var max = str.length * num;
20959 if (cache$1 !== str || typeof cache$1 === 'undefined') {
20960 cache$1 = str;
20961 res = '';
20962 } else if (res.length >= max) {
20963 return res.substr(0, max);
20964 }
20965
20966 while (max > res.length && num > 1) {
20967 if (num & 1) {
20968 res += str;
20969 }
20970
20971 num >>= 1;
20972 str += str;
20973 }
20974
20975 res += str;
20976 res = res.substr(0, max);
20977 return res;
20978}
20979
20980var cache$2 = {};
20981
20982function toRegexRange(min, max, options) {
20983 if (isNumber(min) === false) {
20984 throw new RangeError('toRegexRange: first argument is invalid.');
20985 }
20986
20987 if (typeof max === 'undefined' || min === max) {
20988 return String(min);
20989 }
20990
20991 if (isNumber(max) === false) {
20992 throw new RangeError('toRegexRange: second argument is invalid.');
20993 }
20994
20995 options = options || {};
20996 var relax = String(options.relaxZeros);
20997 var shorthand = String(options.shorthand);
20998 var capture = String(options.capture);
20999 var key = min + ':' + max + '=' + relax + shorthand + capture;
21000 if (cache$2.hasOwnProperty(key)) {
21001 return cache$2[key].result;
21002 }
21003
21004 var a = Math.min(min, max);
21005 var b = Math.max(min, max);
21006
21007 if (Math.abs(a - b) === 1) {
21008 var result = min + '|' + max;
21009 if (options.capture) {
21010 return '(' + result + ')';
21011 }
21012 return result;
21013 }
21014
21015 var isPadded = padding(min) || padding(max);
21016 var positives = [];
21017 var negatives = [];
21018
21019 var tok = {min: min, max: max, a: a, b: b};
21020 if (isPadded) {
21021 tok.isPadded = isPadded;
21022 tok.maxLen = String(tok.max).length;
21023 }
21024
21025 if (a < 0) {
21026 var newMin = b < 0 ? Math.abs(b) : 1;
21027 var newMax = Math.abs(a);
21028 negatives = splitToPatterns(newMin, newMax, tok, options);
21029 a = tok.a = 0;
21030 }
21031
21032 if (b >= 0) {
21033 positives = splitToPatterns(a, b, tok, options);
21034 }
21035
21036 tok.negatives = negatives;
21037 tok.positives = positives;
21038 tok.result = siftPatterns(negatives, positives, options);
21039
21040 if (options.capture && (positives.length + negatives.length) > 1) {
21041 tok.result = '(' + tok.result + ')';
21042 }
21043
21044 cache$2[key] = tok;
21045 return tok.result;
21046}
21047
21048function siftPatterns(neg, pos, options) {
21049 var onlyNegative = filterPatterns(neg, pos, '-', false, options) || [];
21050 var onlyPositive = filterPatterns(pos, neg, '', false, options) || [];
21051 var intersected = filterPatterns(neg, pos, '-?', true, options) || [];
21052 var subpatterns = onlyNegative.concat(intersected).concat(onlyPositive);
21053 return subpatterns.join('|');
21054}
21055
21056function splitToRanges(min, max) {
21057 min = Number(min);
21058 max = Number(max);
21059
21060 var nines = 1;
21061 var stops = [max];
21062 var stop = +countNines(min, nines);
21063
21064 while (min <= stop && stop <= max) {
21065 stops = push(stops, stop);
21066 nines += 1;
21067 stop = +countNines(min, nines);
21068 }
21069
21070 var zeros = 1;
21071 stop = countZeros(max + 1, zeros) - 1;
21072
21073 while (min < stop && stop <= max) {
21074 stops = push(stops, stop);
21075 zeros += 1;
21076 stop = countZeros(max + 1, zeros) - 1;
21077 }
21078
21079 stops.sort(compare);
21080 return stops;
21081}
21082
21083/**
21084 * Convert a range to a regex pattern
21085 * @param {Number} `start`
21086 * @param {Number} `stop`
21087 * @return {String}
21088 */
21089
21090function rangeToPattern(start, stop, options) {
21091 if (start === stop) {
21092 return {pattern: String(start), digits: []};
21093 }
21094
21095 var zipped = zip(String(start), String(stop));
21096 var len = zipped.length, i = -1;
21097
21098 var pattern = '';
21099 var digits = 0;
21100
21101 while (++i < len) {
21102 var numbers = zipped[i];
21103 var startDigit = numbers[0];
21104 var stopDigit = numbers[1];
21105
21106 if (startDigit === stopDigit) {
21107 pattern += startDigit;
21108
21109 } else if (startDigit !== '0' || stopDigit !== '9') {
21110 pattern += toCharacterClass(startDigit, stopDigit);
21111
21112 } else {
21113 digits += 1;
21114 }
21115 }
21116
21117 if (digits) {
21118 pattern += options.shorthand ? '\\d' : '[0-9]';
21119 }
21120
21121 return { pattern: pattern, digits: [digits] };
21122}
21123
21124function splitToPatterns(min, max, tok, options) {
21125 var ranges = splitToRanges(min, max);
21126 var len = ranges.length;
21127 var idx = -1;
21128
21129 var tokens = [];
21130 var start = min;
21131 var prev;
21132
21133 while (++idx < len) {
21134 var range = ranges[idx];
21135 var obj = rangeToPattern(start, range, options);
21136 var zeros = '';
21137
21138 if (!tok.isPadded && prev && prev.pattern === obj.pattern) {
21139 if (prev.digits.length > 1) {
21140 prev.digits.pop();
21141 }
21142 prev.digits.push(obj.digits[0]);
21143 prev.string = prev.pattern + toQuantifier(prev.digits);
21144 start = range + 1;
21145 continue;
21146 }
21147
21148 if (tok.isPadded) {
21149 zeros = padZeros(range, tok);
21150 }
21151
21152 obj.string = zeros + obj.pattern + toQuantifier(obj.digits);
21153 tokens.push(obj);
21154 start = range + 1;
21155 prev = obj;
21156 }
21157
21158 return tokens;
21159}
21160
21161function filterPatterns(arr, comparison, prefix, intersection, options) {
21162 var res = [];
21163
21164 for (var i = 0; i < arr.length; i++) {
21165 var tok = arr[i];
21166 var ele = tok.string;
21167
21168 if (options.relaxZeros !== false) {
21169 if (prefix === '-' && ele.charAt(0) === '0') {
21170 if (ele.charAt(1) === '{') {
21171 ele = '0*' + ele.replace(/^0\{\d+\}/, '');
21172 } else {
21173 ele = '0*' + ele.slice(1);
21174 }
21175 }
21176 }
21177
21178 if (!intersection && !contains(comparison, 'string', ele)) {
21179 res.push(prefix + ele);
21180 }
21181
21182 if (intersection && contains(comparison, 'string', ele)) {
21183 res.push(prefix + ele);
21184 }
21185 }
21186 return res;
21187}
21188
21189/**
21190 * Zip strings (`for in` can be used on string characters)
21191 */
21192
21193function zip(a, b) {
21194 var arr = [];
21195 for (var ch in a) arr.push([a[ch], b[ch]]);
21196 return arr;
21197}
21198
21199function compare(a, b) {
21200 return a > b ? 1 : b > a ? -1 : 0;
21201}
21202
21203function push(arr, ele) {
21204 if (arr.indexOf(ele) === -1) arr.push(ele);
21205 return arr;
21206}
21207
21208function contains(arr, key, val) {
21209 for (var i = 0; i < arr.length; i++) {
21210 if (arr[i][key] === val) {
21211 return true;
21212 }
21213 }
21214 return false;
21215}
21216
21217function countNines(min, len) {
21218 return String(min).slice(0, -len) + repeatString('9', len);
21219}
21220
21221function countZeros(integer, zeros) {
21222 return integer - (integer % Math.pow(10, zeros));
21223}
21224
21225function toQuantifier(digits) {
21226 var start = digits[0];
21227 var stop = digits[1] ? (',' + digits[1]) : '';
21228 if (!stop && (!start || start === 1)) {
21229 return '';
21230 }
21231 return '{' + start + stop + '}';
21232}
21233
21234function toCharacterClass(a, b) {
21235 return '[' + a + ((b - a === 1) ? '' : '-') + b + ']';
21236}
21237
21238function padding(str) {
21239 return /^-?(0+)\d/.exec(str);
21240}
21241
21242function padZeros(val, tok) {
21243 if (tok.isPadded) {
21244 var diff = Math.abs(tok.maxLen - String(val).length);
21245 switch (diff) {
21246 case 0:
21247 return '';
21248 case 1:
21249 return '0';
21250 default: {
21251 return '0{' + diff + '}';
21252 }
21253 }
21254 }
21255 return val;
21256}
21257
21258/**
21259 * Expose `toRegexRange`
21260 */
21261
21262var toRegexRange_1 = toRegexRange;
21263
21264/**
21265 * Return a range of numbers or letters.
21266 *
21267 * @param {String} `start` Start of the range
21268 * @param {String} `stop` End of the range
21269 * @param {String} `step` Increment or decrement to use.
21270 * @param {Function} `fn` Custom function to modify each element in the range.
21271 * @return {Array}
21272 */
21273
21274function fillRange(start, stop, step, options) {
21275 if (typeof start === 'undefined') {
21276 return [];
21277 }
21278
21279 if (typeof stop === 'undefined' || start === stop) {
21280 // special case, for handling negative zero
21281 var isString = typeof start === 'string';
21282 if (isNumber(start) && !toNumber(start)) {
21283 return [isString ? '0' : 0];
21284 }
21285 return [start];
21286 }
21287
21288 if (typeof step !== 'number' && typeof step !== 'string') {
21289 options = step;
21290 step = undefined;
21291 }
21292
21293 if (typeof options === 'function') {
21294 options = { transform: options };
21295 }
21296
21297 var opts = extendShallow$2({step: step}, options);
21298 if (opts.step && !isValidNumber(opts.step)) {
21299 if (opts.strictRanges === true) {
21300 throw new TypeError('expected options.step to be a number');
21301 }
21302 return [];
21303 }
21304
21305 opts.isNumber = isValidNumber(start) && isValidNumber(stop);
21306 if (!opts.isNumber && !isValid(start, stop)) {
21307 if (opts.strictRanges === true) {
21308 throw new RangeError('invalid range arguments: ' + util$2.inspect([start, stop]));
21309 }
21310 return [];
21311 }
21312
21313 opts.isPadded = isPadded(start) || isPadded(stop);
21314 opts.toString = opts.stringify
21315 || typeof opts.step === 'string'
21316 || typeof start === 'string'
21317 || typeof stop === 'string'
21318 || !opts.isNumber;
21319
21320 if (opts.isPadded) {
21321 opts.maxLength = Math.max(String(start).length, String(stop).length);
21322 }
21323
21324 // support legacy minimatch/fill-range options
21325 if (typeof opts.optimize === 'boolean') opts.toRegex = opts.optimize;
21326 if (typeof opts.makeRe === 'boolean') opts.toRegex = opts.makeRe;
21327 return expand(start, stop, opts);
21328}
21329
21330function expand(start, stop, options) {
21331 var a = options.isNumber ? toNumber(start) : start.charCodeAt(0);
21332 var b = options.isNumber ? toNumber(stop) : stop.charCodeAt(0);
21333
21334 var step = Math.abs(toNumber(options.step)) || 1;
21335 if (options.toRegex && step === 1) {
21336 return toRange(a, b, start, stop, options);
21337 }
21338
21339 var zero = {greater: [], lesser: []};
21340 var asc = a < b;
21341 var arr = new Array(Math.round((asc ? b - a : a - b) / step));
21342 var idx = 0;
21343
21344 while (asc ? a <= b : a >= b) {
21345 var val = options.isNumber ? a : String.fromCharCode(a);
21346 if (options.toRegex && (val >= 0 || !options.isNumber)) {
21347 zero.greater.push(val);
21348 } else {
21349 zero.lesser.push(Math.abs(val));
21350 }
21351
21352 if (options.isPadded) {
21353 val = zeros(val, options);
21354 }
21355
21356 if (options.toString) {
21357 val = String(val);
21358 }
21359
21360 if (typeof options.transform === 'function') {
21361 arr[idx++] = options.transform(val, a, b, step, idx, arr, options);
21362 } else {
21363 arr[idx++] = val;
21364 }
21365
21366 if (asc) {
21367 a += step;
21368 } else {
21369 a -= step;
21370 }
21371 }
21372
21373 if (options.toRegex === true) {
21374 return toSequence(arr, zero, options);
21375 }
21376 return arr;
21377}
21378
21379function toRange(a, b, start, stop, options) {
21380 if (options.isPadded) {
21381 return toRegexRange_1(start, stop, options);
21382 }
21383
21384 if (options.isNumber) {
21385 return toRegexRange_1(Math.min(a, b), Math.max(a, b), options);
21386 }
21387
21388 var start = String.fromCharCode(Math.min(a, b));
21389 var stop = String.fromCharCode(Math.max(a, b));
21390 return '[' + start + '-' + stop + ']';
21391}
21392
21393function toSequence(arr, zeros, options) {
21394 var greater = '', lesser = '';
21395 if (zeros.greater.length) {
21396 greater = zeros.greater.join('|');
21397 }
21398 if (zeros.lesser.length) {
21399 lesser = '-(' + zeros.lesser.join('|') + ')';
21400 }
21401 var res = greater && lesser
21402 ? greater + '|' + lesser
21403 : greater || lesser;
21404
21405 if (options.capture) {
21406 return '(' + res + ')';
21407 }
21408 return res;
21409}
21410
21411function zeros(val, options) {
21412 if (options.isPadded) {
21413 var str = String(val);
21414 var len = str.length;
21415 var dash = '';
21416 if (str.charAt(0) === '-') {
21417 dash = '-';
21418 str = str.slice(1);
21419 }
21420 var diff = options.maxLength - len;
21421 var pad = repeatString('0', diff);
21422 val = (dash + pad + str);
21423 }
21424 if (options.stringify) {
21425 return String(val);
21426 }
21427 return val;
21428}
21429
21430function toNumber(val) {
21431 return Number(val) || 0;
21432}
21433
21434function isPadded(str) {
21435 return /^-?0\d/.test(str);
21436}
21437
21438function isValid(min, max) {
21439 return (isValidNumber(min) || isValidLetter(min))
21440 && (isValidNumber(max) || isValidLetter(max));
21441}
21442
21443function isValidLetter(ch) {
21444 return typeof ch === 'string' && ch.length === 1 && /^\w+$/.test(ch);
21445}
21446
21447function isValidNumber(n) {
21448 return isNumber(n) && !/\./.test(n);
21449}
21450
21451/**
21452 * Expose `fillRange`
21453 * @type {Function}
21454 */
21455
21456var fillRange_1 = fillRange;
21457
21458/*!
21459 * repeat-element <https://github.com/jonschlinkert/repeat-element>
21460 *
21461 * Copyright (c) 2015-present, Jon Schlinkert.
21462 * Licensed under the MIT license.
21463 */
21464
21465var repeatElement = function repeat(ele, num) {
21466 var arr = new Array(num);
21467
21468 for (var i = 0; i < num; i++) {
21469 arr[i] = ele;
21470 }
21471
21472 return arr;
21473};
21474
21475var utils_1 = createCommonjsModule(function (module) {
21476
21477
21478var utils = module.exports;
21479
21480/**
21481 * Module dependencies
21482 */
21483
21484utils.extend = extendShallow$1;
21485utils.flatten = arrFlatten;
21486utils.isObject = isobject;
21487utils.fillRange = fillRange_1;
21488utils.repeat = repeatElement;
21489utils.unique = arrayUnique;
21490
21491utils.define = function(obj, key, val) {
21492 Object.defineProperty(obj, key, {
21493 writable: true,
21494 configurable: true,
21495 enumerable: false,
21496 value: val
21497 });
21498};
21499
21500/**
21501 * Returns true if the given string contains only empty brace sets.
21502 */
21503
21504utils.isEmptySets = function(str) {
21505 return /^(?:\{,\})+$/.test(str);
21506};
21507
21508/**
21509 * Returns true if the given string contains only empty brace sets.
21510 */
21511
21512utils.isQuotedString = function(str) {
21513 var open = str.charAt(0);
21514 if (open === '\'' || open === '"' || open === '`') {
21515 return str.slice(-1) === open;
21516 }
21517 return false;
21518};
21519
21520/**
21521 * Create the key to use for memoization. The unique key is generated
21522 * by iterating over the options and concatenating key-value pairs
21523 * to the pattern string.
21524 */
21525
21526utils.createKey = function(pattern, options) {
21527 var id = pattern;
21528 if (typeof options === 'undefined') {
21529 return id;
21530 }
21531 var keys = Object.keys(options);
21532 for (var i = 0; i < keys.length; i++) {
21533 var key = keys[i];
21534 id += ';' + key + '=' + String(options[key]);
21535 }
21536 return id;
21537};
21538
21539/**
21540 * Normalize options
21541 */
21542
21543utils.createOptions = function(options) {
21544 var opts = utils.extend.apply(null, arguments);
21545 if (typeof opts.expand === 'boolean') {
21546 opts.optimize = !opts.expand;
21547 }
21548 if (typeof opts.optimize === 'boolean') {
21549 opts.expand = !opts.optimize;
21550 }
21551 if (opts.optimize === true) {
21552 opts.makeRe = true;
21553 }
21554 return opts;
21555};
21556
21557/**
21558 * Join patterns in `a` to patterns in `b`
21559 */
21560
21561utils.join = function(a, b, options) {
21562 options = options || {};
21563 a = utils.arrayify(a);
21564 b = utils.arrayify(b);
21565
21566 if (!a.length) return b;
21567 if (!b.length) return a;
21568
21569 var len = a.length;
21570 var idx = -1;
21571 var arr = [];
21572
21573 while (++idx < len) {
21574 var val = a[idx];
21575 if (Array.isArray(val)) {
21576 for (var i = 0; i < val.length; i++) {
21577 val[i] = utils.join(val[i], b, options);
21578 }
21579 arr.push(val);
21580 continue;
21581 }
21582
21583 for (var j = 0; j < b.length; j++) {
21584 var bval = b[j];
21585
21586 if (Array.isArray(bval)) {
21587 arr.push(utils.join(val, bval, options));
21588 } else {
21589 arr.push(val + bval);
21590 }
21591 }
21592 }
21593 return arr;
21594};
21595
21596/**
21597 * Split the given string on `,` if not escaped.
21598 */
21599
21600utils.split = function(str, options) {
21601 var opts = utils.extend({sep: ','}, options);
21602 if (typeof opts.keepQuotes !== 'boolean') {
21603 opts.keepQuotes = true;
21604 }
21605 if (opts.unescape === false) {
21606 opts.keepEscaping = true;
21607 }
21608 return splitString(str, opts, utils.escapeBrackets(opts));
21609};
21610
21611/**
21612 * Expand ranges or sets in the given `pattern`.
21613 *
21614 * @param {String} `str`
21615 * @param {Object} `options`
21616 * @return {Object}
21617 */
21618
21619utils.expand = function(str, options) {
21620 var opts = utils.extend({rangeLimit: 10000}, options);
21621 var segs = utils.split(str, opts);
21622 var tok = { segs: segs };
21623
21624 if (utils.isQuotedString(str)) {
21625 return tok;
21626 }
21627
21628 if (opts.rangeLimit === true) {
21629 opts.rangeLimit = 10000;
21630 }
21631
21632 if (segs.length > 1) {
21633 if (opts.optimize === false) {
21634 tok.val = segs[0];
21635 return tok;
21636 }
21637
21638 tok.segs = utils.stringifyArray(tok.segs);
21639 } else if (segs.length === 1) {
21640 var arr = str.split('..');
21641
21642 if (arr.length === 1) {
21643 tok.val = tok.segs[tok.segs.length - 1] || tok.val || str;
21644 tok.segs = [];
21645 return tok;
21646 }
21647
21648 if (arr.length === 2 && arr[0] === arr[1]) {
21649 tok.escaped = true;
21650 tok.val = arr[0];
21651 tok.segs = [];
21652 return tok;
21653 }
21654
21655 if (arr.length > 1) {
21656 if (opts.optimize !== false) {
21657 opts.optimize = true;
21658 delete opts.expand;
21659 }
21660
21661 if (opts.optimize !== true) {
21662 var min = Math.min(arr[0], arr[1]);
21663 var max = Math.max(arr[0], arr[1]);
21664 var step = arr[2] || 1;
21665
21666 if (opts.rangeLimit !== false && ((max - min) / step >= opts.rangeLimit)) {
21667 throw new RangeError('expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.');
21668 }
21669 }
21670
21671 arr.push(opts);
21672 tok.segs = utils.fillRange.apply(null, arr);
21673
21674 if (!tok.segs.length) {
21675 tok.escaped = true;
21676 tok.val = str;
21677 return tok;
21678 }
21679
21680 if (opts.optimize === true) {
21681 tok.segs = utils.stringifyArray(tok.segs);
21682 }
21683
21684 if (tok.segs === '') {
21685 tok.val = str;
21686 } else {
21687 tok.val = tok.segs[0];
21688 }
21689 return tok;
21690 }
21691 } else {
21692 tok.val = str;
21693 }
21694 return tok;
21695};
21696
21697/**
21698 * Ensure commas inside brackets and parens are not split.
21699 * @param {Object} `tok` Token from the `split-string` module
21700 * @return {undefined}
21701 */
21702
21703utils.escapeBrackets = function(options) {
21704 return function(tok) {
21705 if (tok.escaped && tok.val === 'b') {
21706 tok.val = '\\b';
21707 return;
21708 }
21709
21710 if (tok.val !== '(' && tok.val !== '[') return;
21711 var opts = utils.extend({}, options);
21712 var stack = [];
21713 var val = tok.val;
21714 var str = tok.str;
21715 var i = tok.idx - 1;
21716
21717 while (++i < str.length) {
21718 var ch = str[i];
21719
21720 if (ch === '\\') {
21721 val += (opts.keepEscaping === false ? '' : ch) + str[++i];
21722 continue;
21723 }
21724
21725 if (ch === '(') {
21726 stack.push(ch);
21727 }
21728
21729 if (ch === '[') {
21730 stack.push(ch);
21731 }
21732
21733 if (ch === ')') {
21734 stack.pop();
21735 if (!stack.length) {
21736 val += ch;
21737 break;
21738 }
21739 }
21740
21741 if (ch === ']') {
21742 stack.pop();
21743 if (!stack.length) {
21744 val += ch;
21745 break;
21746 }
21747 }
21748 val += ch;
21749 }
21750
21751 tok.split = false;
21752 tok.val = val.slice(1);
21753 tok.idx = i;
21754 };
21755};
21756
21757/**
21758 * Returns true if the given string looks like a regex quantifier
21759 * @return {Boolean}
21760 */
21761
21762utils.isQuantifier = function(str) {
21763 return /^(?:[0-9]?,[0-9]|[0-9],)$/.test(str);
21764};
21765
21766/**
21767 * Cast `val` to an array.
21768 * @param {*} `val`
21769 */
21770
21771utils.stringifyArray = function(arr) {
21772 return [utils.arrayify(arr).join('|')];
21773};
21774
21775/**
21776 * Cast `val` to an array.
21777 * @param {*} `val`
21778 */
21779
21780utils.arrayify = function(arr) {
21781 if (typeof arr === 'undefined') {
21782 return [];
21783 }
21784 if (typeof arr === 'string') {
21785 return [arr];
21786 }
21787 return arr;
21788};
21789
21790/**
21791 * Returns true if the given `str` is a non-empty string
21792 * @return {Boolean}
21793 */
21794
21795utils.isString = function(str) {
21796 return str != null && typeof str === 'string';
21797};
21798
21799/**
21800 * Get the last element from `array`
21801 * @param {Array} `array`
21802 * @return {*}
21803 */
21804
21805utils.last = function(arr, n) {
21806 return arr[arr.length - (n || 1)];
21807};
21808
21809utils.escapeRegex = function(str) {
21810 return str.replace(/\\?([!^*?()[\]{}+?/])/g, '\\$1');
21811};
21812});
21813
21814var compilers = function(braces, options) {
21815 braces.compiler
21816
21817 /**
21818 * bos
21819 */
21820
21821 .set('bos', function() {
21822 if (this.output) return;
21823 this.ast.queue = isEscaped(this.ast) ? [this.ast.val] : [];
21824 this.ast.count = 1;
21825 })
21826
21827 /**
21828 * Square brackets
21829 */
21830
21831 .set('bracket', function(node) {
21832 var close = node.close;
21833 var open = !node.escaped ? '[' : '\\[';
21834 var negated = node.negated;
21835 var inner = node.inner;
21836
21837 inner = inner.replace(/\\(?=[\\\w]|$)/g, '\\\\');
21838 if (inner === ']-') {
21839 inner = '\\]\\-';
21840 }
21841
21842 if (negated && inner.indexOf('.') === -1) {
21843 inner += '.';
21844 }
21845 if (negated && inner.indexOf('/') === -1) {
21846 inner += '/';
21847 }
21848
21849 var val = open + negated + inner + close;
21850 var queue = node.parent.queue;
21851 var last = utils_1.arrayify(queue.pop());
21852
21853 queue.push(utils_1.join(last, val));
21854 queue.push.apply(queue, []);
21855 })
21856
21857 /**
21858 * Brace
21859 */
21860
21861 .set('brace', function(node) {
21862 node.queue = isEscaped(node) ? [node.val] : [];
21863 node.count = 1;
21864 return this.mapVisit(node.nodes);
21865 })
21866
21867 /**
21868 * Open
21869 */
21870
21871 .set('brace.open', function(node) {
21872 node.parent.open = node.val;
21873 })
21874
21875 /**
21876 * Inner
21877 */
21878
21879 .set('text', function(node) {
21880 var queue = node.parent.queue;
21881 var escaped = node.escaped;
21882 var segs = [node.val];
21883
21884 if (node.optimize === false) {
21885 options = utils_1.extend({}, options, {optimize: false});
21886 }
21887
21888 if (node.multiplier > 1) {
21889 node.parent.count *= node.multiplier;
21890 }
21891
21892 if (options.quantifiers === true && utils_1.isQuantifier(node.val)) {
21893 escaped = true;
21894
21895 } else if (node.val.length > 1) {
21896 if (isType(node.parent, 'brace') && !isEscaped(node)) {
21897 var expanded = utils_1.expand(node.val, options);
21898 segs = expanded.segs;
21899
21900 if (expanded.isOptimized) {
21901 node.parent.isOptimized = true;
21902 }
21903
21904 // if nothing was expanded, we probably have a literal brace
21905 if (!segs.length) {
21906 var val = (expanded.val || node.val);
21907 if (options.unescape !== false) {
21908 // unescape unexpanded brace sequence/set separators
21909 val = val.replace(/\\([,.])/g, '$1');
21910 // strip quotes
21911 val = val.replace(/["'`]/g, '');
21912 }
21913
21914 segs = [val];
21915 escaped = true;
21916 }
21917 }
21918
21919 } else if (node.val === ',') {
21920 if (options.expand) {
21921 node.parent.queue.push(['']);
21922 segs = [''];
21923 } else {
21924 segs = ['|'];
21925 }
21926 } else {
21927 escaped = true;
21928 }
21929
21930 if (escaped && isType(node.parent, 'brace')) {
21931 if (node.parent.nodes.length <= 4 && node.parent.count === 1) {
21932 node.parent.escaped = true;
21933 } else if (node.parent.length <= 3) {
21934 node.parent.escaped = true;
21935 }
21936 }
21937
21938 if (!hasQueue(node.parent)) {
21939 node.parent.queue = segs;
21940 return;
21941 }
21942
21943 var last = utils_1.arrayify(queue.pop());
21944 if (node.parent.count > 1 && options.expand) {
21945 last = multiply(last, node.parent.count);
21946 node.parent.count = 1;
21947 }
21948
21949 queue.push(utils_1.join(utils_1.flatten(last), segs.shift()));
21950 queue.push.apply(queue, segs);
21951 })
21952
21953 /**
21954 * Close
21955 */
21956
21957 .set('brace.close', function(node) {
21958 var queue = node.parent.queue;
21959 var prev = node.parent.parent;
21960 var last = prev.queue.pop();
21961 var open = node.parent.open;
21962 var close = node.val;
21963
21964 if (open && close && isOptimized(node, options)) {
21965 open = '(';
21966 close = ')';
21967 }
21968
21969 // if a close brace exists, and the previous segment is one character
21970 // don't wrap the result in braces or parens
21971 var ele = utils_1.last(queue);
21972 if (node.parent.count > 1 && options.expand) {
21973 ele = multiply(queue.pop(), node.parent.count);
21974 node.parent.count = 1;
21975 queue.push(ele);
21976 }
21977
21978 if (close && typeof ele === 'string' && ele.length === 1) {
21979 open = '';
21980 close = '';
21981 }
21982
21983 if ((isLiteralBrace(node, options) || noInner(node)) && !node.parent.hasEmpty) {
21984 queue.push(utils_1.join(open, queue.pop() || ''));
21985 queue = utils_1.flatten(utils_1.join(queue, close));
21986 }
21987
21988 if (typeof last === 'undefined') {
21989 prev.queue = [queue];
21990 } else {
21991 prev.queue.push(utils_1.flatten(utils_1.join(last, queue)));
21992 }
21993 })
21994
21995 /**
21996 * eos
21997 */
21998
21999 .set('eos', function(node) {
22000 if (this.input) return;
22001
22002 if (options.optimize !== false) {
22003 this.output = utils_1.last(utils_1.flatten(this.ast.queue));
22004 } else if (Array.isArray(utils_1.last(this.ast.queue))) {
22005 this.output = utils_1.flatten(this.ast.queue.pop());
22006 } else {
22007 this.output = utils_1.flatten(this.ast.queue);
22008 }
22009
22010 if (node.parent.count > 1 && options.expand) {
22011 this.output = multiply(this.output, node.parent.count);
22012 }
22013
22014 this.output = utils_1.arrayify(this.output);
22015 this.ast.queue = [];
22016 });
22017
22018};
22019
22020/**
22021 * Multiply the segments in the current brace level
22022 */
22023
22024function multiply(queue, n, options) {
22025 return utils_1.flatten(utils_1.repeat(utils_1.arrayify(queue), n));
22026}
22027
22028/**
22029 * Return true if `node` is escaped
22030 */
22031
22032function isEscaped(node) {
22033 return node.escaped === true;
22034}
22035
22036/**
22037 * Returns true if regex parens should be used for sets. If the parent `type`
22038 * is not `brace`, then we're on a root node, which means we should never
22039 * expand segments and open/close braces should be `{}` (since this indicates
22040 * a brace is missing from the set)
22041 */
22042
22043function isOptimized(node, options) {
22044 if (node.parent.isOptimized) return true;
22045 return isType(node.parent, 'brace')
22046 && !isEscaped(node.parent)
22047 && options.expand !== true;
22048}
22049
22050/**
22051 * Returns true if the value in `node` should be wrapped in a literal brace.
22052 * @return {Boolean}
22053 */
22054
22055function isLiteralBrace(node, options) {
22056 return isEscaped(node.parent) || options.optimize !== false;
22057}
22058
22059/**
22060 * Returns true if the given `node` does not have an inner value.
22061 * @return {Boolean}
22062 */
22063
22064function noInner(node, type) {
22065 if (node.parent.queue.length === 1) {
22066 return true;
22067 }
22068 var nodes = node.parent.nodes;
22069 return nodes.length === 3
22070 && isType(nodes[0], 'brace.open')
22071 && !isType(nodes[1], 'text')
22072 && isType(nodes[2], 'brace.close');
22073}
22074
22075/**
22076 * Returns true if the given `node` is the given `type`
22077 * @return {Boolean}
22078 */
22079
22080function isType(node, type) {
22081 return typeof node !== 'undefined' && node.type === type;
22082}
22083
22084/**
22085 * Returns true if the given `node` has a non-empty queue.
22086 * @return {Boolean}
22087 */
22088
22089function hasQueue(node) {
22090 return Array.isArray(node.queue) && node.queue.length;
22091}
22092
22093// accessor descriptor properties
22094var accessor$1 = {
22095 get: 'function',
22096 set: 'function',
22097 configurable: 'boolean',
22098 enumerable: 'boolean'
22099};
22100
22101function isAccessorDescriptor$1(obj, prop) {
22102 if (typeof prop === 'string') {
22103 var val = Object.getOwnPropertyDescriptor(obj, prop);
22104 return typeof val !== 'undefined';
22105 }
22106
22107 if (kindOf(obj) !== 'object') {
22108 return false;
22109 }
22110
22111 if (has$2(obj, 'value') || has$2(obj, 'writable')) {
22112 return false;
22113 }
22114
22115 if (!has$2(obj, 'get') || typeof obj.get !== 'function') {
22116 return false;
22117 }
22118
22119 // tldr: it's valid to have "set" be undefined
22120 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
22121 // was used to get the value, and only `get` was defined by the user
22122 if (has$2(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
22123 return false;
22124 }
22125
22126 for (var key in obj) {
22127 if (!accessor$1.hasOwnProperty(key)) {
22128 continue;
22129 }
22130
22131 if (kindOf(obj[key]) === accessor$1[key]) {
22132 continue;
22133 }
22134
22135 if (typeof obj[key] !== 'undefined') {
22136 return false;
22137 }
22138 }
22139 return true;
22140}
22141
22142function has$2(obj, key) {
22143 return {}.hasOwnProperty.call(obj, key);
22144}
22145
22146/**
22147 * Expose `isAccessorDescriptor`
22148 */
22149
22150var isAccessorDescriptor_1$1 = isAccessorDescriptor$1;
22151
22152var isDataDescriptor$1 = function isDataDescriptor(obj, prop) {
22153 // data descriptor properties
22154 var data = {
22155 configurable: 'boolean',
22156 enumerable: 'boolean',
22157 writable: 'boolean'
22158 };
22159
22160 if (kindOf(obj) !== 'object') {
22161 return false;
22162 }
22163
22164 if (typeof prop === 'string') {
22165 var val = Object.getOwnPropertyDescriptor(obj, prop);
22166 return typeof val !== 'undefined';
22167 }
22168
22169 if (!('value' in obj) && !('writable' in obj)) {
22170 return false;
22171 }
22172
22173 for (var key in obj) {
22174 if (key === 'value') continue;
22175
22176 if (!data.hasOwnProperty(key)) {
22177 continue;
22178 }
22179
22180 if (kindOf(obj[key]) === data[key]) {
22181 continue;
22182 }
22183
22184 if (typeof obj[key] !== 'undefined') {
22185 return false;
22186 }
22187 }
22188 return true;
22189};
22190
22191var isDescriptor$1 = function isDescriptor(obj, key) {
22192 if (kindOf(obj) !== 'object') {
22193 return false;
22194 }
22195 if ('get' in obj) {
22196 return isAccessorDescriptor_1$1(obj, key);
22197 }
22198 return isDataDescriptor$1(obj, key);
22199};
22200
22201var defineProperty$1 = function defineProperty(obj, prop, val) {
22202 if (typeof obj !== 'object' && typeof obj !== 'function') {
22203 throw new TypeError('expected an object or function.');
22204 }
22205
22206 if (typeof prop !== 'string') {
22207 throw new TypeError('expected `prop` to be a string.');
22208 }
22209
22210 if (isDescriptor$1(val) && ('set' in val || 'get' in val)) {
22211 return Object.defineProperty(obj, prop, val);
22212 }
22213
22214 return Object.defineProperty(obj, prop, {
22215 configurable: true,
22216 enumerable: false,
22217 writable: true,
22218 value: val
22219 });
22220};
22221
22222var toString$3 = Object.prototype.toString;
22223
22224/**
22225 * Get the native `typeof` a value.
22226 *
22227 * @param {*} `val`
22228 * @return {*} Native javascript type
22229 */
22230
22231var kindOf$2 = function kindOf(val) {
22232 // primitivies
22233 if (typeof val === 'undefined') {
22234 return 'undefined';
22235 }
22236 if (val === null) {
22237 return 'null';
22238 }
22239 if (val === true || val === false || val instanceof Boolean) {
22240 return 'boolean';
22241 }
22242 if (typeof val === 'string' || val instanceof String) {
22243 return 'string';
22244 }
22245 if (typeof val === 'number' || val instanceof Number) {
22246 return 'number';
22247 }
22248
22249 // functions
22250 if (typeof val === 'function' || val instanceof Function) {
22251 return 'function';
22252 }
22253
22254 // array
22255 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
22256 return 'array';
22257 }
22258
22259 // check for instances of RegExp and Date before calling `toString`
22260 if (val instanceof RegExp) {
22261 return 'regexp';
22262 }
22263 if (val instanceof Date) {
22264 return 'date';
22265 }
22266
22267 // other objects
22268 var type = toString$3.call(val);
22269
22270 if (type === '[object RegExp]') {
22271 return 'regexp';
22272 }
22273 if (type === '[object Date]') {
22274 return 'date';
22275 }
22276 if (type === '[object Arguments]') {
22277 return 'arguments';
22278 }
22279 if (type === '[object Error]') {
22280 return 'error';
22281 }
22282
22283 // buffer
22284 if (isBuffer_1(val)) {
22285 return 'buffer';
22286 }
22287
22288 // es6: Map, WeakMap, Set, WeakSet
22289 if (type === '[object Set]') {
22290 return 'set';
22291 }
22292 if (type === '[object WeakSet]') {
22293 return 'weakset';
22294 }
22295 if (type === '[object Map]') {
22296 return 'map';
22297 }
22298 if (type === '[object WeakMap]') {
22299 return 'weakmap';
22300 }
22301 if (type === '[object Symbol]') {
22302 return 'symbol';
22303 }
22304
22305 // typed arrays
22306 if (type === '[object Int8Array]') {
22307 return 'int8array';
22308 }
22309 if (type === '[object Uint8Array]') {
22310 return 'uint8array';
22311 }
22312 if (type === '[object Uint8ClampedArray]') {
22313 return 'uint8clampedarray';
22314 }
22315 if (type === '[object Int16Array]') {
22316 return 'int16array';
22317 }
22318 if (type === '[object Uint16Array]') {
22319 return 'uint16array';
22320 }
22321 if (type === '[object Int32Array]') {
22322 return 'int32array';
22323 }
22324 if (type === '[object Uint32Array]') {
22325 return 'uint32array';
22326 }
22327 if (type === '[object Float32Array]') {
22328 return 'float32array';
22329 }
22330 if (type === '[object Float64Array]') {
22331 return 'float64array';
22332 }
22333
22334 // must be a plain object
22335 return 'object';
22336};
22337
22338var snapdragonUtil = createCommonjsModule(function (module) {
22339
22340
22341var utils = module.exports;
22342
22343/**
22344 * Returns true if the given value is a node.
22345 *
22346 * ```js
22347 * var Node = require('snapdragon-node');
22348 * var node = new Node({type: 'foo'});
22349 * console.log(utils.isNode(node)); //=> true
22350 * console.log(utils.isNode({})); //=> false
22351 * ```
22352 * @param {Object} `node` Instance of [snapdragon-node][]
22353 * @returns {Boolean}
22354 * @api public
22355 */
22356
22357utils.isNode = function(node) {
22358 return kindOf$2(node) === 'object' && node.isNode === true;
22359};
22360
22361/**
22362 * Emit an empty string for the given `node`.
22363 *
22364 * ```js
22365 * // do nothing for beginning-of-string
22366 * snapdragon.compiler.set('bos', utils.noop);
22367 * ```
22368 * @param {Object} `node` Instance of [snapdragon-node][]
22369 * @returns {undefined}
22370 * @api public
22371 */
22372
22373utils.noop = function(node) {
22374 append(this, '', node);
22375};
22376
22377/**
22378 * Appdend `node.val` to `compiler.output`, exactly as it was created
22379 * by the parser.
22380 *
22381 * ```js
22382 * snapdragon.compiler.set('text', utils.identity);
22383 * ```
22384 * @param {Object} `node` Instance of [snapdragon-node][]
22385 * @returns {undefined}
22386 * @api public
22387 */
22388
22389utils.identity = function(node) {
22390 append(this, node.val, node);
22391};
22392
22393/**
22394 * Previously named `.emit`, this method appends the given `val`
22395 * to `compiler.output` for the given node. Useful when you know
22396 * what value should be appended advance, regardless of the actual
22397 * value of `node.val`.
22398 *
22399 * ```js
22400 * snapdragon.compiler
22401 * .set('i', function(node) {
22402 * this.mapVisit(node);
22403 * })
22404 * .set('i.open', utils.append('<i>'))
22405 * .set('i.close', utils.append('</i>'))
22406 * ```
22407 * @param {Object} `node` Instance of [snapdragon-node][]
22408 * @returns {Function} Returns a compiler middleware function.
22409 * @api public
22410 */
22411
22412utils.append = function(val) {
22413 return function(node) {
22414 append(this, val, node);
22415 };
22416};
22417
22418/**
22419 * Used in compiler middleware, this onverts an AST node into
22420 * an empty `text` node and deletes `node.nodes` if it exists.
22421 * The advantage of this method is that, as opposed to completely
22422 * removing the node, indices will not need to be re-calculated
22423 * in sibling nodes, and nothing is appended to the output.
22424 *
22425 * ```js
22426 * utils.toNoop(node);
22427 * // convert `node.nodes` to the given value instead of deleting it
22428 * utils.toNoop(node, []);
22429 * ```
22430 * @param {Object} `node` Instance of [snapdragon-node][]
22431 * @param {Array} `nodes` Optionally pass a new `nodes` value, to replace the existing `node.nodes` array.
22432 * @api public
22433 */
22434
22435utils.toNoop = function(node, nodes) {
22436 if (nodes) {
22437 node.nodes = nodes;
22438 } else {
22439 delete node.nodes;
22440 node.type = 'text';
22441 node.val = '';
22442 }
22443};
22444
22445/**
22446 * Visit `node` with the given `fn`. The built-in `.visit` method in snapdragon
22447 * automatically calls registered compilers, this allows you to pass a visitor
22448 * function.
22449 *
22450 * ```js
22451 * snapdragon.compiler.set('i', function(node) {
22452 * utils.visit(node, function(childNode) {
22453 * // do stuff with "childNode"
22454 * return childNode;
22455 * });
22456 * });
22457 * ```
22458 * @param {Object} `node` Instance of [snapdragon-node][]
22459 * @param {Function} `fn`
22460 * @return {Object} returns the node after recursively visiting all child nodes.
22461 * @api public
22462 */
22463
22464utils.visit = function(node, fn) {
22465 assert(utils.isNode(node), 'expected node to be an instance of Node');
22466 assert(isFunction(fn), 'expected a visitor function');
22467 fn(node);
22468 return node.nodes ? utils.mapVisit(node, fn) : node;
22469};
22470
22471/**
22472 * Map [visit](#visit) the given `fn` over `node.nodes`. This is called by
22473 * [visit](#visit), use this method if you do not want `fn` to be called on
22474 * the first node.
22475 *
22476 * ```js
22477 * snapdragon.compiler.set('i', function(node) {
22478 * utils.mapVisit(node, function(childNode) {
22479 * // do stuff with "childNode"
22480 * return childNode;
22481 * });
22482 * });
22483 * ```
22484 * @param {Object} `node` Instance of [snapdragon-node][]
22485 * @param {Object} `options`
22486 * @param {Function} `fn`
22487 * @return {Object} returns the node
22488 * @api public
22489 */
22490
22491utils.mapVisit = function(node, fn) {
22492 assert(utils.isNode(node), 'expected node to be an instance of Node');
22493 assert(isArray(node.nodes), 'expected node.nodes to be an array');
22494 assert(isFunction(fn), 'expected a visitor function');
22495
22496 for (var i = 0; i < node.nodes.length; i++) {
22497 utils.visit(node.nodes[i], fn);
22498 }
22499 return node;
22500};
22501
22502/**
22503 * Unshift an `*.open` node onto `node.nodes`.
22504 *
22505 * ```js
22506 * var Node = require('snapdragon-node');
22507 * snapdragon.parser.set('brace', function(node) {
22508 * var match = this.match(/^{/);
22509 * if (match) {
22510 * var parent = new Node({type: 'brace'});
22511 * utils.addOpen(parent, Node);
22512 * console.log(parent.nodes[0]):
22513 * // { type: 'brace.open', val: '' };
22514 *
22515 * // push the parent "brace" node onto the stack
22516 * this.push(parent);
22517 *
22518 * // return the parent node, so it's also added to the AST
22519 * return brace;
22520 * }
22521 * });
22522 * ```
22523 * @param {Object} `node` Instance of [snapdragon-node][]
22524 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
22525 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
22526 * @return {Object} Returns the created opening node.
22527 * @api public
22528 */
22529
22530utils.addOpen = function(node, Node, val, filter) {
22531 assert(utils.isNode(node), 'expected node to be an instance of Node');
22532 assert(isFunction(Node), 'expected Node to be a constructor function');
22533
22534 if (typeof val === 'function') {
22535 filter = val;
22536 val = '';
22537 }
22538
22539 if (typeof filter === 'function' && !filter(node)) return;
22540 var open = new Node({ type: node.type + '.open', val: val});
22541 var unshift = node.unshift || node.unshiftNode;
22542 if (typeof unshift === 'function') {
22543 unshift.call(node, open);
22544 } else {
22545 utils.unshiftNode(node, open);
22546 }
22547 return open;
22548};
22549
22550/**
22551 * Push a `*.close` node onto `node.nodes`.
22552 *
22553 * ```js
22554 * var Node = require('snapdragon-node');
22555 * snapdragon.parser.set('brace', function(node) {
22556 * var match = this.match(/^}/);
22557 * if (match) {
22558 * var parent = this.parent();
22559 * if (parent.type !== 'brace') {
22560 * throw new Error('missing opening: ' + '}');
22561 * }
22562 *
22563 * utils.addClose(parent, Node);
22564 * console.log(parent.nodes[parent.nodes.length - 1]):
22565 * // { type: 'brace.close', val: '' };
22566 *
22567 * // no need to return a node, since the parent
22568 * // was already added to the AST
22569 * return;
22570 * }
22571 * });
22572 * ```
22573 * @param {Object} `node` Instance of [snapdragon-node][]
22574 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
22575 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
22576 * @return {Object} Returns the created closing node.
22577 * @api public
22578 */
22579
22580utils.addClose = function(node, Node, val, filter) {
22581 assert(utils.isNode(node), 'expected node to be an instance of Node');
22582 assert(isFunction(Node), 'expected Node to be a constructor function');
22583
22584 if (typeof val === 'function') {
22585 filter = val;
22586 val = '';
22587 }
22588
22589 if (typeof filter === 'function' && !filter(node)) return;
22590 var close = new Node({ type: node.type + '.close', val: val});
22591 var push = node.push || node.pushNode;
22592 if (typeof push === 'function') {
22593 push.call(node, close);
22594 } else {
22595 utils.pushNode(node, close);
22596 }
22597 return close;
22598};
22599
22600/**
22601 * Wraps the given `node` with `*.open` and `*.close` nodes.
22602 *
22603 * @param {Object} `node` Instance of [snapdragon-node][]
22604 * @param {Function} `Node` (required) Node constructor function from [snapdragon-node][].
22605 * @param {Function} `filter` Optionaly specify a filter function to exclude the node.
22606 * @return {Object} Returns the node
22607 * @api public
22608 */
22609
22610utils.wrapNodes = function(node, Node, filter) {
22611 assert(utils.isNode(node), 'expected node to be an instance of Node');
22612 assert(isFunction(Node), 'expected Node to be a constructor function');
22613
22614 utils.addOpen(node, Node, filter);
22615 utils.addClose(node, Node, filter);
22616 return node;
22617};
22618
22619/**
22620 * Push the given `node` onto `parent.nodes`, and set `parent` as `node.parent.
22621 *
22622 * ```js
22623 * var parent = new Node({type: 'foo'});
22624 * var node = new Node({type: 'bar'});
22625 * utils.pushNode(parent, node);
22626 * console.log(parent.nodes[0].type) // 'bar'
22627 * console.log(node.parent.type) // 'foo'
22628 * ```
22629 * @param {Object} `parent`
22630 * @param {Object} `node` Instance of [snapdragon-node][]
22631 * @return {Object} Returns the child node
22632 * @api public
22633 */
22634
22635utils.pushNode = function(parent, node) {
22636 assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
22637 assert(utils.isNode(node), 'expected node to be an instance of Node');
22638
22639 node.define('parent', parent);
22640 parent.nodes = parent.nodes || [];
22641 parent.nodes.push(node);
22642 return node;
22643};
22644
22645/**
22646 * Unshift `node` onto `parent.nodes`, and set `parent` as `node.parent.
22647 *
22648 * ```js
22649 * var parent = new Node({type: 'foo'});
22650 * var node = new Node({type: 'bar'});
22651 * utils.unshiftNode(parent, node);
22652 * console.log(parent.nodes[0].type) // 'bar'
22653 * console.log(node.parent.type) // 'foo'
22654 * ```
22655 * @param {Object} `parent`
22656 * @param {Object} `node` Instance of [snapdragon-node][]
22657 * @return {undefined}
22658 * @api public
22659 */
22660
22661utils.unshiftNode = function(parent, node) {
22662 assert(utils.isNode(parent), 'expected parent node to be an instance of Node');
22663 assert(utils.isNode(node), 'expected node to be an instance of Node');
22664
22665 node.define('parent', parent);
22666 parent.nodes = parent.nodes || [];
22667 parent.nodes.unshift(node);
22668};
22669
22670/**
22671 * Pop the last `node` off of `parent.nodes`. The advantage of
22672 * using this method is that it checks for `node.nodes` and works
22673 * with any version of `snapdragon-node`.
22674 *
22675 * ```js
22676 * var parent = new Node({type: 'foo'});
22677 * utils.pushNode(parent, new Node({type: 'foo'}));
22678 * utils.pushNode(parent, new Node({type: 'bar'}));
22679 * utils.pushNode(parent, new Node({type: 'baz'}));
22680 * console.log(parent.nodes.length); //=> 3
22681 * utils.popNode(parent);
22682 * console.log(parent.nodes.length); //=> 2
22683 * ```
22684 * @param {Object} `parent`
22685 * @param {Object} `node` Instance of [snapdragon-node][]
22686 * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
22687 * @api public
22688 */
22689
22690utils.popNode = function(node) {
22691 assert(utils.isNode(node), 'expected node to be an instance of Node');
22692 if (typeof node.pop === 'function') {
22693 return node.pop();
22694 }
22695 return node.nodes && node.nodes.pop();
22696};
22697
22698/**
22699 * Shift the first `node` off of `parent.nodes`. The advantage of
22700 * using this method is that it checks for `node.nodes` and works
22701 * with any version of `snapdragon-node`.
22702 *
22703 * ```js
22704 * var parent = new Node({type: 'foo'});
22705 * utils.pushNode(parent, new Node({type: 'foo'}));
22706 * utils.pushNode(parent, new Node({type: 'bar'}));
22707 * utils.pushNode(parent, new Node({type: 'baz'}));
22708 * console.log(parent.nodes.length); //=> 3
22709 * utils.shiftNode(parent);
22710 * console.log(parent.nodes.length); //=> 2
22711 * ```
22712 * @param {Object} `parent`
22713 * @param {Object} `node` Instance of [snapdragon-node][]
22714 * @return {Number|Undefined} Returns the length of `node.nodes` or undefined.
22715 * @api public
22716 */
22717
22718utils.shiftNode = function(node) {
22719 assert(utils.isNode(node), 'expected node to be an instance of Node');
22720 if (typeof node.shift === 'function') {
22721 return node.shift();
22722 }
22723 return node.nodes && node.nodes.shift();
22724};
22725
22726/**
22727 * Remove the specified `node` from `parent.nodes`.
22728 *
22729 * ```js
22730 * var parent = new Node({type: 'abc'});
22731 * var foo = new Node({type: 'foo'});
22732 * utils.pushNode(parent, foo);
22733 * utils.pushNode(parent, new Node({type: 'bar'}));
22734 * utils.pushNode(parent, new Node({type: 'baz'}));
22735 * console.log(parent.nodes.length); //=> 3
22736 * utils.removeNode(parent, foo);
22737 * console.log(parent.nodes.length); //=> 2
22738 * ```
22739 * @param {Object} `parent`
22740 * @param {Object} `node` Instance of [snapdragon-node][]
22741 * @return {Object|undefined} Returns the removed node, if successful, or undefined if it does not exist on `parent.nodes`.
22742 * @api public
22743 */
22744
22745utils.removeNode = function(parent, node) {
22746 assert(utils.isNode(parent), 'expected parent.node to be an instance of Node');
22747 assert(utils.isNode(node), 'expected node to be an instance of Node');
22748
22749 if (!parent.nodes) {
22750 return null;
22751 }
22752
22753 if (typeof parent.remove === 'function') {
22754 return parent.remove(node);
22755 }
22756
22757 var idx = parent.nodes.indexOf(node);
22758 if (idx !== -1) {
22759 return parent.nodes.splice(idx, 1);
22760 }
22761};
22762
22763/**
22764 * Returns true if `node.type` matches the given `type`. Throws a
22765 * `TypeError` if `node` is not an instance of `Node`.
22766 *
22767 * ```js
22768 * var Node = require('snapdragon-node');
22769 * var node = new Node({type: 'foo'});
22770 * console.log(utils.isType(node, 'foo')); // false
22771 * console.log(utils.isType(node, 'bar')); // true
22772 * ```
22773 * @param {Object} `node` Instance of [snapdragon-node][]
22774 * @param {String} `type`
22775 * @return {Boolean}
22776 * @api public
22777 */
22778
22779utils.isType = function(node, type) {
22780 assert(utils.isNode(node), 'expected node to be an instance of Node');
22781 switch (kindOf$2(type)) {
22782 case 'array':
22783 var types = type.slice();
22784 for (var i = 0; i < types.length; i++) {
22785 if (utils.isType(node, types[i])) {
22786 return true;
22787 }
22788 }
22789 return false;
22790 case 'string':
22791 return node.type === type;
22792 case 'regexp':
22793 return type.test(node.type);
22794 default: {
22795 throw new TypeError('expected "type" to be an array, string or regexp');
22796 }
22797 }
22798};
22799
22800/**
22801 * Returns true if the given `node` has the given `type` in `node.nodes`.
22802 * Throws a `TypeError` if `node` is not an instance of `Node`.
22803 *
22804 * ```js
22805 * var Node = require('snapdragon-node');
22806 * var node = new Node({
22807 * type: 'foo',
22808 * nodes: [
22809 * new Node({type: 'bar'}),
22810 * new Node({type: 'baz'})
22811 * ]
22812 * });
22813 * console.log(utils.hasType(node, 'xyz')); // false
22814 * console.log(utils.hasType(node, 'baz')); // true
22815 * ```
22816 * @param {Object} `node` Instance of [snapdragon-node][]
22817 * @param {String} `type`
22818 * @return {Boolean}
22819 * @api public
22820 */
22821
22822utils.hasType = function(node, type) {
22823 assert(utils.isNode(node), 'expected node to be an instance of Node');
22824 if (!Array.isArray(node.nodes)) return false;
22825 for (var i = 0; i < node.nodes.length; i++) {
22826 if (utils.isType(node.nodes[i], type)) {
22827 return true;
22828 }
22829 }
22830 return false;
22831};
22832
22833/**
22834 * Returns the first node from `node.nodes` of the given `type`
22835 *
22836 * ```js
22837 * var node = new Node({
22838 * type: 'foo',
22839 * nodes: [
22840 * new Node({type: 'text', val: 'abc'}),
22841 * new Node({type: 'text', val: 'xyz'})
22842 * ]
22843 * });
22844 *
22845 * var textNode = utils.firstOfType(node.nodes, 'text');
22846 * console.log(textNode.val);
22847 * //=> 'abc'
22848 * ```
22849 * @param {Array} `nodes`
22850 * @param {String} `type`
22851 * @return {Object|undefined} Returns the first matching node or undefined.
22852 * @api public
22853 */
22854
22855utils.firstOfType = function(nodes, type) {
22856 for (var i = 0; i < nodes.length; i++) {
22857 var node = nodes[i];
22858 if (utils.isType(node, type)) {
22859 return node;
22860 }
22861 }
22862};
22863
22864/**
22865 * Returns the node at the specified index, or the first node of the
22866 * given `type` from `node.nodes`.
22867 *
22868 * ```js
22869 * var node = new Node({
22870 * type: 'foo',
22871 * nodes: [
22872 * new Node({type: 'text', val: 'abc'}),
22873 * new Node({type: 'text', val: 'xyz'})
22874 * ]
22875 * });
22876 *
22877 * var nodeOne = utils.findNode(node.nodes, 'text');
22878 * console.log(nodeOne.val);
22879 * //=> 'abc'
22880 *
22881 * var nodeTwo = utils.findNode(node.nodes, 1);
22882 * console.log(nodeTwo.val);
22883 * //=> 'xyz'
22884 * ```
22885 *
22886 * @param {Array} `nodes`
22887 * @param {String|Number} `type` Node type or index.
22888 * @return {Object} Returns a node or undefined.
22889 * @api public
22890 */
22891
22892utils.findNode = function(nodes, type) {
22893 if (!Array.isArray(nodes)) {
22894 return null;
22895 }
22896 if (typeof type === 'number') {
22897 return nodes[type];
22898 }
22899 return utils.firstOfType(nodes, type);
22900};
22901
22902/**
22903 * Returns true if the given node is an "*.open" node.
22904 *
22905 * ```js
22906 * var Node = require('snapdragon-node');
22907 * var brace = new Node({type: 'brace'});
22908 * var open = new Node({type: 'brace.open'});
22909 * var close = new Node({type: 'brace.close'});
22910 *
22911 * console.log(utils.isOpen(brace)); // false
22912 * console.log(utils.isOpen(open)); // true
22913 * console.log(utils.isOpen(close)); // false
22914 * ```
22915 * @param {Object} `node` Instance of [snapdragon-node][]
22916 * @return {Boolean}
22917 * @api public
22918 */
22919
22920utils.isOpen = function(node) {
22921 assert(utils.isNode(node), 'expected node to be an instance of Node');
22922 return node.type.slice(-5) === '.open';
22923};
22924
22925/**
22926 * Returns true if the given node is a "*.close" node.
22927 *
22928 * ```js
22929 * var Node = require('snapdragon-node');
22930 * var brace = new Node({type: 'brace'});
22931 * var open = new Node({type: 'brace.open'});
22932 * var close = new Node({type: 'brace.close'});
22933 *
22934 * console.log(utils.isClose(brace)); // false
22935 * console.log(utils.isClose(open)); // false
22936 * console.log(utils.isClose(close)); // true
22937 * ```
22938 * @param {Object} `node` Instance of [snapdragon-node][]
22939 * @return {Boolean}
22940 * @api public
22941 */
22942
22943utils.isClose = function(node) {
22944 assert(utils.isNode(node), 'expected node to be an instance of Node');
22945 return node.type.slice(-6) === '.close';
22946};
22947
22948/**
22949 * Returns true if `node.nodes` **has** an `.open` node
22950 *
22951 * ```js
22952 * var Node = require('snapdragon-node');
22953 * var brace = new Node({
22954 * type: 'brace',
22955 * nodes: []
22956 * });
22957 *
22958 * var open = new Node({type: 'brace.open'});
22959 * console.log(utils.hasOpen(brace)); // false
22960 *
22961 * brace.pushNode(open);
22962 * console.log(utils.hasOpen(brace)); // true
22963 * ```
22964 * @param {Object} `node` Instance of [snapdragon-node][]
22965 * @return {Boolean}
22966 * @api public
22967 */
22968
22969utils.hasOpen = function(node) {
22970 assert(utils.isNode(node), 'expected node to be an instance of Node');
22971 var first = node.first || node.nodes ? node.nodes[0] : null;
22972 if (utils.isNode(first)) {
22973 return first.type === node.type + '.open';
22974 }
22975 return false;
22976};
22977
22978/**
22979 * Returns true if `node.nodes` **has** a `.close` node
22980 *
22981 * ```js
22982 * var Node = require('snapdragon-node');
22983 * var brace = new Node({
22984 * type: 'brace',
22985 * nodes: []
22986 * });
22987 *
22988 * var close = new Node({type: 'brace.close'});
22989 * console.log(utils.hasClose(brace)); // false
22990 *
22991 * brace.pushNode(close);
22992 * console.log(utils.hasClose(brace)); // true
22993 * ```
22994 * @param {Object} `node` Instance of [snapdragon-node][]
22995 * @return {Boolean}
22996 * @api public
22997 */
22998
22999utils.hasClose = function(node) {
23000 assert(utils.isNode(node), 'expected node to be an instance of Node');
23001 var last = node.last || node.nodes ? node.nodes[node.nodes.length - 1] : null;
23002 if (utils.isNode(last)) {
23003 return last.type === node.type + '.close';
23004 }
23005 return false;
23006};
23007
23008/**
23009 * Returns true if `node.nodes` has both `.open` and `.close` nodes
23010 *
23011 * ```js
23012 * var Node = require('snapdragon-node');
23013 * var brace = new Node({
23014 * type: 'brace',
23015 * nodes: []
23016 * });
23017 *
23018 * var open = new Node({type: 'brace.open'});
23019 * var close = new Node({type: 'brace.close'});
23020 * console.log(utils.hasOpen(brace)); // false
23021 * console.log(utils.hasClose(brace)); // false
23022 *
23023 * brace.pushNode(open);
23024 * brace.pushNode(close);
23025 * console.log(utils.hasOpen(brace)); // true
23026 * console.log(utils.hasClose(brace)); // true
23027 * ```
23028 * @param {Object} `node` Instance of [snapdragon-node][]
23029 * @return {Boolean}
23030 * @api public
23031 */
23032
23033utils.hasOpenAndClose = function(node) {
23034 return utils.hasOpen(node) && utils.hasClose(node);
23035};
23036
23037/**
23038 * Push the given `node` onto the `state.inside` array for the
23039 * given type. This array is used as a specialized "stack" for
23040 * only the given `node.type`.
23041 *
23042 * ```js
23043 * var state = { inside: {}};
23044 * var node = new Node({type: 'brace'});
23045 * utils.addType(state, node);
23046 * console.log(state.inside);
23047 * //=> { brace: [{type: 'brace'}] }
23048 * ```
23049 * @param {Object} `state` The `compiler.state` object or custom state object.
23050 * @param {Object} `node` Instance of [snapdragon-node][]
23051 * @return {Array} Returns the `state.inside` stack for the given type.
23052 * @api public
23053 */
23054
23055utils.addType = function(state, node) {
23056 assert(utils.isNode(node), 'expected node to be an instance of Node');
23057 assert(isObject(state), 'expected state to be an object');
23058
23059 var type = node.parent
23060 ? node.parent.type
23061 : node.type.replace(/\.open$/, '');
23062
23063 if (!state.hasOwnProperty('inside')) {
23064 state.inside = {};
23065 }
23066 if (!state.inside.hasOwnProperty(type)) {
23067 state.inside[type] = [];
23068 }
23069
23070 var arr = state.inside[type];
23071 arr.push(node);
23072 return arr;
23073};
23074
23075/**
23076 * Remove the given `node` from the `state.inside` array for the
23077 * given type. This array is used as a specialized "stack" for
23078 * only the given `node.type`.
23079 *
23080 * ```js
23081 * var state = { inside: {}};
23082 * var node = new Node({type: 'brace'});
23083 * utils.addType(state, node);
23084 * console.log(state.inside);
23085 * //=> { brace: [{type: 'brace'}] }
23086 * utils.removeType(state, node);
23087 * //=> { brace: [] }
23088 * ```
23089 * @param {Object} `state` The `compiler.state` object or custom state object.
23090 * @param {Object} `node` Instance of [snapdragon-node][]
23091 * @return {Array} Returns the `state.inside` stack for the given type.
23092 * @api public
23093 */
23094
23095utils.removeType = function(state, node) {
23096 assert(utils.isNode(node), 'expected node to be an instance of Node');
23097 assert(isObject(state), 'expected state to be an object');
23098
23099 var type = node.parent
23100 ? node.parent.type
23101 : node.type.replace(/\.close$/, '');
23102
23103 if (state.inside.hasOwnProperty(type)) {
23104 return state.inside[type].pop();
23105 }
23106};
23107
23108/**
23109 * Returns true if `node.val` is an empty string, or `node.nodes` does
23110 * not contain any non-empty text nodes.
23111 *
23112 * ```js
23113 * var node = new Node({type: 'text'});
23114 * utils.isEmpty(node); //=> true
23115 * node.val = 'foo';
23116 * utils.isEmpty(node); //=> false
23117 * ```
23118 * @param {Object} `node` Instance of [snapdragon-node][]
23119 * @param {Function} `fn`
23120 * @return {Boolean}
23121 * @api public
23122 */
23123
23124utils.isEmpty = function(node, fn) {
23125 assert(utils.isNode(node), 'expected node to be an instance of Node');
23126
23127 if (!Array.isArray(node.nodes)) {
23128 if (node.type !== 'text') {
23129 return true;
23130 }
23131 if (typeof fn === 'function') {
23132 return fn(node, node.parent);
23133 }
23134 return !utils.trim(node.val);
23135 }
23136
23137 for (var i = 0; i < node.nodes.length; i++) {
23138 var child = node.nodes[i];
23139 if (utils.isOpen(child) || utils.isClose(child)) {
23140 continue;
23141 }
23142 if (!utils.isEmpty(child, fn)) {
23143 return false;
23144 }
23145 }
23146
23147 return true;
23148};
23149
23150/**
23151 * Returns true if the `state.inside` stack for the given type exists
23152 * and has one or more nodes on it.
23153 *
23154 * ```js
23155 * var state = { inside: {}};
23156 * var node = new Node({type: 'brace'});
23157 * console.log(utils.isInsideType(state, 'brace')); //=> false
23158 * utils.addType(state, node);
23159 * console.log(utils.isInsideType(state, 'brace')); //=> true
23160 * utils.removeType(state, node);
23161 * console.log(utils.isInsideType(state, 'brace')); //=> false
23162 * ```
23163 * @param {Object} `state`
23164 * @param {String} `type`
23165 * @return {Boolean}
23166 * @api public
23167 */
23168
23169utils.isInsideType = function(state, type) {
23170 assert(isObject(state), 'expected state to be an object');
23171 assert(isString(type), 'expected type to be a string');
23172
23173 if (!state.hasOwnProperty('inside')) {
23174 return false;
23175 }
23176
23177 if (!state.inside.hasOwnProperty(type)) {
23178 return false;
23179 }
23180
23181 return state.inside[type].length > 0;
23182};
23183
23184/**
23185 * Returns true if `node` is either a child or grand-child of the given `type`,
23186 * or `state.inside[type]` is a non-empty array.
23187 *
23188 * ```js
23189 * var state = { inside: {}};
23190 * var node = new Node({type: 'brace'});
23191 * var open = new Node({type: 'brace.open'});
23192 * console.log(utils.isInside(state, open, 'brace')); //=> false
23193 * utils.pushNode(node, open);
23194 * console.log(utils.isInside(state, open, 'brace')); //=> true
23195 * ```
23196 * @param {Object} `state` Either the `compiler.state` object, if it exists, or a user-supplied state object.
23197 * @param {Object} `node` Instance of [snapdragon-node][]
23198 * @param {String} `type` The `node.type` to check for.
23199 * @return {Boolean}
23200 * @api public
23201 */
23202
23203utils.isInside = function(state, node, type) {
23204 assert(utils.isNode(node), 'expected node to be an instance of Node');
23205 assert(isObject(state), 'expected state to be an object');
23206
23207 if (Array.isArray(type)) {
23208 for (var i = 0; i < type.length; i++) {
23209 if (utils.isInside(state, node, type[i])) {
23210 return true;
23211 }
23212 }
23213 return false;
23214 }
23215
23216 var parent = node.parent;
23217 if (typeof type === 'string') {
23218 return (parent && parent.type === type) || utils.isInsideType(state, type);
23219 }
23220
23221 if (kindOf$2(type) === 'regexp') {
23222 if (parent && parent.type && type.test(parent.type)) {
23223 return true;
23224 }
23225
23226 var keys = Object.keys(state.inside);
23227 var len = keys.length;
23228 var idx = -1;
23229 while (++idx < len) {
23230 var key = keys[idx];
23231 var val = state.inside[key];
23232
23233 if (Array.isArray(val) && val.length !== 0 && type.test(key)) {
23234 return true;
23235 }
23236 }
23237 }
23238 return false;
23239};
23240
23241/**
23242 * Get the last `n` element from the given `array`. Used for getting
23243 * a node from `node.nodes.`
23244 *
23245 * @param {Array} `array`
23246 * @param {Number} `n`
23247 * @return {undefined}
23248 * @api public
23249 */
23250
23251utils.last = function(arr, n) {
23252 return arr[arr.length - (n || 1)];
23253};
23254
23255/**
23256 * Cast the given `val` to an array.
23257 *
23258 * ```js
23259 * console.log(utils.arrayify(''));
23260 * //=> []
23261 * console.log(utils.arrayify('foo'));
23262 * //=> ['foo']
23263 * console.log(utils.arrayify(['foo']));
23264 * //=> ['foo']
23265 * ```
23266 * @param {any} `val`
23267 * @return {Array}
23268 * @api public
23269 */
23270
23271utils.arrayify = function(val) {
23272 if (typeof val === 'string' && val !== '') {
23273 return [val];
23274 }
23275 if (!Array.isArray(val)) {
23276 return [];
23277 }
23278 return val;
23279};
23280
23281/**
23282 * Convert the given `val` to a string by joining with `,`. Useful
23283 * for creating a cheerio/CSS/DOM-style selector from a list of strings.
23284 *
23285 * @param {any} `val`
23286 * @return {Array}
23287 * @api public
23288 */
23289
23290utils.stringify = function(val) {
23291 return utils.arrayify(val).join(',');
23292};
23293
23294/**
23295 * Ensure that the given value is a string and call `.trim()` on it,
23296 * or return an empty string.
23297 *
23298 * @param {String} `str`
23299 * @return {String}
23300 * @api public
23301 */
23302
23303utils.trim = function(str) {
23304 return typeof str === 'string' ? str.trim() : '';
23305};
23306
23307/**
23308 * Return true if val is an object
23309 */
23310
23311function isObject(val) {
23312 return kindOf$2(val) === 'object';
23313}
23314
23315/**
23316 * Return true if val is a string
23317 */
23318
23319function isString(val) {
23320 return typeof val === 'string';
23321}
23322
23323/**
23324 * Return true if val is a function
23325 */
23326
23327function isFunction(val) {
23328 return typeof val === 'function';
23329}
23330
23331/**
23332 * Return true if val is an array
23333 */
23334
23335function isArray(val) {
23336 return Array.isArray(val);
23337}
23338
23339/**
23340 * Shim to ensure the `.append` methods work with any version of snapdragon
23341 */
23342
23343function append(compiler, val, node) {
23344 if (typeof compiler.append !== 'function') {
23345 return compiler.emit(val, node);
23346 }
23347 return compiler.append(val, node);
23348}
23349
23350/**
23351 * Simplified assertion. Throws an error is `val` is falsey.
23352 */
23353
23354function assert(val, message) {
23355 if (!val) throw new Error(message);
23356}
23357});
23358
23359var snapdragonNode = createCommonjsModule(function (module, exports) {
23360
23361
23362
23363
23364var ownNames;
23365
23366/**
23367 * Create a new AST `Node` with the given `val` and `type`.
23368 *
23369 * ```js
23370 * var node = new Node('*', 'Star');
23371 * var node = new Node({type: 'star', val: '*'});
23372 * ```
23373 * @name Node
23374 * @param {String|Object} `val` Pass a matched substring, or an object to merge onto the node.
23375 * @param {String} `type` The node type to use when `val` is a string.
23376 * @return {Object} node instance
23377 * @api public
23378 */
23379
23380function Node(val, type, parent) {
23381 if (typeof type !== 'string') {
23382 parent = type;
23383 type = null;
23384 }
23385
23386 defineProperty$1(this, 'parent', parent);
23387 defineProperty$1(this, 'isNode', true);
23388 defineProperty$1(this, 'expect', null);
23389
23390 if (typeof type !== 'string' && isobject(val)) {
23391 lazyKeys();
23392 var keys = Object.keys(val);
23393 for (var i = 0; i < keys.length; i++) {
23394 var key = keys[i];
23395 if (ownNames.indexOf(key) === -1) {
23396 this[key] = val[key];
23397 }
23398 }
23399 } else {
23400 this.type = type;
23401 this.val = val;
23402 }
23403}
23404
23405/**
23406 * Returns true if the given value is a node.
23407 *
23408 * ```js
23409 * var Node = require('snapdragon-node');
23410 * var node = new Node({type: 'foo'});
23411 * console.log(Node.isNode(node)); //=> true
23412 * console.log(Node.isNode({})); //=> false
23413 * ```
23414 * @param {Object} `node`
23415 * @returns {Boolean}
23416 * @api public
23417 */
23418
23419Node.isNode = function(node) {
23420 return snapdragonUtil.isNode(node);
23421};
23422
23423/**
23424 * Define a non-enumberable property on the node instance.
23425 * Useful for adding properties that shouldn't be extended
23426 * or visible during debugging.
23427 *
23428 * ```js
23429 * var node = new Node();
23430 * node.define('foo', 'something non-enumerable');
23431 * ```
23432 * @param {String} `name`
23433 * @param {any} `val`
23434 * @return {Object} returns the node instance
23435 * @api public
23436 */
23437
23438Node.prototype.define = function(name, val) {
23439 defineProperty$1(this, name, val);
23440 return this;
23441};
23442
23443/**
23444 * Returns true if `node.val` is an empty string, or `node.nodes` does
23445 * not contain any non-empty text nodes.
23446 *
23447 * ```js
23448 * var node = new Node({type: 'text'});
23449 * node.isEmpty(); //=> true
23450 * node.val = 'foo';
23451 * node.isEmpty(); //=> false
23452 * ```
23453 * @param {Function} `fn` (optional) Filter function that is called on `node` and/or child nodes. `isEmpty` will return false immediately when the filter function returns false on any nodes.
23454 * @return {Boolean}
23455 * @api public
23456 */
23457
23458Node.prototype.isEmpty = function(fn) {
23459 return snapdragonUtil.isEmpty(this, fn);
23460};
23461
23462/**
23463 * Given node `foo` and node `bar`, push node `bar` onto `foo.nodes`, and
23464 * set `foo` as `bar.parent`.
23465 *
23466 * ```js
23467 * var foo = new Node({type: 'foo'});
23468 * var bar = new Node({type: 'bar'});
23469 * foo.push(bar);
23470 * ```
23471 * @param {Object} `node`
23472 * @return {Number} Returns the length of `node.nodes`
23473 * @api public
23474 */
23475
23476Node.prototype.push = function(node) {
23477 assert(Node.isNode(node), 'expected node to be an instance of Node');
23478 defineProperty$1(node, 'parent', this);
23479
23480 this.nodes = this.nodes || [];
23481 return this.nodes.push(node);
23482};
23483
23484/**
23485 * Given node `foo` and node `bar`, unshift node `bar` onto `foo.nodes`, and
23486 * set `foo` as `bar.parent`.
23487 *
23488 * ```js
23489 * var foo = new Node({type: 'foo'});
23490 * var bar = new Node({type: 'bar'});
23491 * foo.unshift(bar);
23492 * ```
23493 * @param {Object} `node`
23494 * @return {Number} Returns the length of `node.nodes`
23495 * @api public
23496 */
23497
23498Node.prototype.unshift = function(node) {
23499 assert(Node.isNode(node), 'expected node to be an instance of Node');
23500 defineProperty$1(node, 'parent', this);
23501
23502 this.nodes = this.nodes || [];
23503 return this.nodes.unshift(node);
23504};
23505
23506/**
23507 * Pop a node from `node.nodes`.
23508 *
23509 * ```js
23510 * var node = new Node({type: 'foo'});
23511 * node.push(new Node({type: 'a'}));
23512 * node.push(new Node({type: 'b'}));
23513 * node.push(new Node({type: 'c'}));
23514 * node.push(new Node({type: 'd'}));
23515 * console.log(node.nodes.length);
23516 * //=> 4
23517 * node.pop();
23518 * console.log(node.nodes.length);
23519 * //=> 3
23520 * ```
23521 * @return {Number} Returns the popped `node`
23522 * @api public
23523 */
23524
23525Node.prototype.pop = function() {
23526 return this.nodes && this.nodes.pop();
23527};
23528
23529/**
23530 * Shift a node from `node.nodes`.
23531 *
23532 * ```js
23533 * var node = new Node({type: 'foo'});
23534 * node.push(new Node({type: 'a'}));
23535 * node.push(new Node({type: 'b'}));
23536 * node.push(new Node({type: 'c'}));
23537 * node.push(new Node({type: 'd'}));
23538 * console.log(node.nodes.length);
23539 * //=> 4
23540 * node.shift();
23541 * console.log(node.nodes.length);
23542 * //=> 3
23543 * ```
23544 * @return {Object} Returns the shifted `node`
23545 * @api public
23546 */
23547
23548Node.prototype.shift = function() {
23549 return this.nodes && this.nodes.shift();
23550};
23551
23552/**
23553 * Remove `node` from `node.nodes`.
23554 *
23555 * ```js
23556 * node.remove(childNode);
23557 * ```
23558 * @param {Object} `node`
23559 * @return {Object} Returns the removed node.
23560 * @api public
23561 */
23562
23563Node.prototype.remove = function(node) {
23564 assert(Node.isNode(node), 'expected node to be an instance of Node');
23565 this.nodes = this.nodes || [];
23566 var idx = node.index;
23567 if (idx !== -1) {
23568 node.index = -1;
23569 return this.nodes.splice(idx, 1);
23570 }
23571 return null;
23572};
23573
23574/**
23575 * Get the first child node from `node.nodes` that matches the given `type`.
23576 * If `type` is a number, the child node at that index is returned.
23577 *
23578 * ```js
23579 * var child = node.find(1); //<= index of the node to get
23580 * var child = node.find('foo'); //<= node.type of a child node
23581 * var child = node.find(/^(foo|bar)$/); //<= regex to match node.type
23582 * var child = node.find(['foo', 'bar']); //<= array of node.type(s)
23583 * ```
23584 * @param {String} `type`
23585 * @return {Object} Returns a child node or undefined.
23586 * @api public
23587 */
23588
23589Node.prototype.find = function(type) {
23590 return snapdragonUtil.findNode(this.nodes, type);
23591};
23592
23593/**
23594 * Return true if the node is the given `type`.
23595 *
23596 * ```js
23597 * var node = new Node({type: 'bar'});
23598 * cosole.log(node.isType('foo')); // false
23599 * cosole.log(node.isType(/^(foo|bar)$/)); // true
23600 * cosole.log(node.isType(['foo', 'bar'])); // true
23601 * ```
23602 * @param {String} `type`
23603 * @return {Boolean}
23604 * @api public
23605 */
23606
23607Node.prototype.isType = function(type) {
23608 return snapdragonUtil.isType(this, type);
23609};
23610
23611/**
23612 * Return true if the `node.nodes` has the given `type`.
23613 *
23614 * ```js
23615 * var foo = new Node({type: 'foo'});
23616 * var bar = new Node({type: 'bar'});
23617 * foo.push(bar);
23618 *
23619 * cosole.log(foo.hasType('qux')); // false
23620 * cosole.log(foo.hasType(/^(qux|bar)$/)); // true
23621 * cosole.log(foo.hasType(['qux', 'bar'])); // true
23622 * ```
23623 * @param {String} `type`
23624 * @return {Boolean}
23625 * @api public
23626 */
23627
23628Node.prototype.hasType = function(type) {
23629 return snapdragonUtil.hasType(this, type);
23630};
23631
23632/**
23633 * Get the siblings array, or `null` if it doesn't exist.
23634 *
23635 * ```js
23636 * var foo = new Node({type: 'foo'});
23637 * var bar = new Node({type: 'bar'});
23638 * var baz = new Node({type: 'baz'});
23639 * foo.push(bar);
23640 * foo.push(baz);
23641 *
23642 * console.log(bar.siblings.length) // 2
23643 * console.log(baz.siblings.length) // 2
23644 * ```
23645 * @return {Array}
23646 * @api public
23647 */
23648
23649Object.defineProperty(Node.prototype, 'siblings', {
23650 set: function() {
23651 throw new Error('node.siblings is a getter and cannot be defined');
23652 },
23653 get: function() {
23654 return this.parent ? this.parent.nodes : null;
23655 }
23656});
23657
23658/**
23659 * Get the node's current index from `node.parent.nodes`.
23660 * This should always be correct, even when the parent adds nodes.
23661 *
23662 * ```js
23663 * var foo = new Node({type: 'foo'});
23664 * var bar = new Node({type: 'bar'});
23665 * var baz = new Node({type: 'baz'});
23666 * var qux = new Node({type: 'qux'});
23667 * foo.push(bar);
23668 * foo.push(baz);
23669 * foo.unshift(qux);
23670 *
23671 * console.log(bar.index) // 1
23672 * console.log(baz.index) // 2
23673 * console.log(qux.index) // 0
23674 * ```
23675 * @return {Number}
23676 * @api public
23677 */
23678
23679Object.defineProperty(Node.prototype, 'index', {
23680 set: function(index) {
23681 defineProperty$1(this, 'idx', index);
23682 },
23683 get: function() {
23684 if (!Array.isArray(this.siblings)) {
23685 return -1;
23686 }
23687 var tok = this.idx !== -1 ? this.siblings[this.idx] : null;
23688 if (tok !== this) {
23689 this.idx = this.siblings.indexOf(this);
23690 }
23691 return this.idx;
23692 }
23693});
23694
23695/**
23696 * Get the previous node from the siblings array or `null`.
23697 *
23698 * ```js
23699 * var foo = new Node({type: 'foo'});
23700 * var bar = new Node({type: 'bar'});
23701 * var baz = new Node({type: 'baz'});
23702 * foo.push(bar);
23703 * foo.push(baz);
23704 *
23705 * console.log(baz.prev.type) // 'bar'
23706 * ```
23707 * @return {Object}
23708 * @api public
23709 */
23710
23711Object.defineProperty(Node.prototype, 'prev', {
23712 set: function() {
23713 throw new Error('node.prev is a getter and cannot be defined');
23714 },
23715 get: function() {
23716 if (Array.isArray(this.siblings)) {
23717 return this.siblings[this.index - 1] || this.parent.prev;
23718 }
23719 return null;
23720 }
23721});
23722
23723/**
23724 * Get the siblings array, or `null` if it doesn't exist.
23725 *
23726 * ```js
23727 * var foo = new Node({type: 'foo'});
23728 * var bar = new Node({type: 'bar'});
23729 * var baz = new Node({type: 'baz'});
23730 * foo.push(bar);
23731 * foo.push(baz);
23732 *
23733 * console.log(bar.siblings.length) // 2
23734 * console.log(baz.siblings.length) // 2
23735 * ```
23736 * @return {Object}
23737 * @api public
23738 */
23739
23740Object.defineProperty(Node.prototype, 'next', {
23741 set: function() {
23742 throw new Error('node.next is a getter and cannot be defined');
23743 },
23744 get: function() {
23745 if (Array.isArray(this.siblings)) {
23746 return this.siblings[this.index + 1] || this.parent.next;
23747 }
23748 return null;
23749 }
23750});
23751
23752/**
23753 * Get the first node from `node.nodes`.
23754 *
23755 * ```js
23756 * var foo = new Node({type: 'foo'});
23757 * var bar = new Node({type: 'bar'});
23758 * var baz = new Node({type: 'baz'});
23759 * var qux = new Node({type: 'qux'});
23760 * foo.push(bar);
23761 * foo.push(baz);
23762 * foo.push(qux);
23763 *
23764 * console.log(foo.first.type) // 'bar'
23765 * ```
23766 * @return {Object} The first node, or undefiend
23767 * @api public
23768 */
23769
23770Object.defineProperty(Node.prototype, 'first', {
23771 get: function() {
23772 return this.nodes ? this.nodes[0] : null;
23773 }
23774});
23775
23776/**
23777 * Get the last node from `node.nodes`.
23778 *
23779 * ```js
23780 * var foo = new Node({type: 'foo'});
23781 * var bar = new Node({type: 'bar'});
23782 * var baz = new Node({type: 'baz'});
23783 * var qux = new Node({type: 'qux'});
23784 * foo.push(bar);
23785 * foo.push(baz);
23786 * foo.push(qux);
23787 *
23788 * console.log(foo.last.type) // 'qux'
23789 * ```
23790 * @return {Object} The last node, or undefiend
23791 * @api public
23792 */
23793
23794Object.defineProperty(Node.prototype, 'last', {
23795 get: function() {
23796 return this.nodes ? snapdragonUtil.last(this.nodes) : null;
23797 }
23798});
23799
23800/**
23801 * Get the last node from `node.nodes`.
23802 *
23803 * ```js
23804 * var foo = new Node({type: 'foo'});
23805 * var bar = new Node({type: 'bar'});
23806 * var baz = new Node({type: 'baz'});
23807 * var qux = new Node({type: 'qux'});
23808 * foo.push(bar);
23809 * foo.push(baz);
23810 * foo.push(qux);
23811 *
23812 * console.log(foo.last.type) // 'qux'
23813 * ```
23814 * @return {Object} The last node, or undefiend
23815 * @api public
23816 */
23817
23818Object.defineProperty(Node.prototype, 'scope', {
23819 get: function() {
23820 if (this.isScope !== true) {
23821 return this.parent ? this.parent.scope : this;
23822 }
23823 return this;
23824 }
23825});
23826
23827/**
23828 * Get own property names from Node prototype, but only the
23829 * first time `Node` is instantiated
23830 */
23831
23832function lazyKeys() {
23833 if (!ownNames) {
23834 ownNames = Object.getOwnPropertyNames(Node.prototype);
23835 }
23836}
23837
23838/**
23839 * Simplified assertion. Throws an error is `val` is falsey.
23840 */
23841
23842function assert(val, message) {
23843 if (!val) throw new Error(message);
23844}
23845
23846/**
23847 * Expose `Node`
23848 */
23849
23850exports = module.exports = Node;
23851});
23852
23853/**
23854 * Braces parsers
23855 */
23856
23857var parsers = function(braces, options) {
23858 braces.parser
23859 .set('bos', function() {
23860 if (!this.parsed) {
23861 this.ast = this.nodes[0] = new snapdragonNode(this.ast);
23862 }
23863 })
23864
23865 /**
23866 * Character parsers
23867 */
23868
23869 .set('escape', function() {
23870 var pos = this.position();
23871 var m = this.match(/^(?:\\(.)|\$\{)/);
23872 if (!m) return;
23873
23874 var prev = this.prev();
23875 var last = utils_1.last(prev.nodes);
23876
23877 var node = pos(new snapdragonNode({
23878 type: 'text',
23879 multiplier: 1,
23880 val: m[0]
23881 }));
23882
23883 if (node.val === '\\\\') {
23884 return node;
23885 }
23886
23887 if (node.val === '${') {
23888 var str = this.input;
23889 var idx = -1;
23890 var ch;
23891
23892 while ((ch = str[++idx])) {
23893 this.consume(1);
23894 node.val += ch;
23895 if (ch === '\\') {
23896 node.val += str[++idx];
23897 continue;
23898 }
23899 if (ch === '}') {
23900 break;
23901 }
23902 }
23903 }
23904
23905 if (this.options.unescape !== false) {
23906 node.val = node.val.replace(/\\([{}])/g, '$1');
23907 }
23908
23909 if (last.val === '"' && this.input.charAt(0) === '"') {
23910 last.val = node.val;
23911 this.consume(1);
23912 return;
23913 }
23914
23915 return concatNodes.call(this, pos, node, prev, options);
23916 })
23917
23918 /**
23919 * Brackets: "[...]" (basic, this is overridden by
23920 * other parsers in more advanced implementations)
23921 */
23922
23923 .set('bracket', function() {
23924 var isInside = this.isInside('brace');
23925 var pos = this.position();
23926 var m = this.match(/^(?:\[([!^]?)([^\]]{2,}|\]-)(\]|[^*+?]+)|\[)/);
23927 if (!m) return;
23928
23929 var prev = this.prev();
23930 var val = m[0];
23931 var negated = m[1] ? '^' : '';
23932 var inner = m[2] || '';
23933 var close = m[3] || '';
23934
23935 if (isInside && prev.type === 'brace') {
23936 prev.text = prev.text || '';
23937 prev.text += val;
23938 }
23939
23940 var esc = this.input.slice(0, 2);
23941 if (inner === '' && esc === '\\]') {
23942 inner += esc;
23943 this.consume(2);
23944
23945 var str = this.input;
23946 var idx = -1;
23947 var ch;
23948
23949 while ((ch = str[++idx])) {
23950 this.consume(1);
23951 if (ch === ']') {
23952 close = ch;
23953 break;
23954 }
23955 inner += ch;
23956 }
23957 }
23958
23959 return pos(new snapdragonNode({
23960 type: 'bracket',
23961 val: val,
23962 escaped: close !== ']',
23963 negated: negated,
23964 inner: inner,
23965 close: close
23966 }));
23967 })
23968
23969 /**
23970 * Empty braces (we capture these early to
23971 * speed up processing in the compiler)
23972 */
23973
23974 .set('multiplier', function() {
23975 var isInside = this.isInside('brace');
23976 var pos = this.position();
23977 var m = this.match(/^\{((?:,|\{,+\})+)\}/);
23978 if (!m) return;
23979
23980 this.multiplier = true;
23981 var prev = this.prev();
23982 var val = m[0];
23983
23984 if (isInside && prev.type === 'brace') {
23985 prev.text = prev.text || '';
23986 prev.text += val;
23987 }
23988
23989 var node = pos(new snapdragonNode({
23990 type: 'text',
23991 multiplier: 1,
23992 match: m,
23993 val: val
23994 }));
23995
23996 return concatNodes.call(this, pos, node, prev, options);
23997 })
23998
23999 /**
24000 * Open
24001 */
24002
24003 .set('brace.open', function() {
24004 var pos = this.position();
24005 var m = this.match(/^\{(?!(?:[^\\}]?|,+)\})/);
24006 if (!m) return;
24007
24008 var prev = this.prev();
24009 var last = utils_1.last(prev.nodes);
24010
24011 // if the last parsed character was an extglob character
24012 // we need to _not optimize_ the brace pattern because
24013 // it might be mistaken for an extglob by a downstream parser
24014 if (last && last.val && isExtglobChar(last.val.slice(-1))) {
24015 last.optimize = false;
24016 }
24017
24018 var open = pos(new snapdragonNode({
24019 type: 'brace.open',
24020 val: m[0]
24021 }));
24022
24023 var node = pos(new snapdragonNode({
24024 type: 'brace',
24025 nodes: []
24026 }));
24027
24028 node.push(open);
24029 prev.push(node);
24030 this.push('brace', node);
24031 })
24032
24033 /**
24034 * Close
24035 */
24036
24037 .set('brace.close', function() {
24038 var pos = this.position();
24039 var m = this.match(/^\}/);
24040 if (!m || !m[0]) return;
24041
24042 var brace = this.pop('brace');
24043 var node = pos(new snapdragonNode({
24044 type: 'brace.close',
24045 val: m[0]
24046 }));
24047
24048 if (!this.isType(brace, 'brace')) {
24049 if (this.options.strict) {
24050 throw new Error('missing opening "{"');
24051 }
24052 node.type = 'text';
24053 node.multiplier = 0;
24054 node.escaped = true;
24055 return node;
24056 }
24057
24058 var prev = this.prev();
24059 var last = utils_1.last(prev.nodes);
24060 if (last.text) {
24061 var lastNode = utils_1.last(last.nodes);
24062 if (lastNode.val === ')' && /[!@*?+]\(/.test(last.text)) {
24063 var open = last.nodes[0];
24064 var text = last.nodes[1];
24065 if (open.type === 'brace.open' && text && text.type === 'text') {
24066 text.optimize = false;
24067 }
24068 }
24069 }
24070
24071 if (brace.nodes.length > 2) {
24072 var first = brace.nodes[1];
24073 if (first.type === 'text' && first.val === ',') {
24074 brace.nodes.splice(1, 1);
24075 brace.nodes.push(first);
24076 }
24077 }
24078
24079 brace.push(node);
24080 })
24081
24082 /**
24083 * Capture boundary characters
24084 */
24085
24086 .set('boundary', function() {
24087 var pos = this.position();
24088 var m = this.match(/^[$^](?!\{)/);
24089 if (!m) return;
24090 return pos(new snapdragonNode({
24091 type: 'text',
24092 val: m[0]
24093 }));
24094 })
24095
24096 /**
24097 * One or zero, non-comma characters wrapped in braces
24098 */
24099
24100 .set('nobrace', function() {
24101 var isInside = this.isInside('brace');
24102 var pos = this.position();
24103 var m = this.match(/^\{[^,]?\}/);
24104 if (!m) return;
24105
24106 var prev = this.prev();
24107 var val = m[0];
24108
24109 if (isInside && prev.type === 'brace') {
24110 prev.text = prev.text || '';
24111 prev.text += val;
24112 }
24113
24114 return pos(new snapdragonNode({
24115 type: 'text',
24116 multiplier: 0,
24117 val: val
24118 }));
24119 })
24120
24121 /**
24122 * Text
24123 */
24124
24125 .set('text', function() {
24126 var isInside = this.isInside('brace');
24127 var pos = this.position();
24128 var m = this.match(/^((?!\\)[^${}[\]])+/);
24129 if (!m) return;
24130
24131 var prev = this.prev();
24132 var val = m[0];
24133
24134 if (isInside && prev.type === 'brace') {
24135 prev.text = prev.text || '';
24136 prev.text += val;
24137 }
24138
24139 var node = pos(new snapdragonNode({
24140 type: 'text',
24141 multiplier: 1,
24142 val: val
24143 }));
24144
24145 return concatNodes.call(this, pos, node, prev, options);
24146 });
24147};
24148
24149/**
24150 * Returns true if the character is an extglob character.
24151 */
24152
24153function isExtglobChar(ch) {
24154 return ch === '!' || ch === '@' || ch === '*' || ch === '?' || ch === '+';
24155}
24156
24157/**
24158 * Combine text nodes, and calculate empty sets (`{,,}`)
24159 * @param {Function} `pos` Function to calculate node position
24160 * @param {Object} `node` AST node
24161 * @return {Object}
24162 */
24163
24164function concatNodes(pos, node, parent, options) {
24165 node.orig = node.val;
24166 var prev = this.prev();
24167 var last = utils_1.last(prev.nodes);
24168 var isEscaped = false;
24169
24170 if (node.val.length > 1) {
24171 var a = node.val.charAt(0);
24172 var b = node.val.slice(-1);
24173
24174 isEscaped = (a === '"' && b === '"')
24175 || (a === "'" && b === "'")
24176 || (a === '`' && b === '`');
24177 }
24178
24179 if (isEscaped && options.unescape !== false) {
24180 node.val = node.val.slice(1, node.val.length - 1);
24181 node.escaped = true;
24182 }
24183
24184 if (node.match) {
24185 var match = node.match[1];
24186 if (!match || match.indexOf('}') === -1) {
24187 match = node.match[0];
24188 }
24189
24190 // replace each set with a single ","
24191 var val = match.replace(/\{/g, ',').replace(/\}/g, '');
24192 node.multiplier *= val.length;
24193 node.val = '';
24194 }
24195
24196 var simpleText = last.type === 'text'
24197 && last.multiplier === 1
24198 && node.multiplier === 1
24199 && node.val;
24200
24201 if (simpleText) {
24202 last.val += node.val;
24203 return;
24204 }
24205
24206 prev.push(node);
24207}
24208
24209// accessor descriptor properties
24210var accessor$2 = {
24211 get: 'function',
24212 set: 'function',
24213 configurable: 'boolean',
24214 enumerable: 'boolean'
24215};
24216
24217function isAccessorDescriptor$2(obj, prop) {
24218 if (typeof prop === 'string') {
24219 var val = Object.getOwnPropertyDescriptor(obj, prop);
24220 return typeof val !== 'undefined';
24221 }
24222
24223 if (kindOf(obj) !== 'object') {
24224 return false;
24225 }
24226
24227 if (has$3(obj, 'value') || has$3(obj, 'writable')) {
24228 return false;
24229 }
24230
24231 if (!has$3(obj, 'get') || typeof obj.get !== 'function') {
24232 return false;
24233 }
24234
24235 // tldr: it's valid to have "set" be undefined
24236 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
24237 // was used to get the value, and only `get` was defined by the user
24238 if (has$3(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
24239 return false;
24240 }
24241
24242 for (var key in obj) {
24243 if (!accessor$2.hasOwnProperty(key)) {
24244 continue;
24245 }
24246
24247 if (kindOf(obj[key]) === accessor$2[key]) {
24248 continue;
24249 }
24250
24251 if (typeof obj[key] !== 'undefined') {
24252 return false;
24253 }
24254 }
24255 return true;
24256}
24257
24258function has$3(obj, key) {
24259 return {}.hasOwnProperty.call(obj, key);
24260}
24261
24262/**
24263 * Expose `isAccessorDescriptor`
24264 */
24265
24266var isAccessorDescriptor_1$2 = isAccessorDescriptor$2;
24267
24268var isDataDescriptor$2 = function isDataDescriptor(obj, prop) {
24269 // data descriptor properties
24270 var data = {
24271 configurable: 'boolean',
24272 enumerable: 'boolean',
24273 writable: 'boolean'
24274 };
24275
24276 if (kindOf(obj) !== 'object') {
24277 return false;
24278 }
24279
24280 if (typeof prop === 'string') {
24281 var val = Object.getOwnPropertyDescriptor(obj, prop);
24282 return typeof val !== 'undefined';
24283 }
24284
24285 if (!('value' in obj) && !('writable' in obj)) {
24286 return false;
24287 }
24288
24289 for (var key in obj) {
24290 if (key === 'value') continue;
24291
24292 if (!data.hasOwnProperty(key)) {
24293 continue;
24294 }
24295
24296 if (kindOf(obj[key]) === data[key]) {
24297 continue;
24298 }
24299
24300 if (typeof obj[key] !== 'undefined') {
24301 return false;
24302 }
24303 }
24304 return true;
24305};
24306
24307var isDescriptor$2 = function isDescriptor(obj, key) {
24308 if (kindOf(obj) !== 'object') {
24309 return false;
24310 }
24311 if ('get' in obj) {
24312 return isAccessorDescriptor_1$2(obj, key);
24313 }
24314 return isDataDescriptor$2(obj, key);
24315};
24316
24317var defineProperty$2 = function defineProperty(obj, prop, val) {
24318 if (typeof obj !== 'object' && typeof obj !== 'function') {
24319 throw new TypeError('expected an object or function.');
24320 }
24321
24322 if (typeof prop !== 'string') {
24323 throw new TypeError('expected `prop` to be a string.');
24324 }
24325
24326 if (isDescriptor$2(val) && ('set' in val || 'get' in val)) {
24327 return Object.defineProperty(obj, prop, val);
24328 }
24329
24330 return Object.defineProperty(obj, prop, {
24331 configurable: true,
24332 enumerable: false,
24333 writable: true,
24334 value: val
24335 });
24336};
24337
24338var componentEmitter = createCommonjsModule(function (module) {
24339/**
24340 * Expose `Emitter`.
24341 */
24342
24343{
24344 module.exports = Emitter;
24345}
24346
24347/**
24348 * Initialize a new `Emitter`.
24349 *
24350 * @api public
24351 */
24352
24353function Emitter(obj) {
24354 if (obj) return mixin(obj);
24355}
24356/**
24357 * Mixin the emitter properties.
24358 *
24359 * @param {Object} obj
24360 * @return {Object}
24361 * @api private
24362 */
24363
24364function mixin(obj) {
24365 for (var key in Emitter.prototype) {
24366 obj[key] = Emitter.prototype[key];
24367 }
24368 return obj;
24369}
24370
24371/**
24372 * Listen on the given `event` with `fn`.
24373 *
24374 * @param {String} event
24375 * @param {Function} fn
24376 * @return {Emitter}
24377 * @api public
24378 */
24379
24380Emitter.prototype.on =
24381Emitter.prototype.addEventListener = function(event, fn){
24382 this._callbacks = this._callbacks || {};
24383 (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
24384 .push(fn);
24385 return this;
24386};
24387
24388/**
24389 * Adds an `event` listener that will be invoked a single
24390 * time then automatically removed.
24391 *
24392 * @param {String} event
24393 * @param {Function} fn
24394 * @return {Emitter}
24395 * @api public
24396 */
24397
24398Emitter.prototype.once = function(event, fn){
24399 function on() {
24400 this.off(event, on);
24401 fn.apply(this, arguments);
24402 }
24403
24404 on.fn = fn;
24405 this.on(event, on);
24406 return this;
24407};
24408
24409/**
24410 * Remove the given callback for `event` or all
24411 * registered callbacks.
24412 *
24413 * @param {String} event
24414 * @param {Function} fn
24415 * @return {Emitter}
24416 * @api public
24417 */
24418
24419Emitter.prototype.off =
24420Emitter.prototype.removeListener =
24421Emitter.prototype.removeAllListeners =
24422Emitter.prototype.removeEventListener = function(event, fn){
24423 this._callbacks = this._callbacks || {};
24424
24425 // all
24426 if (0 == arguments.length) {
24427 this._callbacks = {};
24428 return this;
24429 }
24430
24431 // specific event
24432 var callbacks = this._callbacks['$' + event];
24433 if (!callbacks) return this;
24434
24435 // remove all handlers
24436 if (1 == arguments.length) {
24437 delete this._callbacks['$' + event];
24438 return this;
24439 }
24440
24441 // remove specific handler
24442 var cb;
24443 for (var i = 0; i < callbacks.length; i++) {
24444 cb = callbacks[i];
24445 if (cb === fn || cb.fn === fn) {
24446 callbacks.splice(i, 1);
24447 break;
24448 }
24449 }
24450 return this;
24451};
24452
24453/**
24454 * Emit `event` with the given args.
24455 *
24456 * @param {String} event
24457 * @param {Mixed} ...
24458 * @return {Emitter}
24459 */
24460
24461Emitter.prototype.emit = function(event){
24462 this._callbacks = this._callbacks || {};
24463 var args = [].slice.call(arguments, 1)
24464 , callbacks = this._callbacks['$' + event];
24465
24466 if (callbacks) {
24467 callbacks = callbacks.slice(0);
24468 for (var i = 0, len = callbacks.length; i < len; ++i) {
24469 callbacks[i].apply(this, args);
24470 }
24471 }
24472
24473 return this;
24474};
24475
24476/**
24477 * Return array of callbacks for `event`.
24478 *
24479 * @param {String} event
24480 * @return {Array}
24481 * @api public
24482 */
24483
24484Emitter.prototype.listeners = function(event){
24485 this._callbacks = this._callbacks || {};
24486 return this._callbacks['$' + event] || [];
24487};
24488
24489/**
24490 * Check if this emitter has `event` handlers.
24491 *
24492 * @param {String} event
24493 * @return {Boolean}
24494 * @api public
24495 */
24496
24497Emitter.prototype.hasListeners = function(event){
24498 return !! this.listeners(event).length;
24499};
24500});
24501
24502var objectVisit = function visit(thisArg, method, target, val) {
24503 if (!isobject(thisArg) && typeof thisArg !== 'function') {
24504 throw new Error('object-visit expects `thisArg` to be an object.');
24505 }
24506
24507 if (typeof method !== 'string') {
24508 throw new Error('object-visit expects `method` name to be a string');
24509 }
24510
24511 if (typeof thisArg[method] !== 'function') {
24512 return thisArg;
24513 }
24514
24515 var args = [].slice.call(arguments, 3);
24516 target = target || {};
24517
24518 for (var key in target) {
24519 var arr = [key, target[key]].concat(args);
24520 thisArg[method].apply(thisArg, arr);
24521 }
24522 return thisArg;
24523};
24524
24525/**
24526 * Map `visit` over an array of objects.
24527 *
24528 * @param {Object} `collection` The context in which to invoke `method`
24529 * @param {String} `method` Name of the method to call on `collection`
24530 * @param {Object} `arr` Array of objects.
24531 */
24532
24533var mapVisit = function mapVisit(collection, method, val) {
24534 if (isObject$2(val)) {
24535 return objectVisit.apply(null, arguments);
24536 }
24537
24538 if (!Array.isArray(val)) {
24539 throw new TypeError('expected an array: ' + util$2.inspect(val));
24540 }
24541
24542 var args = [].slice.call(arguments, 3);
24543
24544 for (var i = 0; i < val.length; i++) {
24545 var ele = val[i];
24546 if (isObject$2(ele)) {
24547 objectVisit.apply(null, [collection, method, ele].concat(args));
24548 } else {
24549 collection[method].apply(collection, [ele].concat(args));
24550 }
24551 }
24552};
24553
24554function isObject$2(val) {
24555 return val && (typeof val === 'function' || (!Array.isArray(val) && typeof val === 'object'));
24556}
24557
24558var collectionVisit = function(collection, method, val) {
24559 var result;
24560
24561 if (typeof val === 'string' && (method in collection)) {
24562 var args = [].slice.call(arguments, 2);
24563 result = collection[method].apply(collection, args);
24564 } else if (Array.isArray(val)) {
24565 result = mapVisit.apply(null, arguments);
24566 } else {
24567 result = objectVisit.apply(null, arguments);
24568 }
24569
24570 if (typeof result !== 'undefined') {
24571 return result;
24572 }
24573
24574 return collection;
24575};
24576
24577var toString$4 = Object.prototype.toString;
24578
24579/**
24580 * Get the native `typeof` a value.
24581 *
24582 * @param {*} `val`
24583 * @return {*} Native javascript type
24584 */
24585
24586var kindOf$3 = function kindOf(val) {
24587 // primitivies
24588 if (typeof val === 'undefined') {
24589 return 'undefined';
24590 }
24591 if (val === null) {
24592 return 'null';
24593 }
24594 if (val === true || val === false || val instanceof Boolean) {
24595 return 'boolean';
24596 }
24597 if (typeof val === 'string' || val instanceof String) {
24598 return 'string';
24599 }
24600 if (typeof val === 'number' || val instanceof Number) {
24601 return 'number';
24602 }
24603
24604 // functions
24605 if (typeof val === 'function' || val instanceof Function) {
24606 return 'function';
24607 }
24608
24609 // array
24610 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
24611 return 'array';
24612 }
24613
24614 // check for instances of RegExp and Date before calling `toString`
24615 if (val instanceof RegExp) {
24616 return 'regexp';
24617 }
24618 if (val instanceof Date) {
24619 return 'date';
24620 }
24621
24622 // other objects
24623 var type = toString$4.call(val);
24624
24625 if (type === '[object RegExp]') {
24626 return 'regexp';
24627 }
24628 if (type === '[object Date]') {
24629 return 'date';
24630 }
24631 if (type === '[object Arguments]') {
24632 return 'arguments';
24633 }
24634 if (type === '[object Error]') {
24635 return 'error';
24636 }
24637
24638 // buffer
24639 if (isBuffer_1(val)) {
24640 return 'buffer';
24641 }
24642
24643 // es6: Map, WeakMap, Set, WeakSet
24644 if (type === '[object Set]') {
24645 return 'set';
24646 }
24647 if (type === '[object WeakSet]') {
24648 return 'weakset';
24649 }
24650 if (type === '[object Map]') {
24651 return 'map';
24652 }
24653 if (type === '[object WeakMap]') {
24654 return 'weakmap';
24655 }
24656 if (type === '[object Symbol]') {
24657 return 'symbol';
24658 }
24659
24660 // typed arrays
24661 if (type === '[object Int8Array]') {
24662 return 'int8array';
24663 }
24664 if (type === '[object Uint8Array]') {
24665 return 'uint8array';
24666 }
24667 if (type === '[object Uint8ClampedArray]') {
24668 return 'uint8clampedarray';
24669 }
24670 if (type === '[object Int16Array]') {
24671 return 'int16array';
24672 }
24673 if (type === '[object Uint16Array]') {
24674 return 'uint16array';
24675 }
24676 if (type === '[object Int32Array]') {
24677 return 'int32array';
24678 }
24679 if (type === '[object Uint32Array]') {
24680 return 'uint32array';
24681 }
24682 if (type === '[object Float32Array]') {
24683 return 'float32array';
24684 }
24685 if (type === '[object Float64Array]') {
24686 return 'float64array';
24687 }
24688
24689 // must be a plain object
24690 return 'object';
24691};
24692
24693var toObjectPath = function toPath(args) {
24694 if (kindOf$3(args) !== 'arguments') {
24695 args = arguments;
24696 }
24697 return filter(args).join('.');
24698};
24699
24700function filter(arr) {
24701 var len = arr.length;
24702 var idx = -1;
24703 var res = [];
24704
24705 while (++idx < len) {
24706 var ele = arr[idx];
24707 if (kindOf$3(ele) === 'arguments' || Array.isArray(ele)) {
24708 res.push.apply(res, filter(ele));
24709 } else if (typeof ele === 'string') {
24710 res.push(ele);
24711 }
24712 }
24713 return res;
24714}
24715
24716var arrUnion = function union(init) {
24717 if (!Array.isArray(init)) {
24718 throw new TypeError('arr-union expects the first argument to be an array.');
24719 }
24720
24721 var len = arguments.length;
24722 var i = 0;
24723
24724 while (++i < len) {
24725 var arg = arguments[i];
24726 if (!arg) continue;
24727
24728 if (!Array.isArray(arg)) {
24729 arg = [arg];
24730 }
24731
24732 for (var j = 0; j < arg.length; j++) {
24733 var ele = arg[j];
24734
24735 if (init.indexOf(ele) >= 0) {
24736 continue;
24737 }
24738 init.push(ele);
24739 }
24740 }
24741 return init;
24742};
24743
24744/*!
24745 * get-value <https://github.com/jonschlinkert/get-value>
24746 *
24747 * Copyright (c) 2014-2015, Jon Schlinkert.
24748 * Licensed under the MIT License.
24749 */
24750
24751var getValue = function(obj, prop, a, b, c) {
24752 if (!isObject$3(obj) || !prop) {
24753 return obj;
24754 }
24755
24756 prop = toString$5(prop);
24757
24758 // allowing for multiple properties to be passed as
24759 // a string or array, but much faster (3-4x) than doing
24760 // `[].slice.call(arguments)`
24761 if (a) prop += '.' + toString$5(a);
24762 if (b) prop += '.' + toString$5(b);
24763 if (c) prop += '.' + toString$5(c);
24764
24765 if (prop in obj) {
24766 return obj[prop];
24767 }
24768
24769 var segs = prop.split('.');
24770 var len = segs.length;
24771 var i = -1;
24772
24773 while (obj && (++i < len)) {
24774 var key = segs[i];
24775 while (key[key.length - 1] === '\\') {
24776 key = key.slice(0, -1) + '.' + segs[++i];
24777 }
24778 obj = obj[key];
24779 }
24780 return obj;
24781};
24782
24783function isObject$3(val) {
24784 return val !== null && (typeof val === 'object' || typeof val === 'function');
24785}
24786
24787function toString$5(val) {
24788 if (!val) return '';
24789 if (Array.isArray(val)) {
24790 return val.join('.');
24791 }
24792 return val;
24793}
24794
24795var extendShallow$3 = function extend(o/*, objects*/) {
24796 if (!isExtendable$1(o)) { o = {}; }
24797
24798 var len = arguments.length;
24799 for (var i = 1; i < len; i++) {
24800 var obj = arguments[i];
24801
24802 if (isExtendable$1(obj)) {
24803 assign$3(o, obj);
24804 }
24805 }
24806 return o;
24807};
24808
24809function assign$3(a, b) {
24810 for (var key in b) {
24811 if (hasOwn$3(b, key)) {
24812 a[key] = b[key];
24813 }
24814 }
24815}
24816
24817/**
24818 * Returns true if the given `key` is an own property of `obj`.
24819 */
24820
24821function hasOwn$3(obj, key) {
24822 return Object.prototype.hasOwnProperty.call(obj, key);
24823}
24824
24825var setValue = function(obj, path, val) {
24826 if (!isExtendable$1(obj)) {
24827 return obj;
24828 }
24829
24830 if (Array.isArray(path)) {
24831 path = toObjectPath(path);
24832 }
24833
24834 if (typeof path !== 'string') {
24835 return obj;
24836 }
24837
24838 var segs = path.split('.');
24839 var len = segs.length, i = -1;
24840 var res = obj;
24841 var last;
24842
24843 while (++i < len) {
24844 var key = segs[i];
24845
24846 while (key[key.length - 1] === '\\') {
24847 key = key.slice(0, -1) + '.' + segs[++i];
24848 }
24849
24850 if (i === len - 1) {
24851 last = key;
24852 break;
24853 }
24854
24855 if (!isExtendable$1(obj[key])) {
24856 obj[key] = {};
24857 }
24858 obj = obj[key];
24859 }
24860
24861 if (obj.hasOwnProperty(last) && isExtendable$1(obj[last])) {
24862 if (isPlainObject(val)) {
24863 extendShallow$3(obj[last], val);
24864 } else {
24865 obj[last] = val;
24866 }
24867
24868 } else {
24869 obj[last] = val;
24870 }
24871 return res;
24872};
24873
24874var unionValue = function unionValue(obj, prop, value) {
24875 if (!isExtendable$1(obj)) {
24876 throw new TypeError('union-value expects the first argument to be an object.');
24877 }
24878
24879 if (typeof prop !== 'string') {
24880 throw new TypeError('union-value expects `prop` to be a string.');
24881 }
24882
24883 var arr = arrayify(getValue(obj, prop));
24884 setValue(obj, prop, arrUnion(arr, arrayify(value)));
24885 return obj;
24886};
24887
24888function arrayify(val) {
24889 if (val === null || typeof val === 'undefined') {
24890 return [];
24891 }
24892 if (Array.isArray(val)) {
24893 return val;
24894 }
24895 return [val];
24896}
24897
24898var toString$6 = {}.toString;
24899
24900var isarray = Array.isArray || function (arr) {
24901 return toString$6.call(arr) == '[object Array]';
24902};
24903
24904var isobject$1 = function isObject(val) {
24905 return val != null && typeof val === 'object' && isarray(val) === false;
24906};
24907
24908/*!
24909 * has-values <https://github.com/jonschlinkert/has-values>
24910 *
24911 * Copyright (c) 2014-2015, Jon Schlinkert.
24912 * Licensed under the MIT License.
24913 */
24914
24915var hasValues = function hasValue(o, noZero) {
24916 if (o === null || o === undefined) {
24917 return false;
24918 }
24919
24920 if (typeof o === 'boolean') {
24921 return true;
24922 }
24923
24924 if (typeof o === 'number') {
24925 if (o === 0 && noZero === true) {
24926 return false;
24927 }
24928 return true;
24929 }
24930
24931 if (o.length !== undefined) {
24932 return o.length !== 0;
24933 }
24934
24935 for (var key in o) {
24936 if (o.hasOwnProperty(key)) {
24937 return true;
24938 }
24939 }
24940 return false;
24941};
24942
24943var hasValue = function(obj, prop, noZero) {
24944 if (isobject$1(obj)) {
24945 return hasValues(getValue(obj, prop), noZero);
24946 }
24947 return hasValues(obj, prop);
24948};
24949
24950var unsetValue = function unset(obj, prop) {
24951 if (!isobject(obj)) {
24952 throw new TypeError('expected an object.');
24953 }
24954 if (obj.hasOwnProperty(prop)) {
24955 delete obj[prop];
24956 return true;
24957 }
24958
24959 if (hasValue(obj, prop)) {
24960 var segs = prop.split('.');
24961 var last = segs.pop();
24962 while (segs.length && segs[segs.length - 1].slice(-1) === '\\') {
24963 last = segs.pop().slice(0, -1) + '.' + last;
24964 }
24965 while (segs.length) obj = obj[prop = segs.shift()];
24966 return (delete obj[last]);
24967 }
24968 return true;
24969};
24970
24971var extendShallow$4 = function extend(o/*, objects*/) {
24972 if (!isExtendable$1(o)) { o = {}; }
24973
24974 var len = arguments.length;
24975 for (var i = 1; i < len; i++) {
24976 var obj = arguments[i];
24977
24978 if (isExtendable$1(obj)) {
24979 assign$4(o, obj);
24980 }
24981 }
24982 return o;
24983};
24984
24985function assign$4(a, b) {
24986 for (var key in b) {
24987 if (hasOwn$4(b, key)) {
24988 a[key] = b[key];
24989 }
24990 }
24991}
24992
24993/**
24994 * Returns true if the given `key` is an own property of `obj`.
24995 */
24996
24997function hasOwn$4(obj, key) {
24998 return Object.prototype.hasOwnProperty.call(obj, key);
24999}
25000
25001var setValue$1 = function(obj, prop, val) {
25002 if (!isExtendable$1(obj)) {
25003 return obj;
25004 }
25005
25006 if (Array.isArray(prop)) {
25007 prop = [].concat.apply([], prop).join('.');
25008 }
25009
25010 if (typeof prop !== 'string') {
25011 return obj;
25012 }
25013
25014 var keys = splitString(prop, {sep: '.', brackets: true});
25015 var len = keys.length;
25016 var idx = -1;
25017 var current = obj;
25018
25019 while (++idx < len) {
25020 var key = keys[idx];
25021 if (idx !== len - 1) {
25022 if (!isExtendable$1(current[key])) {
25023 current[key] = {};
25024 }
25025 current = current[key];
25026 continue;
25027 }
25028
25029 if (isPlainObject(current[key]) && isPlainObject(val)) {
25030 current[key] = extendShallow$4({}, current[key], val);
25031 } else {
25032 current[key] = val;
25033 }
25034 }
25035
25036 return obj;
25037};
25038
25039/**
25040 * Create a `Cache` constructor that when instantiated will
25041 * store values on the given `prop`.
25042 *
25043 * ```js
25044 * var Cache = require('cache-base').namespace('data');
25045 * var cache = new Cache();
25046 *
25047 * cache.set('foo', 'bar');
25048 * //=> {data: {foo: 'bar'}}
25049 * ```
25050 * @param {String} `prop` The property name to use for storing values.
25051 * @return {Function} Returns a custom `Cache` constructor
25052 * @api public
25053 */
25054
25055function namespace(prop) {
25056
25057 /**
25058 * Create a new `Cache`. Internally the `Cache` constructor is created using
25059 * the `namespace` function, with `cache` defined as the storage object.
25060 *
25061 * ```js
25062 * var app = new Cache();
25063 * ```
25064 * @param {Object} `cache` Optionally pass an object to initialize with.
25065 * @constructor
25066 * @api public
25067 */
25068
25069 function Cache(cache) {
25070 if (prop) {
25071 this[prop] = {};
25072 }
25073 if (cache) {
25074 this.set(cache);
25075 }
25076 }
25077
25078 /**
25079 * Inherit Emitter
25080 */
25081
25082 componentEmitter(Cache.prototype);
25083
25084 /**
25085 * Assign `value` to `key`. Also emits `set` with
25086 * the key and value.
25087 *
25088 * ```js
25089 * app.on('set', function(key, val) {
25090 * // do something when `set` is emitted
25091 * });
25092 *
25093 * app.set(key, value);
25094 *
25095 * // also takes an object or array
25096 * app.set({name: 'Halle'});
25097 * app.set([{foo: 'bar'}, {baz: 'quux'}]);
25098 * console.log(app);
25099 * //=> {name: 'Halle', foo: 'bar', baz: 'quux'}
25100 * ```
25101 *
25102 * @name .set
25103 * @emits `set` with `key` and `value` as arguments.
25104 * @param {String} `key`
25105 * @param {any} `value`
25106 * @return {Object} Returns the instance for chaining.
25107 * @api public
25108 */
25109
25110 Cache.prototype.set = function(key, val) {
25111 if (Array.isArray(key) && arguments.length === 2) {
25112 key = toObjectPath(key);
25113 }
25114 if (isobject(key) || Array.isArray(key)) {
25115 this.visit('set', key);
25116 } else {
25117 setValue$1(prop ? this[prop] : this, key, val);
25118 this.emit('set', key, val);
25119 }
25120 return this;
25121 };
25122
25123 /**
25124 * Union `array` to `key`. Also emits `set` with
25125 * the key and value.
25126 *
25127 * ```js
25128 * app.union('a.b', ['foo']);
25129 * app.union('a.b', ['bar']);
25130 * console.log(app.get('a'));
25131 * //=> {b: ['foo', 'bar']}
25132 * ```
25133 * @name .union
25134 * @param {String} `key`
25135 * @param {any} `value`
25136 * @return {Object} Returns the instance for chaining.
25137 * @api public
25138 */
25139
25140 Cache.prototype.union = function(key, val) {
25141 if (Array.isArray(key) && arguments.length === 2) {
25142 key = toObjectPath(key);
25143 }
25144 var ctx = prop ? this[prop] : this;
25145 unionValue(ctx, key, arrayify$1(val));
25146 this.emit('union', val);
25147 return this;
25148 };
25149
25150 /**
25151 * Return the value of `key`. Dot notation may be used
25152 * to get [nested property values][get-value].
25153 *
25154 * ```js
25155 * app.set('a.b.c', 'd');
25156 * app.get('a.b');
25157 * //=> {c: 'd'}
25158 *
25159 * app.get(['a', 'b']);
25160 * //=> {c: 'd'}
25161 * ```
25162 *
25163 * @name .get
25164 * @emits `get` with `key` and `value` as arguments.
25165 * @param {String} `key` The name of the property to get. Dot-notation may be used.
25166 * @return {any} Returns the value of `key`
25167 * @api public
25168 */
25169
25170 Cache.prototype.get = function(key) {
25171 key = toObjectPath(arguments);
25172
25173 var ctx = prop ? this[prop] : this;
25174 var val = getValue(ctx, key);
25175
25176 this.emit('get', key, val);
25177 return val;
25178 };
25179
25180 /**
25181 * Return true if app has a stored value for `key`,
25182 * false only if value is `undefined`.
25183 *
25184 * ```js
25185 * app.set('foo', 'bar');
25186 * app.has('foo');
25187 * //=> true
25188 * ```
25189 *
25190 * @name .has
25191 * @emits `has` with `key` and true or false as arguments.
25192 * @param {String} `key`
25193 * @return {Boolean}
25194 * @api public
25195 */
25196
25197 Cache.prototype.has = function(key) {
25198 key = toObjectPath(arguments);
25199
25200 var ctx = prop ? this[prop] : this;
25201 var val = getValue(ctx, key);
25202
25203 var has = typeof val !== 'undefined';
25204 this.emit('has', key, has);
25205 return has;
25206 };
25207
25208 /**
25209 * Delete one or more properties from the instance.
25210 *
25211 * ```js
25212 * app.del(); // delete all
25213 * // or
25214 * app.del('foo');
25215 * // or
25216 * app.del(['foo', 'bar']);
25217 * ```
25218 * @name .del
25219 * @emits `del` with the `key` as the only argument.
25220 * @param {String|Array} `key` Property name or array of property names.
25221 * @return {Object} Returns the instance for chaining.
25222 * @api public
25223 */
25224
25225 Cache.prototype.del = function(key) {
25226 if (Array.isArray(key)) {
25227 this.visit('del', key);
25228 } else {
25229 unsetValue(prop ? this[prop] : this, key);
25230 this.emit('del', key);
25231 }
25232 return this;
25233 };
25234
25235 /**
25236 * Reset the entire cache to an empty object.
25237 *
25238 * ```js
25239 * app.clear();
25240 * ```
25241 * @api public
25242 */
25243
25244 Cache.prototype.clear = function() {
25245 if (prop) {
25246 this[prop] = {};
25247 }
25248 };
25249
25250 /**
25251 * Visit `method` over the properties in the given object, or map
25252 * visit over the object-elements in an array.
25253 *
25254 * @name .visit
25255 * @param {String} `method` The name of the `base` method to call.
25256 * @param {Object|Array} `val` The object or array to iterate over.
25257 * @return {Object} Returns the instance for chaining.
25258 * @api public
25259 */
25260
25261 Cache.prototype.visit = function(method, val) {
25262 collectionVisit(this, method, val);
25263 return this;
25264 };
25265
25266 return Cache;
25267}
25268
25269/**
25270 * Cast val to an array
25271 */
25272
25273function arrayify$1(val) {
25274 return val ? (Array.isArray(val) ? val : [val]) : [];
25275}
25276
25277/**
25278 * Expose `Cache`
25279 */
25280
25281var cacheBase = namespace();
25282
25283/**
25284 * Expose `Cache.namespace`
25285 */
25286
25287var namespace_1 = namespace;
25288cacheBase.namespace = namespace_1;
25289
25290var isExtendable$2 = function isExtendable(val) {
25291 return isPlainObject(val) || typeof val === 'function' || Array.isArray(val);
25292};
25293
25294/*!
25295 * for-in <https://github.com/jonschlinkert/for-in>
25296 *
25297 * Copyright (c) 2014-2017, Jon Schlinkert.
25298 * Released under the MIT License.
25299 */
25300
25301var forIn = function forIn(obj, fn, thisArg) {
25302 for (var key in obj) {
25303 if (fn.call(thisArg, obj[key], key, obj) === false) {
25304 break;
25305 }
25306 }
25307};
25308
25309function mixinDeep(target, objects) {
25310 var len = arguments.length, i = 0;
25311 while (++i < len) {
25312 var obj = arguments[i];
25313 if (isObject$4(obj)) {
25314 forIn(obj, copy, target);
25315 }
25316 }
25317 return target;
25318}
25319
25320/**
25321 * Copy properties from the source object to the
25322 * target object.
25323 *
25324 * @param {*} `val`
25325 * @param {String} `key`
25326 */
25327
25328function copy(val, key) {
25329 if (key === '__proto__') {
25330 return;
25331 }
25332
25333 var obj = this[key];
25334 if (isObject$4(val) && isObject$4(obj)) {
25335 mixinDeep(obj, val);
25336 } else {
25337 this[key] = val;
25338 }
25339}
25340
25341/**
25342 * Returns true if `val` is an object or function.
25343 *
25344 * @param {any} val
25345 * @return {Boolean}
25346 */
25347
25348function isObject$4(val) {
25349 return isExtendable$2(val) && !Array.isArray(val);
25350}
25351
25352/**
25353 * Expose `mixinDeep`
25354 */
25355
25356var mixinDeep_1 = mixinDeep;
25357
25358/*!
25359 * pascalcase <https://github.com/jonschlinkert/pascalcase>
25360 *
25361 * Copyright (c) 2015, Jon Schlinkert.
25362 * Licensed under the MIT License.
25363 */
25364
25365function pascalcase(str) {
25366 if (typeof str !== 'string') {
25367 throw new TypeError('expected a string.');
25368 }
25369 str = str.replace(/([A-Z])/g, ' $1');
25370 if (str.length === 1) { return str.toUpperCase(); }
25371 str = str.replace(/^[\W_]+|[\W_]+$/g, '').toLowerCase();
25372 str = str.charAt(0).toUpperCase() + str.slice(1);
25373 return str.replace(/[\W_]+(\w|$)/g, function (_, ch) {
25374 return ch.toUpperCase();
25375 });
25376}
25377
25378var pascalcase_1 = pascalcase;
25379
25380var toString$7 = Object.prototype.toString;
25381
25382/**
25383 * Get the native `typeof` a value.
25384 *
25385 * @param {*} `val`
25386 * @return {*} Native javascript type
25387 */
25388
25389var kindOf$4 = function kindOf(val) {
25390 var type = typeof val;
25391
25392 // primitivies
25393 if (type === 'undefined') {
25394 return 'undefined';
25395 }
25396 if (val === null) {
25397 return 'null';
25398 }
25399 if (val === true || val === false || val instanceof Boolean) {
25400 return 'boolean';
25401 }
25402 if (type === 'string' || val instanceof String) {
25403 return 'string';
25404 }
25405 if (type === 'number' || val instanceof Number) {
25406 return 'number';
25407 }
25408
25409 // functions
25410 if (type === 'function' || val instanceof Function) {
25411 if (typeof val.constructor.name !== 'undefined' && val.constructor.name.slice(0, 9) === 'Generator') {
25412 return 'generatorfunction';
25413 }
25414 return 'function';
25415 }
25416
25417 // array
25418 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
25419 return 'array';
25420 }
25421
25422 // check for instances of RegExp and Date before calling `toString`
25423 if (val instanceof RegExp) {
25424 return 'regexp';
25425 }
25426 if (val instanceof Date) {
25427 return 'date';
25428 }
25429
25430 // other objects
25431 type = toString$7.call(val);
25432
25433 if (type === '[object RegExp]') {
25434 return 'regexp';
25435 }
25436 if (type === '[object Date]') {
25437 return 'date';
25438 }
25439 if (type === '[object Arguments]') {
25440 return 'arguments';
25441 }
25442 if (type === '[object Error]') {
25443 return 'error';
25444 }
25445 if (type === '[object Promise]') {
25446 return 'promise';
25447 }
25448
25449 // buffer
25450 if (isBuffer$2(val)) {
25451 return 'buffer';
25452 }
25453
25454 // es6: Map, WeakMap, Set, WeakSet
25455 if (type === '[object Set]') {
25456 return 'set';
25457 }
25458 if (type === '[object WeakSet]') {
25459 return 'weakset';
25460 }
25461 if (type === '[object Map]') {
25462 return 'map';
25463 }
25464 if (type === '[object WeakMap]') {
25465 return 'weakmap';
25466 }
25467 if (type === '[object Symbol]') {
25468 return 'symbol';
25469 }
25470
25471 if (type === '[object Map Iterator]') {
25472 return 'mapiterator';
25473 }
25474 if (type === '[object Set Iterator]') {
25475 return 'setiterator';
25476 }
25477 if (type === '[object String Iterator]') {
25478 return 'stringiterator';
25479 }
25480 if (type === '[object Array Iterator]') {
25481 return 'arrayiterator';
25482 }
25483
25484 // typed arrays
25485 if (type === '[object Int8Array]') {
25486 return 'int8array';
25487 }
25488 if (type === '[object Uint8Array]') {
25489 return 'uint8array';
25490 }
25491 if (type === '[object Uint8ClampedArray]') {
25492 return 'uint8clampedarray';
25493 }
25494 if (type === '[object Int16Array]') {
25495 return 'int16array';
25496 }
25497 if (type === '[object Uint16Array]') {
25498 return 'uint16array';
25499 }
25500 if (type === '[object Int32Array]') {
25501 return 'int32array';
25502 }
25503 if (type === '[object Uint32Array]') {
25504 return 'uint32array';
25505 }
25506 if (type === '[object Float32Array]') {
25507 return 'float32array';
25508 }
25509 if (type === '[object Float64Array]') {
25510 return 'float64array';
25511 }
25512
25513 // must be a plain object
25514 return 'object';
25515};
25516
25517/**
25518 * If you need to support Safari 5-7 (8-10 yr-old browser),
25519 * take a look at https://github.com/feross/is-buffer
25520 */
25521
25522function isBuffer$2(val) {
25523 return val.constructor
25524 && typeof val.constructor.isBuffer === 'function'
25525 && val.constructor.isBuffer(val);
25526}
25527
25528var toString$8 = Object.prototype.toString;
25529
25530/**
25531 * Get the native `typeof` a value.
25532 *
25533 * @param {*} `val`
25534 * @return {*} Native javascript type
25535 */
25536
25537var kindOf$5 = function kindOf(val) {
25538 // primitivies
25539 if (typeof val === 'undefined') {
25540 return 'undefined';
25541 }
25542 if (val === null) {
25543 return 'null';
25544 }
25545 if (val === true || val === false || val instanceof Boolean) {
25546 return 'boolean';
25547 }
25548 if (typeof val === 'string' || val instanceof String) {
25549 return 'string';
25550 }
25551 if (typeof val === 'number' || val instanceof Number) {
25552 return 'number';
25553 }
25554
25555 // functions
25556 if (typeof val === 'function' || val instanceof Function) {
25557 return 'function';
25558 }
25559
25560 // array
25561 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
25562 return 'array';
25563 }
25564
25565 // check for instances of RegExp and Date before calling `toString`
25566 if (val instanceof RegExp) {
25567 return 'regexp';
25568 }
25569 if (val instanceof Date) {
25570 return 'date';
25571 }
25572
25573 // other objects
25574 var type = toString$8.call(val);
25575
25576 if (type === '[object RegExp]') {
25577 return 'regexp';
25578 }
25579 if (type === '[object Date]') {
25580 return 'date';
25581 }
25582 if (type === '[object Arguments]') {
25583 return 'arguments';
25584 }
25585 if (type === '[object Error]') {
25586 return 'error';
25587 }
25588
25589 // buffer
25590 if (isBuffer_1(val)) {
25591 return 'buffer';
25592 }
25593
25594 // es6: Map, WeakMap, Set, WeakSet
25595 if (type === '[object Set]') {
25596 return 'set';
25597 }
25598 if (type === '[object WeakSet]') {
25599 return 'weakset';
25600 }
25601 if (type === '[object Map]') {
25602 return 'map';
25603 }
25604 if (type === '[object WeakMap]') {
25605 return 'weakmap';
25606 }
25607 if (type === '[object Symbol]') {
25608 return 'symbol';
25609 }
25610
25611 // typed arrays
25612 if (type === '[object Int8Array]') {
25613 return 'int8array';
25614 }
25615 if (type === '[object Uint8Array]') {
25616 return 'uint8array';
25617 }
25618 if (type === '[object Uint8ClampedArray]') {
25619 return 'uint8clampedarray';
25620 }
25621 if (type === '[object Int16Array]') {
25622 return 'int16array';
25623 }
25624 if (type === '[object Uint16Array]') {
25625 return 'uint16array';
25626 }
25627 if (type === '[object Int32Array]') {
25628 return 'int32array';
25629 }
25630 if (type === '[object Uint32Array]') {
25631 return 'uint32array';
25632 }
25633 if (type === '[object Float32Array]') {
25634 return 'float32array';
25635 }
25636 if (type === '[object Float64Array]') {
25637 return 'float64array';
25638 }
25639
25640 // must be a plain object
25641 return 'object';
25642};
25643
25644// accessor descriptor properties
25645var accessor$3 = {
25646 get: 'function',
25647 set: 'function',
25648 configurable: 'boolean',
25649 enumerable: 'boolean'
25650};
25651
25652function isAccessorDescriptor$3(obj, prop) {
25653 if (typeof prop === 'string') {
25654 var val = Object.getOwnPropertyDescriptor(obj, prop);
25655 return typeof val !== 'undefined';
25656 }
25657
25658 if (kindOf$5(obj) !== 'object') {
25659 return false;
25660 }
25661
25662 if (has$4(obj, 'value') || has$4(obj, 'writable')) {
25663 return false;
25664 }
25665
25666 if (!has$4(obj, 'get') || typeof obj.get !== 'function') {
25667 return false;
25668 }
25669
25670 // tldr: it's valid to have "set" be undefined
25671 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
25672 // was used to get the value, and only `get` was defined by the user
25673 if (has$4(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
25674 return false;
25675 }
25676
25677 for (var key in obj) {
25678 if (!accessor$3.hasOwnProperty(key)) {
25679 continue;
25680 }
25681
25682 if (kindOf$5(obj[key]) === accessor$3[key]) {
25683 continue;
25684 }
25685
25686 if (typeof obj[key] !== 'undefined') {
25687 return false;
25688 }
25689 }
25690 return true;
25691}
25692
25693function has$4(obj, key) {
25694 return {}.hasOwnProperty.call(obj, key);
25695}
25696
25697/**
25698 * Expose `isAccessorDescriptor`
25699 */
25700
25701var isAccessorDescriptor_1$3 = isAccessorDescriptor$3;
25702
25703var toString$9 = Object.prototype.toString;
25704
25705/**
25706 * Get the native `typeof` a value.
25707 *
25708 * @param {*} `val`
25709 * @return {*} Native javascript type
25710 */
25711
25712var kindOf$6 = function kindOf(val) {
25713 // primitivies
25714 if (typeof val === 'undefined') {
25715 return 'undefined';
25716 }
25717 if (val === null) {
25718 return 'null';
25719 }
25720 if (val === true || val === false || val instanceof Boolean) {
25721 return 'boolean';
25722 }
25723 if (typeof val === 'string' || val instanceof String) {
25724 return 'string';
25725 }
25726 if (typeof val === 'number' || val instanceof Number) {
25727 return 'number';
25728 }
25729
25730 // functions
25731 if (typeof val === 'function' || val instanceof Function) {
25732 return 'function';
25733 }
25734
25735 // array
25736 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
25737 return 'array';
25738 }
25739
25740 // check for instances of RegExp and Date before calling `toString`
25741 if (val instanceof RegExp) {
25742 return 'regexp';
25743 }
25744 if (val instanceof Date) {
25745 return 'date';
25746 }
25747
25748 // other objects
25749 var type = toString$9.call(val);
25750
25751 if (type === '[object RegExp]') {
25752 return 'regexp';
25753 }
25754 if (type === '[object Date]') {
25755 return 'date';
25756 }
25757 if (type === '[object Arguments]') {
25758 return 'arguments';
25759 }
25760 if (type === '[object Error]') {
25761 return 'error';
25762 }
25763
25764 // buffer
25765 if (isBuffer_1(val)) {
25766 return 'buffer';
25767 }
25768
25769 // es6: Map, WeakMap, Set, WeakSet
25770 if (type === '[object Set]') {
25771 return 'set';
25772 }
25773 if (type === '[object WeakSet]') {
25774 return 'weakset';
25775 }
25776 if (type === '[object Map]') {
25777 return 'map';
25778 }
25779 if (type === '[object WeakMap]') {
25780 return 'weakmap';
25781 }
25782 if (type === '[object Symbol]') {
25783 return 'symbol';
25784 }
25785
25786 // typed arrays
25787 if (type === '[object Int8Array]') {
25788 return 'int8array';
25789 }
25790 if (type === '[object Uint8Array]') {
25791 return 'uint8array';
25792 }
25793 if (type === '[object Uint8ClampedArray]') {
25794 return 'uint8clampedarray';
25795 }
25796 if (type === '[object Int16Array]') {
25797 return 'int16array';
25798 }
25799 if (type === '[object Uint16Array]') {
25800 return 'uint16array';
25801 }
25802 if (type === '[object Int32Array]') {
25803 return 'int32array';
25804 }
25805 if (type === '[object Uint32Array]') {
25806 return 'uint32array';
25807 }
25808 if (type === '[object Float32Array]') {
25809 return 'float32array';
25810 }
25811 if (type === '[object Float64Array]') {
25812 return 'float64array';
25813 }
25814
25815 // must be a plain object
25816 return 'object';
25817};
25818
25819// data descriptor properties
25820var data = {
25821 configurable: 'boolean',
25822 enumerable: 'boolean',
25823 writable: 'boolean'
25824};
25825
25826function isDataDescriptor$3(obj, prop) {
25827 if (kindOf$6(obj) !== 'object') {
25828 return false;
25829 }
25830
25831 if (typeof prop === 'string') {
25832 var val = Object.getOwnPropertyDescriptor(obj, prop);
25833 return typeof val !== 'undefined';
25834 }
25835
25836 if (!('value' in obj) && !('writable' in obj)) {
25837 return false;
25838 }
25839
25840 for (var key in obj) {
25841 if (key === 'value') continue;
25842
25843 if (!data.hasOwnProperty(key)) {
25844 continue;
25845 }
25846
25847 if (kindOf$6(obj[key]) === data[key]) {
25848 continue;
25849 }
25850
25851 if (typeof obj[key] !== 'undefined') {
25852 return false;
25853 }
25854 }
25855 return true;
25856}
25857
25858/**
25859 * Expose `isDataDescriptor`
25860 */
25861
25862var isDataDescriptor_1 = isDataDescriptor$3;
25863
25864var isDescriptor$3 = function isDescriptor(obj, key) {
25865 if (kindOf$4(obj) !== 'object') {
25866 return false;
25867 }
25868 if ('get' in obj) {
25869 return isAccessorDescriptor_1$3(obj, key);
25870 }
25871 return isDataDescriptor_1(obj, key);
25872};
25873
25874var defineProperty$3 = function defineProperty(obj, prop, val) {
25875 if (typeof obj !== 'object' && typeof obj !== 'function') {
25876 throw new TypeError('expected an object or function.');
25877 }
25878
25879 if (typeof prop !== 'string') {
25880 throw new TypeError('expected `prop` to be a string.');
25881 }
25882
25883 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
25884 return Object.defineProperty(obj, prop, val);
25885 }
25886
25887 return Object.defineProperty(obj, prop, {
25888 configurable: true,
25889 enumerable: false,
25890 writable: true,
25891 value: val
25892 });
25893};
25894
25895var toString$a = Object.prototype.toString;
25896
25897/**
25898 * Get the native `typeof` a value.
25899 *
25900 * @param {*} `val`
25901 * @return {*} Native javascript type
25902 */
25903
25904var kindOf$7 = function kindOf(val) {
25905 // primitivies
25906 if (typeof val === 'undefined') {
25907 return 'undefined';
25908 }
25909 if (val === null) {
25910 return 'null';
25911 }
25912 if (val === true || val === false || val instanceof Boolean) {
25913 return 'boolean';
25914 }
25915 if (typeof val === 'string' || val instanceof String) {
25916 return 'string';
25917 }
25918 if (typeof val === 'number' || val instanceof Number) {
25919 return 'number';
25920 }
25921
25922 // functions
25923 if (typeof val === 'function' || val instanceof Function) {
25924 return 'function';
25925 }
25926
25927 // array
25928 if (typeof Array.isArray !== 'undefined' && Array.isArray(val)) {
25929 return 'array';
25930 }
25931
25932 // check for instances of RegExp and Date before calling `toString`
25933 if (val instanceof RegExp) {
25934 return 'regexp';
25935 }
25936 if (val instanceof Date) {
25937 return 'date';
25938 }
25939
25940 // other objects
25941 var type = toString$a.call(val);
25942
25943 if (type === '[object RegExp]') {
25944 return 'regexp';
25945 }
25946 if (type === '[object Date]') {
25947 return 'date';
25948 }
25949 if (type === '[object Arguments]') {
25950 return 'arguments';
25951 }
25952 if (type === '[object Error]') {
25953 return 'error';
25954 }
25955
25956 // buffer
25957 if (isBuffer_1(val)) {
25958 return 'buffer';
25959 }
25960
25961 // es6: Map, WeakMap, Set, WeakSet
25962 if (type === '[object Set]') {
25963 return 'set';
25964 }
25965 if (type === '[object WeakSet]') {
25966 return 'weakset';
25967 }
25968 if (type === '[object Map]') {
25969 return 'map';
25970 }
25971 if (type === '[object WeakMap]') {
25972 return 'weakmap';
25973 }
25974 if (type === '[object Symbol]') {
25975 return 'symbol';
25976 }
25977
25978 // typed arrays
25979 if (type === '[object Int8Array]') {
25980 return 'int8array';
25981 }
25982 if (type === '[object Uint8Array]') {
25983 return 'uint8array';
25984 }
25985 if (type === '[object Uint8ClampedArray]') {
25986 return 'uint8clampedarray';
25987 }
25988 if (type === '[object Int16Array]') {
25989 return 'int16array';
25990 }
25991 if (type === '[object Uint16Array]') {
25992 return 'uint16array';
25993 }
25994 if (type === '[object Int32Array]') {
25995 return 'int32array';
25996 }
25997 if (type === '[object Uint32Array]') {
25998 return 'uint32array';
25999 }
26000 if (type === '[object Float32Array]') {
26001 return 'float32array';
26002 }
26003 if (type === '[object Float64Array]') {
26004 return 'float64array';
26005 }
26006
26007 // must be a plain object
26008 return 'object';
26009};
26010
26011/*!
26012 * copy-descriptor <https://github.com/jonschlinkert/copy-descriptor>
26013 *
26014 * Copyright (c) 2015, Jon Schlinkert.
26015 * Licensed under the MIT License.
26016 */
26017
26018/**
26019 * Copy a descriptor from one object to another.
26020 *
26021 * ```js
26022 * function App() {
26023 * this.cache = {};
26024 * }
26025 * App.prototype.set = function(key, val) {
26026 * this.cache[key] = val;
26027 * return this;
26028 * };
26029 * Object.defineProperty(App.prototype, 'count', {
26030 * get: function() {
26031 * return Object.keys(this.cache).length;
26032 * }
26033 * });
26034 *
26035 * copy(App.prototype, 'count', 'len');
26036 *
26037 * // create an instance
26038 * var app = new App();
26039 *
26040 * app.set('a', true);
26041 * app.set('b', true);
26042 * app.set('c', true);
26043 *
26044 * console.log(app.count);
26045 * //=> 3
26046 * console.log(app.len);
26047 * //=> 3
26048 * ```
26049 * @name copy
26050 * @param {Object} `receiver` The target object
26051 * @param {Object} `provider` The provider object
26052 * @param {String} `from` The key to copy on provider.
26053 * @param {String} `to` Optionally specify a new key name to use.
26054 * @return {Object}
26055 * @api public
26056 */
26057
26058var copyDescriptor = function copyDescriptor(receiver, provider, from, to) {
26059 if (!isObject$5(provider) && typeof provider !== 'function') {
26060 to = from;
26061 from = provider;
26062 provider = receiver;
26063 }
26064 if (!isObject$5(receiver) && typeof receiver !== 'function') {
26065 throw new TypeError('expected the first argument to be an object');
26066 }
26067 if (!isObject$5(provider) && typeof provider !== 'function') {
26068 throw new TypeError('expected provider to be an object');
26069 }
26070
26071 if (typeof to !== 'string') {
26072 to = from;
26073 }
26074 if (typeof from !== 'string') {
26075 throw new TypeError('expected key to be a string');
26076 }
26077
26078 if (!(from in provider)) {
26079 throw new Error('property "' + from + '" does not exist');
26080 }
26081
26082 var val = Object.getOwnPropertyDescriptor(provider, from);
26083 if (val) Object.defineProperty(receiver, to, val);
26084};
26085
26086function isObject$5(val) {
26087 return {}.toString.call(val) === '[object Object]';
26088}
26089
26090var defineProperty$4 = function defineProperty(obj, prop, val) {
26091 if (typeof obj !== 'object' && typeof obj !== 'function') {
26092 throw new TypeError('expected an object or function.');
26093 }
26094
26095 if (typeof prop !== 'string') {
26096 throw new TypeError('expected `prop` to be a string.');
26097 }
26098
26099 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
26100 return Object.defineProperty(obj, prop, val);
26101 }
26102
26103 return Object.defineProperty(obj, prop, {
26104 configurable: true,
26105 enumerable: false,
26106 writable: true,
26107 value: val
26108 });
26109};
26110
26111/**
26112 * Copy static properties, prototype properties, and descriptors from one object to another.
26113 *
26114 * ```js
26115 * function App() {}
26116 * var proto = App.prototype;
26117 * App.prototype.set = function() {};
26118 * App.prototype.get = function() {};
26119 *
26120 * var obj = {};
26121 * copy(obj, proto);
26122 * ```
26123 * @param {Object} `receiver`
26124 * @param {Object} `provider`
26125 * @param {String|Array} `omit` One or more properties to omit
26126 * @return {Object}
26127 * @api public
26128 */
26129
26130function copy$1(receiver, provider, omit) {
26131 if (!isObject$6(receiver)) {
26132 throw new TypeError('expected receiving object to be an object.');
26133 }
26134 if (!isObject$6(provider)) {
26135 throw new TypeError('expected providing object to be an object.');
26136 }
26137
26138 var props = nativeKeys(provider);
26139 var keys = Object.keys(provider);
26140 var len = props.length;
26141 omit = arrayify$2(omit);
26142
26143 while (len--) {
26144 var key = props[len];
26145
26146 if (has$5(keys, key)) {
26147 defineProperty$4(receiver, key, provider[key]);
26148 } else if (!(key in receiver) && !has$5(omit, key)) {
26149 copyDescriptor(receiver, provider, key);
26150 }
26151 }
26152}
26153/**
26154 * Return true if the given value is an object or function
26155 */
26156
26157function isObject$6(val) {
26158 return kindOf$7(val) === 'object' || typeof val === 'function';
26159}
26160
26161/**
26162 * Returns true if an array has any of the given elements, or an
26163 * object has any of the give keys.
26164 *
26165 * ```js
26166 * has(['a', 'b', 'c'], 'c');
26167 * //=> true
26168 *
26169 * has(['a', 'b', 'c'], ['c', 'z']);
26170 * //=> true
26171 *
26172 * has({a: 'b', c: 'd'}, ['c', 'z']);
26173 * //=> true
26174 * ```
26175 * @param {Object} `obj`
26176 * @param {String|Array} `val`
26177 * @return {Boolean}
26178 */
26179
26180function has$5(obj, val) {
26181 val = arrayify$2(val);
26182 var len = val.length;
26183
26184 if (isObject$6(obj)) {
26185 for (var key in obj) {
26186 if (val.indexOf(key) > -1) {
26187 return true;
26188 }
26189 }
26190
26191 var keys = nativeKeys(obj);
26192 return has$5(keys, val);
26193 }
26194
26195 if (Array.isArray(obj)) {
26196 var arr = obj;
26197 while (len--) {
26198 if (arr.indexOf(val[len]) > -1) {
26199 return true;
26200 }
26201 }
26202 return false;
26203 }
26204
26205 throw new TypeError('expected an array or object.');
26206}
26207
26208/**
26209 * Cast the given value to an array.
26210 *
26211 * ```js
26212 * arrayify('foo');
26213 * //=> ['foo']
26214 *
26215 * arrayify(['foo']);
26216 * //=> ['foo']
26217 * ```
26218 *
26219 * @param {String|Array} `val`
26220 * @return {Array}
26221 */
26222
26223function arrayify$2(val) {
26224 return val ? (Array.isArray(val) ? val : [val]) : [];
26225}
26226
26227/**
26228 * Returns true if a value has a `contructor`
26229 *
26230 * ```js
26231 * hasConstructor({});
26232 * //=> true
26233 *
26234 * hasConstructor(Object.create(null));
26235 * //=> false
26236 * ```
26237 * @param {Object} `value`
26238 * @return {Boolean}
26239 */
26240
26241function hasConstructor(val) {
26242 return isObject$6(val) && typeof val.constructor !== 'undefined';
26243}
26244
26245/**
26246 * Get the native `ownPropertyNames` from the constructor of the
26247 * given `object`. An empty array is returned if the object does
26248 * not have a constructor.
26249 *
26250 * ```js
26251 * nativeKeys({a: 'b', b: 'c', c: 'd'})
26252 * //=> ['a', 'b', 'c']
26253 *
26254 * nativeKeys(function(){})
26255 * //=> ['length', 'caller']
26256 * ```
26257 *
26258 * @param {Object} `obj` Object that has a `constructor`.
26259 * @return {Array} Array of keys.
26260 */
26261
26262function nativeKeys(val) {
26263 if (!hasConstructor(val)) return [];
26264 return Object.getOwnPropertyNames(val);
26265}
26266
26267/**
26268 * Expose `copy`
26269 */
26270
26271var objectCopy = copy$1;
26272
26273/**
26274 * Expose `copy.has` for tests
26275 */
26276
26277var has_1 = has$5;
26278objectCopy.has = has_1;
26279
26280var defineProperty$5 = function defineProperty(obj, prop, val) {
26281 if (typeof obj !== 'object' && typeof obj !== 'function') {
26282 throw new TypeError('expected an object or function.');
26283 }
26284
26285 if (typeof prop !== 'string') {
26286 throw new TypeError('expected `prop` to be a string.');
26287 }
26288
26289 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
26290 return Object.defineProperty(obj, prop, val);
26291 }
26292
26293 return Object.defineProperty(obj, prop, {
26294 configurable: true,
26295 enumerable: false,
26296 writable: true,
26297 value: val
26298 });
26299};
26300
26301/**
26302 * Returns a function for extending the static properties,
26303 * prototype properties, and descriptors from the `Parent`
26304 * constructor onto `Child` constructors.
26305 *
26306 * ```js
26307 * var extend = require('static-extend');
26308 * Parent.extend = extend(Parent);
26309 *
26310 * // optionally pass a custom merge function as the second arg
26311 * Parent.extend = extend(Parent, function(Child) {
26312 * Child.prototype.mixin = function(key, val) {
26313 * Child.prototype[key] = val;
26314 * };
26315 * });
26316 *
26317 * // extend "child" constructors
26318 * Parent.extend(Child);
26319 *
26320 * // optionally define prototype methods as the second arg
26321 * Parent.extend(Child, {
26322 * foo: function() {},
26323 * bar: function() {}
26324 * });
26325 * ```
26326 * @param {Function} `Parent` Parent ctor
26327 * @param {Function} `extendFn` Optional extend function for handling any necessary custom merging. Useful when updating methods that require a specific prototype.
26328 * @param {Function} `Child` Child ctor
26329 * @param {Object} `proto` Optionally pass additional prototype properties to inherit.
26330 * @return {Object}
26331 * @api public
26332 */
26333
26334function extend(Parent, extendFn) {
26335 if (typeof Parent !== 'function') {
26336 throw new TypeError('expected Parent to be a function.');
26337 }
26338
26339 return function(Ctor, proto) {
26340 if (typeof Ctor !== 'function') {
26341 throw new TypeError('expected Ctor to be a function.');
26342 }
26343
26344 util$2.inherits(Ctor, Parent);
26345 objectCopy(Ctor, Parent);
26346
26347 // proto can be null or a plain object
26348 if (typeof proto === 'object') {
26349 var obj = Object.create(proto);
26350
26351 for (var k in obj) {
26352 Ctor.prototype[k] = obj[k];
26353 }
26354 }
26355
26356 // keep a reference to the parent prototype
26357 defineProperty$5(Ctor.prototype, '_parent_', {
26358 configurable: true,
26359 set: function() {},
26360 get: function() {
26361 return Parent.prototype;
26362 }
26363 });
26364
26365 if (typeof extendFn === 'function') {
26366 extendFn(Ctor, Parent);
26367 }
26368
26369 Ctor.extend = extend(Ctor, extendFn);
26370 };
26371}
26372/**
26373 * Expose `extend`
26374 */
26375
26376var staticExtend = extend;
26377
26378var classUtils = createCommonjsModule(function (module) {
26379
26380
26381
26382
26383
26384
26385
26386/**
26387 * Expose class utils
26388 */
26389
26390var cu = module.exports;
26391
26392/**
26393 * Expose class utils: `cu`
26394 */
26395
26396cu.isObject = function isObject(val) {
26397 return isobject(val) || typeof val === 'function';
26398};
26399
26400/**
26401 * Returns true if an array has any of the given elements, or an
26402 * object has any of the give keys.
26403 *
26404 * ```js
26405 * cu.has(['a', 'b', 'c'], 'c');
26406 * //=> true
26407 *
26408 * cu.has(['a', 'b', 'c'], ['c', 'z']);
26409 * //=> true
26410 *
26411 * cu.has({a: 'b', c: 'd'}, ['c', 'z']);
26412 * //=> true
26413 * ```
26414 * @param {Object} `obj`
26415 * @param {String|Array} `val`
26416 * @return {Boolean}
26417 * @api public
26418 */
26419
26420cu.has = function has(obj, val) {
26421 val = cu.arrayify(val);
26422 var len = val.length;
26423
26424 if (cu.isObject(obj)) {
26425 for (var key in obj) {
26426 if (val.indexOf(key) > -1) {
26427 return true;
26428 }
26429 }
26430
26431 var keys = cu.nativeKeys(obj);
26432 return cu.has(keys, val);
26433 }
26434
26435 if (Array.isArray(obj)) {
26436 var arr = obj;
26437 while (len--) {
26438 if (arr.indexOf(val[len]) > -1) {
26439 return true;
26440 }
26441 }
26442 return false;
26443 }
26444
26445 throw new TypeError('expected an array or object.');
26446};
26447
26448/**
26449 * Returns true if an array or object has all of the given values.
26450 *
26451 * ```js
26452 * cu.hasAll(['a', 'b', 'c'], 'c');
26453 * //=> true
26454 *
26455 * cu.hasAll(['a', 'b', 'c'], ['c', 'z']);
26456 * //=> false
26457 *
26458 * cu.hasAll({a: 'b', c: 'd'}, ['c', 'z']);
26459 * //=> false
26460 * ```
26461 * @param {Object|Array} `val`
26462 * @param {String|Array} `values`
26463 * @return {Boolean}
26464 * @api public
26465 */
26466
26467cu.hasAll = function hasAll(val, values) {
26468 values = cu.arrayify(values);
26469 var len = values.length;
26470 while (len--) {
26471 if (!cu.has(val, values[len])) {
26472 return false;
26473 }
26474 }
26475 return true;
26476};
26477
26478/**
26479 * Cast the given value to an array.
26480 *
26481 * ```js
26482 * cu.arrayify('foo');
26483 * //=> ['foo']
26484 *
26485 * cu.arrayify(['foo']);
26486 * //=> ['foo']
26487 * ```
26488 *
26489 * @param {String|Array} `val`
26490 * @return {Array}
26491 * @api public
26492 */
26493
26494cu.arrayify = function arrayify(val) {
26495 return val ? (Array.isArray(val) ? val : [val]) : [];
26496};
26497
26498/**
26499 * Noop
26500 */
26501
26502cu.noop = function noop() {
26503 return;
26504};
26505
26506/**
26507 * Returns the first argument passed to the function.
26508 */
26509
26510cu.identity = function identity(val) {
26511 return val;
26512};
26513
26514/**
26515 * Returns true if a value has a `contructor`
26516 *
26517 * ```js
26518 * cu.hasConstructor({});
26519 * //=> true
26520 *
26521 * cu.hasConstructor(Object.create(null));
26522 * //=> false
26523 * ```
26524 * @param {Object} `value`
26525 * @return {Boolean}
26526 * @api public
26527 */
26528
26529cu.hasConstructor = function hasConstructor(val) {
26530 return cu.isObject(val) && typeof val.constructor !== 'undefined';
26531};
26532
26533/**
26534 * Get the native `ownPropertyNames` from the constructor of the
26535 * given `object`. An empty array is returned if the object does
26536 * not have a constructor.
26537 *
26538 * ```js
26539 * cu.nativeKeys({a: 'b', b: 'c', c: 'd'})
26540 * //=> ['a', 'b', 'c']
26541 *
26542 * cu.nativeKeys(function(){})
26543 * //=> ['length', 'caller']
26544 * ```
26545 *
26546 * @param {Object} `obj` Object that has a `constructor`.
26547 * @return {Array} Array of keys.
26548 * @api public
26549 */
26550
26551cu.nativeKeys = function nativeKeys(val) {
26552 if (!cu.hasConstructor(val)) return [];
26553 var keys = Object.getOwnPropertyNames(val);
26554 if ('caller' in val) keys.push('caller');
26555 return keys;
26556};
26557
26558/**
26559 * Returns property descriptor `key` if it's an "own" property
26560 * of the given object.
26561 *
26562 * ```js
26563 * function App() {}
26564 * Object.defineProperty(App.prototype, 'count', {
26565 * get: function() {
26566 * return Object.keys(this).length;
26567 * }
26568 * });
26569 * cu.getDescriptor(App.prototype, 'count');
26570 * // returns:
26571 * // {
26572 * // get: [Function],
26573 * // set: undefined,
26574 * // enumerable: false,
26575 * // configurable: false
26576 * // }
26577 * ```
26578 *
26579 * @param {Object} `obj`
26580 * @param {String} `key`
26581 * @return {Object} Returns descriptor `key`
26582 * @api public
26583 */
26584
26585cu.getDescriptor = function getDescriptor(obj, key) {
26586 if (!cu.isObject(obj)) {
26587 throw new TypeError('expected an object.');
26588 }
26589 if (typeof key !== 'string') {
26590 throw new TypeError('expected key to be a string.');
26591 }
26592 return Object.getOwnPropertyDescriptor(obj, key);
26593};
26594
26595/**
26596 * Copy a descriptor from one object to another.
26597 *
26598 * ```js
26599 * function App() {}
26600 * Object.defineProperty(App.prototype, 'count', {
26601 * get: function() {
26602 * return Object.keys(this).length;
26603 * }
26604 * });
26605 * var obj = {};
26606 * cu.copyDescriptor(obj, App.prototype, 'count');
26607 * ```
26608 * @param {Object} `receiver`
26609 * @param {Object} `provider`
26610 * @param {String} `name`
26611 * @return {Object}
26612 * @api public
26613 */
26614
26615cu.copyDescriptor = function copyDescriptor(receiver, provider, name) {
26616 if (!cu.isObject(receiver)) {
26617 throw new TypeError('expected receiving object to be an object.');
26618 }
26619 if (!cu.isObject(provider)) {
26620 throw new TypeError('expected providing object to be an object.');
26621 }
26622 if (typeof name !== 'string') {
26623 throw new TypeError('expected name to be a string.');
26624 }
26625
26626 var val = cu.getDescriptor(provider, name);
26627 if (val) Object.defineProperty(receiver, name, val);
26628};
26629
26630/**
26631 * Copy static properties, prototype properties, and descriptors
26632 * from one object to another.
26633 *
26634 * @param {Object} `receiver`
26635 * @param {Object} `provider`
26636 * @param {String|Array} `omit` One or more properties to omit
26637 * @return {Object}
26638 * @api public
26639 */
26640
26641cu.copy = function copy(receiver, provider, omit) {
26642 if (!cu.isObject(receiver)) {
26643 throw new TypeError('expected receiving object to be an object.');
26644 }
26645 if (!cu.isObject(provider)) {
26646 throw new TypeError('expected providing object to be an object.');
26647 }
26648 var props = Object.getOwnPropertyNames(provider);
26649 var keys = Object.keys(provider);
26650 var len = props.length,
26651 key;
26652 omit = cu.arrayify(omit);
26653
26654 while (len--) {
26655 key = props[len];
26656
26657 if (cu.has(keys, key)) {
26658 defineProperty$3(receiver, key, provider[key]);
26659 } else if (!(key in receiver) && !cu.has(omit, key)) {
26660 cu.copyDescriptor(receiver, provider, key);
26661 }
26662 }
26663};
26664
26665/**
26666 * Inherit the static properties, prototype properties, and descriptors
26667 * from of an object.
26668 *
26669 * @param {Object} `receiver`
26670 * @param {Object} `provider`
26671 * @param {String|Array} `omit` One or more properties to omit
26672 * @return {Object}
26673 * @api public
26674 */
26675
26676cu.inherit = function inherit(receiver, provider, omit) {
26677 if (!cu.isObject(receiver)) {
26678 throw new TypeError('expected receiving object to be an object.');
26679 }
26680 if (!cu.isObject(provider)) {
26681 throw new TypeError('expected providing object to be an object.');
26682 }
26683
26684 var keys = [];
26685 for (var key in provider) {
26686 keys.push(key);
26687 receiver[key] = provider[key];
26688 }
26689
26690 keys = keys.concat(cu.arrayify(omit));
26691
26692 var a = provider.prototype || provider;
26693 var b = receiver.prototype || receiver;
26694 cu.copy(b, a, keys);
26695};
26696
26697/**
26698 * Returns a function for extending the static properties,
26699 * prototype properties, and descriptors from the `Parent`
26700 * constructor onto `Child` constructors.
26701 *
26702 * ```js
26703 * var extend = cu.extend(Parent);
26704 * Parent.extend(Child);
26705 *
26706 * // optional methods
26707 * Parent.extend(Child, {
26708 * foo: function() {},
26709 * bar: function() {}
26710 * });
26711 * ```
26712 * @param {Function} `Parent` Parent ctor
26713 * @param {Function} `extend` Optional extend function to handle custom extensions. Useful when updating methods that require a specific prototype.
26714 * @param {Function} `Child` Child ctor
26715 * @param {Object} `proto` Optionally pass additional prototype properties to inherit.
26716 * @return {Object}
26717 * @api public
26718 */
26719
26720cu.extend = function() {
26721 // keep it lazy, instead of assigning to `cu.extend`
26722 return staticExtend.apply(null, arguments);
26723};
26724
26725/**
26726 * Bubble up events emitted from static methods on the Parent ctor.
26727 *
26728 * @param {Object} `Parent`
26729 * @param {Array} `events` Event names to bubble up
26730 * @api public
26731 */
26732
26733cu.bubble = function(Parent, events) {
26734 events = events || [];
26735 Parent.bubble = function(Child, arr) {
26736 if (Array.isArray(arr)) {
26737 events = arrUnion([], events, arr);
26738 }
26739 var len = events.length;
26740 var idx = -1;
26741 while (++idx < len) {
26742 var name = events[idx];
26743 Parent.on(name, Child.emit.bind(Child, name));
26744 }
26745 cu.bubble(Child, events);
26746 };
26747};
26748});
26749
26750/**
26751 * Optionally define a custom `cache` namespace to use.
26752 */
26753
26754function namespace$1(name) {
26755 var Cache = name ? cacheBase.namespace(name) : cacheBase;
26756 var fns = [];
26757
26758 /**
26759 * Create an instance of `Base` with the given `config` and `options`.
26760 *
26761 * ```js
26762 * // initialize with `config` and `options`
26763 * var app = new Base({isApp: true}, {abc: true});
26764 * app.set('foo', 'bar');
26765 *
26766 * // values defined with the given `config` object will be on the root of the instance
26767 * console.log(app.baz); //=> undefined
26768 * console.log(app.foo); //=> 'bar'
26769 * // or use `.get`
26770 * console.log(app.get('isApp')); //=> true
26771 * console.log(app.get('foo')); //=> 'bar'
26772 *
26773 * // values defined with the given `options` object will be on `app.options
26774 * console.log(app.options.abc); //=> true
26775 * ```
26776 *
26777 * @param {Object} `config` If supplied, this object is passed to [cache-base][] to merge onto the the instance upon instantiation.
26778 * @param {Object} `options` If supplied, this object is used to initialize the `base.options` object.
26779 * @api public
26780 */
26781
26782 function Base(config, options) {
26783 if (!(this instanceof Base)) {
26784 return new Base(config, options);
26785 }
26786 Cache.call(this, config);
26787 this.is('base');
26788 this.initBase(config, options);
26789 }
26790
26791 /**
26792 * Inherit cache-base
26793 */
26794
26795 util$2.inherits(Base, Cache);
26796
26797 /**
26798 * Add static emitter methods
26799 */
26800
26801 componentEmitter(Base);
26802
26803 /**
26804 * Initialize `Base` defaults with the given `config` object
26805 */
26806
26807 Base.prototype.initBase = function(config, options) {
26808 this.options = mixinDeep_1({}, this.options, options);
26809 this.cache = this.cache || {};
26810 this.define('registered', {});
26811 if (name) this[name] = {};
26812
26813 // make `app._callbacks` non-enumerable
26814 this.define('_callbacks', this._callbacks);
26815 if (isobject(config)) {
26816 this.visit('set', config);
26817 }
26818 Base.run(this, 'use', fns);
26819 };
26820
26821 /**
26822 * Set the given `name` on `app._name` and `app.is*` properties. Used for doing
26823 * lookups in plugins.
26824 *
26825 * ```js
26826 * app.is('foo');
26827 * console.log(app._name);
26828 * //=> 'foo'
26829 * console.log(app.isFoo);
26830 * //=> true
26831 * app.is('bar');
26832 * console.log(app.isFoo);
26833 * //=> true
26834 * console.log(app.isBar);
26835 * //=> true
26836 * console.log(app._name);
26837 * //=> 'bar'
26838 * ```
26839 * @name .is
26840 * @param {String} `name`
26841 * @return {Boolean}
26842 * @api public
26843 */
26844
26845 Base.prototype.is = function(name) {
26846 if (typeof name !== 'string') {
26847 throw new TypeError('expected name to be a string');
26848 }
26849 this.define('is' + pascalcase_1(name), true);
26850 this.define('_name', name);
26851 this.define('_appname', name);
26852 return this;
26853 };
26854
26855 /**
26856 * Returns true if a plugin has already been registered on an instance.
26857 *
26858 * Plugin implementors are encouraged to use this first thing in a plugin
26859 * to prevent the plugin from being called more than once on the same
26860 * instance.
26861 *
26862 * ```js
26863 * var base = new Base();
26864 * base.use(function(app) {
26865 * if (app.isRegistered('myPlugin')) return;
26866 * // do stuff to `app`
26867 * });
26868 *
26869 * // to also record the plugin as being registered
26870 * base.use(function(app) {
26871 * if (app.isRegistered('myPlugin', true)) return;
26872 * // do stuff to `app`
26873 * });
26874 * ```
26875 * @name .isRegistered
26876 * @emits `plugin` Emits the name of the plugin being registered. Useful for unit tests, to ensure plugins are only registered once.
26877 * @param {String} `name` The plugin name.
26878 * @param {Boolean} `register` If the plugin if not already registered, to record it as being registered pass `true` as the second argument.
26879 * @return {Boolean} Returns true if a plugin is already registered.
26880 * @api public
26881 */
26882
26883 Base.prototype.isRegistered = function(name, register) {
26884 if (this.registered.hasOwnProperty(name)) {
26885 return true;
26886 }
26887 if (register !== false) {
26888 this.registered[name] = true;
26889 this.emit('plugin', name);
26890 }
26891 return false;
26892 };
26893
26894 /**
26895 * Define a plugin function to be called immediately upon init. Plugins are chainable
26896 * and expose the following arguments to the plugin function:
26897 *
26898 * - `app`: the current instance of `Base`
26899 * - `base`: the [first ancestor instance](#base) of `Base`
26900 *
26901 * ```js
26902 * var app = new Base()
26903 * .use(foo)
26904 * .use(bar)
26905 * .use(baz)
26906 * ```
26907 * @name .use
26908 * @param {Function} `fn` plugin function to call
26909 * @return {Object} Returns the item instance for chaining.
26910 * @api public
26911 */
26912
26913 Base.prototype.use = function(fn) {
26914 fn.call(this, this);
26915 return this;
26916 };
26917
26918 /**
26919 * The `.define` method is used for adding non-enumerable property on the instance.
26920 * Dot-notation is **not supported** with `define`.
26921 *
26922 * ```js
26923 * // arbitrary `render` function using lodash `template`
26924 * app.define('render', function(str, locals) {
26925 * return _.template(str)(locals);
26926 * });
26927 * ```
26928 * @name .define
26929 * @param {String} `key` The name of the property to define.
26930 * @param {any} `value`
26931 * @return {Object} Returns the instance for chaining.
26932 * @api public
26933 */
26934
26935 Base.prototype.define = function(key, val) {
26936 if (isobject(key)) {
26937 return this.visit('define', key);
26938 }
26939 defineProperty$2(this, key, val);
26940 return this;
26941 };
26942
26943 /**
26944 * Mix property `key` onto the Base prototype. If base is inherited using
26945 * `Base.extend` this method will be overridden by a new `mixin` method that will
26946 * only add properties to the prototype of the inheriting application.
26947 *
26948 * ```js
26949 * app.mixin('foo', function() {
26950 * // do stuff
26951 * });
26952 * ```
26953 * @name .mixin
26954 * @param {String} `key`
26955 * @param {Object|Array} `val`
26956 * @return {Object} Returns the `base` instance for chaining.
26957 * @api public
26958 */
26959
26960 Base.prototype.mixin = function(key, val) {
26961 Base.prototype[key] = val;
26962 return this;
26963 };
26964
26965 /**
26966 * Non-enumberable mixin array, used by the static [Base.mixin]() method.
26967 */
26968
26969 Base.prototype.mixins = Base.prototype.mixins || [];
26970
26971 /**
26972 * Getter/setter used when creating nested instances of `Base`, for storing a reference
26973 * to the first ancestor instance. This works by setting an instance of `Base` on the `parent`
26974 * property of a "child" instance. The `base` property defaults to the current instance if
26975 * no `parent` property is defined.
26976 *
26977 * ```js
26978 * // create an instance of `Base`, this is our first ("base") instance
26979 * var first = new Base();
26980 * first.foo = 'bar'; // arbitrary property, to make it easier to see what's happening later
26981 *
26982 * // create another instance
26983 * var second = new Base();
26984 * // create a reference to the first instance (`first`)
26985 * second.parent = first;
26986 *
26987 * // create another instance
26988 * var third = new Base();
26989 * // create a reference to the previous instance (`second`)
26990 * // repeat this pattern every time a "child" instance is created
26991 * third.parent = second;
26992 *
26993 * // we can always access the first instance using the `base` property
26994 * console.log(first.base.foo);
26995 * //=> 'bar'
26996 * console.log(second.base.foo);
26997 * //=> 'bar'
26998 * console.log(third.base.foo);
26999 * //=> 'bar'
27000 * // and now you know how to get to third base ;)
27001 * ```
27002 * @name .base
27003 * @api public
27004 */
27005
27006 Object.defineProperty(Base.prototype, 'base', {
27007 configurable: true,
27008 get: function() {
27009 return this.parent ? this.parent.base : this;
27010 }
27011 });
27012
27013 /**
27014 * Static method for adding global plugin functions that will
27015 * be added to an instance when created.
27016 *
27017 * ```js
27018 * Base.use(function(app) {
27019 * app.foo = 'bar';
27020 * });
27021 * var app = new Base();
27022 * console.log(app.foo);
27023 * //=> 'bar'
27024 * ```
27025 * @name #use
27026 * @param {Function} `fn` Plugin function to use on each instance.
27027 * @return {Object} Returns the `Base` constructor for chaining
27028 * @api public
27029 */
27030
27031 defineProperty$2(Base, 'use', function(fn) {
27032 fns.push(fn);
27033 return Base;
27034 });
27035
27036 /**
27037 * Run an array of functions by passing each function
27038 * to a method on the given object specified by the given property.
27039 *
27040 * @param {Object} `obj` Object containing method to use.
27041 * @param {String} `prop` Name of the method on the object to use.
27042 * @param {Array} `arr` Array of functions to pass to the method.
27043 */
27044
27045 defineProperty$2(Base, 'run', function(obj, prop, arr) {
27046 var len = arr.length, i = 0;
27047 while (len--) {
27048 obj[prop](arr[i++]);
27049 }
27050 return Base;
27051 });
27052
27053 /**
27054 * Static method for inheriting the prototype and static methods of the `Base` class.
27055 * This method greatly simplifies the process of creating inheritance-based applications.
27056 * See [static-extend][] for more details.
27057 *
27058 * ```js
27059 * var extend = cu.extend(Parent);
27060 * Parent.extend(Child);
27061 *
27062 * // optional methods
27063 * Parent.extend(Child, {
27064 * foo: function() {},
27065 * bar: function() {}
27066 * });
27067 * ```
27068 * @name #extend
27069 * @param {Function} `Ctor` constructor to extend
27070 * @param {Object} `methods` Optional prototype properties to mix in.
27071 * @return {Object} Returns the `Base` constructor for chaining
27072 * @api public
27073 */
27074
27075 defineProperty$2(Base, 'extend', classUtils.extend(Base, function(Ctor, Parent) {
27076 Ctor.prototype.mixins = Ctor.prototype.mixins || [];
27077
27078 defineProperty$2(Ctor, 'mixin', function(fn) {
27079 var mixin = fn(Ctor.prototype, Ctor);
27080 if (typeof mixin === 'function') {
27081 Ctor.prototype.mixins.push(mixin);
27082 }
27083 return Ctor;
27084 });
27085
27086 defineProperty$2(Ctor, 'mixins', function(Child) {
27087 Base.run(Child, 'mixin', Ctor.prototype.mixins);
27088 return Ctor;
27089 });
27090
27091 Ctor.prototype.mixin = function(key, value) {
27092 Ctor.prototype[key] = value;
27093 return this;
27094 };
27095 return Base;
27096 }));
27097
27098 /**
27099 * Used for adding methods to the `Base` prototype, and/or to the prototype of child instances.
27100 * When a mixin function returns a function, the returned function is pushed onto the `.mixins`
27101 * array, making it available to be used on inheriting classes whenever `Base.mixins()` is
27102 * called (e.g. `Base.mixins(Child)`).
27103 *
27104 * ```js
27105 * Base.mixin(function(proto) {
27106 * proto.foo = function(msg) {
27107 * return 'foo ' + msg;
27108 * };
27109 * });
27110 * ```
27111 * @name #mixin
27112 * @param {Function} `fn` Function to call
27113 * @return {Object} Returns the `Base` constructor for chaining
27114 * @api public
27115 */
27116
27117 defineProperty$2(Base, 'mixin', function(fn) {
27118 var mixin = fn(Base.prototype, Base);
27119 if (typeof mixin === 'function') {
27120 Base.prototype.mixins.push(mixin);
27121 }
27122 return Base;
27123 });
27124
27125 /**
27126 * Static method for running global mixin functions against a child constructor.
27127 * Mixins must be registered before calling this method.
27128 *
27129 * ```js
27130 * Base.extend(Child);
27131 * Base.mixins(Child);
27132 * ```
27133 * @name #mixins
27134 * @param {Function} `Child` Constructor function of a child class
27135 * @return {Object} Returns the `Base` constructor for chaining
27136 * @api public
27137 */
27138
27139 defineProperty$2(Base, 'mixins', function(Child) {
27140 Base.run(Child, 'mixin', Base.prototype.mixins);
27141 return Base;
27142 });
27143
27144 /**
27145 * Similar to `util.inherit`, but copies all static properties, prototype properties, and
27146 * getters/setters from `Provider` to `Receiver`. See [class-utils][]{#inherit} for more details.
27147 *
27148 * ```js
27149 * Base.inherit(Foo, Bar);
27150 * ```
27151 * @name #inherit
27152 * @param {Function} `Receiver` Receiving (child) constructor
27153 * @param {Function} `Provider` Providing (parent) constructor
27154 * @return {Object} Returns the `Base` constructor for chaining
27155 * @api public
27156 */
27157
27158 defineProperty$2(Base, 'inherit', classUtils.inherit);
27159 defineProperty$2(Base, 'bubble', classUtils.bubble);
27160 return Base;
27161}
27162
27163/**
27164 * Expose `Base` with default settings
27165 */
27166
27167var base$2 = namespace$1();
27168
27169/**
27170 * Allow users to define a namespace
27171 */
27172
27173var namespace_1$1 = namespace$1;
27174base$2.namespace = namespace_1$1;
27175
27176var defineProperty$6 = function defineProperty(obj, prop, val) {
27177 if (typeof obj !== 'object' && typeof obj !== 'function') {
27178 throw new TypeError('expected an object or function.');
27179 }
27180
27181 if (typeof prop !== 'string') {
27182 throw new TypeError('expected `prop` to be a string.');
27183 }
27184
27185 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
27186 return Object.defineProperty(obj, prop, val);
27187 }
27188
27189 return Object.defineProperty(obj, prop, {
27190 configurable: true,
27191 enumerable: false,
27192 writable: true,
27193 value: val
27194 });
27195};
27196
27197/*!
27198 * use <https://github.com/jonschlinkert/use>
27199 *
27200 * Copyright (c) 2015-2017, Jon Schlinkert.
27201 * Released under the MIT License.
27202 */
27203
27204var use = function base(app, options) {
27205 if (!isObject$7(app) && typeof app !== 'function') {
27206 throw new TypeError('expected an object or function');
27207 }
27208
27209 var opts = isObject$7(options) ? options : {};
27210 var prop = typeof opts.prop === 'string' ? opts.prop : 'fns';
27211 if (!Array.isArray(app[prop])) {
27212 define$1(app, prop, []);
27213 }
27214
27215 /**
27216 * Define a plugin function to be passed to use. The only
27217 * parameter exposed to the plugin is `app`, the object or function.
27218 * passed to `use(app)`. `app` is also exposed as `this` in plugins.
27219 *
27220 * Additionally, **if a plugin returns a function, the function will
27221 * be pushed onto the `fns` array**, allowing the plugin to be
27222 * called at a later point by the `run` method.
27223 *
27224 * ```js
27225 * var use = require('use');
27226 *
27227 * // define a plugin
27228 * function foo(app) {
27229 * // do stuff
27230 * }
27231 *
27232 * var app = function(){};
27233 * use(app);
27234 *
27235 * // register plugins
27236 * app.use(foo);
27237 * app.use(bar);
27238 * app.use(baz);
27239 * ```
27240 * @name .use
27241 * @param {Function} `fn` plugin function to call
27242 * @api public
27243 */
27244
27245 define$1(app, 'use', use);
27246
27247 /**
27248 * Run all plugins on `fns`. Any plugin that returns a function
27249 * when called by `use` is pushed onto the `fns` array.
27250 *
27251 * ```js
27252 * var config = {};
27253 * app.run(config);
27254 * ```
27255 * @name .run
27256 * @param {Object} `value` Object to be modified by plugins.
27257 * @return {Object} Returns the object passed to `run`
27258 * @api public
27259 */
27260
27261 define$1(app, 'run', function(val) {
27262 if (!isObject$7(val)) return;
27263
27264 if (!val.use || !val.run) {
27265 define$1(val, prop, val[prop] || []);
27266 define$1(val, 'use', use);
27267 }
27268
27269 if (!val[prop] || val[prop].indexOf(base) === -1) {
27270 val.use(base);
27271 }
27272
27273 var self = this || app;
27274 var fns = self[prop];
27275 var len = fns.length;
27276 var idx = -1;
27277
27278 while (++idx < len) {
27279 val.use(fns[idx]);
27280 }
27281 return val;
27282 });
27283
27284 /**
27285 * Call plugin `fn`. If a function is returned push it into the
27286 * `fns` array to be called by the `run` method.
27287 */
27288
27289 function use(type, fn, options) {
27290 var offset = 1;
27291
27292 if (typeof type === 'string' || Array.isArray(type)) {
27293 fn = wrap(type, fn);
27294 offset++;
27295 } else {
27296 options = fn;
27297 fn = type;
27298 }
27299
27300 if (typeof fn !== 'function') {
27301 throw new TypeError('expected a function');
27302 }
27303
27304 var self = this || app;
27305 var fns = self[prop];
27306
27307 var args = [].slice.call(arguments, offset);
27308 args.unshift(self);
27309
27310 if (typeof opts.hook === 'function') {
27311 opts.hook.apply(self, args);
27312 }
27313
27314 var val = fn.apply(self, args);
27315 if (typeof val === 'function' && fns.indexOf(val) === -1) {
27316 fns.push(val);
27317 }
27318 return self;
27319 }
27320
27321 /**
27322 * Wrap a named plugin function so that it's only called on objects of the
27323 * given `type`
27324 *
27325 * @param {String} `type`
27326 * @param {Function} `fn` Plugin function
27327 * @return {Function}
27328 */
27329
27330 function wrap(type, fn) {
27331 return function plugin() {
27332 return this.type === type ? fn.apply(this, arguments) : plugin;
27333 };
27334 }
27335
27336 return app;
27337};
27338
27339function isObject$7(val) {
27340 return val && typeof val === 'object' && !Array.isArray(val);
27341}
27342
27343function define$1(obj, key, val) {
27344 Object.defineProperty(obj, key, {
27345 configurable: true,
27346 writable: true,
27347 value: val
27348 });
27349}
27350
27351/**
27352 * Helpers.
27353 */
27354
27355var s = 1000;
27356var m = s * 60;
27357var h = m * 60;
27358var d = h * 24;
27359var y = d * 365.25;
27360
27361/**
27362 * Parse or format the given `val`.
27363 *
27364 * Options:
27365 *
27366 * - `long` verbose formatting [false]
27367 *
27368 * @param {String|Number} val
27369 * @param {Object} [options]
27370 * @throws {Error} throw an error if val is not a non-empty string or a number
27371 * @return {String|Number}
27372 * @api public
27373 */
27374
27375var ms = function(val, options) {
27376 options = options || {};
27377 var type = typeof val;
27378 if (type === 'string' && val.length > 0) {
27379 return parse(val);
27380 } else if (type === 'number' && isNaN(val) === false) {
27381 return options.long ? fmtLong(val) : fmtShort(val);
27382 }
27383 throw new Error(
27384 'val is not a non-empty string or a valid number. val=' +
27385 JSON.stringify(val)
27386 );
27387};
27388
27389/**
27390 * Parse the given `str` and return milliseconds.
27391 *
27392 * @param {String} str
27393 * @return {Number}
27394 * @api private
27395 */
27396
27397function parse(str) {
27398 str = String(str);
27399 if (str.length > 100) {
27400 return;
27401 }
27402 var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
27403 str
27404 );
27405 if (!match) {
27406 return;
27407 }
27408 var n = parseFloat(match[1]);
27409 var type = (match[2] || 'ms').toLowerCase();
27410 switch (type) {
27411 case 'years':
27412 case 'year':
27413 case 'yrs':
27414 case 'yr':
27415 case 'y':
27416 return n * y;
27417 case 'days':
27418 case 'day':
27419 case 'd':
27420 return n * d;
27421 case 'hours':
27422 case 'hour':
27423 case 'hrs':
27424 case 'hr':
27425 case 'h':
27426 return n * h;
27427 case 'minutes':
27428 case 'minute':
27429 case 'mins':
27430 case 'min':
27431 case 'm':
27432 return n * m;
27433 case 'seconds':
27434 case 'second':
27435 case 'secs':
27436 case 'sec':
27437 case 's':
27438 return n * s;
27439 case 'milliseconds':
27440 case 'millisecond':
27441 case 'msecs':
27442 case 'msec':
27443 case 'ms':
27444 return n;
27445 default:
27446 return undefined;
27447 }
27448}
27449
27450/**
27451 * Short format for `ms`.
27452 *
27453 * @param {Number} ms
27454 * @return {String}
27455 * @api private
27456 */
27457
27458function fmtShort(ms) {
27459 if (ms >= d) {
27460 return Math.round(ms / d) + 'd';
27461 }
27462 if (ms >= h) {
27463 return Math.round(ms / h) + 'h';
27464 }
27465 if (ms >= m) {
27466 return Math.round(ms / m) + 'm';
27467 }
27468 if (ms >= s) {
27469 return Math.round(ms / s) + 's';
27470 }
27471 return ms + 'ms';
27472}
27473
27474/**
27475 * Long format for `ms`.
27476 *
27477 * @param {Number} ms
27478 * @return {String}
27479 * @api private
27480 */
27481
27482function fmtLong(ms) {
27483 return plural(ms, d, 'day') ||
27484 plural(ms, h, 'hour') ||
27485 plural(ms, m, 'minute') ||
27486 plural(ms, s, 'second') ||
27487 ms + ' ms';
27488}
27489
27490/**
27491 * Pluralization helper.
27492 */
27493
27494function plural(ms, n, name) {
27495 if (ms < n) {
27496 return;
27497 }
27498 if (ms < n * 1.5) {
27499 return Math.floor(ms / n) + ' ' + name;
27500 }
27501 return Math.ceil(ms / n) + ' ' + name + 's';
27502}
27503
27504var debug = createCommonjsModule(function (module, exports) {
27505/**
27506 * This is the common logic for both the Node.js and web browser
27507 * implementations of `debug()`.
27508 *
27509 * Expose `debug()` as the module.
27510 */
27511
27512exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
27513exports.coerce = coerce;
27514exports.disable = disable;
27515exports.enable = enable;
27516exports.enabled = enabled;
27517exports.humanize = ms;
27518
27519/**
27520 * The currently active debug mode names, and names to skip.
27521 */
27522
27523exports.names = [];
27524exports.skips = [];
27525
27526/**
27527 * Map of special "%n" handling functions, for the debug "format" argument.
27528 *
27529 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
27530 */
27531
27532exports.formatters = {};
27533
27534/**
27535 * Previous log timestamp.
27536 */
27537
27538var prevTime;
27539
27540/**
27541 * Select a color.
27542 * @param {String} namespace
27543 * @return {Number}
27544 * @api private
27545 */
27546
27547function selectColor(namespace) {
27548 var hash = 0, i;
27549
27550 for (i in namespace) {
27551 hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
27552 hash |= 0; // Convert to 32bit integer
27553 }
27554
27555 return exports.colors[Math.abs(hash) % exports.colors.length];
27556}
27557
27558/**
27559 * Create a debugger with the given `namespace`.
27560 *
27561 * @param {String} namespace
27562 * @return {Function}
27563 * @api public
27564 */
27565
27566function createDebug(namespace) {
27567
27568 function debug() {
27569 // disabled?
27570 if (!debug.enabled) return;
27571
27572 var self = debug;
27573
27574 // set `diff` timestamp
27575 var curr = +new Date();
27576 var ms = curr - (prevTime || curr);
27577 self.diff = ms;
27578 self.prev = prevTime;
27579 self.curr = curr;
27580 prevTime = curr;
27581
27582 // turn the `arguments` into a proper Array
27583 var args = new Array(arguments.length);
27584 for (var i = 0; i < args.length; i++) {
27585 args[i] = arguments[i];
27586 }
27587
27588 args[0] = exports.coerce(args[0]);
27589
27590 if ('string' !== typeof args[0]) {
27591 // anything else let's inspect with %O
27592 args.unshift('%O');
27593 }
27594
27595 // apply any `formatters` transformations
27596 var index = 0;
27597 args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
27598 // if we encounter an escaped % then don't increase the array index
27599 if (match === '%%') return match;
27600 index++;
27601 var formatter = exports.formatters[format];
27602 if ('function' === typeof formatter) {
27603 var val = args[index];
27604 match = formatter.call(self, val);
27605
27606 // now we need to remove `args[index]` since it's inlined in the `format`
27607 args.splice(index, 1);
27608 index--;
27609 }
27610 return match;
27611 });
27612
27613 // apply env-specific formatting (colors, etc.)
27614 exports.formatArgs.call(self, args);
27615
27616 var logFn = debug.log || exports.log || console.log.bind(console);
27617 logFn.apply(self, args);
27618 }
27619
27620 debug.namespace = namespace;
27621 debug.enabled = exports.enabled(namespace);
27622 debug.useColors = exports.useColors();
27623 debug.color = selectColor(namespace);
27624
27625 // env-specific initialization logic for debug instances
27626 if ('function' === typeof exports.init) {
27627 exports.init(debug);
27628 }
27629
27630 return debug;
27631}
27632
27633/**
27634 * Enables a debug mode by namespaces. This can include modes
27635 * separated by a colon and wildcards.
27636 *
27637 * @param {String} namespaces
27638 * @api public
27639 */
27640
27641function enable(namespaces) {
27642 exports.save(namespaces);
27643
27644 exports.names = [];
27645 exports.skips = [];
27646
27647 var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
27648 var len = split.length;
27649
27650 for (var i = 0; i < len; i++) {
27651 if (!split[i]) continue; // ignore empty strings
27652 namespaces = split[i].replace(/\*/g, '.*?');
27653 if (namespaces[0] === '-') {
27654 exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
27655 } else {
27656 exports.names.push(new RegExp('^' + namespaces + '$'));
27657 }
27658 }
27659}
27660
27661/**
27662 * Disable debug output.
27663 *
27664 * @api public
27665 */
27666
27667function disable() {
27668 exports.enable('');
27669}
27670
27671/**
27672 * Returns true if the given mode name is enabled, false otherwise.
27673 *
27674 * @param {String} name
27675 * @return {Boolean}
27676 * @api public
27677 */
27678
27679function enabled(name) {
27680 var i, len;
27681 for (i = 0, len = exports.skips.length; i < len; i++) {
27682 if (exports.skips[i].test(name)) {
27683 return false;
27684 }
27685 }
27686 for (i = 0, len = exports.names.length; i < len; i++) {
27687 if (exports.names[i].test(name)) {
27688 return true;
27689 }
27690 }
27691 return false;
27692}
27693
27694/**
27695 * Coerce `val`.
27696 *
27697 * @param {Mixed} val
27698 * @return {Mixed}
27699 * @api private
27700 */
27701
27702function coerce(val) {
27703 if (val instanceof Error) return val.stack || val.message;
27704 return val;
27705}
27706});
27707
27708var browser = createCommonjsModule(function (module, exports) {
27709/**
27710 * This is the web browser implementation of `debug()`.
27711 *
27712 * Expose `debug()` as the module.
27713 */
27714
27715exports = module.exports = debug;
27716exports.log = log;
27717exports.formatArgs = formatArgs;
27718exports.save = save;
27719exports.load = load;
27720exports.useColors = useColors;
27721exports.storage = 'undefined' != typeof chrome
27722 && 'undefined' != typeof chrome.storage
27723 ? chrome.storage.local
27724 : localstorage();
27725
27726/**
27727 * Colors.
27728 */
27729
27730exports.colors = [
27731 'lightseagreen',
27732 'forestgreen',
27733 'goldenrod',
27734 'dodgerblue',
27735 'darkorchid',
27736 'crimson'
27737];
27738
27739/**
27740 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
27741 * and the Firebug extension (any Firefox version) are known
27742 * to support "%c" CSS customizations.
27743 *
27744 * TODO: add a `localStorage` variable to explicitly enable/disable colors
27745 */
27746
27747function useColors() {
27748 // NB: In an Electron preload script, document will be defined but not fully
27749 // initialized. Since we know we're in Chrome, we'll just detect this case
27750 // explicitly
27751 if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
27752 return true;
27753 }
27754
27755 // is webkit? http://stackoverflow.com/a/16459606/376773
27756 // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
27757 return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
27758 // is firebug? http://stackoverflow.com/a/398120/376773
27759 (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
27760 // is firefox >= v31?
27761 // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
27762 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
27763 // double check webkit in userAgent just in case we are in a worker
27764 (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
27765}
27766
27767/**
27768 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
27769 */
27770
27771exports.formatters.j = function(v) {
27772 try {
27773 return JSON.stringify(v);
27774 } catch (err) {
27775 return '[UnexpectedJSONParseError]: ' + err.message;
27776 }
27777};
27778
27779
27780/**
27781 * Colorize log arguments if enabled.
27782 *
27783 * @api public
27784 */
27785
27786function formatArgs(args) {
27787 var useColors = this.useColors;
27788
27789 args[0] = (useColors ? '%c' : '')
27790 + this.namespace
27791 + (useColors ? ' %c' : ' ')
27792 + args[0]
27793 + (useColors ? '%c ' : ' ')
27794 + '+' + exports.humanize(this.diff);
27795
27796 if (!useColors) return;
27797
27798 var c = 'color: ' + this.color;
27799 args.splice(1, 0, c, 'color: inherit');
27800
27801 // the final "%c" is somewhat tricky, because there could be other
27802 // arguments passed either before or after the %c, so we need to
27803 // figure out the correct index to insert the CSS into
27804 var index = 0;
27805 var lastC = 0;
27806 args[0].replace(/%[a-zA-Z%]/g, function(match) {
27807 if ('%%' === match) return;
27808 index++;
27809 if ('%c' === match) {
27810 // we only are interested in the *last* %c
27811 // (the user may have provided their own)
27812 lastC = index;
27813 }
27814 });
27815
27816 args.splice(lastC, 0, c);
27817}
27818
27819/**
27820 * Invokes `console.log()` when available.
27821 * No-op when `console.log` is not a "function".
27822 *
27823 * @api public
27824 */
27825
27826function log() {
27827 // this hackery is required for IE8/9, where
27828 // the `console.log` function doesn't have 'apply'
27829 return 'object' === typeof console
27830 && console.log
27831 && Function.prototype.apply.call(console.log, console, arguments);
27832}
27833
27834/**
27835 * Save `namespaces`.
27836 *
27837 * @param {String} namespaces
27838 * @api private
27839 */
27840
27841function save(namespaces) {
27842 try {
27843 if (null == namespaces) {
27844 exports.storage.removeItem('debug');
27845 } else {
27846 exports.storage.debug = namespaces;
27847 }
27848 } catch(e) {}
27849}
27850
27851/**
27852 * Load `namespaces`.
27853 *
27854 * @return {String} returns the previously persisted debug modes
27855 * @api private
27856 */
27857
27858function load() {
27859 var r;
27860 try {
27861 r = exports.storage.debug;
27862 } catch(e) {}
27863
27864 // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
27865 if (!r && typeof process !== 'undefined' && 'env' in process) {
27866 r = process.env.DEBUG;
27867 }
27868
27869 return r;
27870}
27871
27872/**
27873 * Enable namespaces listed in `localStorage.debug` initially.
27874 */
27875
27876exports.enable(load());
27877
27878/**
27879 * Localstorage attempts to return the localstorage.
27880 *
27881 * This is necessary because safari throws
27882 * when a user disables cookies/localstorage
27883 * and you attempt to access it.
27884 *
27885 * @return {LocalStorage}
27886 * @api private
27887 */
27888
27889function localstorage() {
27890 try {
27891 return window.localStorage;
27892 } catch (e) {}
27893}
27894});
27895
27896var node = createCommonjsModule(function (module, exports) {
27897/**
27898 * Module dependencies.
27899 */
27900
27901
27902
27903
27904/**
27905 * This is the Node.js implementation of `debug()`.
27906 *
27907 * Expose `debug()` as the module.
27908 */
27909
27910exports = module.exports = debug;
27911exports.init = init;
27912exports.log = log;
27913exports.formatArgs = formatArgs;
27914exports.save = save;
27915exports.load = load;
27916exports.useColors = useColors;
27917
27918/**
27919 * Colors.
27920 */
27921
27922exports.colors = [6, 2, 3, 4, 5, 1];
27923
27924/**
27925 * Build up the default `inspectOpts` object from the environment variables.
27926 *
27927 * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
27928 */
27929
27930exports.inspectOpts = Object.keys(process.env).filter(function (key) {
27931 return /^debug_/i.test(key);
27932}).reduce(function (obj, key) {
27933 // camel-case
27934 var prop = key
27935 .substring(6)
27936 .toLowerCase()
27937 .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });
27938
27939 // coerce string value into JS value
27940 var val = process.env[key];
27941 if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
27942 else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
27943 else if (val === 'null') val = null;
27944 else val = Number(val);
27945
27946 obj[prop] = val;
27947 return obj;
27948}, {});
27949
27950/**
27951 * The file descriptor to write the `debug()` calls to.
27952 * Set the `DEBUG_FD` env variable to override with another value. i.e.:
27953 *
27954 * $ DEBUG_FD=3 node script.js 3>debug.log
27955 */
27956
27957var fd = parseInt(process.env.DEBUG_FD, 10) || 2;
27958
27959if (1 !== fd && 2 !== fd) {
27960 util$2.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')();
27961}
27962
27963var stream = 1 === fd ? process.stdout :
27964 2 === fd ? process.stderr :
27965 createWritableStdioStream(fd);
27966
27967/**
27968 * Is stdout a TTY? Colored output is enabled when `true`.
27969 */
27970
27971function useColors() {
27972 return 'colors' in exports.inspectOpts
27973 ? Boolean(exports.inspectOpts.colors)
27974 : tty.isatty(fd);
27975}
27976
27977/**
27978 * Map %o to `util.inspect()`, all on a single line.
27979 */
27980
27981exports.formatters.o = function(v) {
27982 this.inspectOpts.colors = this.useColors;
27983 return util$2.inspect(v, this.inspectOpts)
27984 .split('\n').map(function(str) {
27985 return str.trim()
27986 }).join(' ');
27987};
27988
27989/**
27990 * Map %o to `util.inspect()`, allowing multiple lines if needed.
27991 */
27992
27993exports.formatters.O = function(v) {
27994 this.inspectOpts.colors = this.useColors;
27995 return util$2.inspect(v, this.inspectOpts);
27996};
27997
27998/**
27999 * Adds ANSI color escape codes if enabled.
28000 *
28001 * @api public
28002 */
28003
28004function formatArgs(args) {
28005 var name = this.namespace;
28006 var useColors = this.useColors;
28007
28008 if (useColors) {
28009 var c = this.color;
28010 var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';
28011
28012 args[0] = prefix + args[0].split('\n').join('\n' + prefix);
28013 args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
28014 } else {
28015 args[0] = new Date().toUTCString()
28016 + ' ' + name + ' ' + args[0];
28017 }
28018}
28019
28020/**
28021 * Invokes `util.format()` with the specified arguments and writes to `stream`.
28022 */
28023
28024function log() {
28025 return stream.write(util$2.format.apply(util$2, arguments) + '\n');
28026}
28027
28028/**
28029 * Save `namespaces`.
28030 *
28031 * @param {String} namespaces
28032 * @api private
28033 */
28034
28035function save(namespaces) {
28036 if (null == namespaces) {
28037 // If you set a process.env field to null or undefined, it gets cast to the
28038 // string 'null' or 'undefined'. Just delete instead.
28039 delete process.env.DEBUG;
28040 } else {
28041 process.env.DEBUG = namespaces;
28042 }
28043}
28044
28045/**
28046 * Load `namespaces`.
28047 *
28048 * @return {String} returns the previously persisted debug modes
28049 * @api private
28050 */
28051
28052function load() {
28053 return process.env.DEBUG;
28054}
28055
28056/**
28057 * Copied from `node/src/node.js`.
28058 *
28059 * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
28060 * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
28061 */
28062
28063function createWritableStdioStream (fd) {
28064 var stream;
28065 var tty_wrap = process.binding('tty_wrap');
28066
28067 // Note stream._type is used for test-module-load-list.js
28068
28069 switch (tty_wrap.guessHandleType(fd)) {
28070 case 'TTY':
28071 stream = new tty.WriteStream(fd);
28072 stream._type = 'tty';
28073
28074 // Hack to have stream not keep the event loop alive.
28075 // See https://github.com/joyent/node/issues/1726
28076 if (stream._handle && stream._handle.unref) {
28077 stream._handle.unref();
28078 }
28079 break;
28080
28081 case 'FILE':
28082 var fs = fs__default;
28083 stream = new fs.SyncWriteStream(fd, { autoClose: false });
28084 stream._type = 'fs';
28085 break;
28086
28087 case 'PIPE':
28088 case 'TCP':
28089 var net$1 = net;
28090 stream = new net$1.Socket({
28091 fd: fd,
28092 readable: false,
28093 writable: true
28094 });
28095
28096 // FIXME Should probably have an option in net.Socket to create a
28097 // stream from an existing fd which is writable only. But for now
28098 // we'll just add this hack and set the `readable` member to false.
28099 // Test: ./node test/fixtures/echo.js < /etc/passwd
28100 stream.readable = false;
28101 stream.read = null;
28102 stream._type = 'pipe';
28103
28104 // FIXME Hack to have stream not keep the event loop alive.
28105 // See https://github.com/joyent/node/issues/1726
28106 if (stream._handle && stream._handle.unref) {
28107 stream._handle.unref();
28108 }
28109 break;
28110
28111 default:
28112 // Probably an error on in uv_guess_handle()
28113 throw new Error('Implement me. Unknown stream file type!');
28114 }
28115
28116 // For supporting legacy API we put the FD here.
28117 stream.fd = fd;
28118
28119 stream._isStdio = true;
28120
28121 return stream;
28122}
28123
28124/**
28125 * Init logic for `debug` instances.
28126 *
28127 * Create a new `inspectOpts` object in case `useColors` is set
28128 * differently for a particular `debug` instance.
28129 */
28130
28131function init (debug) {
28132 debug.inspectOpts = {};
28133
28134 var keys = Object.keys(exports.inspectOpts);
28135 for (var i = 0; i < keys.length; i++) {
28136 debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
28137 }
28138}
28139
28140/**
28141 * Enable namespaces listed in `process.env.DEBUG` initially.
28142 */
28143
28144exports.enable(load());
28145});
28146
28147var src = createCommonjsModule(function (module) {
28148/**
28149 * Detect Electron renderer process, which is node, but we should
28150 * treat as a browser.
28151 */
28152
28153if (typeof process !== 'undefined' && process.type === 'renderer') {
28154 module.exports = browser;
28155} else {
28156 module.exports = node;
28157}
28158});
28159
28160var extendShallow$5 = function extend(o/*, objects*/) {
28161 if (!isExtendable$1(o)) { o = {}; }
28162
28163 var len = arguments.length;
28164 for (var i = 1; i < len; i++) {
28165 var obj = arguments[i];
28166
28167 if (isExtendable$1(obj)) {
28168 assign$5(o, obj);
28169 }
28170 }
28171 return o;
28172};
28173
28174function assign$5(a, b) {
28175 for (var key in b) {
28176 if (hasOwn$5(b, key)) {
28177 a[key] = b[key];
28178 }
28179 }
28180}
28181
28182/**
28183 * Returns true if the given `key` is an own property of `obj`.
28184 */
28185
28186function hasOwn$5(obj, key) {
28187 return Object.prototype.hasOwnProperty.call(obj, key);
28188}
28189
28190/* -*- Mode: js; js-indent-level: 2; -*- */
28191/*
28192 * Copyright 2011 Mozilla Foundation and contributors
28193 * Licensed under the New BSD license. See LICENSE or:
28194 * http://opensource.org/licenses/BSD-3-Clause
28195 */
28196
28197var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
28198
28199/**
28200 * Encode an integer in the range of 0 to 63 to a single base 64 digit.
28201 */
28202var encode$1 = function (number) {
28203 if (0 <= number && number < intToCharMap.length) {
28204 return intToCharMap[number];
28205 }
28206 throw new TypeError("Must be between 0 and 63: " + number);
28207};
28208
28209/**
28210 * Decode a single base 64 character code digit to an integer. Returns -1 on
28211 * failure.
28212 */
28213var decode$1 = function (charCode) {
28214 var bigA = 65; // 'A'
28215 var bigZ = 90; // 'Z'
28216
28217 var littleA = 97; // 'a'
28218 var littleZ = 122; // 'z'
28219
28220 var zero = 48; // '0'
28221 var nine = 57; // '9'
28222
28223 var plus = 43; // '+'
28224 var slash = 47; // '/'
28225
28226 var littleOffset = 26;
28227 var numberOffset = 52;
28228
28229 // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ
28230 if (bigA <= charCode && charCode <= bigZ) {
28231 return (charCode - bigA);
28232 }
28233
28234 // 26 - 51: abcdefghijklmnopqrstuvwxyz
28235 if (littleA <= charCode && charCode <= littleZ) {
28236 return (charCode - littleA + littleOffset);
28237 }
28238
28239 // 52 - 61: 0123456789
28240 if (zero <= charCode && charCode <= nine) {
28241 return (charCode - zero + numberOffset);
28242 }
28243
28244 // 62: +
28245 if (charCode == plus) {
28246 return 62;
28247 }
28248
28249 // 63: /
28250 if (charCode == slash) {
28251 return 63;
28252 }
28253
28254 // Invalid base64 digit.
28255 return -1;
28256};
28257
28258var base64 = {
28259 encode: encode$1,
28260 decode: decode$1
28261};
28262
28263/* -*- Mode: js; js-indent-level: 2; -*- */
28264/*
28265 * Copyright 2011 Mozilla Foundation and contributors
28266 * Licensed under the New BSD license. See LICENSE or:
28267 * http://opensource.org/licenses/BSD-3-Clause
28268 *
28269 * Based on the Base 64 VLQ implementation in Closure Compiler:
28270 * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
28271 *
28272 * Copyright 2011 The Closure Compiler Authors. All rights reserved.
28273 * Redistribution and use in source and binary forms, with or without
28274 * modification, are permitted provided that the following conditions are
28275 * met:
28276 *
28277 * * Redistributions of source code must retain the above copyright
28278 * notice, this list of conditions and the following disclaimer.
28279 * * Redistributions in binary form must reproduce the above
28280 * copyright notice, this list of conditions and the following
28281 * disclaimer in the documentation and/or other materials provided
28282 * with the distribution.
28283 * * Neither the name of Google Inc. nor the names of its
28284 * contributors may be used to endorse or promote products derived
28285 * from this software without specific prior written permission.
28286 *
28287 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28288 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
28289 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
28290 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
28291 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28292 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
28293 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
28294 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28295 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28296 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28297 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28298 */
28299
28300
28301
28302// A single base 64 digit can contain 6 bits of data. For the base 64 variable
28303// length quantities we use in the source map spec, the first bit is the sign,
28304// the next four bits are the actual value, and the 6th bit is the
28305// continuation bit. The continuation bit tells us whether there are more
28306// digits in this value following this digit.
28307//
28308// Continuation
28309// | Sign
28310// | |
28311// V V
28312// 101011
28313
28314var VLQ_BASE_SHIFT = 5;
28315
28316// binary: 100000
28317var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
28318
28319// binary: 011111
28320var VLQ_BASE_MASK = VLQ_BASE - 1;
28321
28322// binary: 100000
28323var VLQ_CONTINUATION_BIT = VLQ_BASE;
28324
28325/**
28326 * Converts from a two-complement value to a value where the sign bit is
28327 * placed in the least significant bit. For example, as decimals:
28328 * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
28329 * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
28330 */
28331function toVLQSigned(aValue) {
28332 return aValue < 0
28333 ? ((-aValue) << 1) + 1
28334 : (aValue << 1) + 0;
28335}
28336
28337/**
28338 * Converts to a two-complement value from a value where the sign bit is
28339 * placed in the least significant bit. For example, as decimals:
28340 * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
28341 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
28342 */
28343function fromVLQSigned(aValue) {
28344 var isNegative = (aValue & 1) === 1;
28345 var shifted = aValue >> 1;
28346 return isNegative
28347 ? -shifted
28348 : shifted;
28349}
28350
28351/**
28352 * Returns the base 64 VLQ encoded value.
28353 */
28354var encode$2 = function base64VLQ_encode(aValue) {
28355 var encoded = "";
28356 var digit;
28357
28358 var vlq = toVLQSigned(aValue);
28359
28360 do {
28361 digit = vlq & VLQ_BASE_MASK;
28362 vlq >>>= VLQ_BASE_SHIFT;
28363 if (vlq > 0) {
28364 // There are still more digits in this value, so we must make sure the
28365 // continuation bit is marked.
28366 digit |= VLQ_CONTINUATION_BIT;
28367 }
28368 encoded += base64.encode(digit);
28369 } while (vlq > 0);
28370
28371 return encoded;
28372};
28373
28374/**
28375 * Decodes the next base 64 VLQ value from the given string and returns the
28376 * value and the rest of the string via the out parameter.
28377 */
28378var decode$2 = function base64VLQ_decode(aStr, aIndex, aOutParam) {
28379 var strLen = aStr.length;
28380 var result = 0;
28381 var shift = 0;
28382 var continuation, digit;
28383
28384 do {
28385 if (aIndex >= strLen) {
28386 throw new Error("Expected more digits in base 64 VLQ value.");
28387 }
28388
28389 digit = base64.decode(aStr.charCodeAt(aIndex++));
28390 if (digit === -1) {
28391 throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1));
28392 }
28393
28394 continuation = !!(digit & VLQ_CONTINUATION_BIT);
28395 digit &= VLQ_BASE_MASK;
28396 result = result + (digit << shift);
28397 shift += VLQ_BASE_SHIFT;
28398 } while (continuation);
28399
28400 aOutParam.value = fromVLQSigned(result);
28401 aOutParam.rest = aIndex;
28402};
28403
28404var base64Vlq = {
28405 encode: encode$2,
28406 decode: decode$2
28407};
28408
28409var util$1 = createCommonjsModule(function (module, exports) {
28410/* -*- Mode: js; js-indent-level: 2; -*- */
28411/*
28412 * Copyright 2011 Mozilla Foundation and contributors
28413 * Licensed under the New BSD license. See LICENSE or:
28414 * http://opensource.org/licenses/BSD-3-Clause
28415 */
28416
28417/**
28418 * This is a helper function for getting values from parameter/options
28419 * objects.
28420 *
28421 * @param args The object we are extracting values from
28422 * @param name The name of the property we are getting.
28423 * @param defaultValue An optional value to return if the property is missing
28424 * from the object. If this is not specified and the property is missing, an
28425 * error will be thrown.
28426 */
28427function getArg(aArgs, aName, aDefaultValue) {
28428 if (aName in aArgs) {
28429 return aArgs[aName];
28430 } else if (arguments.length === 3) {
28431 return aDefaultValue;
28432 } else {
28433 throw new Error('"' + aName + '" is a required argument.');
28434 }
28435}
28436exports.getArg = getArg;
28437
28438var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;
28439var dataUrlRegexp = /^data:.+\,.+$/;
28440
28441function urlParse(aUrl) {
28442 var match = aUrl.match(urlRegexp);
28443 if (!match) {
28444 return null;
28445 }
28446 return {
28447 scheme: match[1],
28448 auth: match[2],
28449 host: match[3],
28450 port: match[4],
28451 path: match[5]
28452 };
28453}
28454exports.urlParse = urlParse;
28455
28456function urlGenerate(aParsedUrl) {
28457 var url = '';
28458 if (aParsedUrl.scheme) {
28459 url += aParsedUrl.scheme + ':';
28460 }
28461 url += '//';
28462 if (aParsedUrl.auth) {
28463 url += aParsedUrl.auth + '@';
28464 }
28465 if (aParsedUrl.host) {
28466 url += aParsedUrl.host;
28467 }
28468 if (aParsedUrl.port) {
28469 url += ":" + aParsedUrl.port;
28470 }
28471 if (aParsedUrl.path) {
28472 url += aParsedUrl.path;
28473 }
28474 return url;
28475}
28476exports.urlGenerate = urlGenerate;
28477
28478/**
28479 * Normalizes a path, or the path portion of a URL:
28480 *
28481 * - Replaces consecutive slashes with one slash.
28482 * - Removes unnecessary '.' parts.
28483 * - Removes unnecessary '<dir>/..' parts.
28484 *
28485 * Based on code in the Node.js 'path' core module.
28486 *
28487 * @param aPath The path or url to normalize.
28488 */
28489function normalize(aPath) {
28490 var path = aPath;
28491 var url = urlParse(aPath);
28492 if (url) {
28493 if (!url.path) {
28494 return aPath;
28495 }
28496 path = url.path;
28497 }
28498 var isAbsolute = exports.isAbsolute(path);
28499
28500 var parts = path.split(/\/+/);
28501 for (var part, up = 0, i = parts.length - 1; i >= 0; i--) {
28502 part = parts[i];
28503 if (part === '.') {
28504 parts.splice(i, 1);
28505 } else if (part === '..') {
28506 up++;
28507 } else if (up > 0) {
28508 if (part === '') {
28509 // The first part is blank if the path is absolute. Trying to go
28510 // above the root is a no-op. Therefore we can remove all '..' parts
28511 // directly after the root.
28512 parts.splice(i + 1, up);
28513 up = 0;
28514 } else {
28515 parts.splice(i, 2);
28516 up--;
28517 }
28518 }
28519 }
28520 path = parts.join('/');
28521
28522 if (path === '') {
28523 path = isAbsolute ? '/' : '.';
28524 }
28525
28526 if (url) {
28527 url.path = path;
28528 return urlGenerate(url);
28529 }
28530 return path;
28531}
28532exports.normalize = normalize;
28533
28534/**
28535 * Joins two paths/URLs.
28536 *
28537 * @param aRoot The root path or URL.
28538 * @param aPath The path or URL to be joined with the root.
28539 *
28540 * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a
28541 * scheme-relative URL: Then the scheme of aRoot, if any, is prepended
28542 * first.
28543 * - Otherwise aPath is a path. If aRoot is a URL, then its path portion
28544 * is updated with the result and aRoot is returned. Otherwise the result
28545 * is returned.
28546 * - If aPath is absolute, the result is aPath.
28547 * - Otherwise the two paths are joined with a slash.
28548 * - Joining for example 'http://' and 'www.example.com' is also supported.
28549 */
28550function join(aRoot, aPath) {
28551 if (aRoot === "") {
28552 aRoot = ".";
28553 }
28554 if (aPath === "") {
28555 aPath = ".";
28556 }
28557 var aPathUrl = urlParse(aPath);
28558 var aRootUrl = urlParse(aRoot);
28559 if (aRootUrl) {
28560 aRoot = aRootUrl.path || '/';
28561 }
28562
28563 // `join(foo, '//www.example.org')`
28564 if (aPathUrl && !aPathUrl.scheme) {
28565 if (aRootUrl) {
28566 aPathUrl.scheme = aRootUrl.scheme;
28567 }
28568 return urlGenerate(aPathUrl);
28569 }
28570
28571 if (aPathUrl || aPath.match(dataUrlRegexp)) {
28572 return aPath;
28573 }
28574
28575 // `join('http://', 'www.example.com')`
28576 if (aRootUrl && !aRootUrl.host && !aRootUrl.path) {
28577 aRootUrl.host = aPath;
28578 return urlGenerate(aRootUrl);
28579 }
28580
28581 var joined = aPath.charAt(0) === '/'
28582 ? aPath
28583 : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath);
28584
28585 if (aRootUrl) {
28586 aRootUrl.path = joined;
28587 return urlGenerate(aRootUrl);
28588 }
28589 return joined;
28590}
28591exports.join = join;
28592
28593exports.isAbsolute = function (aPath) {
28594 return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp);
28595};
28596
28597/**
28598 * Make a path relative to a URL or another path.
28599 *
28600 * @param aRoot The root path or URL.
28601 * @param aPath The path or URL to be made relative to aRoot.
28602 */
28603function relative(aRoot, aPath) {
28604 if (aRoot === "") {
28605 aRoot = ".";
28606 }
28607
28608 aRoot = aRoot.replace(/\/$/, '');
28609
28610 // It is possible for the path to be above the root. In this case, simply
28611 // checking whether the root is a prefix of the path won't work. Instead, we
28612 // need to remove components from the root one by one, until either we find
28613 // a prefix that fits, or we run out of components to remove.
28614 var level = 0;
28615 while (aPath.indexOf(aRoot + '/') !== 0) {
28616 var index = aRoot.lastIndexOf("/");
28617 if (index < 0) {
28618 return aPath;
28619 }
28620
28621 // If the only part of the root that is left is the scheme (i.e. http://,
28622 // file:///, etc.), one or more slashes (/), or simply nothing at all, we
28623 // have exhausted all components, so the path is not relative to the root.
28624 aRoot = aRoot.slice(0, index);
28625 if (aRoot.match(/^([^\/]+:\/)?\/*$/)) {
28626 return aPath;
28627 }
28628
28629 ++level;
28630 }
28631
28632 // Make sure we add a "../" for each component we removed from the root.
28633 return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1);
28634}
28635exports.relative = relative;
28636
28637var supportsNullProto = (function () {
28638 var obj = Object.create(null);
28639 return !('__proto__' in obj);
28640}());
28641
28642function identity (s) {
28643 return s;
28644}
28645
28646/**
28647 * Because behavior goes wacky when you set `__proto__` on objects, we
28648 * have to prefix all the strings in our set with an arbitrary character.
28649 *
28650 * See https://github.com/mozilla/source-map/pull/31 and
28651 * https://github.com/mozilla/source-map/issues/30
28652 *
28653 * @param String aStr
28654 */
28655function toSetString(aStr) {
28656 if (isProtoString(aStr)) {
28657 return '$' + aStr;
28658 }
28659
28660 return aStr;
28661}
28662exports.toSetString = supportsNullProto ? identity : toSetString;
28663
28664function fromSetString(aStr) {
28665 if (isProtoString(aStr)) {
28666 return aStr.slice(1);
28667 }
28668
28669 return aStr;
28670}
28671exports.fromSetString = supportsNullProto ? identity : fromSetString;
28672
28673function isProtoString(s) {
28674 if (!s) {
28675 return false;
28676 }
28677
28678 var length = s.length;
28679
28680 if (length < 9 /* "__proto__".length */) {
28681 return false;
28682 }
28683
28684 if (s.charCodeAt(length - 1) !== 95 /* '_' */ ||
28685 s.charCodeAt(length - 2) !== 95 /* '_' */ ||
28686 s.charCodeAt(length - 3) !== 111 /* 'o' */ ||
28687 s.charCodeAt(length - 4) !== 116 /* 't' */ ||
28688 s.charCodeAt(length - 5) !== 111 /* 'o' */ ||
28689 s.charCodeAt(length - 6) !== 114 /* 'r' */ ||
28690 s.charCodeAt(length - 7) !== 112 /* 'p' */ ||
28691 s.charCodeAt(length - 8) !== 95 /* '_' */ ||
28692 s.charCodeAt(length - 9) !== 95 /* '_' */) {
28693 return false;
28694 }
28695
28696 for (var i = length - 10; i >= 0; i--) {
28697 if (s.charCodeAt(i) !== 36 /* '$' */) {
28698 return false;
28699 }
28700 }
28701
28702 return true;
28703}
28704
28705/**
28706 * Comparator between two mappings where the original positions are compared.
28707 *
28708 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
28709 * mappings with the same original source/line/column, but different generated
28710 * line and column the same. Useful when searching for a mapping with a
28711 * stubbed out mapping.
28712 */
28713function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
28714 var cmp = mappingA.source - mappingB.source;
28715 if (cmp !== 0) {
28716 return cmp;
28717 }
28718
28719 cmp = mappingA.originalLine - mappingB.originalLine;
28720 if (cmp !== 0) {
28721 return cmp;
28722 }
28723
28724 cmp = mappingA.originalColumn - mappingB.originalColumn;
28725 if (cmp !== 0 || onlyCompareOriginal) {
28726 return cmp;
28727 }
28728
28729 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
28730 if (cmp !== 0) {
28731 return cmp;
28732 }
28733
28734 cmp = mappingA.generatedLine - mappingB.generatedLine;
28735 if (cmp !== 0) {
28736 return cmp;
28737 }
28738
28739 return mappingA.name - mappingB.name;
28740}
28741exports.compareByOriginalPositions = compareByOriginalPositions;
28742
28743/**
28744 * Comparator between two mappings with deflated source and name indices where
28745 * the generated positions are compared.
28746 *
28747 * Optionally pass in `true` as `onlyCompareGenerated` to consider two
28748 * mappings with the same generated line and column, but different
28749 * source/name/original line and column the same. Useful when searching for a
28750 * mapping with a stubbed out mapping.
28751 */
28752function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) {
28753 var cmp = mappingA.generatedLine - mappingB.generatedLine;
28754 if (cmp !== 0) {
28755 return cmp;
28756 }
28757
28758 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
28759 if (cmp !== 0 || onlyCompareGenerated) {
28760 return cmp;
28761 }
28762
28763 cmp = mappingA.source - mappingB.source;
28764 if (cmp !== 0) {
28765 return cmp;
28766 }
28767
28768 cmp = mappingA.originalLine - mappingB.originalLine;
28769 if (cmp !== 0) {
28770 return cmp;
28771 }
28772
28773 cmp = mappingA.originalColumn - mappingB.originalColumn;
28774 if (cmp !== 0) {
28775 return cmp;
28776 }
28777
28778 return mappingA.name - mappingB.name;
28779}
28780exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated;
28781
28782function strcmp(aStr1, aStr2) {
28783 if (aStr1 === aStr2) {
28784 return 0;
28785 }
28786
28787 if (aStr1 > aStr2) {
28788 return 1;
28789 }
28790
28791 return -1;
28792}
28793
28794/**
28795 * Comparator between two mappings with inflated source and name strings where
28796 * the generated positions are compared.
28797 */
28798function compareByGeneratedPositionsInflated(mappingA, mappingB) {
28799 var cmp = mappingA.generatedLine - mappingB.generatedLine;
28800 if (cmp !== 0) {
28801 return cmp;
28802 }
28803
28804 cmp = mappingA.generatedColumn - mappingB.generatedColumn;
28805 if (cmp !== 0) {
28806 return cmp;
28807 }
28808
28809 cmp = strcmp(mappingA.source, mappingB.source);
28810 if (cmp !== 0) {
28811 return cmp;
28812 }
28813
28814 cmp = mappingA.originalLine - mappingB.originalLine;
28815 if (cmp !== 0) {
28816 return cmp;
28817 }
28818
28819 cmp = mappingA.originalColumn - mappingB.originalColumn;
28820 if (cmp !== 0) {
28821 return cmp;
28822 }
28823
28824 return strcmp(mappingA.name, mappingB.name);
28825}
28826exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated;
28827});
28828
28829/* -*- Mode: js; js-indent-level: 2; -*- */
28830/*
28831 * Copyright 2011 Mozilla Foundation and contributors
28832 * Licensed under the New BSD license. See LICENSE or:
28833 * http://opensource.org/licenses/BSD-3-Clause
28834 */
28835
28836
28837var has$6 = Object.prototype.hasOwnProperty;
28838var hasNativeMap = typeof Map !== "undefined";
28839
28840/**
28841 * A data structure which is a combination of an array and a set. Adding a new
28842 * member is O(1), testing for membership is O(1), and finding the index of an
28843 * element is O(1). Removing elements from the set is not supported. Only
28844 * strings are supported for membership.
28845 */
28846function ArraySet() {
28847 this._array = [];
28848 this._set = hasNativeMap ? new Map() : Object.create(null);
28849}
28850
28851/**
28852 * Static method for creating ArraySet instances from an existing array.
28853 */
28854ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
28855 var set = new ArraySet();
28856 for (var i = 0, len = aArray.length; i < len; i++) {
28857 set.add(aArray[i], aAllowDuplicates);
28858 }
28859 return set;
28860};
28861
28862/**
28863 * Return how many unique items are in this ArraySet. If duplicates have been
28864 * added, than those do not count towards the size.
28865 *
28866 * @returns Number
28867 */
28868ArraySet.prototype.size = function ArraySet_size() {
28869 return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length;
28870};
28871
28872/**
28873 * Add the given string to this set.
28874 *
28875 * @param String aStr
28876 */
28877ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
28878 var sStr = hasNativeMap ? aStr : util$1.toSetString(aStr);
28879 var isDuplicate = hasNativeMap ? this.has(aStr) : has$6.call(this._set, sStr);
28880 var idx = this._array.length;
28881 if (!isDuplicate || aAllowDuplicates) {
28882 this._array.push(aStr);
28883 }
28884 if (!isDuplicate) {
28885 if (hasNativeMap) {
28886 this._set.set(aStr, idx);
28887 } else {
28888 this._set[sStr] = idx;
28889 }
28890 }
28891};
28892
28893/**
28894 * Is the given string a member of this set?
28895 *
28896 * @param String aStr
28897 */
28898ArraySet.prototype.has = function ArraySet_has(aStr) {
28899 if (hasNativeMap) {
28900 return this._set.has(aStr);
28901 } else {
28902 var sStr = util$1.toSetString(aStr);
28903 return has$6.call(this._set, sStr);
28904 }
28905};
28906
28907/**
28908 * What is the index of the given string in the array?
28909 *
28910 * @param String aStr
28911 */
28912ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
28913 if (hasNativeMap) {
28914 var idx = this._set.get(aStr);
28915 if (idx >= 0) {
28916 return idx;
28917 }
28918 } else {
28919 var sStr = util$1.toSetString(aStr);
28920 if (has$6.call(this._set, sStr)) {
28921 return this._set[sStr];
28922 }
28923 }
28924
28925 throw new Error('"' + aStr + '" is not in the set.');
28926};
28927
28928/**
28929 * What is the element at the given index?
28930 *
28931 * @param Number aIdx
28932 */
28933ArraySet.prototype.at = function ArraySet_at(aIdx) {
28934 if (aIdx >= 0 && aIdx < this._array.length) {
28935 return this._array[aIdx];
28936 }
28937 throw new Error('No element indexed by ' + aIdx);
28938};
28939
28940/**
28941 * Returns the array representation of this set (which has the proper indices
28942 * indicated by indexOf). Note that this is a copy of the internal array used
28943 * for storing the members so that no one can mess with internal state.
28944 */
28945ArraySet.prototype.toArray = function ArraySet_toArray() {
28946 return this._array.slice();
28947};
28948
28949var ArraySet_1 = ArraySet;
28950
28951var arraySet = {
28952 ArraySet: ArraySet_1
28953};
28954
28955/* -*- Mode: js; js-indent-level: 2; -*- */
28956/*
28957 * Copyright 2014 Mozilla Foundation and contributors
28958 * Licensed under the New BSD license. See LICENSE or:
28959 * http://opensource.org/licenses/BSD-3-Clause
28960 */
28961
28962
28963
28964/**
28965 * Determine whether mappingB is after mappingA with respect to generated
28966 * position.
28967 */
28968function generatedPositionAfter(mappingA, mappingB) {
28969 // Optimized for most common case
28970 var lineA = mappingA.generatedLine;
28971 var lineB = mappingB.generatedLine;
28972 var columnA = mappingA.generatedColumn;
28973 var columnB = mappingB.generatedColumn;
28974 return lineB > lineA || lineB == lineA && columnB >= columnA ||
28975 util$1.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0;
28976}
28977
28978/**
28979 * A data structure to provide a sorted view of accumulated mappings in a
28980 * performance conscious manner. It trades a neglibable overhead in general
28981 * case for a large speedup in case of mappings being added in order.
28982 */
28983function MappingList() {
28984 this._array = [];
28985 this._sorted = true;
28986 // Serves as infimum
28987 this._last = {generatedLine: -1, generatedColumn: 0};
28988}
28989
28990/**
28991 * Iterate through internal items. This method takes the same arguments that
28992 * `Array.prototype.forEach` takes.
28993 *
28994 * NOTE: The order of the mappings is NOT guaranteed.
28995 */
28996MappingList.prototype.unsortedForEach =
28997 function MappingList_forEach(aCallback, aThisArg) {
28998 this._array.forEach(aCallback, aThisArg);
28999 };
29000
29001/**
29002 * Add the given source mapping.
29003 *
29004 * @param Object aMapping
29005 */
29006MappingList.prototype.add = function MappingList_add(aMapping) {
29007 if (generatedPositionAfter(this._last, aMapping)) {
29008 this._last = aMapping;
29009 this._array.push(aMapping);
29010 } else {
29011 this._sorted = false;
29012 this._array.push(aMapping);
29013 }
29014};
29015
29016/**
29017 * Returns the flat, sorted array of mappings. The mappings are sorted by
29018 * generated position.
29019 *
29020 * WARNING: This method returns internal data without copying, for
29021 * performance. The return value must NOT be mutated, and should be treated as
29022 * an immutable borrow. If you want to take ownership, you must make your own
29023 * copy.
29024 */
29025MappingList.prototype.toArray = function MappingList_toArray() {
29026 if (!this._sorted) {
29027 this._array.sort(util$1.compareByGeneratedPositionsInflated);
29028 this._sorted = true;
29029 }
29030 return this._array;
29031};
29032
29033var MappingList_1 = MappingList;
29034
29035var mappingList = {
29036 MappingList: MappingList_1
29037};
29038
29039/* -*- Mode: js; js-indent-level: 2; -*- */
29040/*
29041 * Copyright 2011 Mozilla Foundation and contributors
29042 * Licensed under the New BSD license. See LICENSE or:
29043 * http://opensource.org/licenses/BSD-3-Clause
29044 */
29045
29046
29047
29048var ArraySet$1 = arraySet.ArraySet;
29049var MappingList$1 = mappingList.MappingList;
29050
29051/**
29052 * An instance of the SourceMapGenerator represents a source map which is
29053 * being built incrementally. You may pass an object with the following
29054 * properties:
29055 *
29056 * - file: The filename of the generated source.
29057 * - sourceRoot: A root for all relative URLs in this source map.
29058 */
29059function SourceMapGenerator(aArgs) {
29060 if (!aArgs) {
29061 aArgs = {};
29062 }
29063 this._file = util$1.getArg(aArgs, 'file', null);
29064 this._sourceRoot = util$1.getArg(aArgs, 'sourceRoot', null);
29065 this._skipValidation = util$1.getArg(aArgs, 'skipValidation', false);
29066 this._sources = new ArraySet$1();
29067 this._names = new ArraySet$1();
29068 this._mappings = new MappingList$1();
29069 this._sourcesContents = null;
29070}
29071
29072SourceMapGenerator.prototype._version = 3;
29073
29074/**
29075 * Creates a new SourceMapGenerator based on a SourceMapConsumer
29076 *
29077 * @param aSourceMapConsumer The SourceMap.
29078 */
29079SourceMapGenerator.fromSourceMap =
29080 function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
29081 var sourceRoot = aSourceMapConsumer.sourceRoot;
29082 var generator = new SourceMapGenerator({
29083 file: aSourceMapConsumer.file,
29084 sourceRoot: sourceRoot
29085 });
29086 aSourceMapConsumer.eachMapping(function (mapping) {
29087 var newMapping = {
29088 generated: {
29089 line: mapping.generatedLine,
29090 column: mapping.generatedColumn
29091 }
29092 };
29093
29094 if (mapping.source != null) {
29095 newMapping.source = mapping.source;
29096 if (sourceRoot != null) {
29097 newMapping.source = util$1.relative(sourceRoot, newMapping.source);
29098 }
29099
29100 newMapping.original = {
29101 line: mapping.originalLine,
29102 column: mapping.originalColumn
29103 };
29104
29105 if (mapping.name != null) {
29106 newMapping.name = mapping.name;
29107 }
29108 }
29109
29110 generator.addMapping(newMapping);
29111 });
29112 aSourceMapConsumer.sources.forEach(function (sourceFile) {
29113 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
29114 if (content != null) {
29115 generator.setSourceContent(sourceFile, content);
29116 }
29117 });
29118 return generator;
29119 };
29120
29121/**
29122 * Add a single mapping from original source line and column to the generated
29123 * source's line and column for this source map being created. The mapping
29124 * object should have the following properties:
29125 *
29126 * - generated: An object with the generated line and column positions.
29127 * - original: An object with the original line and column positions.
29128 * - source: The original source file (relative to the sourceRoot).
29129 * - name: An optional original token name for this mapping.
29130 */
29131SourceMapGenerator.prototype.addMapping =
29132 function SourceMapGenerator_addMapping(aArgs) {
29133 var generated = util$1.getArg(aArgs, 'generated');
29134 var original = util$1.getArg(aArgs, 'original', null);
29135 var source = util$1.getArg(aArgs, 'source', null);
29136 var name = util$1.getArg(aArgs, 'name', null);
29137
29138 if (!this._skipValidation) {
29139 this._validateMapping(generated, original, source, name);
29140 }
29141
29142 if (source != null) {
29143 source = String(source);
29144 if (!this._sources.has(source)) {
29145 this._sources.add(source);
29146 }
29147 }
29148
29149 if (name != null) {
29150 name = String(name);
29151 if (!this._names.has(name)) {
29152 this._names.add(name);
29153 }
29154 }
29155
29156 this._mappings.add({
29157 generatedLine: generated.line,
29158 generatedColumn: generated.column,
29159 originalLine: original != null && original.line,
29160 originalColumn: original != null && original.column,
29161 source: source,
29162 name: name
29163 });
29164 };
29165
29166/**
29167 * Set the source content for a source file.
29168 */
29169SourceMapGenerator.prototype.setSourceContent =
29170 function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
29171 var source = aSourceFile;
29172 if (this._sourceRoot != null) {
29173 source = util$1.relative(this._sourceRoot, source);
29174 }
29175
29176 if (aSourceContent != null) {
29177 // Add the source content to the _sourcesContents map.
29178 // Create a new _sourcesContents map if the property is null.
29179 if (!this._sourcesContents) {
29180 this._sourcesContents = Object.create(null);
29181 }
29182 this._sourcesContents[util$1.toSetString(source)] = aSourceContent;
29183 } else if (this._sourcesContents) {
29184 // Remove the source file from the _sourcesContents map.
29185 // If the _sourcesContents map is empty, set the property to null.
29186 delete this._sourcesContents[util$1.toSetString(source)];
29187 if (Object.keys(this._sourcesContents).length === 0) {
29188 this._sourcesContents = null;
29189 }
29190 }
29191 };
29192
29193/**
29194 * Applies the mappings of a sub-source-map for a specific source file to the
29195 * source map being generated. Each mapping to the supplied source file is
29196 * rewritten using the supplied source map. Note: The resolution for the
29197 * resulting mappings is the minimium of this map and the supplied map.
29198 *
29199 * @param aSourceMapConsumer The source map to be applied.
29200 * @param aSourceFile Optional. The filename of the source file.
29201 * If omitted, SourceMapConsumer's file property will be used.
29202 * @param aSourceMapPath Optional. The dirname of the path to the source map
29203 * to be applied. If relative, it is relative to the SourceMapConsumer.
29204 * This parameter is needed when the two source maps aren't in the same
29205 * directory, and the source map to be applied contains relative source
29206 * paths. If so, those relative source paths need to be rewritten
29207 * relative to the SourceMapGenerator.
29208 */
29209SourceMapGenerator.prototype.applySourceMap =
29210 function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) {
29211 var sourceFile = aSourceFile;
29212 // If aSourceFile is omitted, we will use the file property of the SourceMap
29213 if (aSourceFile == null) {
29214 if (aSourceMapConsumer.file == null) {
29215 throw new Error(
29216 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' +
29217 'or the source map\'s "file" property. Both were omitted.'
29218 );
29219 }
29220 sourceFile = aSourceMapConsumer.file;
29221 }
29222 var sourceRoot = this._sourceRoot;
29223 // Make "sourceFile" relative if an absolute Url is passed.
29224 if (sourceRoot != null) {
29225 sourceFile = util$1.relative(sourceRoot, sourceFile);
29226 }
29227 // Applying the SourceMap can add and remove items from the sources and
29228 // the names array.
29229 var newSources = new ArraySet$1();
29230 var newNames = new ArraySet$1();
29231
29232 // Find mappings for the "sourceFile"
29233 this._mappings.unsortedForEach(function (mapping) {
29234 if (mapping.source === sourceFile && mapping.originalLine != null) {
29235 // Check if it can be mapped by the source map, then update the mapping.
29236 var original = aSourceMapConsumer.originalPositionFor({
29237 line: mapping.originalLine,
29238 column: mapping.originalColumn
29239 });
29240 if (original.source != null) {
29241 // Copy mapping
29242 mapping.source = original.source;
29243 if (aSourceMapPath != null) {
29244 mapping.source = util$1.join(aSourceMapPath, mapping.source);
29245 }
29246 if (sourceRoot != null) {
29247 mapping.source = util$1.relative(sourceRoot, mapping.source);
29248 }
29249 mapping.originalLine = original.line;
29250 mapping.originalColumn = original.column;
29251 if (original.name != null) {
29252 mapping.name = original.name;
29253 }
29254 }
29255 }
29256
29257 var source = mapping.source;
29258 if (source != null && !newSources.has(source)) {
29259 newSources.add(source);
29260 }
29261
29262 var name = mapping.name;
29263 if (name != null && !newNames.has(name)) {
29264 newNames.add(name);
29265 }
29266
29267 }, this);
29268 this._sources = newSources;
29269 this._names = newNames;
29270
29271 // Copy sourcesContents of applied map.
29272 aSourceMapConsumer.sources.forEach(function (sourceFile) {
29273 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
29274 if (content != null) {
29275 if (aSourceMapPath != null) {
29276 sourceFile = util$1.join(aSourceMapPath, sourceFile);
29277 }
29278 if (sourceRoot != null) {
29279 sourceFile = util$1.relative(sourceRoot, sourceFile);
29280 }
29281 this.setSourceContent(sourceFile, content);
29282 }
29283 }, this);
29284 };
29285
29286/**
29287 * A mapping can have one of the three levels of data:
29288 *
29289 * 1. Just the generated position.
29290 * 2. The Generated position, original position, and original source.
29291 * 3. Generated and original position, original source, as well as a name
29292 * token.
29293 *
29294 * To maintain consistency, we validate that any new mapping being added falls
29295 * in to one of these categories.
29296 */
29297SourceMapGenerator.prototype._validateMapping =
29298 function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
29299 aName) {
29300 // When aOriginal is truthy but has empty values for .line and .column,
29301 // it is most likely a programmer error. In this case we throw a very
29302 // specific error message to try to guide them the right way.
29303 // For example: https://github.com/Polymer/polymer-bundler/pull/519
29304 if (aOriginal && typeof aOriginal.line !== 'number' && typeof aOriginal.column !== 'number') {
29305 throw new Error(
29306 'original.line and original.column are not numbers -- you probably meant to omit ' +
29307 'the original mapping entirely and only map the generated position. If so, pass ' +
29308 'null for the original mapping instead of an object with empty or null values.'
29309 );
29310 }
29311
29312 if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
29313 && aGenerated.line > 0 && aGenerated.column >= 0
29314 && !aOriginal && !aSource && !aName) {
29315 // Case 1.
29316 return;
29317 }
29318 else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
29319 && aOriginal && 'line' in aOriginal && 'column' in aOriginal
29320 && aGenerated.line > 0 && aGenerated.column >= 0
29321 && aOriginal.line > 0 && aOriginal.column >= 0
29322 && aSource) {
29323 // Cases 2 and 3.
29324 return;
29325 }
29326 else {
29327 throw new Error('Invalid mapping: ' + JSON.stringify({
29328 generated: aGenerated,
29329 source: aSource,
29330 original: aOriginal,
29331 name: aName
29332 }));
29333 }
29334 };
29335
29336/**
29337 * Serialize the accumulated mappings in to the stream of base 64 VLQs
29338 * specified by the source map format.
29339 */
29340SourceMapGenerator.prototype._serializeMappings =
29341 function SourceMapGenerator_serializeMappings() {
29342 var previousGeneratedColumn = 0;
29343 var previousGeneratedLine = 1;
29344 var previousOriginalColumn = 0;
29345 var previousOriginalLine = 0;
29346 var previousName = 0;
29347 var previousSource = 0;
29348 var result = '';
29349 var next;
29350 var mapping;
29351 var nameIdx;
29352 var sourceIdx;
29353
29354 var mappings = this._mappings.toArray();
29355 for (var i = 0, len = mappings.length; i < len; i++) {
29356 mapping = mappings[i];
29357 next = '';
29358
29359 if (mapping.generatedLine !== previousGeneratedLine) {
29360 previousGeneratedColumn = 0;
29361 while (mapping.generatedLine !== previousGeneratedLine) {
29362 next += ';';
29363 previousGeneratedLine++;
29364 }
29365 }
29366 else {
29367 if (i > 0) {
29368 if (!util$1.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) {
29369 continue;
29370 }
29371 next += ',';
29372 }
29373 }
29374
29375 next += base64Vlq.encode(mapping.generatedColumn
29376 - previousGeneratedColumn);
29377 previousGeneratedColumn = mapping.generatedColumn;
29378
29379 if (mapping.source != null) {
29380 sourceIdx = this._sources.indexOf(mapping.source);
29381 next += base64Vlq.encode(sourceIdx - previousSource);
29382 previousSource = sourceIdx;
29383
29384 // lines are stored 0-based in SourceMap spec version 3
29385 next += base64Vlq.encode(mapping.originalLine - 1
29386 - previousOriginalLine);
29387 previousOriginalLine = mapping.originalLine - 1;
29388
29389 next += base64Vlq.encode(mapping.originalColumn
29390 - previousOriginalColumn);
29391 previousOriginalColumn = mapping.originalColumn;
29392
29393 if (mapping.name != null) {
29394 nameIdx = this._names.indexOf(mapping.name);
29395 next += base64Vlq.encode(nameIdx - previousName);
29396 previousName = nameIdx;
29397 }
29398 }
29399
29400 result += next;
29401 }
29402
29403 return result;
29404 };
29405
29406SourceMapGenerator.prototype._generateSourcesContent =
29407 function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
29408 return aSources.map(function (source) {
29409 if (!this._sourcesContents) {
29410 return null;
29411 }
29412 if (aSourceRoot != null) {
29413 source = util$1.relative(aSourceRoot, source);
29414 }
29415 var key = util$1.toSetString(source);
29416 return Object.prototype.hasOwnProperty.call(this._sourcesContents, key)
29417 ? this._sourcesContents[key]
29418 : null;
29419 }, this);
29420 };
29421
29422/**
29423 * Externalize the source map.
29424 */
29425SourceMapGenerator.prototype.toJSON =
29426 function SourceMapGenerator_toJSON() {
29427 var map = {
29428 version: this._version,
29429 sources: this._sources.toArray(),
29430 names: this._names.toArray(),
29431 mappings: this._serializeMappings()
29432 };
29433 if (this._file != null) {
29434 map.file = this._file;
29435 }
29436 if (this._sourceRoot != null) {
29437 map.sourceRoot = this._sourceRoot;
29438 }
29439 if (this._sourcesContents) {
29440 map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
29441 }
29442
29443 return map;
29444 };
29445
29446/**
29447 * Render the source map being generated to a string.
29448 */
29449SourceMapGenerator.prototype.toString =
29450 function SourceMapGenerator_toString() {
29451 return JSON.stringify(this.toJSON());
29452 };
29453
29454var SourceMapGenerator_1 = SourceMapGenerator;
29455
29456var sourceMapGenerator = {
29457 SourceMapGenerator: SourceMapGenerator_1
29458};
29459
29460var binarySearch = createCommonjsModule(function (module, exports) {
29461/* -*- Mode: js; js-indent-level: 2; -*- */
29462/*
29463 * Copyright 2011 Mozilla Foundation and contributors
29464 * Licensed under the New BSD license. See LICENSE or:
29465 * http://opensource.org/licenses/BSD-3-Clause
29466 */
29467
29468exports.GREATEST_LOWER_BOUND = 1;
29469exports.LEAST_UPPER_BOUND = 2;
29470
29471/**
29472 * Recursive implementation of binary search.
29473 *
29474 * @param aLow Indices here and lower do not contain the needle.
29475 * @param aHigh Indices here and higher do not contain the needle.
29476 * @param aNeedle The element being searched for.
29477 * @param aHaystack The non-empty array being searched.
29478 * @param aCompare Function which takes two elements and returns -1, 0, or 1.
29479 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
29480 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
29481 * closest element that is smaller than or greater than the one we are
29482 * searching for, respectively, if the exact element cannot be found.
29483 */
29484function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) {
29485 // This function terminates when one of the following is true:
29486 //
29487 // 1. We find the exact element we are looking for.
29488 //
29489 // 2. We did not find the exact element, but we can return the index of
29490 // the next-closest element.
29491 //
29492 // 3. We did not find the exact element, and there is no next-closest
29493 // element than the one we are searching for, so we return -1.
29494 var mid = Math.floor((aHigh - aLow) / 2) + aLow;
29495 var cmp = aCompare(aNeedle, aHaystack[mid], true);
29496 if (cmp === 0) {
29497 // Found the element we are looking for.
29498 return mid;
29499 }
29500 else if (cmp > 0) {
29501 // Our needle is greater than aHaystack[mid].
29502 if (aHigh - mid > 1) {
29503 // The element is in the upper half.
29504 return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias);
29505 }
29506
29507 // The exact needle element was not found in this haystack. Determine if
29508 // we are in termination case (3) or (2) and return the appropriate thing.
29509 if (aBias == exports.LEAST_UPPER_BOUND) {
29510 return aHigh < aHaystack.length ? aHigh : -1;
29511 } else {
29512 return mid;
29513 }
29514 }
29515 else {
29516 // Our needle is less than aHaystack[mid].
29517 if (mid - aLow > 1) {
29518 // The element is in the lower half.
29519 return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias);
29520 }
29521
29522 // we are in termination case (3) or (2) and return the appropriate thing.
29523 if (aBias == exports.LEAST_UPPER_BOUND) {
29524 return mid;
29525 } else {
29526 return aLow < 0 ? -1 : aLow;
29527 }
29528 }
29529}
29530
29531/**
29532 * This is an implementation of binary search which will always try and return
29533 * the index of the closest element if there is no exact hit. This is because
29534 * mappings between original and generated line/col pairs are single points,
29535 * and there is an implicit region between each of them, so a miss just means
29536 * that you aren't on the very start of a region.
29537 *
29538 * @param aNeedle The element you are looking for.
29539 * @param aHaystack The array that is being searched.
29540 * @param aCompare A function which takes the needle and an element in the
29541 * array and returns -1, 0, or 1 depending on whether the needle is less
29542 * than, equal to, or greater than the element, respectively.
29543 * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or
29544 * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the
29545 * closest element that is smaller than or greater than the one we are
29546 * searching for, respectively, if the exact element cannot be found.
29547 * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'.
29548 */
29549exports.search = function search(aNeedle, aHaystack, aCompare, aBias) {
29550 if (aHaystack.length === 0) {
29551 return -1;
29552 }
29553
29554 var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack,
29555 aCompare, aBias || exports.GREATEST_LOWER_BOUND);
29556 if (index < 0) {
29557 return -1;
29558 }
29559
29560 // We have found either the exact element, or the next-closest element than
29561 // the one we are searching for. However, there may be more than one such
29562 // element. Make sure we always return the smallest of these.
29563 while (index - 1 >= 0) {
29564 if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) {
29565 break;
29566 }
29567 --index;
29568 }
29569
29570 return index;
29571};
29572});
29573
29574/* -*- Mode: js; js-indent-level: 2; -*- */
29575/*
29576 * Copyright 2011 Mozilla Foundation and contributors
29577 * Licensed under the New BSD license. See LICENSE or:
29578 * http://opensource.org/licenses/BSD-3-Clause
29579 */
29580
29581// It turns out that some (most?) JavaScript engines don't self-host
29582// `Array.prototype.sort`. This makes sense because C++ will likely remain
29583// faster than JS when doing raw CPU-intensive sorting. However, when using a
29584// custom comparator function, calling back and forth between the VM's C++ and
29585// JIT'd JS is rather slow *and* loses JIT type information, resulting in
29586// worse generated code for the comparator function than would be optimal. In
29587// fact, when sorting with a comparator, these costs outweigh the benefits of
29588// sorting in C++. By using our own JS-implemented Quick Sort (below), we get
29589// a ~3500ms mean speed-up in `bench/bench.html`.
29590
29591/**
29592 * Swap the elements indexed by `x` and `y` in the array `ary`.
29593 *
29594 * @param {Array} ary
29595 * The array.
29596 * @param {Number} x
29597 * The index of the first item.
29598 * @param {Number} y
29599 * The index of the second item.
29600 */
29601function swap(ary, x, y) {
29602 var temp = ary[x];
29603 ary[x] = ary[y];
29604 ary[y] = temp;
29605}
29606
29607/**
29608 * Returns a random integer within the range `low .. high` inclusive.
29609 *
29610 * @param {Number} low
29611 * The lower bound on the range.
29612 * @param {Number} high
29613 * The upper bound on the range.
29614 */
29615function randomIntInRange(low, high) {
29616 return Math.round(low + (Math.random() * (high - low)));
29617}
29618
29619/**
29620 * The Quick Sort algorithm.
29621 *
29622 * @param {Array} ary
29623 * An array to sort.
29624 * @param {function} comparator
29625 * Function to use to compare two items.
29626 * @param {Number} p
29627 * Start index of the array
29628 * @param {Number} r
29629 * End index of the array
29630 */
29631function doQuickSort(ary, comparator, p, r) {
29632 // If our lower bound is less than our upper bound, we (1) partition the
29633 // array into two pieces and (2) recurse on each half. If it is not, this is
29634 // the empty array and our base case.
29635
29636 if (p < r) {
29637 // (1) Partitioning.
29638 //
29639 // The partitioning chooses a pivot between `p` and `r` and moves all
29640 // elements that are less than or equal to the pivot to the before it, and
29641 // all the elements that are greater than it after it. The effect is that
29642 // once partition is done, the pivot is in the exact place it will be when
29643 // the array is put in sorted order, and it will not need to be moved
29644 // again. This runs in O(n) time.
29645
29646 // Always choose a random pivot so that an input array which is reverse
29647 // sorted does not cause O(n^2) running time.
29648 var pivotIndex = randomIntInRange(p, r);
29649 var i = p - 1;
29650
29651 swap(ary, pivotIndex, r);
29652 var pivot = ary[r];
29653
29654 // Immediately after `j` is incremented in this loop, the following hold
29655 // true:
29656 //
29657 // * Every element in `ary[p .. i]` is less than or equal to the pivot.
29658 //
29659 // * Every element in `ary[i+1 .. j-1]` is greater than the pivot.
29660 for (var j = p; j < r; j++) {
29661 if (comparator(ary[j], pivot) <= 0) {
29662 i += 1;
29663 swap(ary, i, j);
29664 }
29665 }
29666
29667 swap(ary, i + 1, j);
29668 var q = i + 1;
29669
29670 // (2) Recurse on each half.
29671
29672 doQuickSort(ary, comparator, p, q - 1);
29673 doQuickSort(ary, comparator, q + 1, r);
29674 }
29675}
29676
29677/**
29678 * Sort the given array in-place with the given comparator function.
29679 *
29680 * @param {Array} ary
29681 * An array to sort.
29682 * @param {function} comparator
29683 * Function to use to compare two items.
29684 */
29685var quickSort_1 = function (ary, comparator) {
29686 doQuickSort(ary, comparator, 0, ary.length - 1);
29687};
29688
29689var quickSort = {
29690 quickSort: quickSort_1
29691};
29692
29693/* -*- Mode: js; js-indent-level: 2; -*- */
29694/*
29695 * Copyright 2011 Mozilla Foundation and contributors
29696 * Licensed under the New BSD license. See LICENSE or:
29697 * http://opensource.org/licenses/BSD-3-Clause
29698 */
29699
29700
29701
29702var ArraySet$2 = arraySet.ArraySet;
29703
29704var quickSort$1 = quickSort.quickSort;
29705
29706function SourceMapConsumer(aSourceMap) {
29707 var sourceMap = aSourceMap;
29708 if (typeof aSourceMap === 'string') {
29709 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
29710 }
29711
29712 return sourceMap.sections != null
29713 ? new IndexedSourceMapConsumer(sourceMap)
29714 : new BasicSourceMapConsumer(sourceMap);
29715}
29716
29717SourceMapConsumer.fromSourceMap = function(aSourceMap) {
29718 return BasicSourceMapConsumer.fromSourceMap(aSourceMap);
29719};
29720
29721/**
29722 * The version of the source mapping spec that we are consuming.
29723 */
29724SourceMapConsumer.prototype._version = 3;
29725
29726// `__generatedMappings` and `__originalMappings` are arrays that hold the
29727// parsed mapping coordinates from the source map's "mappings" attribute. They
29728// are lazily instantiated, accessed via the `_generatedMappings` and
29729// `_originalMappings` getters respectively, and we only parse the mappings
29730// and create these arrays once queried for a source location. We jump through
29731// these hoops because there can be many thousands of mappings, and parsing
29732// them is expensive, so we only want to do it if we must.
29733//
29734// Each object in the arrays is of the form:
29735//
29736// {
29737// generatedLine: The line number in the generated code,
29738// generatedColumn: The column number in the generated code,
29739// source: The path to the original source file that generated this
29740// chunk of code,
29741// originalLine: The line number in the original source that
29742// corresponds to this chunk of generated code,
29743// originalColumn: The column number in the original source that
29744// corresponds to this chunk of generated code,
29745// name: The name of the original symbol which generated this chunk of
29746// code.
29747// }
29748//
29749// All properties except for `generatedLine` and `generatedColumn` can be
29750// `null`.
29751//
29752// `_generatedMappings` is ordered by the generated positions.
29753//
29754// `_originalMappings` is ordered by the original positions.
29755
29756SourceMapConsumer.prototype.__generatedMappings = null;
29757Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
29758 get: function () {
29759 if (!this.__generatedMappings) {
29760 this._parseMappings(this._mappings, this.sourceRoot);
29761 }
29762
29763 return this.__generatedMappings;
29764 }
29765});
29766
29767SourceMapConsumer.prototype.__originalMappings = null;
29768Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
29769 get: function () {
29770 if (!this.__originalMappings) {
29771 this._parseMappings(this._mappings, this.sourceRoot);
29772 }
29773
29774 return this.__originalMappings;
29775 }
29776});
29777
29778SourceMapConsumer.prototype._charIsMappingSeparator =
29779 function SourceMapConsumer_charIsMappingSeparator(aStr, index) {
29780 var c = aStr.charAt(index);
29781 return c === ";" || c === ",";
29782 };
29783
29784/**
29785 * Parse the mappings in a string in to a data structure which we can easily
29786 * query (the ordered arrays in the `this.__generatedMappings` and
29787 * `this.__originalMappings` properties).
29788 */
29789SourceMapConsumer.prototype._parseMappings =
29790 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
29791 throw new Error("Subclasses must implement _parseMappings");
29792 };
29793
29794SourceMapConsumer.GENERATED_ORDER = 1;
29795SourceMapConsumer.ORIGINAL_ORDER = 2;
29796
29797SourceMapConsumer.GREATEST_LOWER_BOUND = 1;
29798SourceMapConsumer.LEAST_UPPER_BOUND = 2;
29799
29800/**
29801 * Iterate over each mapping between an original source/line/column and a
29802 * generated line/column in this source map.
29803 *
29804 * @param Function aCallback
29805 * The function that is called with each mapping.
29806 * @param Object aContext
29807 * Optional. If specified, this object will be the value of `this` every
29808 * time that `aCallback` is called.
29809 * @param aOrder
29810 * Either `SourceMapConsumer.GENERATED_ORDER` or
29811 * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
29812 * iterate over the mappings sorted by the generated file's line/column
29813 * order or the original's source/line/column order, respectively. Defaults to
29814 * `SourceMapConsumer.GENERATED_ORDER`.
29815 */
29816SourceMapConsumer.prototype.eachMapping =
29817 function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
29818 var context = aContext || null;
29819 var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
29820
29821 var mappings;
29822 switch (order) {
29823 case SourceMapConsumer.GENERATED_ORDER:
29824 mappings = this._generatedMappings;
29825 break;
29826 case SourceMapConsumer.ORIGINAL_ORDER:
29827 mappings = this._originalMappings;
29828 break;
29829 default:
29830 throw new Error("Unknown order of iteration.");
29831 }
29832
29833 var sourceRoot = this.sourceRoot;
29834 mappings.map(function (mapping) {
29835 var source = mapping.source === null ? null : this._sources.at(mapping.source);
29836 if (source != null && sourceRoot != null) {
29837 source = util$1.join(sourceRoot, source);
29838 }
29839 return {
29840 source: source,
29841 generatedLine: mapping.generatedLine,
29842 generatedColumn: mapping.generatedColumn,
29843 originalLine: mapping.originalLine,
29844 originalColumn: mapping.originalColumn,
29845 name: mapping.name === null ? null : this._names.at(mapping.name)
29846 };
29847 }, this).forEach(aCallback, context);
29848 };
29849
29850/**
29851 * Returns all generated line and column information for the original source,
29852 * line, and column provided. If no column is provided, returns all mappings
29853 * corresponding to a either the line we are searching for or the next
29854 * closest line that has any mappings. Otherwise, returns all mappings
29855 * corresponding to the given line and either the column we are searching for
29856 * or the next closest column that has any offsets.
29857 *
29858 * The only argument is an object with the following properties:
29859 *
29860 * - source: The filename of the original source.
29861 * - line: The line number in the original source.
29862 * - column: Optional. the column number in the original source.
29863 *
29864 * and an array of objects is returned, each with the following properties:
29865 *
29866 * - line: The line number in the generated source, or null.
29867 * - column: The column number in the generated source, or null.
29868 */
29869SourceMapConsumer.prototype.allGeneratedPositionsFor =
29870 function SourceMapConsumer_allGeneratedPositionsFor(aArgs) {
29871 var line = util$1.getArg(aArgs, 'line');
29872
29873 // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
29874 // returns the index of the closest mapping less than the needle. By
29875 // setting needle.originalColumn to 0, we thus find the last mapping for
29876 // the given line, provided such a mapping exists.
29877 var needle = {
29878 source: util$1.getArg(aArgs, 'source'),
29879 originalLine: line,
29880 originalColumn: util$1.getArg(aArgs, 'column', 0)
29881 };
29882
29883 if (this.sourceRoot != null) {
29884 needle.source = util$1.relative(this.sourceRoot, needle.source);
29885 }
29886 if (!this._sources.has(needle.source)) {
29887 return [];
29888 }
29889 needle.source = this._sources.indexOf(needle.source);
29890
29891 var mappings = [];
29892
29893 var index = this._findMapping(needle,
29894 this._originalMappings,
29895 "originalLine",
29896 "originalColumn",
29897 util$1.compareByOriginalPositions,
29898 binarySearch.LEAST_UPPER_BOUND);
29899 if (index >= 0) {
29900 var mapping = this._originalMappings[index];
29901
29902 if (aArgs.column === undefined) {
29903 var originalLine = mapping.originalLine;
29904
29905 // Iterate until either we run out of mappings, or we run into
29906 // a mapping for a different line than the one we found. Since
29907 // mappings are sorted, this is guaranteed to find all mappings for
29908 // the line we found.
29909 while (mapping && mapping.originalLine === originalLine) {
29910 mappings.push({
29911 line: util$1.getArg(mapping, 'generatedLine', null),
29912 column: util$1.getArg(mapping, 'generatedColumn', null),
29913 lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
29914 });
29915
29916 mapping = this._originalMappings[++index];
29917 }
29918 } else {
29919 var originalColumn = mapping.originalColumn;
29920
29921 // Iterate until either we run out of mappings, or we run into
29922 // a mapping for a different line than the one we were searching for.
29923 // Since mappings are sorted, this is guaranteed to find all mappings for
29924 // the line we are searching for.
29925 while (mapping &&
29926 mapping.originalLine === line &&
29927 mapping.originalColumn == originalColumn) {
29928 mappings.push({
29929 line: util$1.getArg(mapping, 'generatedLine', null),
29930 column: util$1.getArg(mapping, 'generatedColumn', null),
29931 lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
29932 });
29933
29934 mapping = this._originalMappings[++index];
29935 }
29936 }
29937 }
29938
29939 return mappings;
29940 };
29941
29942var SourceMapConsumer_1 = SourceMapConsumer;
29943
29944/**
29945 * A BasicSourceMapConsumer instance represents a parsed source map which we can
29946 * query for information about the original file positions by giving it a file
29947 * position in the generated source.
29948 *
29949 * The only parameter is the raw source map (either as a JSON string, or
29950 * already parsed to an object). According to the spec, source maps have the
29951 * following attributes:
29952 *
29953 * - version: Which version of the source map spec this map is following.
29954 * - sources: An array of URLs to the original source files.
29955 * - names: An array of identifiers which can be referrenced by individual mappings.
29956 * - sourceRoot: Optional. The URL root from which all sources are relative.
29957 * - sourcesContent: Optional. An array of contents of the original source files.
29958 * - mappings: A string of base64 VLQs which contain the actual mappings.
29959 * - file: Optional. The generated file this source map is associated with.
29960 *
29961 * Here is an example source map, taken from the source map spec[0]:
29962 *
29963 * {
29964 * version : 3,
29965 * file: "out.js",
29966 * sourceRoot : "",
29967 * sources: ["foo.js", "bar.js"],
29968 * names: ["src", "maps", "are", "fun"],
29969 * mappings: "AA,AB;;ABCDE;"
29970 * }
29971 *
29972 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
29973 */
29974function BasicSourceMapConsumer(aSourceMap) {
29975 var sourceMap = aSourceMap;
29976 if (typeof aSourceMap === 'string') {
29977 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
29978 }
29979
29980 var version = util$1.getArg(sourceMap, 'version');
29981 var sources = util$1.getArg(sourceMap, 'sources');
29982 // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
29983 // requires the array) to play nice here.
29984 var names = util$1.getArg(sourceMap, 'names', []);
29985 var sourceRoot = util$1.getArg(sourceMap, 'sourceRoot', null);
29986 var sourcesContent = util$1.getArg(sourceMap, 'sourcesContent', null);
29987 var mappings = util$1.getArg(sourceMap, 'mappings');
29988 var file = util$1.getArg(sourceMap, 'file', null);
29989
29990 // Once again, Sass deviates from the spec and supplies the version as a
29991 // string rather than a number, so we use loose equality checking here.
29992 if (version != this._version) {
29993 throw new Error('Unsupported version: ' + version);
29994 }
29995
29996 sources = sources
29997 .map(String)
29998 // Some source maps produce relative source paths like "./foo.js" instead of
29999 // "foo.js". Normalize these first so that future comparisons will succeed.
30000 // See bugzil.la/1090768.
30001 .map(util$1.normalize)
30002 // Always ensure that absolute sources are internally stored relative to
30003 // the source root, if the source root is absolute. Not doing this would
30004 // be particularly problematic when the source root is a prefix of the
30005 // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
30006 .map(function (source) {
30007 return sourceRoot && util$1.isAbsolute(sourceRoot) && util$1.isAbsolute(source)
30008 ? util$1.relative(sourceRoot, source)
30009 : source;
30010 });
30011
30012 // Pass `true` below to allow duplicate names and sources. While source maps
30013 // are intended to be compressed and deduplicated, the TypeScript compiler
30014 // sometimes generates source maps with duplicates in them. See Github issue
30015 // #72 and bugzil.la/889492.
30016 this._names = ArraySet$2.fromArray(names.map(String), true);
30017 this._sources = ArraySet$2.fromArray(sources, true);
30018
30019 this.sourceRoot = sourceRoot;
30020 this.sourcesContent = sourcesContent;
30021 this._mappings = mappings;
30022 this.file = file;
30023}
30024
30025BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
30026BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer;
30027
30028/**
30029 * Create a BasicSourceMapConsumer from a SourceMapGenerator.
30030 *
30031 * @param SourceMapGenerator aSourceMap
30032 * The source map that will be consumed.
30033 * @returns BasicSourceMapConsumer
30034 */
30035BasicSourceMapConsumer.fromSourceMap =
30036 function SourceMapConsumer_fromSourceMap(aSourceMap) {
30037 var smc = Object.create(BasicSourceMapConsumer.prototype);
30038
30039 var names = smc._names = ArraySet$2.fromArray(aSourceMap._names.toArray(), true);
30040 var sources = smc._sources = ArraySet$2.fromArray(aSourceMap._sources.toArray(), true);
30041 smc.sourceRoot = aSourceMap._sourceRoot;
30042 smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
30043 smc.sourceRoot);
30044 smc.file = aSourceMap._file;
30045
30046 // Because we are modifying the entries (by converting string sources and
30047 // names to indices into the sources and names ArraySets), we have to make
30048 // a copy of the entry or else bad things happen. Shared mutable state
30049 // strikes again! See github issue #191.
30050
30051 var generatedMappings = aSourceMap._mappings.toArray().slice();
30052 var destGeneratedMappings = smc.__generatedMappings = [];
30053 var destOriginalMappings = smc.__originalMappings = [];
30054
30055 for (var i = 0, length = generatedMappings.length; i < length; i++) {
30056 var srcMapping = generatedMappings[i];
30057 var destMapping = new Mapping;
30058 destMapping.generatedLine = srcMapping.generatedLine;
30059 destMapping.generatedColumn = srcMapping.generatedColumn;
30060
30061 if (srcMapping.source) {
30062 destMapping.source = sources.indexOf(srcMapping.source);
30063 destMapping.originalLine = srcMapping.originalLine;
30064 destMapping.originalColumn = srcMapping.originalColumn;
30065
30066 if (srcMapping.name) {
30067 destMapping.name = names.indexOf(srcMapping.name);
30068 }
30069
30070 destOriginalMappings.push(destMapping);
30071 }
30072
30073 destGeneratedMappings.push(destMapping);
30074 }
30075
30076 quickSort$1(smc.__originalMappings, util$1.compareByOriginalPositions);
30077
30078 return smc;
30079 };
30080
30081/**
30082 * The version of the source mapping spec that we are consuming.
30083 */
30084BasicSourceMapConsumer.prototype._version = 3;
30085
30086/**
30087 * The list of original sources.
30088 */
30089Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', {
30090 get: function () {
30091 return this._sources.toArray().map(function (s) {
30092 return this.sourceRoot != null ? util$1.join(this.sourceRoot, s) : s;
30093 }, this);
30094 }
30095});
30096
30097/**
30098 * Provide the JIT with a nice shape / hidden class.
30099 */
30100function Mapping() {
30101 this.generatedLine = 0;
30102 this.generatedColumn = 0;
30103 this.source = null;
30104 this.originalLine = null;
30105 this.originalColumn = null;
30106 this.name = null;
30107}
30108
30109/**
30110 * Parse the mappings in a string in to a data structure which we can easily
30111 * query (the ordered arrays in the `this.__generatedMappings` and
30112 * `this.__originalMappings` properties).
30113 */
30114BasicSourceMapConsumer.prototype._parseMappings =
30115 function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
30116 var generatedLine = 1;
30117 var previousGeneratedColumn = 0;
30118 var previousOriginalLine = 0;
30119 var previousOriginalColumn = 0;
30120 var previousSource = 0;
30121 var previousName = 0;
30122 var length = aStr.length;
30123 var index = 0;
30124 var cachedSegments = {};
30125 var temp = {};
30126 var originalMappings = [];
30127 var generatedMappings = [];
30128 var mapping, str, segment, end, value;
30129
30130 while (index < length) {
30131 if (aStr.charAt(index) === ';') {
30132 generatedLine++;
30133 index++;
30134 previousGeneratedColumn = 0;
30135 }
30136 else if (aStr.charAt(index) === ',') {
30137 index++;
30138 }
30139 else {
30140 mapping = new Mapping();
30141 mapping.generatedLine = generatedLine;
30142
30143 // Because each offset is encoded relative to the previous one,
30144 // many segments often have the same encoding. We can exploit this
30145 // fact by caching the parsed variable length fields of each segment,
30146 // allowing us to avoid a second parse if we encounter the same
30147 // segment again.
30148 for (end = index; end < length; end++) {
30149 if (this._charIsMappingSeparator(aStr, end)) {
30150 break;
30151 }
30152 }
30153 str = aStr.slice(index, end);
30154
30155 segment = cachedSegments[str];
30156 if (segment) {
30157 index += str.length;
30158 } else {
30159 segment = [];
30160 while (index < end) {
30161 base64Vlq.decode(aStr, index, temp);
30162 value = temp.value;
30163 index = temp.rest;
30164 segment.push(value);
30165 }
30166
30167 if (segment.length === 2) {
30168 throw new Error('Found a source, but no line and column');
30169 }
30170
30171 if (segment.length === 3) {
30172 throw new Error('Found a source and line, but no column');
30173 }
30174
30175 cachedSegments[str] = segment;
30176 }
30177
30178 // Generated column.
30179 mapping.generatedColumn = previousGeneratedColumn + segment[0];
30180 previousGeneratedColumn = mapping.generatedColumn;
30181
30182 if (segment.length > 1) {
30183 // Original source.
30184 mapping.source = previousSource + segment[1];
30185 previousSource += segment[1];
30186
30187 // Original line.
30188 mapping.originalLine = previousOriginalLine + segment[2];
30189 previousOriginalLine = mapping.originalLine;
30190 // Lines are stored 0-based
30191 mapping.originalLine += 1;
30192
30193 // Original column.
30194 mapping.originalColumn = previousOriginalColumn + segment[3];
30195 previousOriginalColumn = mapping.originalColumn;
30196
30197 if (segment.length > 4) {
30198 // Original name.
30199 mapping.name = previousName + segment[4];
30200 previousName += segment[4];
30201 }
30202 }
30203
30204 generatedMappings.push(mapping);
30205 if (typeof mapping.originalLine === 'number') {
30206 originalMappings.push(mapping);
30207 }
30208 }
30209 }
30210
30211 quickSort$1(generatedMappings, util$1.compareByGeneratedPositionsDeflated);
30212 this.__generatedMappings = generatedMappings;
30213
30214 quickSort$1(originalMappings, util$1.compareByOriginalPositions);
30215 this.__originalMappings = originalMappings;
30216 };
30217
30218/**
30219 * Find the mapping that best matches the hypothetical "needle" mapping that
30220 * we are searching for in the given "haystack" of mappings.
30221 */
30222BasicSourceMapConsumer.prototype._findMapping =
30223 function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
30224 aColumnName, aComparator, aBias) {
30225 // To return the position we are searching for, we must first find the
30226 // mapping for the given position and then return the opposite position it
30227 // points to. Because the mappings are sorted, we can use binary search to
30228 // find the best mapping.
30229
30230 if (aNeedle[aLineName] <= 0) {
30231 throw new TypeError('Line must be greater than or equal to 1, got '
30232 + aNeedle[aLineName]);
30233 }
30234 if (aNeedle[aColumnName] < 0) {
30235 throw new TypeError('Column must be greater than or equal to 0, got '
30236 + aNeedle[aColumnName]);
30237 }
30238
30239 return binarySearch.search(aNeedle, aMappings, aComparator, aBias);
30240 };
30241
30242/**
30243 * Compute the last column for each generated mapping. The last column is
30244 * inclusive.
30245 */
30246BasicSourceMapConsumer.prototype.computeColumnSpans =
30247 function SourceMapConsumer_computeColumnSpans() {
30248 for (var index = 0; index < this._generatedMappings.length; ++index) {
30249 var mapping = this._generatedMappings[index];
30250
30251 // Mappings do not contain a field for the last generated columnt. We
30252 // can come up with an optimistic estimate, however, by assuming that
30253 // mappings are contiguous (i.e. given two consecutive mappings, the
30254 // first mapping ends where the second one starts).
30255 if (index + 1 < this._generatedMappings.length) {
30256 var nextMapping = this._generatedMappings[index + 1];
30257
30258 if (mapping.generatedLine === nextMapping.generatedLine) {
30259 mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1;
30260 continue;
30261 }
30262 }
30263
30264 // The last mapping for each line spans the entire line.
30265 mapping.lastGeneratedColumn = Infinity;
30266 }
30267 };
30268
30269/**
30270 * Returns the original source, line, and column information for the generated
30271 * source's line and column positions provided. The only argument is an object
30272 * with the following properties:
30273 *
30274 * - line: The line number in the generated source.
30275 * - column: The column number in the generated source.
30276 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
30277 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
30278 * closest element that is smaller than or greater than the one we are
30279 * searching for, respectively, if the exact element cannot be found.
30280 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
30281 *
30282 * and an object is returned with the following properties:
30283 *
30284 * - source: The original source file, or null.
30285 * - line: The line number in the original source, or null.
30286 * - column: The column number in the original source, or null.
30287 * - name: The original identifier, or null.
30288 */
30289BasicSourceMapConsumer.prototype.originalPositionFor =
30290 function SourceMapConsumer_originalPositionFor(aArgs) {
30291 var needle = {
30292 generatedLine: util$1.getArg(aArgs, 'line'),
30293 generatedColumn: util$1.getArg(aArgs, 'column')
30294 };
30295
30296 var index = this._findMapping(
30297 needle,
30298 this._generatedMappings,
30299 "generatedLine",
30300 "generatedColumn",
30301 util$1.compareByGeneratedPositionsDeflated,
30302 util$1.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
30303 );
30304
30305 if (index >= 0) {
30306 var mapping = this._generatedMappings[index];
30307
30308 if (mapping.generatedLine === needle.generatedLine) {
30309 var source = util$1.getArg(mapping, 'source', null);
30310 if (source !== null) {
30311 source = this._sources.at(source);
30312 if (this.sourceRoot != null) {
30313 source = util$1.join(this.sourceRoot, source);
30314 }
30315 }
30316 var name = util$1.getArg(mapping, 'name', null);
30317 if (name !== null) {
30318 name = this._names.at(name);
30319 }
30320 return {
30321 source: source,
30322 line: util$1.getArg(mapping, 'originalLine', null),
30323 column: util$1.getArg(mapping, 'originalColumn', null),
30324 name: name
30325 };
30326 }
30327 }
30328
30329 return {
30330 source: null,
30331 line: null,
30332 column: null,
30333 name: null
30334 };
30335 };
30336
30337/**
30338 * Return true if we have the source content for every source in the source
30339 * map, false otherwise.
30340 */
30341BasicSourceMapConsumer.prototype.hasContentsOfAllSources =
30342 function BasicSourceMapConsumer_hasContentsOfAllSources() {
30343 if (!this.sourcesContent) {
30344 return false;
30345 }
30346 return this.sourcesContent.length >= this._sources.size() &&
30347 !this.sourcesContent.some(function (sc) { return sc == null; });
30348 };
30349
30350/**
30351 * Returns the original source content. The only argument is the url of the
30352 * original source file. Returns null if no original source content is
30353 * available.
30354 */
30355BasicSourceMapConsumer.prototype.sourceContentFor =
30356 function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
30357 if (!this.sourcesContent) {
30358 return null;
30359 }
30360
30361 if (this.sourceRoot != null) {
30362 aSource = util$1.relative(this.sourceRoot, aSource);
30363 }
30364
30365 if (this._sources.has(aSource)) {
30366 return this.sourcesContent[this._sources.indexOf(aSource)];
30367 }
30368
30369 var url;
30370 if (this.sourceRoot != null
30371 && (url = util$1.urlParse(this.sourceRoot))) {
30372 // XXX: file:// URIs and absolute paths lead to unexpected behavior for
30373 // many users. We can help them out when they expect file:// URIs to
30374 // behave like it would if they were running a local HTTP server. See
30375 // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
30376 var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
30377 if (url.scheme == "file"
30378 && this._sources.has(fileUriAbsPath)) {
30379 return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
30380 }
30381
30382 if ((!url.path || url.path == "/")
30383 && this._sources.has("/" + aSource)) {
30384 return this.sourcesContent[this._sources.indexOf("/" + aSource)];
30385 }
30386 }
30387
30388 // This function is used recursively from
30389 // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
30390 // don't want to throw if we can't find the source - we just want to
30391 // return null, so we provide a flag to exit gracefully.
30392 if (nullOnMissing) {
30393 return null;
30394 }
30395 else {
30396 throw new Error('"' + aSource + '" is not in the SourceMap.');
30397 }
30398 };
30399
30400/**
30401 * Returns the generated line and column information for the original source,
30402 * line, and column positions provided. The only argument is an object with
30403 * the following properties:
30404 *
30405 * - source: The filename of the original source.
30406 * - line: The line number in the original source.
30407 * - column: The column number in the original source.
30408 * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
30409 * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
30410 * closest element that is smaller than or greater than the one we are
30411 * searching for, respectively, if the exact element cannot be found.
30412 * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
30413 *
30414 * and an object is returned with the following properties:
30415 *
30416 * - line: The line number in the generated source, or null.
30417 * - column: The column number in the generated source, or null.
30418 */
30419BasicSourceMapConsumer.prototype.generatedPositionFor =
30420 function SourceMapConsumer_generatedPositionFor(aArgs) {
30421 var source = util$1.getArg(aArgs, 'source');
30422 if (this.sourceRoot != null) {
30423 source = util$1.relative(this.sourceRoot, source);
30424 }
30425 if (!this._sources.has(source)) {
30426 return {
30427 line: null,
30428 column: null,
30429 lastColumn: null
30430 };
30431 }
30432 source = this._sources.indexOf(source);
30433
30434 var needle = {
30435 source: source,
30436 originalLine: util$1.getArg(aArgs, 'line'),
30437 originalColumn: util$1.getArg(aArgs, 'column')
30438 };
30439
30440 var index = this._findMapping(
30441 needle,
30442 this._originalMappings,
30443 "originalLine",
30444 "originalColumn",
30445 util$1.compareByOriginalPositions,
30446 util$1.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND)
30447 );
30448
30449 if (index >= 0) {
30450 var mapping = this._originalMappings[index];
30451
30452 if (mapping.source === needle.source) {
30453 return {
30454 line: util$1.getArg(mapping, 'generatedLine', null),
30455 column: util$1.getArg(mapping, 'generatedColumn', null),
30456 lastColumn: util$1.getArg(mapping, 'lastGeneratedColumn', null)
30457 };
30458 }
30459 }
30460
30461 return {
30462 line: null,
30463 column: null,
30464 lastColumn: null
30465 };
30466 };
30467
30468var BasicSourceMapConsumer_1 = BasicSourceMapConsumer;
30469
30470/**
30471 * An IndexedSourceMapConsumer instance represents a parsed source map which
30472 * we can query for information. It differs from BasicSourceMapConsumer in
30473 * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
30474 * input.
30475 *
30476 * The only parameter is a raw source map (either as a JSON string, or already
30477 * parsed to an object). According to the spec for indexed source maps, they
30478 * have the following attributes:
30479 *
30480 * - version: Which version of the source map spec this map is following.
30481 * - file: Optional. The generated file this source map is associated with.
30482 * - sections: A list of section definitions.
30483 *
30484 * Each value under the "sections" field has two fields:
30485 * - offset: The offset into the original specified at which this section
30486 * begins to apply, defined as an object with a "line" and "column"
30487 * field.
30488 * - map: A source map definition. This source map could also be indexed,
30489 * but doesn't have to be.
30490 *
30491 * Instead of the "map" field, it's also possible to have a "url" field
30492 * specifying a URL to retrieve a source map from, but that's currently
30493 * unsupported.
30494 *
30495 * Here's an example source map, taken from the source map spec[0], but
30496 * modified to omit a section which uses the "url" field.
30497 *
30498 * {
30499 * version : 3,
30500 * file: "app.js",
30501 * sections: [{
30502 * offset: {line:100, column:10},
30503 * map: {
30504 * version : 3,
30505 * file: "section.js",
30506 * sources: ["foo.js", "bar.js"],
30507 * names: ["src", "maps", "are", "fun"],
30508 * mappings: "AAAA,E;;ABCDE;"
30509 * }
30510 * }],
30511 * }
30512 *
30513 * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
30514 */
30515function IndexedSourceMapConsumer(aSourceMap) {
30516 var sourceMap = aSourceMap;
30517 if (typeof aSourceMap === 'string') {
30518 sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
30519 }
30520
30521 var version = util$1.getArg(sourceMap, 'version');
30522 var sections = util$1.getArg(sourceMap, 'sections');
30523
30524 if (version != this._version) {
30525 throw new Error('Unsupported version: ' + version);
30526 }
30527
30528 this._sources = new ArraySet$2();
30529 this._names = new ArraySet$2();
30530
30531 var lastOffset = {
30532 line: -1,
30533 column: 0
30534 };
30535 this._sections = sections.map(function (s) {
30536 if (s.url) {
30537 // The url field will require support for asynchronicity.
30538 // See https://github.com/mozilla/source-map/issues/16
30539 throw new Error('Support for url field in sections not implemented.');
30540 }
30541 var offset = util$1.getArg(s, 'offset');
30542 var offsetLine = util$1.getArg(offset, 'line');
30543 var offsetColumn = util$1.getArg(offset, 'column');
30544
30545 if (offsetLine < lastOffset.line ||
30546 (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) {
30547 throw new Error('Section offsets must be ordered and non-overlapping.');
30548 }
30549 lastOffset = offset;
30550
30551 return {
30552 generatedOffset: {
30553 // The offset fields are 0-based, but we use 1-based indices when
30554 // encoding/decoding from VLQ.
30555 generatedLine: offsetLine + 1,
30556 generatedColumn: offsetColumn + 1
30557 },
30558 consumer: new SourceMapConsumer(util$1.getArg(s, 'map'))
30559 }
30560 });
30561}
30562
30563IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype);
30564IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer;
30565
30566/**
30567 * The version of the source mapping spec that we are consuming.
30568 */
30569IndexedSourceMapConsumer.prototype._version = 3;
30570
30571/**
30572 * The list of original sources.
30573 */
30574Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', {
30575 get: function () {
30576 var sources = [];
30577 for (var i = 0; i < this._sections.length; i++) {
30578 for (var j = 0; j < this._sections[i].consumer.sources.length; j++) {
30579 sources.push(this._sections[i].consumer.sources[j]);
30580 }
30581 }
30582 return sources;
30583 }
30584});
30585
30586/**
30587 * Returns the original source, line, and column information for the generated
30588 * source's line and column positions provided. The only argument is an object
30589 * with the following properties:
30590 *
30591 * - line: The line number in the generated source.
30592 * - column: The column number in the generated source.
30593 *
30594 * and an object is returned with the following properties:
30595 *
30596 * - source: The original source file, or null.
30597 * - line: The line number in the original source, or null.
30598 * - column: The column number in the original source, or null.
30599 * - name: The original identifier, or null.
30600 */
30601IndexedSourceMapConsumer.prototype.originalPositionFor =
30602 function IndexedSourceMapConsumer_originalPositionFor(aArgs) {
30603 var needle = {
30604 generatedLine: util$1.getArg(aArgs, 'line'),
30605 generatedColumn: util$1.getArg(aArgs, 'column')
30606 };
30607
30608 // Find the section containing the generated position we're trying to map
30609 // to an original position.
30610 var sectionIndex = binarySearch.search(needle, this._sections,
30611 function(needle, section) {
30612 var cmp = needle.generatedLine - section.generatedOffset.generatedLine;
30613 if (cmp) {
30614 return cmp;
30615 }
30616
30617 return (needle.generatedColumn -
30618 section.generatedOffset.generatedColumn);
30619 });
30620 var section = this._sections[sectionIndex];
30621
30622 if (!section) {
30623 return {
30624 source: null,
30625 line: null,
30626 column: null,
30627 name: null
30628 };
30629 }
30630
30631 return section.consumer.originalPositionFor({
30632 line: needle.generatedLine -
30633 (section.generatedOffset.generatedLine - 1),
30634 column: needle.generatedColumn -
30635 (section.generatedOffset.generatedLine === needle.generatedLine
30636 ? section.generatedOffset.generatedColumn - 1
30637 : 0),
30638 bias: aArgs.bias
30639 });
30640 };
30641
30642/**
30643 * Return true if we have the source content for every source in the source
30644 * map, false otherwise.
30645 */
30646IndexedSourceMapConsumer.prototype.hasContentsOfAllSources =
30647 function IndexedSourceMapConsumer_hasContentsOfAllSources() {
30648 return this._sections.every(function (s) {
30649 return s.consumer.hasContentsOfAllSources();
30650 });
30651 };
30652
30653/**
30654 * Returns the original source content. The only argument is the url of the
30655 * original source file. Returns null if no original source content is
30656 * available.
30657 */
30658IndexedSourceMapConsumer.prototype.sourceContentFor =
30659 function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) {
30660 for (var i = 0; i < this._sections.length; i++) {
30661 var section = this._sections[i];
30662
30663 var content = section.consumer.sourceContentFor(aSource, true);
30664 if (content) {
30665 return content;
30666 }
30667 }
30668 if (nullOnMissing) {
30669 return null;
30670 }
30671 else {
30672 throw new Error('"' + aSource + '" is not in the SourceMap.');
30673 }
30674 };
30675
30676/**
30677 * Returns the generated line and column information for the original source,
30678 * line, and column positions provided. The only argument is an object with
30679 * the following properties:
30680 *
30681 * - source: The filename of the original source.
30682 * - line: The line number in the original source.
30683 * - column: The column number in the original source.
30684 *
30685 * and an object is returned with the following properties:
30686 *
30687 * - line: The line number in the generated source, or null.
30688 * - column: The column number in the generated source, or null.
30689 */
30690IndexedSourceMapConsumer.prototype.generatedPositionFor =
30691 function IndexedSourceMapConsumer_generatedPositionFor(aArgs) {
30692 for (var i = 0; i < this._sections.length; i++) {
30693 var section = this._sections[i];
30694
30695 // Only consider this section if the requested source is in the list of
30696 // sources of the consumer.
30697 if (section.consumer.sources.indexOf(util$1.getArg(aArgs, 'source')) === -1) {
30698 continue;
30699 }
30700 var generatedPosition = section.consumer.generatedPositionFor(aArgs);
30701 if (generatedPosition) {
30702 var ret = {
30703 line: generatedPosition.line +
30704 (section.generatedOffset.generatedLine - 1),
30705 column: generatedPosition.column +
30706 (section.generatedOffset.generatedLine === generatedPosition.line
30707 ? section.generatedOffset.generatedColumn - 1
30708 : 0)
30709 };
30710 return ret;
30711 }
30712 }
30713
30714 return {
30715 line: null,
30716 column: null
30717 };
30718 };
30719
30720/**
30721 * Parse the mappings in a string in to a data structure which we can easily
30722 * query (the ordered arrays in the `this.__generatedMappings` and
30723 * `this.__originalMappings` properties).
30724 */
30725IndexedSourceMapConsumer.prototype._parseMappings =
30726 function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) {
30727 this.__generatedMappings = [];
30728 this.__originalMappings = [];
30729 for (var i = 0; i < this._sections.length; i++) {
30730 var section = this._sections[i];
30731 var sectionMappings = section.consumer._generatedMappings;
30732 for (var j = 0; j < sectionMappings.length; j++) {
30733 var mapping = sectionMappings[j];
30734
30735 var source = section.consumer._sources.at(mapping.source);
30736 if (section.consumer.sourceRoot !== null) {
30737 source = util$1.join(section.consumer.sourceRoot, source);
30738 }
30739 this._sources.add(source);
30740 source = this._sources.indexOf(source);
30741
30742 var name = section.consumer._names.at(mapping.name);
30743 this._names.add(name);
30744 name = this._names.indexOf(name);
30745
30746 // The mappings coming from the consumer for the section have
30747 // generated positions relative to the start of the section, so we
30748 // need to offset them to be relative to the start of the concatenated
30749 // generated file.
30750 var adjustedMapping = {
30751 source: source,
30752 generatedLine: mapping.generatedLine +
30753 (section.generatedOffset.generatedLine - 1),
30754 generatedColumn: mapping.generatedColumn +
30755 (section.generatedOffset.generatedLine === mapping.generatedLine
30756 ? section.generatedOffset.generatedColumn - 1
30757 : 0),
30758 originalLine: mapping.originalLine,
30759 originalColumn: mapping.originalColumn,
30760 name: name
30761 };
30762
30763 this.__generatedMappings.push(adjustedMapping);
30764 if (typeof adjustedMapping.originalLine === 'number') {
30765 this.__originalMappings.push(adjustedMapping);
30766 }
30767 }
30768 }
30769
30770 quickSort$1(this.__generatedMappings, util$1.compareByGeneratedPositionsDeflated);
30771 quickSort$1(this.__originalMappings, util$1.compareByOriginalPositions);
30772 };
30773
30774var IndexedSourceMapConsumer_1 = IndexedSourceMapConsumer;
30775
30776var sourceMapConsumer = {
30777 SourceMapConsumer: SourceMapConsumer_1,
30778 BasicSourceMapConsumer: BasicSourceMapConsumer_1,
30779 IndexedSourceMapConsumer: IndexedSourceMapConsumer_1
30780};
30781
30782/* -*- Mode: js; js-indent-level: 2; -*- */
30783/*
30784 * Copyright 2011 Mozilla Foundation and contributors
30785 * Licensed under the New BSD license. See LICENSE or:
30786 * http://opensource.org/licenses/BSD-3-Clause
30787 */
30788
30789var SourceMapGenerator$1 = sourceMapGenerator.SourceMapGenerator;
30790
30791
30792// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other
30793// operating systems these days (capturing the result).
30794var REGEX_NEWLINE = /(\r?\n)/;
30795
30796// Newline character code for charCodeAt() comparisons
30797var NEWLINE_CODE = 10;
30798
30799// Private symbol for identifying `SourceNode`s when multiple versions of
30800// the source-map library are loaded. This MUST NOT CHANGE across
30801// versions!
30802var isSourceNode = "$$$isSourceNode$$$";
30803
30804/**
30805 * SourceNodes provide a way to abstract over interpolating/concatenating
30806 * snippets of generated JavaScript source code while maintaining the line and
30807 * column information associated with the original source code.
30808 *
30809 * @param aLine The original line number.
30810 * @param aColumn The original column number.
30811 * @param aSource The original source's filename.
30812 * @param aChunks Optional. An array of strings which are snippets of
30813 * generated JS, or other SourceNodes.
30814 * @param aName The original identifier.
30815 */
30816function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
30817 this.children = [];
30818 this.sourceContents = {};
30819 this.line = aLine == null ? null : aLine;
30820 this.column = aColumn == null ? null : aColumn;
30821 this.source = aSource == null ? null : aSource;
30822 this.name = aName == null ? null : aName;
30823 this[isSourceNode] = true;
30824 if (aChunks != null) this.add(aChunks);
30825}
30826
30827/**
30828 * Creates a SourceNode from generated code and a SourceMapConsumer.
30829 *
30830 * @param aGeneratedCode The generated code
30831 * @param aSourceMapConsumer The SourceMap for the generated code
30832 * @param aRelativePath Optional. The path that relative sources in the
30833 * SourceMapConsumer should be relative to.
30834 */
30835SourceNode.fromStringWithSourceMap =
30836 function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) {
30837 // The SourceNode we want to fill with the generated code
30838 // and the SourceMap
30839 var node = new SourceNode();
30840
30841 // All even indices of this array are one line of the generated code,
30842 // while all odd indices are the newlines between two adjacent lines
30843 // (since `REGEX_NEWLINE` captures its match).
30844 // Processed fragments are accessed by calling `shiftNextLine`.
30845 var remainingLines = aGeneratedCode.split(REGEX_NEWLINE);
30846 var remainingLinesIndex = 0;
30847 var shiftNextLine = function() {
30848 var lineContents = getNextLine();
30849 // The last line of a file might not have a newline.
30850 var newLine = getNextLine() || "";
30851 return lineContents + newLine;
30852
30853 function getNextLine() {
30854 return remainingLinesIndex < remainingLines.length ?
30855 remainingLines[remainingLinesIndex++] : undefined;
30856 }
30857 };
30858
30859 // We need to remember the position of "remainingLines"
30860 var lastGeneratedLine = 1, lastGeneratedColumn = 0;
30861
30862 // The generate SourceNodes we need a code range.
30863 // To extract it current and last mapping is used.
30864 // Here we store the last mapping.
30865 var lastMapping = null;
30866
30867 aSourceMapConsumer.eachMapping(function (mapping) {
30868 if (lastMapping !== null) {
30869 // We add the code from "lastMapping" to "mapping":
30870 // First check if there is a new line in between.
30871 if (lastGeneratedLine < mapping.generatedLine) {
30872 // Associate first line with "lastMapping"
30873 addMappingWithCode(lastMapping, shiftNextLine());
30874 lastGeneratedLine++;
30875 lastGeneratedColumn = 0;
30876 // The remaining code is added without mapping
30877 } else {
30878 // There is no new line in between.
30879 // Associate the code between "lastGeneratedColumn" and
30880 // "mapping.generatedColumn" with "lastMapping"
30881 var nextLine = remainingLines[remainingLinesIndex];
30882 var code = nextLine.substr(0, mapping.generatedColumn -
30883 lastGeneratedColumn);
30884 remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn -
30885 lastGeneratedColumn);
30886 lastGeneratedColumn = mapping.generatedColumn;
30887 addMappingWithCode(lastMapping, code);
30888 // No more remaining code, continue
30889 lastMapping = mapping;
30890 return;
30891 }
30892 }
30893 // We add the generated code until the first mapping
30894 // to the SourceNode without any mapping.
30895 // Each line is added as separate string.
30896 while (lastGeneratedLine < mapping.generatedLine) {
30897 node.add(shiftNextLine());
30898 lastGeneratedLine++;
30899 }
30900 if (lastGeneratedColumn < mapping.generatedColumn) {
30901 var nextLine = remainingLines[remainingLinesIndex];
30902 node.add(nextLine.substr(0, mapping.generatedColumn));
30903 remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn);
30904 lastGeneratedColumn = mapping.generatedColumn;
30905 }
30906 lastMapping = mapping;
30907 }, this);
30908 // We have processed all mappings.
30909 if (remainingLinesIndex < remainingLines.length) {
30910 if (lastMapping) {
30911 // Associate the remaining code in the current line with "lastMapping"
30912 addMappingWithCode(lastMapping, shiftNextLine());
30913 }
30914 // and add the remaining lines without any mapping
30915 node.add(remainingLines.splice(remainingLinesIndex).join(""));
30916 }
30917
30918 // Copy sourcesContent into SourceNode
30919 aSourceMapConsumer.sources.forEach(function (sourceFile) {
30920 var content = aSourceMapConsumer.sourceContentFor(sourceFile);
30921 if (content != null) {
30922 if (aRelativePath != null) {
30923 sourceFile = util$1.join(aRelativePath, sourceFile);
30924 }
30925 node.setSourceContent(sourceFile, content);
30926 }
30927 });
30928
30929 return node;
30930
30931 function addMappingWithCode(mapping, code) {
30932 if (mapping === null || mapping.source === undefined) {
30933 node.add(code);
30934 } else {
30935 var source = aRelativePath
30936 ? util$1.join(aRelativePath, mapping.source)
30937 : mapping.source;
30938 node.add(new SourceNode(mapping.originalLine,
30939 mapping.originalColumn,
30940 source,
30941 code,
30942 mapping.name));
30943 }
30944 }
30945 };
30946
30947/**
30948 * Add a chunk of generated JS to this source node.
30949 *
30950 * @param aChunk A string snippet of generated JS code, another instance of
30951 * SourceNode, or an array where each member is one of those things.
30952 */
30953SourceNode.prototype.add = function SourceNode_add(aChunk) {
30954 if (Array.isArray(aChunk)) {
30955 aChunk.forEach(function (chunk) {
30956 this.add(chunk);
30957 }, this);
30958 }
30959 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
30960 if (aChunk) {
30961 this.children.push(aChunk);
30962 }
30963 }
30964 else {
30965 throw new TypeError(
30966 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
30967 );
30968 }
30969 return this;
30970};
30971
30972/**
30973 * Add a chunk of generated JS to the beginning of this source node.
30974 *
30975 * @param aChunk A string snippet of generated JS code, another instance of
30976 * SourceNode, or an array where each member is one of those things.
30977 */
30978SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
30979 if (Array.isArray(aChunk)) {
30980 for (var i = aChunk.length-1; i >= 0; i--) {
30981 this.prepend(aChunk[i]);
30982 }
30983 }
30984 else if (aChunk[isSourceNode] || typeof aChunk === "string") {
30985 this.children.unshift(aChunk);
30986 }
30987 else {
30988 throw new TypeError(
30989 "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
30990 );
30991 }
30992 return this;
30993};
30994
30995/**
30996 * Walk over the tree of JS snippets in this node and its children. The
30997 * walking function is called once for each snippet of JS and is passed that
30998 * snippet and the its original associated source's line/column location.
30999 *
31000 * @param aFn The traversal function.
31001 */
31002SourceNode.prototype.walk = function SourceNode_walk(aFn) {
31003 var chunk;
31004 for (var i = 0, len = this.children.length; i < len; i++) {
31005 chunk = this.children[i];
31006 if (chunk[isSourceNode]) {
31007 chunk.walk(aFn);
31008 }
31009 else {
31010 if (chunk !== '') {
31011 aFn(chunk, { source: this.source,
31012 line: this.line,
31013 column: this.column,
31014 name: this.name });
31015 }
31016 }
31017 }
31018};
31019
31020/**
31021 * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
31022 * each of `this.children`.
31023 *
31024 * @param aSep The separator.
31025 */
31026SourceNode.prototype.join = function SourceNode_join(aSep) {
31027 var newChildren;
31028 var i;
31029 var len = this.children.length;
31030 if (len > 0) {
31031 newChildren = [];
31032 for (i = 0; i < len-1; i++) {
31033 newChildren.push(this.children[i]);
31034 newChildren.push(aSep);
31035 }
31036 newChildren.push(this.children[i]);
31037 this.children = newChildren;
31038 }
31039 return this;
31040};
31041
31042/**
31043 * Call String.prototype.replace on the very right-most source snippet. Useful
31044 * for trimming whitespace from the end of a source node, etc.
31045 *
31046 * @param aPattern The pattern to replace.
31047 * @param aReplacement The thing to replace the pattern with.
31048 */
31049SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
31050 var lastChild = this.children[this.children.length - 1];
31051 if (lastChild[isSourceNode]) {
31052 lastChild.replaceRight(aPattern, aReplacement);
31053 }
31054 else if (typeof lastChild === 'string') {
31055 this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
31056 }
31057 else {
31058 this.children.push(''.replace(aPattern, aReplacement));
31059 }
31060 return this;
31061};
31062
31063/**
31064 * Set the source content for a source file. This will be added to the SourceMapGenerator
31065 * in the sourcesContent field.
31066 *
31067 * @param aSourceFile The filename of the source file
31068 * @param aSourceContent The content of the source file
31069 */
31070SourceNode.prototype.setSourceContent =
31071 function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
31072 this.sourceContents[util$1.toSetString(aSourceFile)] = aSourceContent;
31073 };
31074
31075/**
31076 * Walk over the tree of SourceNodes. The walking function is called for each
31077 * source file content and is passed the filename and source content.
31078 *
31079 * @param aFn The traversal function.
31080 */
31081SourceNode.prototype.walkSourceContents =
31082 function SourceNode_walkSourceContents(aFn) {
31083 for (var i = 0, len = this.children.length; i < len; i++) {
31084 if (this.children[i][isSourceNode]) {
31085 this.children[i].walkSourceContents(aFn);
31086 }
31087 }
31088
31089 var sources = Object.keys(this.sourceContents);
31090 for (var i = 0, len = sources.length; i < len; i++) {
31091 aFn(util$1.fromSetString(sources[i]), this.sourceContents[sources[i]]);
31092 }
31093 };
31094
31095/**
31096 * Return the string representation of this source node. Walks over the tree
31097 * and concatenates all the various snippets together to one string.
31098 */
31099SourceNode.prototype.toString = function SourceNode_toString() {
31100 var str = "";
31101 this.walk(function (chunk) {
31102 str += chunk;
31103 });
31104 return str;
31105};
31106
31107/**
31108 * Returns the string representation of this source node along with a source
31109 * map.
31110 */
31111SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
31112 var generated = {
31113 code: "",
31114 line: 1,
31115 column: 0
31116 };
31117 var map = new SourceMapGenerator$1(aArgs);
31118 var sourceMappingActive = false;
31119 var lastOriginalSource = null;
31120 var lastOriginalLine = null;
31121 var lastOriginalColumn = null;
31122 var lastOriginalName = null;
31123 this.walk(function (chunk, original) {
31124 generated.code += chunk;
31125 if (original.source !== null
31126 && original.line !== null
31127 && original.column !== null) {
31128 if(lastOriginalSource !== original.source
31129 || lastOriginalLine !== original.line
31130 || lastOriginalColumn !== original.column
31131 || lastOriginalName !== original.name) {
31132 map.addMapping({
31133 source: original.source,
31134 original: {
31135 line: original.line,
31136 column: original.column
31137 },
31138 generated: {
31139 line: generated.line,
31140 column: generated.column
31141 },
31142 name: original.name
31143 });
31144 }
31145 lastOriginalSource = original.source;
31146 lastOriginalLine = original.line;
31147 lastOriginalColumn = original.column;
31148 lastOriginalName = original.name;
31149 sourceMappingActive = true;
31150 } else if (sourceMappingActive) {
31151 map.addMapping({
31152 generated: {
31153 line: generated.line,
31154 column: generated.column
31155 }
31156 });
31157 lastOriginalSource = null;
31158 sourceMappingActive = false;
31159 }
31160 for (var idx = 0, length = chunk.length; idx < length; idx++) {
31161 if (chunk.charCodeAt(idx) === NEWLINE_CODE) {
31162 generated.line++;
31163 generated.column = 0;
31164 // Mappings end at eol
31165 if (idx + 1 === length) {
31166 lastOriginalSource = null;
31167 sourceMappingActive = false;
31168 } else if (sourceMappingActive) {
31169 map.addMapping({
31170 source: original.source,
31171 original: {
31172 line: original.line,
31173 column: original.column
31174 },
31175 generated: {
31176 line: generated.line,
31177 column: generated.column
31178 },
31179 name: original.name
31180 });
31181 }
31182 } else {
31183 generated.column++;
31184 }
31185 }
31186 });
31187 this.walkSourceContents(function (sourceFile, sourceContent) {
31188 map.setSourceContent(sourceFile, sourceContent);
31189 });
31190
31191 return { code: generated.code, map: map };
31192};
31193
31194var SourceNode_1 = SourceNode;
31195
31196var sourceNode = {
31197 SourceNode: SourceNode_1
31198};
31199
31200/*
31201 * Copyright 2009-2011 Mozilla Foundation and contributors
31202 * Licensed under the New BSD license. See LICENSE.txt or:
31203 * http://opensource.org/licenses/BSD-3-Clause
31204 */
31205var SourceMapGenerator$2 = sourceMapGenerator.SourceMapGenerator;
31206var SourceMapConsumer$1 = sourceMapConsumer.SourceMapConsumer;
31207var SourceNode$1 = sourceNode.SourceNode;
31208
31209var sourceMap = {
31210 SourceMapGenerator: SourceMapGenerator$2,
31211 SourceMapConsumer: SourceMapConsumer$1,
31212 SourceNode: SourceNode$1
31213};
31214
31215var sourceMapUrl = createCommonjsModule(function (module, exports) {
31216// Copyright 2014 Simon Lydell
31217// X11 (“MIT”) Licensed. (See LICENSE.)
31218
31219void (function(root, factory) {
31220 {
31221 module.exports = factory();
31222 }
31223}(commonjsGlobal, function() {
31224
31225 var innerRegex = /[#@] sourceMappingURL=([^\s'"]*)/;
31226
31227 var regex = RegExp(
31228 "(?:" +
31229 "/\\*" +
31230 "(?:\\s*\r?\n(?://)?)?" +
31231 "(?:" + innerRegex.source + ")" +
31232 "\\s*" +
31233 "\\*/" +
31234 "|" +
31235 "//(?:" + innerRegex.source + ")" +
31236 ")" +
31237 "\\s*"
31238 );
31239
31240 return {
31241
31242 regex: regex,
31243 _innerRegex: innerRegex,
31244
31245 getFrom: function(code) {
31246 var match = code.match(regex);
31247 return (match ? match[1] || match[2] || "" : null)
31248 },
31249
31250 existsIn: function(code) {
31251 return regex.test(code)
31252 },
31253
31254 removeFrom: function(code) {
31255 return code.replace(regex, "")
31256 },
31257
31258 insertBefore: function(code, string) {
31259 var match = code.match(regex);
31260 if (match) {
31261 return code.slice(0, match.index) + string + code.slice(match.index)
31262 } else {
31263 return code + string
31264 }
31265 }
31266 }
31267
31268}));
31269});
31270
31271// Copyright 2014 Simon Lydell
31272// X11 (“MIT”) Licensed. (See LICENSE.)
31273
31274
31275
31276function resolveUrl(/* ...urls */) {
31277 return Array.prototype.reduce.call(arguments, function(resolved, nextUrl) {
31278 return url.resolve(resolved, nextUrl)
31279 })
31280}
31281
31282var resolveUrl_1 = resolveUrl;
31283
31284var token = '%[a-f0-9]{2}';
31285var singleMatcher = new RegExp(token, 'gi');
31286var multiMatcher = new RegExp('(' + token + ')+', 'gi');
31287
31288function decodeComponents(components, split) {
31289 try {
31290 // Try to decode the entire string first
31291 return decodeURIComponent(components.join(''));
31292 } catch (err) {
31293 // Do nothing
31294 }
31295
31296 if (components.length === 1) {
31297 return components;
31298 }
31299
31300 split = split || 1;
31301
31302 // Split the array in 2 parts
31303 var left = components.slice(0, split);
31304 var right = components.slice(split);
31305
31306 return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
31307}
31308
31309function decode$3(input) {
31310 try {
31311 return decodeURIComponent(input);
31312 } catch (err) {
31313 var tokens = input.match(singleMatcher);
31314
31315 for (var i = 1; i < tokens.length; i++) {
31316 input = decodeComponents(tokens, i).join('');
31317
31318 tokens = input.match(singleMatcher);
31319 }
31320
31321 return input;
31322 }
31323}
31324
31325function customDecodeURIComponent(input) {
31326 // Keep track of all the replacements and prefill the map with the `BOM`
31327 var replaceMap = {
31328 '%FE%FF': '\uFFFD\uFFFD',
31329 '%FF%FE': '\uFFFD\uFFFD'
31330 };
31331
31332 var match = multiMatcher.exec(input);
31333 while (match) {
31334 try {
31335 // Decode as big chunks as possible
31336 replaceMap[match[0]] = decodeURIComponent(match[0]);
31337 } catch (err) {
31338 var result = decode$3(match[0]);
31339
31340 if (result !== match[0]) {
31341 replaceMap[match[0]] = result;
31342 }
31343 }
31344
31345 match = multiMatcher.exec(input);
31346 }
31347
31348 // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
31349 replaceMap['%C2'] = '\uFFFD';
31350
31351 var entries = Object.keys(replaceMap);
31352
31353 for (var i = 0; i < entries.length; i++) {
31354 // Replace all decoded components
31355 var key = entries[i];
31356 input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
31357 }
31358
31359 return input;
31360}
31361
31362var decodeUriComponent = function (encodedURI) {
31363 if (typeof encodedURI !== 'string') {
31364 throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
31365 }
31366
31367 try {
31368 encodedURI = encodedURI.replace(/\+/g, ' ');
31369
31370 // Try the built in decoder first
31371 return decodeURIComponent(encodedURI);
31372 } catch (err) {
31373 // Fallback to a more advanced decoder
31374 return customDecodeURIComponent(encodedURI);
31375 }
31376};
31377
31378// Copyright 2017 Simon Lydell
31379// X11 (“MIT”) Licensed. (See LICENSE.)
31380
31381
31382
31383function customDecodeUriComponent(string) {
31384 // `decodeUriComponent` turns `+` into ` `, but that's not wanted.
31385 return decodeUriComponent(string.replace(/\+/g, "%2B"))
31386}
31387
31388var decodeUriComponent_1 = customDecodeUriComponent;
31389
31390function urix(aPath) {
31391 if (path.sep === "\\") {
31392 return aPath
31393 .replace(/\\/g, "/")
31394 .replace(/^[a-z]:\/?/i, "/")
31395 }
31396 return aPath
31397}
31398
31399var urix_1 = urix;
31400
31401function atob(str) {
31402 return Buffer.from(str, 'base64').toString('binary');
31403}
31404
31405var nodeAtob = atob.atob = atob;
31406
31407// Copyright 2014, 2015, 2016, 2017 Simon Lydell
31408// X11 (“MIT”) Licensed. (See LICENSE.)
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418function callbackAsync(callback, error, result) {
31419 setImmediate(function() { callback(error, result); });
31420}
31421
31422function parseMapToJSON(string, data) {
31423 try {
31424 return JSON.parse(string.replace(/^\)\]\}'/, ""))
31425 } catch (error) {
31426 error.sourceMapData = data;
31427 throw error
31428 }
31429}
31430
31431function readSync(read, url, data) {
31432 var readUrl = decodeUriComponent_1(url);
31433 try {
31434 return String(read(readUrl))
31435 } catch (error) {
31436 error.sourceMapData = data;
31437 throw error
31438 }
31439}
31440
31441
31442
31443function resolveSourceMap(code, codeUrl, read, callback) {
31444 var mapData;
31445 try {
31446 mapData = resolveSourceMapHelper(code, codeUrl);
31447 } catch (error) {
31448 return callbackAsync(callback, error)
31449 }
31450 if (!mapData || mapData.map) {
31451 return callbackAsync(callback, null, mapData)
31452 }
31453 var readUrl = decodeUriComponent_1(mapData.url);
31454 read(readUrl, function(error, result) {
31455 if (error) {
31456 error.sourceMapData = mapData;
31457 return callback(error)
31458 }
31459 mapData.map = String(result);
31460 try {
31461 mapData.map = parseMapToJSON(mapData.map, mapData);
31462 } catch (error) {
31463 return callback(error)
31464 }
31465 callback(null, mapData);
31466 });
31467}
31468
31469function resolveSourceMapSync(code, codeUrl, read) {
31470 var mapData = resolveSourceMapHelper(code, codeUrl);
31471 if (!mapData || mapData.map) {
31472 return mapData
31473 }
31474 mapData.map = readSync(read, mapData.url, mapData);
31475 mapData.map = parseMapToJSON(mapData.map, mapData);
31476 return mapData
31477}
31478
31479var dataUriRegex = /^data:([^,;]*)(;[^,;]*)*(?:,(.*))?$/;
31480var jsonMimeTypeRegex = /^(?:application|text)\/json$/;
31481
31482function resolveSourceMapHelper(code, codeUrl) {
31483 codeUrl = urix_1(codeUrl);
31484
31485 var url = sourceMapUrl.getFrom(code);
31486 if (!url) {
31487 return null
31488 }
31489
31490 var dataUri = url.match(dataUriRegex);
31491 if (dataUri) {
31492 var mimeType = dataUri[1];
31493 var lastParameter = dataUri[2] || "";
31494 var encoded = dataUri[3] || "";
31495 var data = {
31496 sourceMappingURL: url,
31497 url: null,
31498 sourcesRelativeTo: codeUrl,
31499 map: encoded
31500 };
31501 if (!jsonMimeTypeRegex.test(mimeType)) {
31502 var error = new Error("Unuseful data uri mime type: " + (mimeType || "text/plain"));
31503 error.sourceMapData = data;
31504 throw error
31505 }
31506 data.map = parseMapToJSON(
31507 lastParameter === ";base64" ? nodeAtob(encoded) : decodeURIComponent(encoded),
31508 data
31509 );
31510 return data
31511 }
31512
31513 var mapUrl = resolveUrl_1(codeUrl, url);
31514 return {
31515 sourceMappingURL: url,
31516 url: mapUrl,
31517 sourcesRelativeTo: mapUrl,
31518 map: null
31519 }
31520}
31521
31522
31523
31524function resolveSources(map, mapUrl, read, options, callback) {
31525 if (typeof options === "function") {
31526 callback = options;
31527 options = {};
31528 }
31529 var pending = map.sources ? map.sources.length : 0;
31530 var result = {
31531 sourcesResolved: [],
31532 sourcesContent: []
31533 };
31534
31535 if (pending === 0) {
31536 callbackAsync(callback, null, result);
31537 return
31538 }
31539
31540 var done = function() {
31541 pending--;
31542 if (pending === 0) {
31543 callback(null, result);
31544 }
31545 };
31546
31547 resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) {
31548 result.sourcesResolved[index] = fullUrl;
31549 if (typeof sourceContent === "string") {
31550 result.sourcesContent[index] = sourceContent;
31551 callbackAsync(done, null);
31552 } else {
31553 var readUrl = decodeUriComponent_1(fullUrl);
31554 read(readUrl, function(error, source) {
31555 result.sourcesContent[index] = error ? error : String(source);
31556 done();
31557 });
31558 }
31559 });
31560}
31561
31562function resolveSourcesSync(map, mapUrl, read, options) {
31563 var result = {
31564 sourcesResolved: [],
31565 sourcesContent: []
31566 };
31567
31568 if (!map.sources || map.sources.length === 0) {
31569 return result
31570 }
31571
31572 resolveSourcesHelper(map, mapUrl, options, function(fullUrl, sourceContent, index) {
31573 result.sourcesResolved[index] = fullUrl;
31574 if (read !== null) {
31575 if (typeof sourceContent === "string") {
31576 result.sourcesContent[index] = sourceContent;
31577 } else {
31578 var readUrl = decodeUriComponent_1(fullUrl);
31579 try {
31580 result.sourcesContent[index] = String(read(readUrl));
31581 } catch (error) {
31582 result.sourcesContent[index] = error;
31583 }
31584 }
31585 }
31586 });
31587
31588 return result
31589}
31590
31591var endingSlash = /\/?$/;
31592
31593function resolveSourcesHelper(map, mapUrl, options, fn) {
31594 options = options || {};
31595 mapUrl = urix_1(mapUrl);
31596 var fullUrl;
31597 var sourceContent;
31598 var sourceRoot;
31599 for (var index = 0, len = map.sources.length; index < len; index++) {
31600 sourceRoot = null;
31601 if (typeof options.sourceRoot === "string") {
31602 sourceRoot = options.sourceRoot;
31603 } else if (typeof map.sourceRoot === "string" && options.sourceRoot !== false) {
31604 sourceRoot = map.sourceRoot;
31605 }
31606 // If the sourceRoot is the empty string, it is equivalent to not setting
31607 // the property at all.
31608 if (sourceRoot === null || sourceRoot === '') {
31609 fullUrl = resolveUrl_1(mapUrl, map.sources[index]);
31610 } else {
31611 // Make sure that the sourceRoot ends with a slash, so that `/scripts/subdir` becomes
31612 // `/scripts/subdir/<source>`, not `/scripts/<source>`. Pointing to a file as source root
31613 // does not make sense.
31614 fullUrl = resolveUrl_1(mapUrl, sourceRoot.replace(endingSlash, "/"), map.sources[index]);
31615 }
31616 sourceContent = (map.sourcesContent || [])[index];
31617 fn(fullUrl, sourceContent, index);
31618 }
31619}
31620
31621
31622
31623function resolve(code, codeUrl, read, options, callback) {
31624 if (typeof options === "function") {
31625 callback = options;
31626 options = {};
31627 }
31628 if (code === null) {
31629 var mapUrl = codeUrl;
31630 var data = {
31631 sourceMappingURL: null,
31632 url: mapUrl,
31633 sourcesRelativeTo: mapUrl,
31634 map: null
31635 };
31636 var readUrl = decodeUriComponent_1(mapUrl);
31637 read(readUrl, function(error, result) {
31638 if (error) {
31639 error.sourceMapData = data;
31640 return callback(error)
31641 }
31642 data.map = String(result);
31643 try {
31644 data.map = parseMapToJSON(data.map, data);
31645 } catch (error) {
31646 return callback(error)
31647 }
31648 _resolveSources(data);
31649 });
31650 } else {
31651 resolveSourceMap(code, codeUrl, read, function(error, mapData) {
31652 if (error) {
31653 return callback(error)
31654 }
31655 if (!mapData) {
31656 return callback(null, null)
31657 }
31658 _resolveSources(mapData);
31659 });
31660 }
31661
31662 function _resolveSources(mapData) {
31663 resolveSources(mapData.map, mapData.sourcesRelativeTo, read, options, function(error, result) {
31664 if (error) {
31665 return callback(error)
31666 }
31667 mapData.sourcesResolved = result.sourcesResolved;
31668 mapData.sourcesContent = result.sourcesContent;
31669 callback(null, mapData);
31670 });
31671 }
31672}
31673
31674function resolveSync(code, codeUrl, read, options) {
31675 var mapData;
31676 if (code === null) {
31677 var mapUrl = codeUrl;
31678 mapData = {
31679 sourceMappingURL: null,
31680 url: mapUrl,
31681 sourcesRelativeTo: mapUrl,
31682 map: null
31683 };
31684 mapData.map = readSync(read, mapUrl, mapData);
31685 mapData.map = parseMapToJSON(mapData.map, mapData);
31686 } else {
31687 mapData = resolveSourceMapSync(code, codeUrl, read);
31688 if (!mapData) {
31689 return null
31690 }
31691 }
31692 var result = resolveSourcesSync(mapData.map, mapData.sourcesRelativeTo, read, options);
31693 mapData.sourcesResolved = result.sourcesResolved;
31694 mapData.sourcesContent = result.sourcesContent;
31695 return mapData
31696}
31697
31698
31699
31700var sourceMapResolveNode = {
31701 resolveSourceMap: resolveSourceMap,
31702 resolveSourceMapSync: resolveSourceMapSync,
31703 resolveSources: resolveSources,
31704 resolveSourcesSync: resolveSourcesSync,
31705 resolve: resolve,
31706 resolveSync: resolveSync,
31707 parseMapToJSON: parseMapToJSON
31708};
31709
31710/**
31711 * Module dependencies
31712 */
31713
31714var extend$1 = extendShallow$5;
31715var SourceMap$1 = sourceMap;
31716var sourceMapResolve = sourceMapResolveNode;
31717
31718/**
31719 * Convert backslash in the given string to forward slashes
31720 */
31721
31722var unixify = function(fp) {
31723 return fp.split(/\\+/).join('/');
31724};
31725
31726/**
31727 * Return true if `val` is a non-empty string
31728 *
31729 * @param {String} `str`
31730 * @return {Boolean}
31731 */
31732
31733var isString$1 = function(str) {
31734 return str && typeof str === 'string';
31735};
31736
31737/**
31738 * Cast `val` to an array
31739 * @return {Array}
31740 */
31741
31742var arrayify$3 = function(val) {
31743 if (typeof val === 'string') return [val];
31744 return val ? (Array.isArray(val) ? val : [val]) : [];
31745};
31746
31747/**
31748 * Get the last `n` element from the given `array`
31749 * @param {Array} `array`
31750 * @return {*}
31751 */
31752
31753var last = function(arr, n) {
31754 return arr[arr.length - (n || 1)];
31755};
31756
31757var utils$1 = {
31758 extend: extend$1,
31759 SourceMap: SourceMap$1,
31760 sourceMapResolve: sourceMapResolve,
31761 unixify: unixify,
31762 isString: isString$1,
31763 arrayify: arrayify$3,
31764 last: last
31765};
31766
31767var sourceMaps = createCommonjsModule(function (module, exports) {
31768
31769
31770
31771
31772
31773
31774/**
31775 * Expose `mixin()`.
31776 * This code is based on `source-maps-support.js` in reworkcss/css
31777 * https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js
31778 * Copyright (c) 2012 TJ Holowaychuk <tj@vision-media.ca>
31779 */
31780
31781module.exports = mixin;
31782
31783/**
31784 * Mixin source map support into `compiler`.
31785 *
31786 * @param {Object} `compiler`
31787 * @api public
31788 */
31789
31790function mixin(compiler) {
31791 defineProperty$6(compiler, '_comment', compiler.comment);
31792 compiler.map = new utils$1.SourceMap.SourceMapGenerator();
31793 compiler.position = { line: 1, column: 1 };
31794 compiler.content = {};
31795 compiler.files = {};
31796
31797 for (var key in exports) {
31798 defineProperty$6(compiler, key, exports[key]);
31799 }
31800}
31801
31802/**
31803 * Update position.
31804 *
31805 * @param {String} str
31806 */
31807
31808exports.updatePosition = function(str) {
31809 var lines = str.match(/\n/g);
31810 if (lines) this.position.line += lines.length;
31811 var i = str.lastIndexOf('\n');
31812 this.position.column = ~i ? str.length - i : this.position.column + str.length;
31813};
31814
31815/**
31816 * Emit `str` with `position`.
31817 *
31818 * @param {String} str
31819 * @param {Object} [pos]
31820 * @return {String}
31821 */
31822
31823exports.emit = function(str, node) {
31824 var position = node.position || {};
31825 var source = position.source;
31826 if (source) {
31827 if (position.filepath) {
31828 source = utils$1.unixify(position.filepath);
31829 }
31830
31831 this.map.addMapping({
31832 source: source,
31833 generated: {
31834 line: this.position.line,
31835 column: Math.max(this.position.column - 1, 0)
31836 },
31837 original: {
31838 line: position.start.line,
31839 column: position.start.column - 1
31840 }
31841 });
31842
31843 if (position.content) {
31844 this.addContent(source, position);
31845 }
31846 if (position.filepath) {
31847 this.addFile(source, position);
31848 }
31849
31850 this.updatePosition(str);
31851 this.output += str;
31852 }
31853 return str;
31854};
31855
31856/**
31857 * Adds a file to the source map output if it has not already been added
31858 * @param {String} `file`
31859 * @param {Object} `pos`
31860 */
31861
31862exports.addFile = function(file, position) {
31863 if (typeof position.content !== 'string') return;
31864 if (Object.prototype.hasOwnProperty.call(this.files, file)) return;
31865 this.files[file] = position.content;
31866};
31867
31868/**
31869 * Adds a content source to the source map output if it has not already been added
31870 * @param {String} `source`
31871 * @param {Object} `position`
31872 */
31873
31874exports.addContent = function(source, position) {
31875 if (typeof position.content !== 'string') return;
31876 if (Object.prototype.hasOwnProperty.call(this.content, source)) return;
31877 this.map.setSourceContent(source, position.content);
31878};
31879
31880/**
31881 * Applies any original source maps to the output and embeds the source file
31882 * contents in the source map.
31883 */
31884
31885exports.applySourceMaps = function() {
31886 Object.keys(this.files).forEach(function(file) {
31887 var content = this.files[file];
31888 this.map.setSourceContent(file, content);
31889
31890 if (this.options.inputSourcemaps === true) {
31891 var originalMap = utils$1.sourceMapResolve.resolveSync(content, file, fs__default.readFileSync);
31892 if (originalMap) {
31893 var map = new utils$1.SourceMap.SourceMapConsumer(originalMap.map);
31894 var relativeTo = originalMap.sourcesRelativeTo;
31895 this.map.applySourceMap(map, file, utils$1.unixify(path.dirname(relativeTo)));
31896 }
31897 }
31898 }, this);
31899};
31900
31901/**
31902 * Process comments, drops sourceMap comments.
31903 * @param {Object} node
31904 */
31905
31906exports.comment = function(node) {
31907 if (/^# sourceMappingURL=/.test(node.comment)) {
31908 return this.emit('', node.position);
31909 }
31910 return this._comment(node);
31911};
31912});
31913
31914var debug$1 = src('snapdragon:compiler');
31915
31916
31917/**
31918 * Create a new `Compiler` with the given `options`.
31919 * @param {Object} `options`
31920 */
31921
31922function Compiler(options, state) {
31923 debug$1('initializing', __filename);
31924 this.options = utils$1.extend({source: 'string'}, options);
31925 this.state = state || {};
31926 this.compilers = {};
31927 this.output = '';
31928 this.set('eos', function(node) {
31929 return this.emit(node.val, node);
31930 });
31931 this.set('noop', function(node) {
31932 return this.emit(node.val, node);
31933 });
31934 this.set('bos', function(node) {
31935 return this.emit(node.val, node);
31936 });
31937 use(this);
31938}
31939
31940/**
31941 * Prototype methods
31942 */
31943
31944Compiler.prototype = {
31945
31946 /**
31947 * Throw an error message with details including the cursor position.
31948 * @param {String} `msg` Message to use in the Error.
31949 */
31950
31951 error: function(msg, node) {
31952 var pos = node.position || {start: {column: 0}};
31953 var message = this.options.source + ' column:' + pos.start.column + ': ' + msg;
31954
31955 var err = new Error(message);
31956 err.reason = msg;
31957 err.column = pos.start.column;
31958 err.source = this.pattern;
31959
31960 if (this.options.silent) {
31961 this.errors.push(err);
31962 } else {
31963 throw err;
31964 }
31965 },
31966
31967 /**
31968 * Define a non-enumberable property on the `Compiler` instance.
31969 *
31970 * ```js
31971 * compiler.define('foo', 'bar');
31972 * ```
31973 * @name .define
31974 * @param {String} `key` propery name
31975 * @param {any} `val` property value
31976 * @return {Object} Returns the Compiler instance for chaining.
31977 * @api public
31978 */
31979
31980 define: function(key, val) {
31981 defineProperty$6(this, key, val);
31982 return this;
31983 },
31984
31985 /**
31986 * Emit `node.val`
31987 */
31988
31989 emit: function(str, node) {
31990 this.output += str;
31991 return str;
31992 },
31993
31994 /**
31995 * Add a compiler `fn` with the given `name`
31996 */
31997
31998 set: function(name, fn) {
31999 this.compilers[name] = fn;
32000 return this;
32001 },
32002
32003 /**
32004 * Get compiler `name`.
32005 */
32006
32007 get: function(name) {
32008 return this.compilers[name];
32009 },
32010
32011 /**
32012 * Get the previous AST node.
32013 */
32014
32015 prev: function(n) {
32016 return this.ast.nodes[this.idx - (n || 1)] || { type: 'bos', val: '' };
32017 },
32018
32019 /**
32020 * Get the next AST node.
32021 */
32022
32023 next: function(n) {
32024 return this.ast.nodes[this.idx + (n || 1)] || { type: 'eos', val: '' };
32025 },
32026
32027 /**
32028 * Visit `node`.
32029 */
32030
32031 visit: function(node, nodes, i) {
32032 var fn = this.compilers[node.type];
32033 this.idx = i;
32034
32035 if (typeof fn !== 'function') {
32036 throw this.error('compiler "' + node.type + '" is not registered', node);
32037 }
32038 return fn.call(this, node, nodes, i);
32039 },
32040
32041 /**
32042 * Map visit over array of `nodes`.
32043 */
32044
32045 mapVisit: function(nodes) {
32046 if (!Array.isArray(nodes)) {
32047 throw new TypeError('expected an array');
32048 }
32049 var len = nodes.length;
32050 var idx = -1;
32051 while (++idx < len) {
32052 this.visit(nodes[idx], nodes, idx);
32053 }
32054 return this;
32055 },
32056
32057 /**
32058 * Compile `ast`.
32059 */
32060
32061 compile: function(ast, options) {
32062 var opts = utils$1.extend({}, this.options, options);
32063 this.ast = ast;
32064 this.parsingErrors = this.ast.errors;
32065 this.output = '';
32066
32067 // source map support
32068 if (opts.sourcemap) {
32069 var sourcemaps = sourceMaps;
32070 sourcemaps(this);
32071 this.mapVisit(this.ast.nodes);
32072 this.applySourceMaps();
32073 this.map = opts.sourcemap === 'generator' ? this.map : this.map.toJSON();
32074 return this;
32075 }
32076
32077 this.mapVisit(this.ast.nodes);
32078 return this;
32079 }
32080};
32081
32082/**
32083 * Expose `Compiler`
32084 */
32085
32086var compiler = Compiler;
32087
32088/*!
32089 * map-cache <https://github.com/jonschlinkert/map-cache>
32090 *
32091 * Copyright (c) 2015, Jon Schlinkert.
32092 * Licensed under the MIT License.
32093 */
32094
32095var hasOwn$6 = Object.prototype.hasOwnProperty;
32096
32097/**
32098 * Expose `MapCache`
32099 */
32100
32101var mapCache = MapCache;
32102
32103/**
32104 * Creates a cache object to store key/value pairs.
32105 *
32106 * ```js
32107 * var cache = new MapCache();
32108 * ```
32109 *
32110 * @api public
32111 */
32112
32113function MapCache(data) {
32114 this.__data__ = data || {};
32115}
32116
32117/**
32118 * Adds `value` to `key` on the cache.
32119 *
32120 * ```js
32121 * cache.set('foo', 'bar');
32122 * ```
32123 *
32124 * @param {String} `key` The key of the value to cache.
32125 * @param {*} `value` The value to cache.
32126 * @returns {Object} Returns the `Cache` object for chaining.
32127 * @api public
32128 */
32129
32130MapCache.prototype.set = function mapSet(key, value) {
32131 if (key !== '__proto__') {
32132 this.__data__[key] = value;
32133 }
32134 return this;
32135};
32136
32137/**
32138 * Gets the cached value for `key`.
32139 *
32140 * ```js
32141 * cache.get('foo');
32142 * //=> 'bar'
32143 * ```
32144 *
32145 * @param {String} `key` The key of the value to get.
32146 * @returns {*} Returns the cached value.
32147 * @api public
32148 */
32149
32150MapCache.prototype.get = function mapGet(key) {
32151 return key === '__proto__' ? undefined : this.__data__[key];
32152};
32153
32154/**
32155 * Checks if a cached value for `key` exists.
32156 *
32157 * ```js
32158 * cache.has('foo');
32159 * //=> true
32160 * ```
32161 *
32162 * @param {String} `key` The key of the entry to check.
32163 * @returns {Boolean} Returns `true` if an entry for `key` exists, else `false`.
32164 * @api public
32165 */
32166
32167MapCache.prototype.has = function mapHas(key) {
32168 return key !== '__proto__' && hasOwn$6.call(this.__data__, key);
32169};
32170
32171/**
32172 * Removes `key` and its value from the cache.
32173 *
32174 * ```js
32175 * cache.del('foo');
32176 * ```
32177 * @title .del
32178 * @param {String} `key` The key of the value to remove.
32179 * @returns {Boolean} Returns `true` if the entry was removed successfully, else `false`.
32180 * @api public
32181 */
32182
32183MapCache.prototype.del = function mapDelete(key) {
32184 return this.has(key) && delete this.__data__[key];
32185};
32186
32187/**
32188 * Store position for a node
32189 */
32190
32191var position = function Position(start, parser) {
32192 this.start = start;
32193 this.end = { line: parser.line, column: parser.column };
32194 defineProperty$6(this, 'content', parser.orig);
32195 defineProperty$6(this, 'source', parser.options.source);
32196};
32197
32198var debug$2 = src('snapdragon:parser');
32199
32200
32201
32202/**
32203 * Create a new `Parser` with the given `input` and `options`.
32204 * @param {String} `input`
32205 * @param {Object} `options`
32206 * @api public
32207 */
32208
32209function Parser(options) {
32210 debug$2('initializing', __filename);
32211 this.options = utils$1.extend({source: 'string'}, options);
32212 this.init(this.options);
32213 use(this);
32214}
32215
32216/**
32217 * Prototype methods
32218 */
32219
32220Parser.prototype = {
32221 constructor: Parser,
32222
32223 init: function(options) {
32224 this.orig = '';
32225 this.input = '';
32226 this.parsed = '';
32227
32228 this.column = 1;
32229 this.line = 1;
32230
32231 this.regex = new mapCache();
32232 this.errors = this.errors || [];
32233 this.parsers = this.parsers || {};
32234 this.types = this.types || [];
32235 this.sets = this.sets || {};
32236 this.fns = this.fns || [];
32237 this.currentType = 'root';
32238
32239 var pos = this.position();
32240 this.bos = pos({type: 'bos', val: ''});
32241
32242 this.ast = {
32243 type: 'root',
32244 errors: this.errors,
32245 nodes: [this.bos]
32246 };
32247
32248 defineProperty$6(this.bos, 'parent', this.ast);
32249 this.nodes = [this.ast];
32250
32251 this.count = 0;
32252 this.setCount = 0;
32253 this.stack = [];
32254 },
32255
32256 /**
32257 * Throw a formatted error with the cursor column and `msg`.
32258 * @param {String} `msg` Message to use in the Error.
32259 */
32260
32261 error: function(msg, node) {
32262 var pos = node.position || {start: {column: 0, line: 0}};
32263 var line = pos.start.line;
32264 var column = pos.start.column;
32265 var source = this.options.source;
32266
32267 var message = source + ' <line:' + line + ' column:' + column + '>: ' + msg;
32268 var err = new Error(message);
32269 err.source = source;
32270 err.reason = msg;
32271 err.pos = pos;
32272
32273 if (this.options.silent) {
32274 this.errors.push(err);
32275 } else {
32276 throw err;
32277 }
32278 },
32279
32280 /**
32281 * Define a non-enumberable property on the `Parser` instance.
32282 *
32283 * ```js
32284 * parser.define('foo', 'bar');
32285 * ```
32286 * @name .define
32287 * @param {String} `key` propery name
32288 * @param {any} `val` property value
32289 * @return {Object} Returns the Parser instance for chaining.
32290 * @api public
32291 */
32292
32293 define: function(key, val) {
32294 defineProperty$6(this, key, val);
32295 return this;
32296 },
32297
32298 /**
32299 * Mark position and patch `node.position`.
32300 */
32301
32302 position: function() {
32303 var start = { line: this.line, column: this.column };
32304 var self = this;
32305
32306 return function(node) {
32307 defineProperty$6(node, 'position', new position(start, self));
32308 return node;
32309 };
32310 },
32311
32312 /**
32313 * Set parser `name` with the given `fn`
32314 * @param {String} `name`
32315 * @param {Function} `fn`
32316 * @api public
32317 */
32318
32319 set: function(type, fn) {
32320 if (this.types.indexOf(type) === -1) {
32321 this.types.push(type);
32322 }
32323 this.parsers[type] = fn.bind(this);
32324 return this;
32325 },
32326
32327 /**
32328 * Get parser `name`
32329 * @param {String} `name`
32330 * @api public
32331 */
32332
32333 get: function(name) {
32334 return this.parsers[name];
32335 },
32336
32337 /**
32338 * Push a `token` onto the `type` stack.
32339 *
32340 * @param {String} `type`
32341 * @return {Object} `token`
32342 * @api public
32343 */
32344
32345 push: function(type, token) {
32346 this.sets[type] = this.sets[type] || [];
32347 this.count++;
32348 this.stack.push(token);
32349 return this.sets[type].push(token);
32350 },
32351
32352 /**
32353 * Pop a token off of the `type` stack
32354 * @param {String} `type`
32355 * @returns {Object} Returns a token
32356 * @api public
32357 */
32358
32359 pop: function(type) {
32360 this.sets[type] = this.sets[type] || [];
32361 this.count--;
32362 this.stack.pop();
32363 return this.sets[type].pop();
32364 },
32365
32366 /**
32367 * Return true if inside a `stack` node. Types are `braces`, `parens` or `brackets`.
32368 *
32369 * @param {String} `type`
32370 * @return {Boolean}
32371 * @api public
32372 */
32373
32374 isInside: function(type) {
32375 this.sets[type] = this.sets[type] || [];
32376 return this.sets[type].length > 0;
32377 },
32378
32379 /**
32380 * Return true if `node` is the given `type`.
32381 *
32382 * ```js
32383 * parser.isType(node, 'brace');
32384 * ```
32385 * @param {Object} `node`
32386 * @param {String} `type`
32387 * @return {Boolean}
32388 * @api public
32389 */
32390
32391 isType: function(node, type) {
32392 return node && node.type === type;
32393 },
32394
32395 /**
32396 * Get the previous AST node
32397 * @return {Object}
32398 */
32399
32400 prev: function(n) {
32401 return this.stack.length > 0
32402 ? utils$1.last(this.stack, n)
32403 : utils$1.last(this.nodes, n);
32404 },
32405
32406 /**
32407 * Update line and column based on `str`.
32408 */
32409
32410 consume: function(len) {
32411 this.input = this.input.substr(len);
32412 },
32413
32414 /**
32415 * Update column based on `str`.
32416 */
32417
32418 updatePosition: function(str, len) {
32419 var lines = str.match(/\n/g);
32420 if (lines) this.line += lines.length;
32421 var i = str.lastIndexOf('\n');
32422 this.column = ~i ? len - i : this.column + len;
32423 this.parsed += str;
32424 this.consume(len);
32425 },
32426
32427 /**
32428 * Match `regex`, return captures, and update the cursor position by `match[0]` length.
32429 * @param {RegExp} `regex`
32430 * @return {Object}
32431 */
32432
32433 match: function(regex) {
32434 var m = regex.exec(this.input);
32435 if (m) {
32436 this.updatePosition(m[0], m[0].length);
32437 return m;
32438 }
32439 },
32440
32441 /**
32442 * Capture `type` with the given regex.
32443 * @param {String} `type`
32444 * @param {RegExp} `regex`
32445 * @return {Function}
32446 */
32447
32448 capture: function(type, regex) {
32449 if (typeof regex === 'function') {
32450 return this.set.apply(this, arguments);
32451 }
32452
32453 this.regex.set(type, regex);
32454 this.set(type, function() {
32455 var parsed = this.parsed;
32456 var pos = this.position();
32457 var m = this.match(regex);
32458 if (!m || !m[0]) return;
32459
32460 var prev = this.prev();
32461 var node = pos({
32462 type: type,
32463 val: m[0],
32464 parsed: parsed,
32465 rest: this.input
32466 });
32467
32468 if (m[1]) {
32469 node.inner = m[1];
32470 }
32471
32472 defineProperty$6(node, 'inside', this.stack.length > 0);
32473 defineProperty$6(node, 'parent', prev);
32474 prev.nodes.push(node);
32475 }.bind(this));
32476 return this;
32477 },
32478
32479 /**
32480 * Create a parser with open and close for parens,
32481 * brackets or braces
32482 */
32483
32484 capturePair: function(type, openRegex, closeRegex, fn) {
32485 this.sets[type] = this.sets[type] || [];
32486
32487 /**
32488 * Open
32489 */
32490
32491 this.set(type + '.open', function() {
32492 var parsed = this.parsed;
32493 var pos = this.position();
32494 var m = this.match(openRegex);
32495 if (!m || !m[0]) return;
32496
32497 var val = m[0];
32498 this.setCount++;
32499 this.specialChars = true;
32500 var open = pos({
32501 type: type + '.open',
32502 val: val,
32503 rest: this.input
32504 });
32505
32506 if (typeof m[1] !== 'undefined') {
32507 open.inner = m[1];
32508 }
32509
32510 var prev = this.prev();
32511 var node = pos({
32512 type: type,
32513 nodes: [open]
32514 });
32515
32516 defineProperty$6(node, 'rest', this.input);
32517 defineProperty$6(node, 'parsed', parsed);
32518 defineProperty$6(node, 'prefix', m[1]);
32519 defineProperty$6(node, 'parent', prev);
32520 defineProperty$6(open, 'parent', node);
32521
32522 if (typeof fn === 'function') {
32523 fn.call(this, open, node);
32524 }
32525
32526 this.push(type, node);
32527 prev.nodes.push(node);
32528 });
32529
32530 /**
32531 * Close
32532 */
32533
32534 this.set(type + '.close', function() {
32535 var pos = this.position();
32536 var m = this.match(closeRegex);
32537 if (!m || !m[0]) return;
32538
32539 var parent = this.pop(type);
32540 var node = pos({
32541 type: type + '.close',
32542 rest: this.input,
32543 suffix: m[1],
32544 val: m[0]
32545 });
32546
32547 if (!this.isType(parent, type)) {
32548 if (this.options.strict) {
32549 throw new Error('missing opening "' + type + '"');
32550 }
32551
32552 this.setCount--;
32553 node.escaped = true;
32554 return node;
32555 }
32556
32557 if (node.suffix === '\\') {
32558 parent.escaped = true;
32559 node.escaped = true;
32560 }
32561
32562 parent.nodes.push(node);
32563 defineProperty$6(node, 'parent', parent);
32564 });
32565
32566 return this;
32567 },
32568
32569 /**
32570 * Capture end-of-string
32571 */
32572
32573 eos: function() {
32574 var pos = this.position();
32575 if (this.input) return;
32576 var prev = this.prev();
32577
32578 while (prev.type !== 'root' && !prev.visited) {
32579 if (this.options.strict === true) {
32580 throw new SyntaxError('invalid syntax:' + util$2.inspect(prev, null, 2));
32581 }
32582
32583 if (!hasDelims(prev)) {
32584 prev.parent.escaped = true;
32585 prev.escaped = true;
32586 }
32587
32588 visit(prev, function(node) {
32589 if (!hasDelims(node.parent)) {
32590 node.parent.escaped = true;
32591 node.escaped = true;
32592 }
32593 });
32594
32595 prev = prev.parent;
32596 }
32597
32598 var tok = pos({
32599 type: 'eos',
32600 val: this.append || ''
32601 });
32602
32603 defineProperty$6(tok, 'parent', this.ast);
32604 return tok;
32605 },
32606
32607 /**
32608 * Run parsers to advance the cursor position
32609 */
32610
32611 next: function() {
32612 var parsed = this.parsed;
32613 var len = this.types.length;
32614 var idx = -1;
32615 var tok;
32616
32617 while (++idx < len) {
32618 if ((tok = this.parsers[this.types[idx]].call(this))) {
32619 defineProperty$6(tok, 'rest', this.input);
32620 defineProperty$6(tok, 'parsed', parsed);
32621 this.last = tok;
32622 return tok;
32623 }
32624 }
32625 },
32626
32627 /**
32628 * Parse the given string.
32629 * @return {Array}
32630 */
32631
32632 parse: function(input) {
32633 if (typeof input !== 'string') {
32634 throw new TypeError('expected a string');
32635 }
32636
32637 this.init(this.options);
32638 this.orig = input;
32639 this.input = input;
32640 var self = this;
32641
32642 function parse() {
32643 // check input before calling `.next()`
32644 input = self.input;
32645
32646 // get the next AST ndoe
32647 var node = self.next();
32648 if (node) {
32649 var prev = self.prev();
32650 if (prev) {
32651 defineProperty$6(node, 'parent', prev);
32652 if (prev.nodes) {
32653 prev.nodes.push(node);
32654 }
32655 }
32656
32657 if (self.sets.hasOwnProperty(prev.type)) {
32658 self.currentType = prev.type;
32659 }
32660 }
32661
32662 // if we got here but input is not changed, throw an error
32663 if (self.input && input === self.input) {
32664 throw new Error('no parsers registered for: "' + self.input.slice(0, 5) + '"');
32665 }
32666 }
32667
32668 while (this.input) parse();
32669 if (this.stack.length && this.options.strict) {
32670 var node = this.stack.pop();
32671 throw this.error('missing opening ' + node.type + ': "' + this.orig + '"');
32672 }
32673
32674 var eos = this.eos();
32675 var tok = this.prev();
32676 if (tok.type !== 'eos') {
32677 this.ast.nodes.push(eos);
32678 }
32679
32680 return this.ast;
32681 }
32682};
32683
32684/**
32685 * Visit `node` with the given `fn`
32686 */
32687
32688function visit(node, fn) {
32689 if (!node.visited) {
32690 defineProperty$6(node, 'visited', true);
32691 return node.nodes ? mapVisit$1(node.nodes, fn) : fn(node);
32692 }
32693 return node;
32694}
32695
32696/**
32697 * Map visit over array of `nodes`.
32698 */
32699
32700function mapVisit$1(nodes, fn) {
32701 var len = nodes.length;
32702 var idx = -1;
32703 while (++idx < len) {
32704 visit(nodes[idx], fn);
32705 }
32706}
32707
32708function hasOpen(node) {
32709 return node.nodes && node.nodes[0].type === (node.type + '.open');
32710}
32711
32712function hasClose(node) {
32713 return node.nodes && utils$1.last(node.nodes).type === (node.type + '.close');
32714}
32715
32716function hasDelims(node) {
32717 return hasOpen(node) && hasClose(node);
32718}
32719
32720/**
32721 * Expose `Parser`
32722 */
32723
32724var parser = Parser;
32725
32726/**
32727 * Create a new instance of `Snapdragon` with the given `options`.
32728 *
32729 * ```js
32730 * var snapdragon = new Snapdragon();
32731 * ```
32732 *
32733 * @param {Object} `options`
32734 * @api public
32735 */
32736
32737function Snapdragon(options) {
32738 base$2.call(this, null, options);
32739 this.options = utils$1.extend({source: 'string'}, this.options);
32740 this.compiler = new compiler(this.options);
32741 this.parser = new parser(this.options);
32742
32743 Object.defineProperty(this, 'compilers', {
32744 get: function() {
32745 return this.compiler.compilers;
32746 }
32747 });
32748
32749 Object.defineProperty(this, 'parsers', {
32750 get: function() {
32751 return this.parser.parsers;
32752 }
32753 });
32754
32755 Object.defineProperty(this, 'regex', {
32756 get: function() {
32757 return this.parser.regex;
32758 }
32759 });
32760}
32761
32762/**
32763 * Inherit Base
32764 */
32765
32766base$2.extend(Snapdragon);
32767
32768/**
32769 * Add a parser to `snapdragon.parsers` for capturing the given `type` using
32770 * the specified regex or parser function. A function is useful if you need
32771 * to customize how the token is created and/or have access to the parser
32772 * instance to check options, etc.
32773 *
32774 * ```js
32775 * snapdragon
32776 * .capture('slash', /^\//)
32777 * .capture('dot', function() {
32778 * var pos = this.position();
32779 * var m = this.match(/^\./);
32780 * if (!m) return;
32781 * return pos({
32782 * type: 'dot',
32783 * val: m[0]
32784 * });
32785 * });
32786 * ```
32787 * @param {String} `type`
32788 * @param {RegExp|Function} `regex`
32789 * @return {Object} Returns the parser instance for chaining
32790 * @api public
32791 */
32792
32793Snapdragon.prototype.capture = function() {
32794 return this.parser.capture.apply(this.parser, arguments);
32795};
32796
32797/**
32798 * Register a plugin `fn`.
32799 *
32800 * ```js
32801 * var snapdragon = new Snapdgragon([options]);
32802 * snapdragon.use(function() {
32803 * console.log(this); //<= snapdragon instance
32804 * console.log(this.parser); //<= parser instance
32805 * console.log(this.compiler); //<= compiler instance
32806 * });
32807 * ```
32808 * @param {Object} `fn`
32809 * @api public
32810 */
32811
32812Snapdragon.prototype.use = function(fn) {
32813 fn.call(this, this);
32814 return this;
32815};
32816
32817/**
32818 * Parse the given `str`.
32819 *
32820 * ```js
32821 * var snapdragon = new Snapdgragon([options]);
32822 * // register parsers
32823 * snapdragon.parser.use(function() {});
32824 *
32825 * // parse
32826 * var ast = snapdragon.parse('foo/bar');
32827 * console.log(ast);
32828 * ```
32829 * @param {String} `str`
32830 * @param {Object} `options` Set `options.sourcemap` to true to enable source maps.
32831 * @return {Object} Returns an AST.
32832 * @api public
32833 */
32834
32835Snapdragon.prototype.parse = function(str, options) {
32836 this.options = utils$1.extend({}, this.options, options);
32837 var parsed = this.parser.parse(str, this.options);
32838
32839 // add non-enumerable parser reference
32840 defineProperty$6(parsed, 'parser', this.parser);
32841 return parsed;
32842};
32843
32844/**
32845 * Compile the given `AST`.
32846 *
32847 * ```js
32848 * var snapdragon = new Snapdgragon([options]);
32849 * // register plugins
32850 * snapdragon.use(function() {});
32851 * // register parser plugins
32852 * snapdragon.parser.use(function() {});
32853 * // register compiler plugins
32854 * snapdragon.compiler.use(function() {});
32855 *
32856 * // parse
32857 * var ast = snapdragon.parse('foo/bar');
32858 *
32859 * // compile
32860 * var res = snapdragon.compile(ast);
32861 * console.log(res.output);
32862 * ```
32863 * @param {Object} `ast`
32864 * @param {Object} `options`
32865 * @return {Object} Returns an object with an `output` property with the rendered string.
32866 * @api public
32867 */
32868
32869Snapdragon.prototype.compile = function(ast, options) {
32870 this.options = utils$1.extend({}, this.options, options);
32871 var compiled = this.compiler.compile(ast, this.options);
32872
32873 // add non-enumerable compiler reference
32874 defineProperty$6(compiled, 'compiler', this.compiler);
32875 return compiled;
32876};
32877
32878/**
32879 * Expose `Snapdragon`
32880 */
32881
32882var snapdragon = Snapdragon;
32883
32884/**
32885 * Expose `Parser` and `Compiler`
32886 */
32887
32888var Compiler_1 = compiler;
32889var Parser_1 = parser;
32890snapdragon.Compiler = Compiler_1;
32891snapdragon.Parser = Parser_1;
32892
32893/**
32894 * Customize Snapdragon parser and renderer
32895 */
32896
32897function Braces(options) {
32898 this.options = extendShallow$1({}, options);
32899}
32900
32901/**
32902 * Initialize braces
32903 */
32904
32905Braces.prototype.init = function(options) {
32906 if (this.isInitialized) return;
32907 this.isInitialized = true;
32908 var opts = utils_1.createOptions({}, this.options, options);
32909 this.snapdragon = this.options.snapdragon || new snapdragon(opts);
32910 this.compiler = this.snapdragon.compiler;
32911 this.parser = this.snapdragon.parser;
32912
32913 compilers(this.snapdragon, opts);
32914 parsers(this.snapdragon, opts);
32915
32916 /**
32917 * Call Snapdragon `.parse` method. When AST is returned, we check to
32918 * see if any unclosed braces are left on the stack and, if so, we iterate
32919 * over the stack and correct the AST so that compilers are called in the correct
32920 * order and unbalance braces are properly escaped.
32921 */
32922
32923 utils_1.define(this.snapdragon, 'parse', function(pattern, options) {
32924 var parsed = snapdragon.prototype.parse.apply(this, arguments);
32925 this.parser.ast.input = pattern;
32926
32927 var stack = this.parser.stack;
32928 while (stack.length) {
32929 addParent({type: 'brace.close', val: ''}, stack.pop());
32930 }
32931
32932 function addParent(node, parent) {
32933 utils_1.define(node, 'parent', parent);
32934 parent.nodes.push(node);
32935 }
32936
32937 // add non-enumerable parser reference
32938 utils_1.define(parsed, 'parser', this.parser);
32939 return parsed;
32940 });
32941};
32942
32943/**
32944 * Decorate `.parse` method
32945 */
32946
32947Braces.prototype.parse = function(ast, options) {
32948 if (ast && typeof ast === 'object' && ast.nodes) return ast;
32949 this.init(options);
32950 return this.snapdragon.parse(ast, options);
32951};
32952
32953/**
32954 * Decorate `.compile` method
32955 */
32956
32957Braces.prototype.compile = function(ast, options) {
32958 if (typeof ast === 'string') {
32959 ast = this.parse(ast, options);
32960 } else {
32961 this.init(options);
32962 }
32963 return this.snapdragon.compile(ast, options);
32964};
32965
32966/**
32967 * Expand
32968 */
32969
32970Braces.prototype.expand = function(pattern) {
32971 var ast = this.parse(pattern, {expand: true});
32972 return this.compile(ast, {expand: true});
32973};
32974
32975/**
32976 * Optimize
32977 */
32978
32979Braces.prototype.optimize = function(pattern) {
32980 var ast = this.parse(pattern, {optimize: true});
32981 return this.compile(ast, {optimize: true});
32982};
32983
32984/**
32985 * Expose `Braces`
32986 */
32987
32988var braces = Braces;
32989
32990/**
32991 * Module dependencies
32992 */
32993
32994
32995
32996
32997
32998/**
32999 * Local dependencies
33000 */
33001
33002
33003
33004
33005
33006var MAX_LENGTH$1 = 1024 * 64;
33007var cache$3 = {};
33008
33009/**
33010 * Convert the given `braces` pattern into a regex-compatible string. By default, only one string is generated for every input string. Set `options.expand` to true to return an array of patterns (similar to Bash or minimatch. Before using `options.expand`, it's recommended that you read the [performance notes](#performance)).
33011 *
33012 * ```js
33013 * var braces = require('braces');
33014 * console.log(braces('{a,b,c}'));
33015 * //=> ['(a|b|c)']
33016 *
33017 * console.log(braces('{a,b,c}', {expand: true}));
33018 * //=> ['a', 'b', 'c']
33019 * ```
33020 * @param {String} `str`
33021 * @param {Object} `options`
33022 * @return {String}
33023 * @api public
33024 */
33025
33026function braces$1(pattern, options) {
33027 var key = utils_1.createKey(String(pattern), options);
33028 var arr = [];
33029
33030 var disabled = options && options.cache === false;
33031 if (!disabled && cache$3.hasOwnProperty(key)) {
33032 return cache$3[key];
33033 }
33034
33035 if (Array.isArray(pattern)) {
33036 for (var i = 0; i < pattern.length; i++) {
33037 arr.push.apply(arr, braces$1.create(pattern[i], options));
33038 }
33039 } else {
33040 arr = braces$1.create(pattern, options);
33041 }
33042
33043 if (options && options.nodupes === true) {
33044 arr = arrayUnique(arr);
33045 }
33046
33047 if (!disabled) {
33048 cache$3[key] = arr;
33049 }
33050 return arr;
33051}
33052
33053/**
33054 * Expands a brace pattern into an array. This method is called by the main [braces](#braces) function when `options.expand` is true. Before using this method it's recommended that you read the [performance notes](#performance)) and advantages of using [.optimize](#optimize) instead.
33055 *
33056 * ```js
33057 * var braces = require('braces');
33058 * console.log(braces.expand('a/{b,c}/d'));
33059 * //=> ['a/b/d', 'a/c/d'];
33060 * ```
33061 * @param {String} `pattern` Brace pattern
33062 * @param {Object} `options`
33063 * @return {Array} Returns an array of expanded values.
33064 * @api public
33065 */
33066
33067braces$1.expand = function(pattern, options) {
33068 return braces$1.create(pattern, extendShallow$1({}, options, {expand: true}));
33069};
33070
33071/**
33072 * Expands a brace pattern into a regex-compatible, optimized string. This method is called by the main [braces](#braces) function by default.
33073 *
33074 * ```js
33075 * var braces = require('braces');
33076 * console.log(braces.expand('a/{b,c}/d'));
33077 * //=> ['a/(b|c)/d']
33078 * ```
33079 * @param {String} `pattern` Brace pattern
33080 * @param {Object} `options`
33081 * @return {Array} Returns an array of expanded values.
33082 * @api public
33083 */
33084
33085braces$1.optimize = function(pattern, options) {
33086 return braces$1.create(pattern, options);
33087};
33088
33089/**
33090 * Processes a brace pattern and returns either an expanded array (if `options.expand` is true), a highly optimized regex-compatible string. This method is called by the main [braces](#braces) function.
33091 *
33092 * ```js
33093 * var braces = require('braces');
33094 * console.log(braces.create('user-{200..300}/project-{a,b,c}-{1..10}'))
33095 * //=> 'user-(20[0-9]|2[1-9][0-9]|300)/project-(a|b|c)-([1-9]|10)'
33096 * ```
33097 * @param {String} `pattern` Brace pattern
33098 * @param {Object} `options`
33099 * @return {Array} Returns an array of expanded values.
33100 * @api public
33101 */
33102
33103braces$1.create = function(pattern, options) {
33104 if (typeof pattern !== 'string') {
33105 throw new TypeError('expected a string');
33106 }
33107
33108 var maxLength = (options && options.maxLength) || MAX_LENGTH$1;
33109 if (pattern.length >= maxLength) {
33110 throw new Error('expected pattern to be less than ' + maxLength + ' characters');
33111 }
33112
33113 function create() {
33114 if (pattern === '' || pattern.length < 3) {
33115 return [pattern];
33116 }
33117
33118 if (utils_1.isEmptySets(pattern)) {
33119 return [];
33120 }
33121
33122 if (utils_1.isQuotedString(pattern)) {
33123 return [pattern.slice(1, -1)];
33124 }
33125
33126 var proto = new braces(options);
33127 var result = !options || options.expand !== true
33128 ? proto.optimize(pattern, options)
33129 : proto.expand(pattern, options);
33130
33131 // get the generated pattern(s)
33132 var arr = result.output;
33133
33134 // filter out empty strings if specified
33135 if (options && options.noempty === true) {
33136 arr = arr.filter(Boolean);
33137 }
33138
33139 // filter out duplicates if specified
33140 if (options && options.nodupes === true) {
33141 arr = arrayUnique(arr);
33142 }
33143
33144 Object.defineProperty(arr, 'result', {
33145 enumerable: false,
33146 value: result
33147 });
33148
33149 return arr;
33150 }
33151
33152 return memoize$1('create', pattern, options, create);
33153};
33154
33155/**
33156 * Create a regular expression from the given string `pattern`.
33157 *
33158 * ```js
33159 * var braces = require('braces');
33160 *
33161 * console.log(braces.makeRe('id-{200..300}'));
33162 * //=> /^(?:id-(20[0-9]|2[1-9][0-9]|300))$/
33163 * ```
33164 * @param {String} `pattern` The pattern to convert to regex.
33165 * @param {Object} `options`
33166 * @return {RegExp}
33167 * @api public
33168 */
33169
33170braces$1.makeRe = function(pattern, options) {
33171 if (typeof pattern !== 'string') {
33172 throw new TypeError('expected a string');
33173 }
33174
33175 var maxLength = (options && options.maxLength) || MAX_LENGTH$1;
33176 if (pattern.length >= maxLength) {
33177 throw new Error('expected pattern to be less than ' + maxLength + ' characters');
33178 }
33179
33180 function makeRe() {
33181 var arr = braces$1(pattern, options);
33182 var opts = extendShallow$1({strictErrors: false}, options);
33183 return toRegex$1(arr, opts);
33184 }
33185
33186 return memoize$1('makeRe', pattern, options, makeRe);
33187};
33188
33189/**
33190 * Parse the given `str` with the given `options`.
33191 *
33192 * ```js
33193 * var braces = require('braces');
33194 * var ast = braces.parse('a/{b,c}/d');
33195 * console.log(ast);
33196 * // { type: 'root',
33197 * // errors: [],
33198 * // input: 'a/{b,c}/d',
33199 * // nodes:
33200 * // [ { type: 'bos', val: '' },
33201 * // { type: 'text', val: 'a/' },
33202 * // { type: 'brace',
33203 * // nodes:
33204 * // [ { type: 'brace.open', val: '{' },
33205 * // { type: 'text', val: 'b,c' },
33206 * // { type: 'brace.close', val: '}' } ] },
33207 * // { type: 'text', val: '/d' },
33208 * // { type: 'eos', val: '' } ] }
33209 * ```
33210 * @param {String} `pattern` Brace pattern to parse
33211 * @param {Object} `options`
33212 * @return {Object} Returns an AST
33213 * @api public
33214 */
33215
33216braces$1.parse = function(pattern, options) {
33217 var proto = new braces(options);
33218 return proto.parse(pattern, options);
33219};
33220
33221/**
33222 * Compile the given `ast` or string with the given `options`.
33223 *
33224 * ```js
33225 * var braces = require('braces');
33226 * var ast = braces.parse('a/{b,c}/d');
33227 * console.log(braces.compile(ast));
33228 * // { options: { source: 'string' },
33229 * // state: {},
33230 * // compilers:
33231 * // { eos: [Function],
33232 * // noop: [Function],
33233 * // bos: [Function],
33234 * // brace: [Function],
33235 * // 'brace.open': [Function],
33236 * // text: [Function],
33237 * // 'brace.close': [Function] },
33238 * // output: [ 'a/(b|c)/d' ],
33239 * // ast:
33240 * // { ... },
33241 * // parsingErrors: [] }
33242 * ```
33243 * @param {Object|String} `ast` AST from [.parse](#parse). If a string is passed it will be parsed first.
33244 * @param {Object} `options`
33245 * @return {Object} Returns an object that has an `output` property with the compiled string.
33246 * @api public
33247 */
33248
33249braces$1.compile = function(ast, options) {
33250 var proto = new braces(options);
33251 return proto.compile(ast, options);
33252};
33253
33254/**
33255 * Clear the regex cache.
33256 *
33257 * ```js
33258 * braces.clearCache();
33259 * ```
33260 * @api public
33261 */
33262
33263braces$1.clearCache = function() {
33264 cache$3 = braces$1.cache = {};
33265};
33266
33267/**
33268 * Memoize a generated regex or function. A unique key is generated
33269 * from the method name, pattern, and user-defined options. Set
33270 * options.memoize to false to disable.
33271 */
33272
33273function memoize$1(type, pattern, options, fn) {
33274 var key = utils_1.createKey(type + ':' + pattern, options);
33275 var disabled = options && options.cache === false;
33276 if (disabled) {
33277 braces$1.clearCache();
33278 return fn(pattern, options);
33279 }
33280
33281 if (cache$3.hasOwnProperty(key)) {
33282 return cache$3[key];
33283 }
33284
33285 var res = fn(pattern, options);
33286 cache$3[key] = res;
33287 return res;
33288}
33289
33290/**
33291 * Expose `Braces` constructor and methods
33292 * @type {Function}
33293 */
33294
33295braces$1.Braces = braces;
33296braces$1.compilers = compilers;
33297braces$1.parsers = parsers;
33298braces$1.cache = cache$3;
33299
33300/**
33301 * Expose `braces`
33302 * @type {Function}
33303 */
33304
33305var braces_1 = braces$1;
33306
33307/**
33308* Nanomatch compilers
33309*/
33310
33311var compilers$1 = function(nanomatch, options) {
33312 function slash() {
33313 if (options && typeof options.slash === 'string') {
33314 return options.slash;
33315 }
33316 if (options && typeof options.slash === 'function') {
33317 return options.slash.call(nanomatch);
33318 }
33319 return '\\\\/';
33320 }
33321
33322 function star() {
33323 if (options && typeof options.star === 'string') {
33324 return options.star;
33325 }
33326 if (options && typeof options.star === 'function') {
33327 return options.star.call(nanomatch);
33328 }
33329 return '[^' + slash() + ']*?';
33330 }
33331
33332 var ast = nanomatch.ast = nanomatch.parser.ast;
33333 ast.state = nanomatch.parser.state;
33334 nanomatch.compiler.state = ast.state;
33335 nanomatch.compiler
33336
33337 /**
33338 * Negation / escaping
33339 */
33340
33341 .set('not', function(node) {
33342 var prev = this.prev();
33343 if (this.options.nonegate === true || prev.type !== 'bos') {
33344 return this.emit('\\' + node.val, node);
33345 }
33346 return this.emit(node.val, node);
33347 })
33348 .set('escape', function(node) {
33349 if (this.options.unescape && /^[-\w_.]/.test(node.val)) {
33350 return this.emit(node.val, node);
33351 }
33352 return this.emit('\\' + node.val, node);
33353 })
33354 .set('quoted', function(node) {
33355 return this.emit(node.val, node);
33356 })
33357
33358 /**
33359 * Regex
33360 */
33361
33362 .set('dollar', function(node) {
33363 if (node.parent.type === 'bracket') {
33364 return this.emit(node.val, node);
33365 }
33366 return this.emit('\\' + node.val, node);
33367 })
33368
33369 /**
33370 * Dot: "."
33371 */
33372
33373 .set('dot', function(node) {
33374 if (node.dotfiles === true) this.dotfiles = true;
33375 return this.emit('\\' + node.val, node);
33376 })
33377
33378 /**
33379 * Slashes: "/" and "\"
33380 */
33381
33382 .set('backslash', function(node) {
33383 return this.emit(node.val, node);
33384 })
33385 .set('slash', function(node, nodes, i) {
33386 var val = '[' + slash() + ']';
33387 var parent = node.parent;
33388 var prev = this.prev();
33389
33390 // set "node.hasSlash" to true on all ancestor parens nodes
33391 while (parent.type === 'paren' && !parent.hasSlash) {
33392 parent.hasSlash = true;
33393 parent = parent.parent;
33394 }
33395
33396 if (prev.addQmark) {
33397 val += '?';
33398 }
33399
33400 // word boundary
33401 if (node.rest.slice(0, 2) === '\\b') {
33402 return this.emit(val, node);
33403 }
33404
33405 // globstars
33406 if (node.parsed === '**' || node.parsed === './**') {
33407 this.output = '(?:' + this.output;
33408 return this.emit(val + ')?', node);
33409 }
33410
33411 // negation
33412 if (node.parsed === '!**' && this.options.nonegate !== true) {
33413 return this.emit(val + '?\\b', node);
33414 }
33415 return this.emit(val, node);
33416 })
33417
33418 /**
33419 * Square brackets
33420 */
33421
33422 .set('bracket', function(node) {
33423 var close = node.close;
33424 var open = !node.escaped ? '[' : '\\[';
33425 var negated = node.negated;
33426 var inner = node.inner;
33427 var val = node.val;
33428
33429 if (node.escaped === true) {
33430 inner = inner.replace(/\\?(\W)/g, '\\$1');
33431 negated = '';
33432 }
33433
33434 if (inner === ']-') {
33435 inner = '\\]\\-';
33436 }
33437
33438 if (negated && inner.indexOf('.') === -1) {
33439 inner += '.';
33440 }
33441 if (negated && inner.indexOf('/') === -1) {
33442 inner += '/';
33443 }
33444
33445 val = open + negated + inner + close;
33446 return this.emit(val, node);
33447 })
33448
33449 /**
33450 * Square: "[.]" (only matches a single character in brackets)
33451 */
33452
33453 .set('square', function(node) {
33454 var val = (/^\W/.test(node.val) ? '\\' : '') + node.val;
33455 return this.emit(val, node);
33456 })
33457
33458 /**
33459 * Question mark: "?"
33460 */
33461
33462 .set('qmark', function(node) {
33463 var prev = this.prev();
33464 // don't use "slash" variable so that we always avoid
33465 // matching backslashes and slashes with a qmark
33466 var val = '[^.\\\\/]';
33467 if (this.options.dot || (prev.type !== 'bos' && prev.type !== 'slash')) {
33468 val = '[^\\\\/]';
33469 }
33470
33471 if (node.parsed.slice(-1) === '(') {
33472 var ch = node.rest.charAt(0);
33473 if (ch === '!' || ch === '=' || ch === ':') {
33474 return this.emit(node.val, node);
33475 }
33476 }
33477
33478 if (node.val.length > 1) {
33479 val += '{' + node.val.length + '}';
33480 }
33481 return this.emit(val, node);
33482 })
33483
33484 /**
33485 * Plus
33486 */
33487
33488 .set('plus', function(node) {
33489 var prev = node.parsed.slice(-1);
33490 if (prev === ']' || prev === ')') {
33491 return this.emit(node.val, node);
33492 }
33493 if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) {
33494 return this.emit('\\+', node);
33495 }
33496 var ch = this.output.slice(-1);
33497 if (/\w/.test(ch) && !node.inside) {
33498 return this.emit('+\\+?', node);
33499 }
33500 return this.emit('+', node);
33501 })
33502
33503 /**
33504 * globstar: '**'
33505 */
33506
33507 .set('globstar', function(node, nodes, i) {
33508 if (!this.output) {
33509 this.state.leadingGlobstar = true;
33510 }
33511
33512 var prev = this.prev();
33513 var before = this.prev(2);
33514 var next = this.next();
33515 var after = this.next(2);
33516 var type = prev.type;
33517 var val = node.val;
33518
33519 if (prev.type === 'slash' && next.type === 'slash') {
33520 if (before.type === 'text') {
33521 this.output += '?';
33522
33523 if (after.type !== 'text') {
33524 this.output += '\\b';
33525 }
33526 }
33527 }
33528
33529 var parsed = node.parsed;
33530 if (parsed.charAt(0) === '!') {
33531 parsed = parsed.slice(1);
33532 }
33533
33534 var isInside = node.isInside.paren || node.isInside.brace;
33535 if (parsed && type !== 'slash' && type !== 'bos' && !isInside) {
33536 val = star();
33537 } else {
33538 val = this.options.dot !== true
33539 ? '(?:(?!(?:[' + slash() + ']|^)\\.).)*?'
33540 : '(?:(?!(?:[' + slash() + ']|^)(?:\\.{1,2})($|[' + slash() + ']))(?!\\.{2}).)*?';
33541 }
33542
33543 if ((type === 'slash' || type === 'bos') && this.options.dot !== true) {
33544 val = '(?!\\.)' + val;
33545 }
33546
33547 if (prev.type === 'slash' && next.type === 'slash' && before.type !== 'text') {
33548 if (after.type === 'text' || after.type === 'star') {
33549 node.addQmark = true;
33550 }
33551 }
33552
33553 if (this.options.capture) {
33554 val = '(' + val + ')';
33555 }
33556
33557 return this.emit(val, node);
33558 })
33559
33560 /**
33561 * Star: "*"
33562 */
33563
33564 .set('star', function(node, nodes, i) {
33565 var prior = nodes[i - 2] || {};
33566 var prev = this.prev();
33567 var next = this.next();
33568 var type = prev.type;
33569
33570 function isStart(n) {
33571 return n.type === 'bos' || n.type === 'slash';
33572 }
33573
33574 if (this.output === '' && this.options.contains !== true) {
33575 this.output = '(?![' + slash() + '])';
33576 }
33577
33578 if (type === 'bracket' && this.options.bash === false) {
33579 var str = next && next.type === 'bracket' ? star() : '*?';
33580 if (!prev.nodes || prev.nodes[1].type !== 'posix') {
33581 return this.emit(str, node);
33582 }
33583 }
33584
33585 var prefix = !this.dotfiles && type !== 'text' && type !== 'escape'
33586 ? (this.options.dot ? '(?!(?:^|[' + slash() + '])\\.{1,2}(?:$|[' + slash() + ']))' : '(?!\\.)')
33587 : '';
33588
33589 if (isStart(prev) || (isStart(prior) && type === 'not')) {
33590 if (prefix !== '(?!\\.)') {
33591 prefix += '(?!(\\.{2}|\\.[' + slash() + ']))(?=.)';
33592 } else {
33593 prefix += '(?=.)';
33594 }
33595 } else if (prefix === '(?!\\.)') {
33596 prefix = '';
33597 }
33598
33599 if (prev.type === 'not' && prior.type === 'bos' && this.options.dot === true) {
33600 this.output = '(?!\\.)' + this.output;
33601 }
33602
33603 var output = prefix + star();
33604 if (this.options.capture) {
33605 output = '(' + output + ')';
33606 }
33607
33608 return this.emit(output, node);
33609 })
33610
33611 /**
33612 * Text
33613 */
33614
33615 .set('text', function(node) {
33616 return this.emit(node.val, node);
33617 })
33618
33619 /**
33620 * End-of-string
33621 */
33622
33623 .set('eos', function(node) {
33624 var prev = this.prev();
33625 var val = node.val;
33626
33627 this.output = '(?:\\.[' + slash() + '](?=.))?' + this.output;
33628 if (this.state.metachar && prev.type !== 'qmark' && prev.type !== 'slash') {
33629 val += (this.options.contains ? '[' + slash() + ']?' : '(?:[' + slash() + ']|$)');
33630 }
33631
33632 return this.emit(val, node);
33633 });
33634
33635 /**
33636 * Allow custom compilers to be passed on options
33637 */
33638
33639 if (options && typeof options.compilers === 'function') {
33640 options.compilers(nanomatch.compiler);
33641 }
33642};
33643
33644/**
33645 * Characters to use in negation regex (we want to "not" match
33646 * characters that are matched by other parsers)
33647 */
33648
33649var cached;
33650var NOT_REGEX = '[\\[!*+?$^"\'.\\\\/]+';
33651var not$1 = createTextRegex(NOT_REGEX);
33652
33653/**
33654 * Nanomatch parsers
33655 */
33656
33657var parsers$1 = function(nanomatch, options) {
33658 var parser = nanomatch.parser;
33659 var opts = parser.options;
33660
33661 parser.state = {
33662 slashes: 0,
33663 paths: []
33664 };
33665
33666 parser.ast.state = parser.state;
33667 parser
33668
33669 /**
33670 * Beginning-of-string
33671 */
33672
33673 .capture('prefix', function() {
33674 if (this.parsed) return;
33675 var m = this.match(/^\.[\\/]/);
33676 if (!m) return;
33677 this.state.strictOpen = !!this.options.strictOpen;
33678 this.state.addPrefix = true;
33679 })
33680
33681 /**
33682 * Escape: "\\."
33683 */
33684
33685 .capture('escape', function() {
33686 if (this.isInside('bracket')) return;
33687 var pos = this.position();
33688 var m = this.match(/^(?:\\(.)|([$^]))/);
33689 if (!m) return;
33690
33691 return pos({
33692 type: 'escape',
33693 val: m[2] || m[1]
33694 });
33695 })
33696
33697 /**
33698 * Quoted strings
33699 */
33700
33701 .capture('quoted', function() {
33702 var pos = this.position();
33703 var m = this.match(/^["']/);
33704 if (!m) return;
33705
33706 var quote = m[0];
33707 if (this.input.indexOf(quote) === -1) {
33708 return pos({
33709 type: 'escape',
33710 val: quote
33711 });
33712 }
33713
33714 var tok = advanceTo(this.input, quote);
33715 this.consume(tok.len);
33716
33717 return pos({
33718 type: 'quoted',
33719 val: tok.esc
33720 });
33721 })
33722
33723 /**
33724 * Negations: "!"
33725 */
33726
33727 .capture('not', function() {
33728 var parsed = this.parsed;
33729 var pos = this.position();
33730 var m = this.match(this.notRegex || /^!+/);
33731 if (!m) return;
33732 var val = m[0];
33733
33734 var isNegated = (val.length % 2) === 1;
33735 if (parsed === '' && !isNegated) {
33736 val = '';
33737 }
33738
33739 // if nothing has been parsed, we know `!` is at the start,
33740 // so we need to wrap the result in a negation regex
33741 if (parsed === '' && isNegated && this.options.nonegate !== true) {
33742 this.bos.val = '(?!^(?:';
33743 this.append = ')$).*';
33744 val = '';
33745 }
33746 return pos({
33747 type: 'not',
33748 val: val
33749 });
33750 })
33751
33752 /**
33753 * Dot: "."
33754 */
33755
33756 .capture('dot', function() {
33757 var parsed = this.parsed;
33758 var pos = this.position();
33759 var m = this.match(/^\.+/);
33760 if (!m) return;
33761
33762 var val = m[0];
33763 this.state.dot = val === '.' && (parsed === '' || parsed.slice(-1) === '/');
33764
33765 return pos({
33766 type: 'dot',
33767 dotfiles: this.state.dot,
33768 val: val
33769 });
33770 })
33771
33772 /**
33773 * Plus: "+"
33774 */
33775
33776 .capture('plus', /^\+(?!\()/)
33777
33778 /**
33779 * Question mark: "?"
33780 */
33781
33782 .capture('qmark', function() {
33783 var parsed = this.parsed;
33784 var pos = this.position();
33785 var m = this.match(/^\?+(?!\()/);
33786 if (!m) return;
33787
33788 this.state.metachar = true;
33789 this.state.qmark = true;
33790
33791 return pos({
33792 type: 'qmark',
33793 parsed: parsed,
33794 val: m[0]
33795 });
33796 })
33797
33798 /**
33799 * Globstar: "**"
33800 */
33801
33802 .capture('globstar', function() {
33803 var parsed = this.parsed;
33804 var pos = this.position();
33805 var m = this.match(/^\*{2}(?![*(])(?=[,)/]|$)/);
33806 if (!m) return;
33807
33808 var type = opts.noglobstar !== true ? 'globstar' : 'star';
33809 var node = pos({type: type, parsed: parsed});
33810 this.state.metachar = true;
33811
33812 while (this.input.slice(0, 4) === '/**/') {
33813 this.input = this.input.slice(3);
33814 }
33815
33816 node.isInside = {
33817 brace: this.isInside('brace'),
33818 paren: this.isInside('paren')
33819 };
33820
33821 if (type === 'globstar') {
33822 this.state.globstar = true;
33823 node.val = '**';
33824
33825 } else {
33826 this.state.star = true;
33827 node.val = '*';
33828 }
33829
33830 return node;
33831 })
33832
33833 /**
33834 * Star: "*"
33835 */
33836
33837 .capture('star', function() {
33838 var pos = this.position();
33839 var starRe = /^(?:\*(?![*(])|[*]{3,}(?!\()|[*]{2}(?![(/]|$)|\*(?=\*\())/;
33840 var m = this.match(starRe);
33841 if (!m) return;
33842
33843 this.state.metachar = true;
33844 this.state.star = true;
33845 return pos({
33846 type: 'star',
33847 val: m[0]
33848 });
33849 })
33850
33851 /**
33852 * Slash: "/"
33853 */
33854
33855 .capture('slash', function() {
33856 var pos = this.position();
33857 var m = this.match(/^\//);
33858 if (!m) return;
33859
33860 this.state.slashes++;
33861 return pos({
33862 type: 'slash',
33863 val: m[0]
33864 });
33865 })
33866
33867 /**
33868 * Backslash: "\\"
33869 */
33870
33871 .capture('backslash', function() {
33872 var pos = this.position();
33873 var m = this.match(/^\\(?![*+?(){}[\]'"])/);
33874 if (!m) return;
33875
33876 var val = m[0];
33877
33878 if (this.isInside('bracket')) {
33879 val = '\\';
33880 } else if (val.length > 1) {
33881 val = '\\\\';
33882 }
33883
33884 return pos({
33885 type: 'backslash',
33886 val: val
33887 });
33888 })
33889
33890 /**
33891 * Square: "[.]"
33892 */
33893
33894 .capture('square', function() {
33895 if (this.isInside('bracket')) return;
33896 var pos = this.position();
33897 var m = this.match(/^\[([^!^\\])\]/);
33898 if (!m) return;
33899
33900 return pos({
33901 type: 'square',
33902 val: m[1]
33903 });
33904 })
33905
33906 /**
33907 * Brackets: "[...]" (basic, this can be overridden by other parsers)
33908 */
33909
33910 .capture('bracket', function() {
33911 var pos = this.position();
33912 var m = this.match(/^(?:\[([!^]?)([^\]]+|\]-)(\]|[^*+?]+)|\[)/);
33913 if (!m) return;
33914
33915 var val = m[0];
33916 var negated = m[1] ? '^' : '';
33917 var inner = (m[2] || '').replace(/\\\\+/, '\\\\');
33918 var close = m[3] || '';
33919
33920 if (m[2] && inner.length < m[2].length) {
33921 val = val.replace(/\\\\+/, '\\\\');
33922 }
33923
33924 var esc = this.input.slice(0, 2);
33925 if (inner === '' && esc === '\\]') {
33926 inner += esc;
33927 this.consume(2);
33928
33929 var str = this.input;
33930 var idx = -1;
33931 var ch;
33932
33933 while ((ch = str[++idx])) {
33934 this.consume(1);
33935 if (ch === ']') {
33936 close = ch;
33937 break;
33938 }
33939 inner += ch;
33940 }
33941 }
33942
33943 return pos({
33944 type: 'bracket',
33945 val: val,
33946 escaped: close !== ']',
33947 negated: negated,
33948 inner: inner,
33949 close: close
33950 });
33951 })
33952
33953 /**
33954 * Text
33955 */
33956
33957 .capture('text', function() {
33958 if (this.isInside('bracket')) return;
33959 var pos = this.position();
33960 var m = this.match(not$1);
33961 if (!m || !m[0]) return;
33962
33963 return pos({
33964 type: 'text',
33965 val: m[0]
33966 });
33967 });
33968
33969 /**
33970 * Allow custom parsers to be passed on options
33971 */
33972
33973 if (options && typeof options.parsers === 'function') {
33974 options.parsers(nanomatch.parser);
33975 }
33976};
33977
33978/**
33979 * Advance to the next non-escaped character
33980 */
33981
33982function advanceTo(input, endChar) {
33983 var ch = input.charAt(0);
33984 var tok = { len: 1, val: '', esc: '' };
33985 var idx = 0;
33986
33987 function advance() {
33988 if (ch !== '\\') {
33989 tok.esc += '\\' + ch;
33990 tok.val += ch;
33991 }
33992
33993 ch = input.charAt(++idx);
33994 tok.len++;
33995
33996 if (ch === '\\') {
33997 advance();
33998 advance();
33999 }
34000 }
34001
34002 while (ch && ch !== endChar) {
34003 advance();
34004 }
34005 return tok;
34006}
34007
34008/**
34009 * Create text regex
34010 */
34011
34012function createTextRegex(pattern) {
34013 if (cached) return cached;
34014 var opts = {contains: true, strictClose: false};
34015 var not = regexNot.create(pattern, opts);
34016 var re = toRegex$1('^(?:[*]\\((?=.)|' + not + ')', opts);
34017 return (cached = re);
34018}
34019
34020/**
34021 * Expose negation string
34022 */
34023
34024var not_1 = NOT_REGEX;
34025parsers$1.not = not_1;
34026
34027var fragmentCache = createCommonjsModule(function (module, exports) {
34028
34029
34030
34031/**
34032 * Create a new `FragmentCache` with an optional object to use for `caches`.
34033 *
34034 * ```js
34035 * var fragment = new FragmentCache();
34036 * ```
34037 * @name FragmentCache
34038 * @param {String} `cacheName`
34039 * @return {Object} Returns the [map-cache][] instance.
34040 * @api public
34041 */
34042
34043function FragmentCache(caches) {
34044 this.caches = caches || {};
34045}
34046
34047/**
34048 * Prototype
34049 */
34050
34051FragmentCache.prototype = {
34052
34053 /**
34054 * Get cache `name` from the `fragment.caches` object. Creates a new
34055 * `MapCache` if it doesn't already exist.
34056 *
34057 * ```js
34058 * var cache = fragment.cache('files');
34059 * console.log(fragment.caches.hasOwnProperty('files'));
34060 * //=> true
34061 * ```
34062 * @name .cache
34063 * @param {String} `cacheName`
34064 * @return {Object} Returns the [map-cache][] instance.
34065 * @api public
34066 */
34067
34068 cache: function(cacheName) {
34069 return this.caches[cacheName] || (this.caches[cacheName] = new mapCache());
34070 },
34071
34072 /**
34073 * Set a value for property `key` on cache `name`
34074 *
34075 * ```js
34076 * fragment.set('files', 'somefile.js', new File({path: 'somefile.js'}));
34077 * ```
34078 * @name .set
34079 * @param {String} `name`
34080 * @param {String} `key` Property name to set
34081 * @param {any} `val` The value of `key`
34082 * @return {Object} The cache instance for chaining
34083 * @api public
34084 */
34085
34086 set: function(cacheName, key, val) {
34087 var cache = this.cache(cacheName);
34088 cache.set(key, val);
34089 return cache;
34090 },
34091
34092 /**
34093 * Returns true if a non-undefined value is set for `key` on fragment cache `name`.
34094 *
34095 * ```js
34096 * var cache = fragment.cache('files');
34097 * cache.set('somefile.js');
34098 *
34099 * console.log(cache.has('somefile.js'));
34100 * //=> true
34101 *
34102 * console.log(cache.has('some-other-file.js'));
34103 * //=> false
34104 * ```
34105 * @name .has
34106 * @param {String} `name` Cache name
34107 * @param {String} `key` Optionally specify a property to check for on cache `name`
34108 * @return {Boolean}
34109 * @api public
34110 */
34111
34112 has: function(cacheName, key) {
34113 return typeof this.get(cacheName, key) !== 'undefined';
34114 },
34115
34116 /**
34117 * Get `name`, or if specified, the value of `key`. Invokes the [cache]() method,
34118 * so that cache `name` will be created it doesn't already exist. If `key` is not passed,
34119 * the entire cache (`name`) is returned.
34120 *
34121 * ```js
34122 * var Vinyl = require('vinyl');
34123 * var cache = fragment.cache('files');
34124 * cache.set('somefile.js', new Vinyl({path: 'somefile.js'}));
34125 * console.log(cache.get('somefile.js'));
34126 * //=> <File "somefile.js">
34127 * ```
34128 * @name .get
34129 * @param {String} `name`
34130 * @return {Object} Returns cache `name`, or the value of `key` if specified
34131 * @api public
34132 */
34133
34134 get: function(name, key) {
34135 var cache = this.cache(name);
34136 if (typeof key === 'string') {
34137 return cache.get(key);
34138 }
34139 return cache;
34140 }
34141};
34142
34143/**
34144 * Expose `FragmentCache`
34145 */
34146
34147exports = module.exports = FragmentCache;
34148});
34149
34150var cache$4 = new (fragmentCache)();
34151
34152var isWindows = createCommonjsModule(function (module, exports) {
34153/*!
34154 * is-windows <https://github.com/jonschlinkert/is-windows>
34155 *
34156 * Copyright © 2015-2018, Jon Schlinkert.
34157 * Released under the MIT License.
34158 */
34159
34160(function(factory) {
34161 if (exports && 'object' === 'object' && 'object' !== 'undefined') {
34162 module.exports = factory();
34163 } else if (typeof window !== 'undefined') {
34164 window.isWindows = factory();
34165 } else if (typeof commonjsGlobal !== 'undefined') {
34166 commonjsGlobal.isWindows = factory();
34167 } else if (typeof self !== 'undefined') {
34168 self.isWindows = factory();
34169 } else {
34170 this.isWindows = factory();
34171 }
34172})(function() {
34173 return function isWindows() {
34174 return process && (process.platform === 'win32' || /^(msys|cygwin)$/.test(process.env.OSTYPE));
34175 };
34176});
34177});
34178
34179/*!
34180 * arr-diff <https://github.com/jonschlinkert/arr-diff>
34181 *
34182 * Copyright (c) 2014-2017, Jon Schlinkert.
34183 * Released under the MIT License.
34184 */
34185
34186var arrDiff = function diff(arr/*, arrays*/) {
34187 var len = arguments.length;
34188 var idx = 0;
34189 while (++idx < len) {
34190 arr = diffArray(arr, arguments[idx]);
34191 }
34192 return arr;
34193};
34194
34195function diffArray(one, two) {
34196 if (!Array.isArray(two)) {
34197 return one.slice();
34198 }
34199
34200 var tlen = two.length;
34201 var olen = one.length;
34202 var idx = -1;
34203 var arr = [];
34204
34205 while (++idx < olen) {
34206 var ele = one[idx];
34207
34208 var hasEle = false;
34209 for (var i = 0; i < tlen; i++) {
34210 var val = two[i];
34211
34212 if (ele === val) {
34213 hasEle = true;
34214 break;
34215 }
34216 }
34217
34218 if (hasEle === false) {
34219 arr.push(ele);
34220 }
34221 }
34222 return arr;
34223}
34224
34225var object_pick = function pick(obj, keys) {
34226 if (!isobject(obj) && typeof obj !== 'function') {
34227 return {};
34228 }
34229
34230 var res = {};
34231 if (typeof keys === 'string') {
34232 if (keys in obj) {
34233 res[keys] = obj[keys];
34234 }
34235 return res;
34236 }
34237
34238 var len = keys.length;
34239 var idx = -1;
34240
34241 while (++idx < len) {
34242 var key = keys[idx];
34243 if (key in obj) {
34244 res[key] = obj[key];
34245 }
34246 }
34247 return res;
34248};
34249
34250var utils_1$1 = createCommonjsModule(function (module) {
34251
34252var utils = module.exports;
34253
34254
34255/**
34256 * Module dependencies
34257 */
34258
34259var isWindows$1 = isWindows();
34260
34261utils.define = defineProperty;
34262utils.diff = arrDiff;
34263utils.extend = extendShallow;
34264utils.pick = object_pick;
34265utils.typeOf = kindOf;
34266utils.unique = arrayUnique;
34267
34268/**
34269 * Returns true if the given value is effectively an empty string
34270 */
34271
34272utils.isEmptyString = function(val) {
34273 return String(val) === '' || String(val) === './';
34274};
34275
34276/**
34277 * Returns true if the platform is windows, or `path.sep` is `\\`.
34278 * This is defined as a function to allow `path.sep` to be set in unit tests,
34279 * or by the user, if there is a reason to do so.
34280 * @return {Boolean}
34281 */
34282
34283utils.isWindows = function() {
34284 return path.sep === '\\' || isWindows$1 === true;
34285};
34286
34287/**
34288 * Return the last element from an array
34289 */
34290
34291utils.last = function(arr, n) {
34292 return arr[arr.length - (n || 1)];
34293};
34294
34295/**
34296 * Get the `Snapdragon` instance to use
34297 */
34298
34299utils.instantiate = function(ast, options) {
34300 var snapdragon$1;
34301 // if an instance was created by `.parse`, use that instance
34302 if (utils.typeOf(ast) === 'object' && ast.snapdragon) {
34303 snapdragon$1 = ast.snapdragon;
34304 // if the user supplies an instance on options, use that instance
34305 } else if (utils.typeOf(options) === 'object' && options.snapdragon) {
34306 snapdragon$1 = options.snapdragon;
34307 // create a new instance
34308 } else {
34309 snapdragon$1 = new snapdragon(options);
34310 }
34311
34312 utils.define(snapdragon$1, 'parse', function(str, options) {
34313 var parsed = snapdragon.prototype.parse.call(this, str, options);
34314 parsed.input = str;
34315
34316 // escape unmatched brace/bracket/parens
34317 var last = this.parser.stack.pop();
34318 if (last && this.options.strictErrors !== true) {
34319 var open = last.nodes[0];
34320 var inner = last.nodes[1];
34321 if (last.type === 'bracket') {
34322 if (inner.val.charAt(0) === '[') {
34323 inner.val = '\\' + inner.val;
34324 }
34325
34326 } else {
34327 open.val = '\\' + open.val;
34328 var sibling = open.parent.nodes[1];
34329 if (sibling.type === 'star') {
34330 sibling.loose = true;
34331 }
34332 }
34333 }
34334
34335 // add non-enumerable parser reference
34336 utils.define(parsed, 'parser', this.parser);
34337 return parsed;
34338 });
34339
34340 return snapdragon$1;
34341};
34342
34343/**
34344 * Create the key to use for memoization. The key is generated
34345 * by iterating over the options and concatenating key-value pairs
34346 * to the pattern string.
34347 */
34348
34349utils.createKey = function(pattern, options) {
34350 if (typeof options === 'undefined') {
34351 return pattern;
34352 }
34353 var key = pattern;
34354 for (var prop in options) {
34355 if (options.hasOwnProperty(prop)) {
34356 key += ';' + prop + '=' + String(options[prop]);
34357 }
34358 }
34359 return key;
34360};
34361
34362/**
34363 * Cast `val` to an array
34364 * @return {Array}
34365 */
34366
34367utils.arrayify = function(val) {
34368 if (typeof val === 'string') return [val];
34369 return val ? (Array.isArray(val) ? val : [val]) : [];
34370};
34371
34372/**
34373 * Return true if `val` is a non-empty string
34374 */
34375
34376utils.isString = function(val) {
34377 return typeof val === 'string';
34378};
34379
34380/**
34381 * Return true if `val` is a non-empty string
34382 */
34383
34384utils.isRegex = function(val) {
34385 return utils.typeOf(val) === 'regexp';
34386};
34387
34388/**
34389 * Return true if `val` is a non-empty string
34390 */
34391
34392utils.isObject = function(val) {
34393 return utils.typeOf(val) === 'object';
34394};
34395
34396/**
34397 * Escape regex characters in the given string
34398 */
34399
34400utils.escapeRegex = function(str) {
34401 return str.replace(/[-[\]{}()^$|*+?.\\/\s]/g, '\\$&');
34402};
34403
34404/**
34405 * Combines duplicate characters in the provided `input` string.
34406 * @param {String} `input`
34407 * @returns {String}
34408 */
34409
34410utils.combineDupes = function(input, patterns) {
34411 patterns = utils.arrayify(patterns).join('|').split('|');
34412 patterns = patterns.map(function(s) {
34413 return s.replace(/\\?([+*\\/])/g, '\\$1');
34414 });
34415 var substr = patterns.join('|');
34416 var regex = new RegExp('(' + substr + ')(?=\\1)', 'g');
34417 return input.replace(regex, '');
34418};
34419
34420/**
34421 * Returns true if the given `str` has special characters
34422 */
34423
34424utils.hasSpecialChars = function(str) {
34425 return /(?:(?:(^|\/)[!.])|[*?+()|[\]{}]|[+@]\()/.test(str);
34426};
34427
34428/**
34429 * Normalize slashes in the given filepath.
34430 *
34431 * @param {String} `filepath`
34432 * @return {String}
34433 */
34434
34435utils.toPosixPath = function(str) {
34436 return str.replace(/\\+/g, '/');
34437};
34438
34439/**
34440 * Strip backslashes before special characters in a string.
34441 *
34442 * @param {String} `str`
34443 * @return {String}
34444 */
34445
34446utils.unescape = function(str) {
34447 return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, ''));
34448};
34449
34450/**
34451 * Strip the drive letter from a windows filepath
34452 * @param {String} `fp`
34453 * @return {String}
34454 */
34455
34456utils.stripDrive = function(fp) {
34457 return utils.isWindows() ? fp.replace(/^[a-z]:[\\/]+?/i, '/') : fp;
34458};
34459
34460/**
34461 * Strip the prefix from a filepath
34462 * @param {String} `fp`
34463 * @return {String}
34464 */
34465
34466utils.stripPrefix = function(str) {
34467 if (str.charAt(0) === '.' && (str.charAt(1) === '/' || str.charAt(1) === '\\')) {
34468 return str.slice(2);
34469 }
34470 return str;
34471};
34472
34473/**
34474 * Returns true if `str` is a common character that doesn't need
34475 * to be processed to be used for matching.
34476 * @param {String} `str`
34477 * @return {Boolean}
34478 */
34479
34480utils.isSimpleChar = function(str) {
34481 return str.trim() === '' || str === '.';
34482};
34483
34484/**
34485 * Returns true if the given str is an escaped or
34486 * unescaped path character
34487 */
34488
34489utils.isSlash = function(str) {
34490 return str === '/' || str === '\\/' || str === '\\' || str === '\\\\';
34491};
34492
34493/**
34494 * Returns a function that returns true if the given
34495 * pattern matches or contains a `filepath`
34496 *
34497 * @param {String} `pattern`
34498 * @return {Function}
34499 */
34500
34501utils.matchPath = function(pattern, options) {
34502 return (options && options.contains)
34503 ? utils.containsPattern(pattern, options)
34504 : utils.equalsPattern(pattern, options);
34505};
34506
34507/**
34508 * Returns true if the given (original) filepath or unixified path are equal
34509 * to the given pattern.
34510 */
34511
34512utils._equals = function(filepath, unixPath, pattern) {
34513 return pattern === filepath || pattern === unixPath;
34514};
34515
34516/**
34517 * Returns true if the given (original) filepath or unixified path contain
34518 * the given pattern.
34519 */
34520
34521utils._contains = function(filepath, unixPath, pattern) {
34522 return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;
34523};
34524
34525/**
34526 * Returns a function that returns true if the given
34527 * pattern is the same as a given `filepath`
34528 *
34529 * @param {String} `pattern`
34530 * @return {Function}
34531 */
34532
34533utils.equalsPattern = function(pattern, options) {
34534 var unixify = utils.unixify(options);
34535 options = options || {};
34536
34537 return function fn(filepath) {
34538 var equal = utils._equals(filepath, unixify(filepath), pattern);
34539 if (equal === true || options.nocase !== true) {
34540 return equal;
34541 }
34542 var lower = filepath.toLowerCase();
34543 return utils._equals(lower, unixify(lower), pattern);
34544 };
34545};
34546
34547/**
34548 * Returns a function that returns true if the given
34549 * pattern contains a `filepath`
34550 *
34551 * @param {String} `pattern`
34552 * @return {Function}
34553 */
34554
34555utils.containsPattern = function(pattern, options) {
34556 var unixify = utils.unixify(options);
34557 options = options || {};
34558
34559 return function(filepath) {
34560 var contains = utils._contains(filepath, unixify(filepath), pattern);
34561 if (contains === true || options.nocase !== true) {
34562 return contains;
34563 }
34564 var lower = filepath.toLowerCase();
34565 return utils._contains(lower, unixify(lower), pattern);
34566 };
34567};
34568
34569/**
34570 * Returns a function that returns true if the given
34571 * regex matches the `filename` of a file path.
34572 *
34573 * @param {RegExp} `re` Matching regex
34574 * @return {Function}
34575 */
34576
34577utils.matchBasename = function(re) {
34578 return function(filepath) {
34579 return re.test(filepath) || re.test(path.basename(filepath));
34580 };
34581};
34582
34583/**
34584 * Returns the given value unchanced.
34585 * @return {any}
34586 */
34587
34588utils.identity = function(val) {
34589 return val;
34590};
34591
34592/**
34593 * Determines the filepath to return based on the provided options.
34594 * @return {any}
34595 */
34596
34597utils.value = function(str, unixify, options) {
34598 if (options && options.unixify === false) {
34599 return str;
34600 }
34601 if (options && typeof options.unixify === 'function') {
34602 return options.unixify(str);
34603 }
34604 return unixify(str);
34605};
34606
34607/**
34608 * Returns a function that normalizes slashes in a string to forward
34609 * slashes, strips `./` from beginning of paths, and optionally unescapes
34610 * special characters.
34611 * @return {Function}
34612 */
34613
34614utils.unixify = function(options) {
34615 var opts = options || {};
34616 return function(filepath) {
34617 if (opts.stripPrefix !== false) {
34618 filepath = utils.stripPrefix(filepath);
34619 }
34620 if (opts.unescape === true) {
34621 filepath = utils.unescape(filepath);
34622 }
34623 if (opts.unixify === true || utils.isWindows()) {
34624 filepath = utils.toPosixPath(filepath);
34625 }
34626 return filepath;
34627 };
34628};
34629});
34630
34631/**
34632 * Module dependencies
34633 */
34634
34635
34636
34637
34638
34639/**
34640 * Local dependencies
34641 */
34642
34643
34644
34645
34646
34647var MAX_LENGTH$2 = 1024 * 64;
34648
34649/**
34650 * The main function takes a list of strings and one or more
34651 * glob patterns to use for matching.
34652 *
34653 * ```js
34654 * var nm = require('nanomatch');
34655 * nm(list, patterns[, options]);
34656 *
34657 * console.log(nm(['a.js', 'a.txt'], ['*.js']));
34658 * //=> [ 'a.js' ]
34659 * ```
34660 * @param {Array} `list` A list of strings to match
34661 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34662 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34663 * @return {Array} Returns an array of matches
34664 * @summary false
34665 * @api public
34666 */
34667
34668function nanomatch(list, patterns, options) {
34669 patterns = utils_1$1.arrayify(patterns);
34670 list = utils_1$1.arrayify(list);
34671
34672 var len = patterns.length;
34673 if (list.length === 0 || len === 0) {
34674 return [];
34675 }
34676
34677 if (len === 1) {
34678 return nanomatch.match(list, patterns[0], options);
34679 }
34680
34681 var negated = false;
34682 var omit = [];
34683 var keep = [];
34684 var idx = -1;
34685
34686 while (++idx < len) {
34687 var pattern = patterns[idx];
34688
34689 if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {
34690 omit.push.apply(omit, nanomatch.match(list, pattern.slice(1), options));
34691 negated = true;
34692 } else {
34693 keep.push.apply(keep, nanomatch.match(list, pattern, options));
34694 }
34695 }
34696
34697 // minimatch.match parity
34698 if (negated && keep.length === 0) {
34699 if (options && options.unixify === false) {
34700 keep = list.slice();
34701 } else {
34702 var unixify = utils_1$1.unixify(options);
34703 for (var i = 0; i < list.length; i++) {
34704 keep.push(unixify(list[i]));
34705 }
34706 }
34707 }
34708
34709 var matches = utils_1$1.diff(keep, omit);
34710 if (!options || options.nodupes !== false) {
34711 return utils_1$1.unique(matches);
34712 }
34713
34714 return matches;
34715}
34716
34717/**
34718 * Similar to the main function, but `pattern` must be a string.
34719 *
34720 * ```js
34721 * var nm = require('nanomatch');
34722 * nm.match(list, pattern[, options]);
34723 *
34724 * console.log(nm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
34725 * //=> ['a.a', 'a.aa']
34726 * ```
34727 * @param {Array} `list` Array of strings to match
34728 * @param {String} `pattern` Glob pattern to use for matching.
34729 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34730 * @return {Array} Returns an array of matches
34731 * @api public
34732 */
34733
34734nanomatch.match = function(list, pattern, options) {
34735 if (Array.isArray(pattern)) {
34736 throw new TypeError('expected pattern to be a string');
34737 }
34738
34739 var unixify = utils_1$1.unixify(options);
34740 var isMatch = memoize$2('match', pattern, options, nanomatch.matcher);
34741 var matches = [];
34742
34743 list = utils_1$1.arrayify(list);
34744 var len = list.length;
34745 var idx = -1;
34746
34747 while (++idx < len) {
34748 var ele = list[idx];
34749 if (ele === pattern || isMatch(ele)) {
34750 matches.push(utils_1$1.value(ele, unixify, options));
34751 }
34752 }
34753
34754 // if no options were passed, uniquify results and return
34755 if (typeof options === 'undefined') {
34756 return utils_1$1.unique(matches);
34757 }
34758
34759 if (matches.length === 0) {
34760 if (options.failglob === true) {
34761 throw new Error('no matches found for "' + pattern + '"');
34762 }
34763 if (options.nonull === true || options.nullglob === true) {
34764 return [options.unescape ? utils_1$1.unescape(pattern) : pattern];
34765 }
34766 }
34767
34768 // if `opts.ignore` was defined, diff ignored list
34769 if (options.ignore) {
34770 matches = nanomatch.not(matches, options.ignore, options);
34771 }
34772
34773 return options.nodupes !== false ? utils_1$1.unique(matches) : matches;
34774};
34775
34776/**
34777 * Returns true if the specified `string` matches the given glob `pattern`.
34778 *
34779 * ```js
34780 * var nm = require('nanomatch');
34781 * nm.isMatch(string, pattern[, options]);
34782 *
34783 * console.log(nm.isMatch('a.a', '*.a'));
34784 * //=> true
34785 * console.log(nm.isMatch('a.b', '*.a'));
34786 * //=> false
34787 * ```
34788 * @param {String} `string` String to match
34789 * @param {String} `pattern` Glob pattern to use for matching.
34790 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34791 * @return {Boolean} Returns true if the string matches the glob pattern.
34792 * @api public
34793 */
34794
34795nanomatch.isMatch = function(str, pattern, options) {
34796 if (typeof str !== 'string') {
34797 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
34798 }
34799
34800 if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(pattern)) {
34801 return false;
34802 }
34803
34804 var equals = utils_1$1.equalsPattern(options);
34805 if (equals(str)) {
34806 return true;
34807 }
34808
34809 var isMatch = memoize$2('isMatch', pattern, options, nanomatch.matcher);
34810 return isMatch(str);
34811};
34812
34813/**
34814 * Returns true if some of the elements in the given `list` match any of the
34815 * given glob `patterns`.
34816 *
34817 * ```js
34818 * var nm = require('nanomatch');
34819 * nm.some(list, patterns[, options]);
34820 *
34821 * console.log(nm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
34822 * // true
34823 * console.log(nm.some(['foo.js'], ['*.js', '!foo.js']));
34824 * // false
34825 * ```
34826 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
34827 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34828 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34829 * @return {Boolean} Returns true if any patterns match `str`
34830 * @api public
34831 */
34832
34833nanomatch.some = function(list, patterns, options) {
34834 if (typeof list === 'string') {
34835 list = [list];
34836 }
34837
34838 for (var i = 0; i < list.length; i++) {
34839 if (nanomatch(list[i], patterns, options).length === 1) {
34840 return true;
34841 }
34842 }
34843
34844 return false;
34845};
34846
34847/**
34848 * Returns true if every element in the given `list` matches
34849 * at least one of the given glob `patterns`.
34850 *
34851 * ```js
34852 * var nm = require('nanomatch');
34853 * nm.every(list, patterns[, options]);
34854 *
34855 * console.log(nm.every('foo.js', ['foo.js']));
34856 * // true
34857 * console.log(nm.every(['foo.js', 'bar.js'], ['*.js']));
34858 * // true
34859 * console.log(nm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
34860 * // false
34861 * console.log(nm.every(['foo.js'], ['*.js', '!foo.js']));
34862 * // false
34863 * ```
34864 * @param {String|Array} `list` The string or array of strings to test.
34865 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34866 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34867 * @return {Boolean} Returns true if any patterns match `str`
34868 * @api public
34869 */
34870
34871nanomatch.every = function(list, patterns, options) {
34872 if (typeof list === 'string') {
34873 list = [list];
34874 }
34875
34876 for (var i = 0; i < list.length; i++) {
34877 if (nanomatch(list[i], patterns, options).length !== 1) {
34878 return false;
34879 }
34880 }
34881
34882 return true;
34883};
34884
34885/**
34886 * Returns true if **any** of the given glob `patterns`
34887 * match the specified `string`.
34888 *
34889 * ```js
34890 * var nm = require('nanomatch');
34891 * nm.any(string, patterns[, options]);
34892 *
34893 * console.log(nm.any('a.a', ['b.*', '*.a']));
34894 * //=> true
34895 * console.log(nm.any('a.a', 'b.*'));
34896 * //=> false
34897 * ```
34898 * @param {String|Array} `str` The string to test.
34899 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34900 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34901 * @return {Boolean} Returns true if any patterns match `str`
34902 * @api public
34903 */
34904
34905nanomatch.any = function(str, patterns, options) {
34906 if (typeof str !== 'string') {
34907 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
34908 }
34909
34910 if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(patterns)) {
34911 return false;
34912 }
34913
34914 if (typeof patterns === 'string') {
34915 patterns = [patterns];
34916 }
34917
34918 for (var i = 0; i < patterns.length; i++) {
34919 if (nanomatch.isMatch(str, patterns[i], options)) {
34920 return true;
34921 }
34922 }
34923 return false;
34924};
34925
34926/**
34927 * Returns true if **all** of the given `patterns`
34928 * match the specified string.
34929 *
34930 * ```js
34931 * var nm = require('nanomatch');
34932 * nm.all(string, patterns[, options]);
34933 *
34934 * console.log(nm.all('foo.js', ['foo.js']));
34935 * // true
34936 *
34937 * console.log(nm.all('foo.js', ['*.js', '!foo.js']));
34938 * // false
34939 *
34940 * console.log(nm.all('foo.js', ['*.js', 'foo.js']));
34941 * // true
34942 *
34943 * console.log(nm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
34944 * // true
34945 * ```
34946 * @param {String|Array} `str` The string to test.
34947 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
34948 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34949 * @return {Boolean} Returns true if any patterns match `str`
34950 * @api public
34951 */
34952
34953nanomatch.all = function(str, patterns, options) {
34954 if (typeof str !== 'string') {
34955 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
34956 }
34957
34958 if (typeof patterns === 'string') {
34959 patterns = [patterns];
34960 }
34961
34962 for (var i = 0; i < patterns.length; i++) {
34963 if (!nanomatch.isMatch(str, patterns[i], options)) {
34964 return false;
34965 }
34966 }
34967 return true;
34968};
34969
34970/**
34971 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
34972 *
34973 * ```js
34974 * var nm = require('nanomatch');
34975 * nm.not(list, patterns[, options]);
34976 *
34977 * console.log(nm.not(['a.a', 'b.b', 'c.c'], '*.a'));
34978 * //=> ['b.b', 'c.c']
34979 * ```
34980 * @param {Array} `list` Array of strings to match.
34981 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
34982 * @param {Object} `options` See available [options](#options) for changing how matches are performed
34983 * @return {Array} Returns an array of strings that **do not match** the given patterns.
34984 * @api public
34985 */
34986
34987nanomatch.not = function(list, patterns, options) {
34988 var opts = extendShallow({}, options);
34989 var ignore = opts.ignore;
34990 delete opts.ignore;
34991
34992 list = utils_1$1.arrayify(list);
34993
34994 var matches = utils_1$1.diff(list, nanomatch(list, patterns, opts));
34995 if (ignore) {
34996 matches = utils_1$1.diff(matches, nanomatch(list, ignore));
34997 }
34998
34999 return opts.nodupes !== false ? utils_1$1.unique(matches) : matches;
35000};
35001
35002/**
35003 * Returns true if the given `string` contains the given pattern. Similar
35004 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
35005 *
35006 * ```js
35007 * var nm = require('nanomatch');
35008 * nm.contains(string, pattern[, options]);
35009 *
35010 * console.log(nm.contains('aa/bb/cc', '*b'));
35011 * //=> true
35012 * console.log(nm.contains('aa/bb/cc', '*d'));
35013 * //=> false
35014 * ```
35015 * @param {String} `str` The string to match.
35016 * @param {String|Array} `patterns` Glob pattern to use for matching.
35017 * @param {Object} `options` See available [options](#options) for changing how matches are performed
35018 * @return {Boolean} Returns true if the patter matches any part of `str`.
35019 * @api public
35020 */
35021
35022nanomatch.contains = function(str, patterns, options) {
35023 if (typeof str !== 'string') {
35024 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
35025 }
35026
35027 if (typeof patterns === 'string') {
35028 if (utils_1$1.isEmptyString(str) || utils_1$1.isEmptyString(patterns)) {
35029 return false;
35030 }
35031
35032 var equals = utils_1$1.equalsPattern(patterns, options);
35033 if (equals(str)) {
35034 return true;
35035 }
35036 var contains = utils_1$1.containsPattern(patterns, options);
35037 if (contains(str)) {
35038 return true;
35039 }
35040 }
35041
35042 var opts = extendShallow({}, options, {contains: true});
35043 return nanomatch.any(str, patterns, opts);
35044};
35045
35046/**
35047 * Returns true if the given pattern and options should enable
35048 * the `matchBase` option.
35049 * @return {Boolean}
35050 * @api private
35051 */
35052
35053nanomatch.matchBase = function(pattern, options) {
35054 if (pattern && pattern.indexOf('/') !== -1 || !options) return false;
35055 return options.basename === true || options.matchBase === true;
35056};
35057
35058/**
35059 * Filter the keys of the given object with the given `glob` pattern
35060 * and `options`. Does not attempt to match nested keys. If you need this feature,
35061 * use [glob-object][] instead.
35062 *
35063 * ```js
35064 * var nm = require('nanomatch');
35065 * nm.matchKeys(object, patterns[, options]);
35066 *
35067 * var obj = { aa: 'a', ab: 'b', ac: 'c' };
35068 * console.log(nm.matchKeys(obj, '*b'));
35069 * //=> { ab: 'b' }
35070 * ```
35071 * @param {Object} `object` The object with keys to filter.
35072 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
35073 * @param {Object} `options` See available [options](#options) for changing how matches are performed
35074 * @return {Object} Returns an object with only keys that match the given patterns.
35075 * @api public
35076 */
35077
35078nanomatch.matchKeys = function(obj, patterns, options) {
35079 if (!utils_1$1.isObject(obj)) {
35080 throw new TypeError('expected the first argument to be an object');
35081 }
35082 var keys = nanomatch(Object.keys(obj), patterns, options);
35083 return utils_1$1.pick(obj, keys);
35084};
35085
35086/**
35087 * Returns a memoized matcher function from the given glob `pattern` and `options`.
35088 * The returned function takes a string to match as its only argument and returns
35089 * true if the string is a match.
35090 *
35091 * ```js
35092 * var nm = require('nanomatch');
35093 * nm.matcher(pattern[, options]);
35094 *
35095 * var isMatch = nm.matcher('*.!(*a)');
35096 * console.log(isMatch('a.a'));
35097 * //=> false
35098 * console.log(isMatch('a.b'));
35099 * //=> true
35100 * ```
35101 * @param {String} `pattern` Glob pattern
35102 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
35103 * @return {Function} Returns a matcher function.
35104 * @api public
35105 */
35106
35107nanomatch.matcher = function matcher(pattern, options) {
35108 if (utils_1$1.isEmptyString(pattern)) {
35109 return function() {
35110 return false;
35111 };
35112 }
35113
35114 if (Array.isArray(pattern)) {
35115 return compose(pattern, options, matcher);
35116 }
35117
35118 // if pattern is a regex
35119 if (pattern instanceof RegExp) {
35120 return test(pattern);
35121 }
35122
35123 // if pattern is invalid
35124 if (!utils_1$1.isString(pattern)) {
35125 throw new TypeError('expected pattern to be an array, string or regex');
35126 }
35127
35128 // if pattern is a non-glob string
35129 if (!utils_1$1.hasSpecialChars(pattern)) {
35130 if (options && options.nocase === true) {
35131 pattern = pattern.toLowerCase();
35132 }
35133 return utils_1$1.matchPath(pattern, options);
35134 }
35135
35136 // if pattern is a glob string
35137 var re = nanomatch.makeRe(pattern, options);
35138
35139 // if `options.matchBase` or `options.basename` is defined
35140 if (nanomatch.matchBase(pattern, options)) {
35141 return utils_1$1.matchBasename(re, options);
35142 }
35143
35144 function test(regex) {
35145 var equals = utils_1$1.equalsPattern(options);
35146 var unixify = utils_1$1.unixify(options);
35147
35148 return function(str) {
35149 if (equals(str)) {
35150 return true;
35151 }
35152
35153 if (regex.test(unixify(str))) {
35154 return true;
35155 }
35156 return false;
35157 };
35158 }
35159
35160 // create matcher function
35161 var matcherFn = test(re);
35162 // set result object from compiler on matcher function,
35163 // as a non-enumerable property. useful for debugging
35164 utils_1$1.define(matcherFn, 'result', re.result);
35165 return matcherFn;
35166};
35167
35168/**
35169 * Returns an array of matches captured by `pattern` in `string, or
35170 * `null` if the pattern did not match.
35171 *
35172 * ```js
35173 * var nm = require('nanomatch');
35174 * nm.capture(pattern, string[, options]);
35175 *
35176 * console.log(nm.capture('test/*.js', 'test/foo.js'));
35177 * //=> ['foo']
35178 * console.log(nm.capture('test/*.js', 'foo/bar.css'));
35179 * //=> null
35180 * ```
35181 * @param {String} `pattern` Glob pattern to use for matching.
35182 * @param {String} `string` String to match
35183 * @param {Object} `options` See available [options](#options) for changing how matches are performed
35184 * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
35185 * @api public
35186 */
35187
35188nanomatch.capture = function(pattern, str, options) {
35189 var re = nanomatch.makeRe(pattern, extendShallow({capture: true}, options));
35190 var unixify = utils_1$1.unixify(options);
35191
35192 function match() {
35193 return function(string) {
35194 var match = re.exec(unixify(string));
35195 if (!match) {
35196 return null;
35197 }
35198
35199 return match.slice(1);
35200 };
35201 }
35202
35203 var capture = memoize$2('capture', pattern, options, match);
35204 return capture(str);
35205};
35206
35207/**
35208 * Create a regular expression from the given glob `pattern`.
35209 *
35210 * ```js
35211 * var nm = require('nanomatch');
35212 * nm.makeRe(pattern[, options]);
35213 *
35214 * console.log(nm.makeRe('*.js'));
35215 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
35216 * ```
35217 * @param {String} `pattern` A glob pattern to convert to regex.
35218 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
35219 * @return {RegExp} Returns a regex created from the given pattern.
35220 * @api public
35221 */
35222
35223nanomatch.makeRe = function(pattern, options) {
35224 if (pattern instanceof RegExp) {
35225 return pattern;
35226 }
35227
35228 if (typeof pattern !== 'string') {
35229 throw new TypeError('expected pattern to be a string');
35230 }
35231
35232 if (pattern.length > MAX_LENGTH$2) {
35233 throw new Error('expected pattern to be less than ' + MAX_LENGTH$2 + ' characters');
35234 }
35235
35236 function makeRe() {
35237 var opts = utils_1$1.extend({wrap: false}, options);
35238 var result = nanomatch.create(pattern, opts);
35239 var regex = toRegex$1(result.output, opts);
35240 utils_1$1.define(regex, 'result', result);
35241 return regex;
35242 }
35243
35244 return memoize$2('makeRe', pattern, options, makeRe);
35245};
35246
35247/**
35248 * Parses the given glob `pattern` and returns an object with the compiled `output`
35249 * and optional source `map`.
35250 *
35251 * ```js
35252 * var nm = require('nanomatch');
35253 * nm.create(pattern[, options]);
35254 *
35255 * console.log(nm.create('abc/*.js'));
35256 * // { options: { source: 'string', sourcemap: true },
35257 * // state: {},
35258 * // compilers:
35259 * // { ... },
35260 * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
35261 * // ast:
35262 * // { type: 'root',
35263 * // errors: [],
35264 * // nodes:
35265 * // [ ... ],
35266 * // dot: false,
35267 * // input: 'abc/*.js' },
35268 * // parsingErrors: [],
35269 * // map:
35270 * // { version: 3,
35271 * // sources: [ 'string' ],
35272 * // names: [],
35273 * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
35274 * // sourcesContent: [ 'abc/*.js' ] },
35275 * // position: { line: 1, column: 28 },
35276 * // content: {},
35277 * // files: {},
35278 * // idx: 6 }
35279 * ```
35280 * @param {String} `pattern` Glob pattern to parse and compile.
35281 * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.
35282 * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.
35283 * @api public
35284 */
35285
35286nanomatch.create = function(pattern, options) {
35287 if (typeof pattern !== 'string') {
35288 throw new TypeError('expected a string');
35289 }
35290 function create() {
35291 return nanomatch.compile(nanomatch.parse(pattern, options), options);
35292 }
35293 return memoize$2('create', pattern, options, create);
35294};
35295
35296/**
35297 * Parse the given `str` with the given `options`.
35298 *
35299 * ```js
35300 * var nm = require('nanomatch');
35301 * nm.parse(pattern[, options]);
35302 *
35303 * var ast = nm.parse('a/{b,c}/d');
35304 * console.log(ast);
35305 * // { type: 'root',
35306 * // errors: [],
35307 * // input: 'a/{b,c}/d',
35308 * // nodes:
35309 * // [ { type: 'bos', val: '' },
35310 * // { type: 'text', val: 'a/' },
35311 * // { type: 'brace',
35312 * // nodes:
35313 * // [ { type: 'brace.open', val: '{' },
35314 * // { type: 'text', val: 'b,c' },
35315 * // { type: 'brace.close', val: '}' } ] },
35316 * // { type: 'text', val: '/d' },
35317 * // { type: 'eos', val: '' } ] }
35318 * ```
35319 * @param {String} `str`
35320 * @param {Object} `options`
35321 * @return {Object} Returns an AST
35322 * @api public
35323 */
35324
35325nanomatch.parse = function(pattern, options) {
35326 if (typeof pattern !== 'string') {
35327 throw new TypeError('expected a string');
35328 }
35329
35330 function parse() {
35331 var snapdragon = utils_1$1.instantiate(null, options);
35332 parsers$1(snapdragon, options);
35333
35334 var ast = snapdragon.parse(pattern, options);
35335 utils_1$1.define(ast, 'snapdragon', snapdragon);
35336 ast.input = pattern;
35337 return ast;
35338 }
35339
35340 return memoize$2('parse', pattern, options, parse);
35341};
35342
35343/**
35344 * Compile the given `ast` or string with the given `options`.
35345 *
35346 * ```js
35347 * var nm = require('nanomatch');
35348 * nm.compile(ast[, options]);
35349 *
35350 * var ast = nm.parse('a/{b,c}/d');
35351 * console.log(nm.compile(ast));
35352 * // { options: { source: 'string' },
35353 * // state: {},
35354 * // compilers:
35355 * // { eos: [Function],
35356 * // noop: [Function],
35357 * // bos: [Function],
35358 * // brace: [Function],
35359 * // 'brace.open': [Function],
35360 * // text: [Function],
35361 * // 'brace.close': [Function] },
35362 * // output: [ 'a/(b|c)/d' ],
35363 * // ast:
35364 * // { ... },
35365 * // parsingErrors: [] }
35366 * ```
35367 * @param {Object|String} `ast`
35368 * @param {Object} `options`
35369 * @return {Object} Returns an object that has an `output` property with the compiled string.
35370 * @api public
35371 */
35372
35373nanomatch.compile = function(ast, options) {
35374 if (typeof ast === 'string') {
35375 ast = nanomatch.parse(ast, options);
35376 }
35377
35378 function compile() {
35379 var snapdragon = utils_1$1.instantiate(ast, options);
35380 compilers$1(snapdragon, options);
35381 return snapdragon.compile(ast, options);
35382 }
35383
35384 return memoize$2('compile', ast.input, options, compile);
35385};
35386
35387/**
35388 * Clear the regex cache.
35389 *
35390 * ```js
35391 * nm.clearCache();
35392 * ```
35393 * @api public
35394 */
35395
35396nanomatch.clearCache = function() {
35397 nanomatch.cache.__data__ = {};
35398};
35399
35400/**
35401 * Compose a matcher function with the given patterns.
35402 * This allows matcher functions to be compiled once and
35403 * called multiple times.
35404 */
35405
35406function compose(patterns, options, matcher) {
35407 var matchers;
35408
35409 return memoize$2('compose', String(patterns), options, function() {
35410 return function(file) {
35411 // delay composition until it's invoked the first time,
35412 // after that it won't be called again
35413 if (!matchers) {
35414 matchers = [];
35415 for (var i = 0; i < patterns.length; i++) {
35416 matchers.push(matcher(patterns[i], options));
35417 }
35418 }
35419
35420 var len = matchers.length;
35421 while (len--) {
35422 if (matchers[len](file) === true) {
35423 return true;
35424 }
35425 }
35426 return false;
35427 };
35428 });
35429}
35430
35431/**
35432 * Memoize a generated regex or function. A unique key is generated
35433 * from the `type` (usually method name), the `pattern`, and
35434 * user-defined options.
35435 */
35436
35437function memoize$2(type, pattern, options, fn) {
35438 var key = utils_1$1.createKey(type + '=' + pattern, options);
35439
35440 if (options && options.cache === false) {
35441 return fn(pattern, options);
35442 }
35443
35444 if (cache$4.has(type, key)) {
35445 return cache$4.get(type, key);
35446 }
35447
35448 var val = fn(pattern, options);
35449 cache$4.set(type, key, val);
35450 return val;
35451}
35452
35453/**
35454 * Expose compiler, parser and cache on `nanomatch`
35455 */
35456
35457nanomatch.compilers = compilers$1;
35458nanomatch.parsers = parsers$1;
35459nanomatch.cache = cache$4;
35460
35461/**
35462 * Expose `nanomatch`
35463 * @type {Function}
35464 */
35465
35466var nanomatch_1 = nanomatch;
35467
35468var extendShallow$6 = function extend(o/*, objects*/) {
35469 if (!isExtendable$1(o)) { o = {}; }
35470
35471 var len = arguments.length;
35472 for (var i = 1; i < len; i++) {
35473 var obj = arguments[i];
35474
35475 if (isExtendable$1(obj)) {
35476 assign$6(o, obj);
35477 }
35478 }
35479 return o;
35480};
35481
35482function assign$6(a, b) {
35483 for (var key in b) {
35484 if (hasOwn$7(b, key)) {
35485 a[key] = b[key];
35486 }
35487 }
35488}
35489
35490/**
35491 * Returns true if the given `key` is an own property of `obj`.
35492 */
35493
35494function hasOwn$7(obj, key) {
35495 return Object.prototype.hasOwnProperty.call(obj, key);
35496}
35497
35498/**
35499 * POSIX character classes
35500 */
35501
35502var posixCharacterClasses = {
35503 alnum: 'a-zA-Z0-9',
35504 alpha: 'a-zA-Z',
35505 ascii: '\\x00-\\x7F',
35506 blank: ' \\t',
35507 cntrl: '\\x00-\\x1F\\x7F',
35508 digit: '0-9',
35509 graph: '\\x21-\\x7E',
35510 lower: 'a-z',
35511 print: '\\x20-\\x7E ',
35512 punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
35513 space: ' \\t\\r\\n\\v\\f',
35514 upper: 'A-Z',
35515 word: 'A-Za-z0-9_',
35516 xdigit: 'A-Fa-f0-9'
35517};
35518
35519var compilers$2 = function(brackets) {
35520 brackets.compiler
35521
35522 /**
35523 * Escaped characters
35524 */
35525
35526 .set('escape', function(node) {
35527 return this.emit('\\' + node.val.replace(/^\\/, ''), node);
35528 })
35529
35530 /**
35531 * Text
35532 */
35533
35534 .set('text', function(node) {
35535 return this.emit(node.val.replace(/([{}])/g, '\\$1'), node);
35536 })
35537
35538 /**
35539 * POSIX character classes
35540 */
35541
35542 .set('posix', function(node) {
35543 if (node.val === '[::]') {
35544 return this.emit('\\[::\\]', node);
35545 }
35546
35547 var val = posixCharacterClasses[node.inner];
35548 if (typeof val === 'undefined') {
35549 val = '[' + node.inner + ']';
35550 }
35551 return this.emit(val, node);
35552 })
35553
35554 /**
35555 * Non-posix brackets
35556 */
35557
35558 .set('bracket', function(node) {
35559 return this.mapVisit(node.nodes);
35560 })
35561 .set('bracket.open', function(node) {
35562 return this.emit(node.val, node);
35563 })
35564 .set('bracket.inner', function(node) {
35565 var inner = node.val;
35566
35567 if (inner === '[' || inner === ']') {
35568 return this.emit('\\' + node.val, node);
35569 }
35570 if (inner === '^]') {
35571 return this.emit('^\\]', node);
35572 }
35573 if (inner === '^') {
35574 return this.emit('^', node);
35575 }
35576
35577 if (/-/.test(inner) && !/(\d-\d|\w-\w)/.test(inner)) {
35578 inner = inner.split('-').join('\\-');
35579 }
35580
35581 var isNegated = inner.charAt(0) === '^';
35582 // add slashes to negated brackets, per spec
35583 if (isNegated && inner.indexOf('/') === -1) {
35584 inner += '/';
35585 }
35586 if (isNegated && inner.indexOf('.') === -1) {
35587 inner += '.';
35588 }
35589
35590 // don't unescape `0` (octal literal)
35591 inner = inner.replace(/\\([1-9])/g, '$1');
35592 return this.emit(inner, node);
35593 })
35594 .set('bracket.close', function(node) {
35595 var val = node.val.replace(/^\\/, '');
35596 if (node.parent.escaped === true) {
35597 return this.emit('\\' + val, node);
35598 }
35599 return this.emit(val, node);
35600 });
35601};
35602
35603var cached$1;
35604
35605/**
35606 * Get the last element from `array`
35607 * @param {Array} `array`
35608 * @return {*}
35609 */
35610
35611var last$1 = function(arr) {
35612 return arr[arr.length - 1];
35613};
35614
35615/**
35616 * Create and cache regex to use for text nodes
35617 */
35618
35619var createRegex = function(pattern, include) {
35620 if (cached$1) return cached$1;
35621 var opts = {contains: true, strictClose: false};
35622 var not = regexNot.create(pattern, opts);
35623 var re;
35624
35625 if (typeof include === 'string') {
35626 re = toRegex$1('^(?:' + include + '|' + not + ')', opts);
35627 } else {
35628 re = toRegex$1(not, opts);
35629 }
35630
35631 return (cached$1 = re);
35632};
35633
35634var utils$2 = {
35635 last: last$1,
35636 createRegex: createRegex
35637};
35638
35639var defineProperty$7 = function defineProperty(obj, prop, val) {
35640 if (typeof obj !== 'object' && typeof obj !== 'function') {
35641 throw new TypeError('expected an object or function.');
35642 }
35643
35644 if (typeof prop !== 'string') {
35645 throw new TypeError('expected `prop` to be a string.');
35646 }
35647
35648 if (isDescriptor$3(val) && ('set' in val || 'get' in val)) {
35649 return Object.defineProperty(obj, prop, val);
35650 }
35651
35652 return Object.defineProperty(obj, prop, {
35653 configurable: true,
35654 enumerable: false,
35655 writable: true,
35656 value: val
35657 });
35658};
35659
35660/**
35661 * Text regex
35662 */
35663
35664var TEXT_REGEX = '(\\[(?=.*\\])|\\])+';
35665var not$2 = utils$2.createRegex(TEXT_REGEX);
35666
35667/**
35668 * Brackets parsers
35669 */
35670
35671function parsers$2(brackets) {
35672 brackets.state = brackets.state || {};
35673 brackets.parser.sets.bracket = brackets.parser.sets.bracket || [];
35674 brackets.parser
35675
35676 .capture('escape', function() {
35677 if (this.isInside('bracket')) return;
35678 var pos = this.position();
35679 var m = this.match(/^\\(.)/);
35680 if (!m) return;
35681
35682 return pos({
35683 type: 'escape',
35684 val: m[0]
35685 });
35686 })
35687
35688 /**
35689 * Text parser
35690 */
35691
35692 .capture('text', function() {
35693 if (this.isInside('bracket')) return;
35694 var pos = this.position();
35695 var m = this.match(not$2);
35696 if (!m || !m[0]) return;
35697
35698 return pos({
35699 type: 'text',
35700 val: m[0]
35701 });
35702 })
35703
35704 /**
35705 * POSIX character classes: "[[:alpha:][:digits:]]"
35706 */
35707
35708 .capture('posix', function() {
35709 var pos = this.position();
35710 var m = this.match(/^\[:(.*?):\](?=.*\])/);
35711 if (!m) return;
35712
35713 var inside = this.isInside('bracket');
35714 if (inside) {
35715 brackets.posix++;
35716 }
35717
35718 return pos({
35719 type: 'posix',
35720 insideBracket: inside,
35721 inner: m[1],
35722 val: m[0]
35723 });
35724 })
35725
35726 /**
35727 * Bracket (noop)
35728 */
35729
35730 .capture('bracket', function() {})
35731
35732 /**
35733 * Open: '['
35734 */
35735
35736 .capture('bracket.open', function() {
35737 var parsed = this.parsed;
35738 var pos = this.position();
35739 var m = this.match(/^\[(?=.*\])/);
35740 if (!m) return;
35741
35742 var prev = this.prev();
35743 var last = utils$2.last(prev.nodes);
35744
35745 if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) {
35746 last.val = last.val.slice(0, last.val.length - 1);
35747 return pos({
35748 type: 'escape',
35749 val: m[0]
35750 });
35751 }
35752
35753 var open = pos({
35754 type: 'bracket.open',
35755 val: m[0]
35756 });
35757
35758 if (last.type === 'bracket.open' || this.isInside('bracket')) {
35759 open.val = '\\' + open.val;
35760 open.type = 'bracket.inner';
35761 open.escaped = true;
35762 return open;
35763 }
35764
35765 var node = pos({
35766 type: 'bracket',
35767 nodes: [open]
35768 });
35769
35770 defineProperty$7(node, 'parent', prev);
35771 defineProperty$7(open, 'parent', node);
35772 this.push('bracket', node);
35773 prev.nodes.push(node);
35774 })
35775
35776 /**
35777 * Bracket text
35778 */
35779
35780 .capture('bracket.inner', function() {
35781 if (!this.isInside('bracket')) return;
35782 var pos = this.position();
35783 var m = this.match(not$2);
35784 if (!m || !m[0]) return;
35785
35786 var next = this.input.charAt(0);
35787 var val = m[0];
35788
35789 var node = pos({
35790 type: 'bracket.inner',
35791 val: val
35792 });
35793
35794 if (val === '\\\\') {
35795 return node;
35796 }
35797
35798 var first = val.charAt(0);
35799 var last = val.slice(-1);
35800
35801 if (first === '!') {
35802 val = '^' + val.slice(1);
35803 }
35804
35805 if (last === '\\' || (val === '^' && next === ']')) {
35806 val += this.input[0];
35807 this.consume(1);
35808 }
35809
35810 node.val = val;
35811 return node;
35812 })
35813
35814 /**
35815 * Close: ']'
35816 */
35817
35818 .capture('bracket.close', function() {
35819 var parsed = this.parsed;
35820 var pos = this.position();
35821 var m = this.match(/^\]/);
35822 if (!m) return;
35823
35824 var prev = this.prev();
35825 var last = utils$2.last(prev.nodes);
35826
35827 if (parsed.slice(-1) === '\\' && !this.isInside('bracket')) {
35828 last.val = last.val.slice(0, last.val.length - 1);
35829
35830 return pos({
35831 type: 'escape',
35832 val: m[0]
35833 });
35834 }
35835
35836 var node = pos({
35837 type: 'bracket.close',
35838 rest: this.input,
35839 val: m[0]
35840 });
35841
35842 if (last.type === 'bracket.open') {
35843 node.type = 'bracket.inner';
35844 node.escaped = true;
35845 return node;
35846 }
35847
35848 var bracket = this.pop('bracket');
35849 if (!this.isType(bracket, 'bracket')) {
35850 if (this.options.strict) {
35851 throw new Error('missing opening "["');
35852 }
35853 node.type = 'bracket.inner';
35854 node.escaped = true;
35855 return node;
35856 }
35857
35858 bracket.nodes.push(node);
35859 defineProperty$7(node, 'parent', bracket);
35860 });
35861}
35862
35863/**
35864 * Brackets parsers
35865 */
35866
35867var parsers_1 = parsers$2;
35868
35869/**
35870 * Expose text regex
35871 */
35872
35873var TEXT_REGEX_1 = TEXT_REGEX;
35874parsers_1.TEXT_REGEX = TEXT_REGEX_1;
35875
35876var extendShallow$7 = function extend(o/*, objects*/) {
35877 if (!isExtendable$1(o)) { o = {}; }
35878
35879 var len = arguments.length;
35880 for (var i = 1; i < len; i++) {
35881 var obj = arguments[i];
35882
35883 if (isExtendable$1(obj)) {
35884 assign$7(o, obj);
35885 }
35886 }
35887 return o;
35888};
35889
35890function assign$7(a, b) {
35891 for (var key in b) {
35892 if (hasOwn$8(b, key)) {
35893 a[key] = b[key];
35894 }
35895 }
35896}
35897
35898/**
35899 * Returns true if the given `key` is an own property of `obj`.
35900 */
35901
35902function hasOwn$8(obj, key) {
35903 return Object.prototype.hasOwnProperty.call(obj, key);
35904}
35905
35906/**
35907 * Local dependencies
35908 */
35909
35910
35911
35912
35913/**
35914 * Module dependencies
35915 */
35916
35917var debug$3 = src('expand-brackets');
35918
35919
35920
35921
35922/**
35923 * Parses the given POSIX character class `pattern` and returns a
35924 * string that can be used for creating regular expressions for matching.
35925 *
35926 * @param {String} `pattern`
35927 * @param {Object} `options`
35928 * @return {Object}
35929 * @api public
35930 */
35931
35932function brackets(pattern, options) {
35933 debug$3('initializing from <%s>', __filename);
35934 var res = brackets.create(pattern, options);
35935 return res.output;
35936}
35937
35938/**
35939 * Takes an array of strings and a POSIX character class pattern, and returns a new
35940 * array with only the strings that matched the pattern.
35941 *
35942 * ```js
35943 * var brackets = require('expand-brackets');
35944 * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]'));
35945 * //=> ['a']
35946 *
35947 * console.log(brackets.match(['1', 'a', 'ab'], '[[:alpha:]]+'));
35948 * //=> ['a', 'ab']
35949 * ```
35950 * @param {Array} `arr` Array of strings to match
35951 * @param {String} `pattern` POSIX character class pattern(s)
35952 * @param {Object} `options`
35953 * @return {Array}
35954 * @api public
35955 */
35956
35957brackets.match = function(arr, pattern, options) {
35958 arr = [].concat(arr);
35959 var opts = extendShallow$7({}, options);
35960 var isMatch = brackets.matcher(pattern, opts);
35961 var len = arr.length;
35962 var idx = -1;
35963 var res = [];
35964
35965 while (++idx < len) {
35966 var ele = arr[idx];
35967 if (isMatch(ele)) {
35968 res.push(ele);
35969 }
35970 }
35971
35972 if (res.length === 0) {
35973 if (opts.failglob === true) {
35974 throw new Error('no matches found for "' + pattern + '"');
35975 }
35976
35977 if (opts.nonull === true || opts.nullglob === true) {
35978 return [pattern.split('\\').join('')];
35979 }
35980 }
35981 return res;
35982};
35983
35984/**
35985 * Returns true if the specified `string` matches the given
35986 * brackets `pattern`.
35987 *
35988 * ```js
35989 * var brackets = require('expand-brackets');
35990 *
35991 * console.log(brackets.isMatch('a.a', '[[:alpha:]].[[:alpha:]]'));
35992 * //=> true
35993 * console.log(brackets.isMatch('1.2', '[[:alpha:]].[[:alpha:]]'));
35994 * //=> false
35995 * ```
35996 * @param {String} `string` String to match
35997 * @param {String} `pattern` Poxis pattern
35998 * @param {String} `options`
35999 * @return {Boolean}
36000 * @api public
36001 */
36002
36003brackets.isMatch = function(str, pattern, options) {
36004 return brackets.matcher(pattern, options)(str);
36005};
36006
36007/**
36008 * Takes a POSIX character class pattern and returns a matcher function. The returned
36009 * function takes the string to match as its only argument.
36010 *
36011 * ```js
36012 * var brackets = require('expand-brackets');
36013 * var isMatch = brackets.matcher('[[:lower:]].[[:upper:]]');
36014 *
36015 * console.log(isMatch('a.a'));
36016 * //=> false
36017 * console.log(isMatch('a.A'));
36018 * //=> true
36019 * ```
36020 * @param {String} `pattern` Poxis pattern
36021 * @param {String} `options`
36022 * @return {Boolean}
36023 * @api public
36024 */
36025
36026brackets.matcher = function(pattern, options) {
36027 var re = brackets.makeRe(pattern, options);
36028 return function(str) {
36029 return re.test(str);
36030 };
36031};
36032
36033/**
36034 * Create a regular expression from the given `pattern`.
36035 *
36036 * ```js
36037 * var brackets = require('expand-brackets');
36038 * var re = brackets.makeRe('[[:alpha:]]');
36039 * console.log(re);
36040 * //=> /^(?:[a-zA-Z])$/
36041 * ```
36042 * @param {String} `pattern` The pattern to convert to regex.
36043 * @param {Object} `options`
36044 * @return {RegExp}
36045 * @api public
36046 */
36047
36048brackets.makeRe = function(pattern, options) {
36049 var res = brackets.create(pattern, options);
36050 var opts = extendShallow$7({strictErrors: false}, options);
36051 return toRegex$1(res.output, opts);
36052};
36053
36054/**
36055 * Parses the given POSIX character class `pattern` and returns an object
36056 * with the compiled `output` and optional source `map`.
36057 *
36058 * ```js
36059 * var brackets = require('expand-brackets');
36060 * console.log(brackets('[[:alpha:]]'));
36061 * // { options: { source: 'string' },
36062 * // input: '[[:alpha:]]',
36063 * // state: {},
36064 * // compilers:
36065 * // { eos: [Function],
36066 * // noop: [Function],
36067 * // bos: [Function],
36068 * // not: [Function],
36069 * // escape: [Function],
36070 * // text: [Function],
36071 * // posix: [Function],
36072 * // bracket: [Function],
36073 * // 'bracket.open': [Function],
36074 * // 'bracket.inner': [Function],
36075 * // 'bracket.literal': [Function],
36076 * // 'bracket.close': [Function] },
36077 * // output: '[a-zA-Z]',
36078 * // ast:
36079 * // { type: 'root',
36080 * // errors: [],
36081 * // nodes: [ [Object], [Object], [Object] ] },
36082 * // parsingErrors: [] }
36083 * ```
36084 * @param {String} `pattern`
36085 * @param {Object} `options`
36086 * @return {Object}
36087 * @api public
36088 */
36089
36090brackets.create = function(pattern, options) {
36091 var snapdragon$1 = (options && options.snapdragon) || new snapdragon(options);
36092 compilers$2(snapdragon$1);
36093 parsers_1(snapdragon$1);
36094
36095 var ast = snapdragon$1.parse(pattern, options);
36096 ast.input = pattern;
36097 var res = snapdragon$1.compile(ast, options);
36098 res.input = pattern;
36099 return res;
36100};
36101
36102/**
36103 * Expose `brackets` constructor, parsers and compilers
36104 */
36105
36106brackets.compilers = compilers$2;
36107brackets.parsers = parsers_1;
36108
36109/**
36110 * Expose `brackets`
36111 * @type {Function}
36112 */
36113
36114var expandBrackets = brackets;
36115
36116/**
36117 * Extglob compilers
36118 */
36119
36120var compilers$3 = function(extglob) {
36121 function star() {
36122 if (typeof extglob.options.star === 'function') {
36123 return extglob.options.star.apply(this, arguments);
36124 }
36125 if (typeof extglob.options.star === 'string') {
36126 return extglob.options.star;
36127 }
36128 return '.*?';
36129 }
36130
36131 /**
36132 * Use `expand-brackets` compilers
36133 */
36134
36135 extglob.use(expandBrackets.compilers);
36136 extglob.compiler
36137
36138 /**
36139 * Escaped: "\\*"
36140 */
36141
36142 .set('escape', function(node) {
36143 return this.emit(node.val, node);
36144 })
36145
36146 /**
36147 * Dot: "."
36148 */
36149
36150 .set('dot', function(node) {
36151 return this.emit('\\' + node.val, node);
36152 })
36153
36154 /**
36155 * Question mark: "?"
36156 */
36157
36158 .set('qmark', function(node) {
36159 var val = '[^\\\\/.]';
36160 var prev = this.prev();
36161
36162 if (node.parsed.slice(-1) === '(') {
36163 var ch = node.rest.charAt(0);
36164 if (ch !== '!' && ch !== '=' && ch !== ':') {
36165 return this.emit(val, node);
36166 }
36167 return this.emit(node.val, node);
36168 }
36169
36170 if (prev.type === 'text' && prev.val) {
36171 return this.emit(val, node);
36172 }
36173
36174 if (node.val.length > 1) {
36175 val += '{' + node.val.length + '}';
36176 }
36177 return this.emit(val, node);
36178 })
36179
36180 /**
36181 * Plus: "+"
36182 */
36183
36184 .set('plus', function(node) {
36185 var prev = node.parsed.slice(-1);
36186 if (prev === ']' || prev === ')') {
36187 return this.emit(node.val, node);
36188 }
36189 var ch = this.output.slice(-1);
36190 if (!this.output || (/[?*+]/.test(ch) && node.parent.type !== 'bracket')) {
36191 return this.emit('\\+', node);
36192 }
36193 if (/\w/.test(ch) && !node.inside) {
36194 return this.emit('+\\+?', node);
36195 }
36196 return this.emit('+', node);
36197 })
36198
36199 /**
36200 * Star: "*"
36201 */
36202
36203 .set('star', function(node) {
36204 var prev = this.prev();
36205 var prefix = prev.type !== 'text' && prev.type !== 'escape'
36206 ? '(?!\\.)'
36207 : '';
36208
36209 return this.emit(prefix + star.call(this, node), node);
36210 })
36211
36212 /**
36213 * Parens
36214 */
36215
36216 .set('paren', function(node) {
36217 return this.mapVisit(node.nodes);
36218 })
36219 .set('paren.open', function(node) {
36220 var capture = this.options.capture ? '(' : '';
36221
36222 switch (node.parent.prefix) {
36223 case '!':
36224 case '^':
36225 return this.emit(capture + '(?:(?!(?:', node);
36226 case '*':
36227 case '+':
36228 case '?':
36229 case '@':
36230 return this.emit(capture + '(?:', node);
36231 default: {
36232 var val = node.val;
36233 if (this.options.bash === true) {
36234 val = '\\' + val;
36235 } else if (!this.options.capture && val === '(' && node.parent.rest[0] !== '?') {
36236 val += '?:';
36237 }
36238
36239 return this.emit(val, node);
36240 }
36241 }
36242 })
36243 .set('paren.close', function(node) {
36244 var capture = this.options.capture ? ')' : '';
36245
36246 switch (node.prefix) {
36247 case '!':
36248 case '^':
36249 var prefix = /^(\)|$)/.test(node.rest) ? '$' : '';
36250 var str = star.call(this, node);
36251
36252 // if the extglob has a slash explicitly defined, we know the user wants
36253 // to match slashes, so we need to ensure the "star" regex allows for it
36254 if (node.parent.hasSlash && !this.options.star && this.options.slash !== false) {
36255 str = '.*?';
36256 }
36257
36258 return this.emit(prefix + ('))' + str + ')') + capture, node);
36259 case '*':
36260 case '+':
36261 case '?':
36262 return this.emit(')' + node.prefix + capture, node);
36263 case '@':
36264 return this.emit(')' + capture, node);
36265 default: {
36266 var val = (this.options.bash === true ? '\\' : '') + ')';
36267 return this.emit(val, node);
36268 }
36269 }
36270 })
36271
36272 /**
36273 * Text
36274 */
36275
36276 .set('text', function(node) {
36277 var val = node.val.replace(/[\[\]]/g, '\\$&');
36278 return this.emit(val, node);
36279 });
36280};
36281
36282// accessor descriptor properties
36283var accessor$4 = {
36284 get: 'function',
36285 set: 'function',
36286 configurable: 'boolean',
36287 enumerable: 'boolean'
36288};
36289
36290function isAccessorDescriptor$4(obj, prop) {
36291 if (typeof prop === 'string') {
36292 var val = Object.getOwnPropertyDescriptor(obj, prop);
36293 return typeof val !== 'undefined';
36294 }
36295
36296 if (kindOf(obj) !== 'object') {
36297 return false;
36298 }
36299
36300 if (has$7(obj, 'value') || has$7(obj, 'writable')) {
36301 return false;
36302 }
36303
36304 if (!has$7(obj, 'get') || typeof obj.get !== 'function') {
36305 return false;
36306 }
36307
36308 // tldr: it's valid to have "set" be undefined
36309 // "set" might be undefined if `Object.getOwnPropertyDescriptor`
36310 // was used to get the value, and only `get` was defined by the user
36311 if (has$7(obj, 'set') && typeof obj[key] !== 'function' && typeof obj[key] !== 'undefined') {
36312 return false;
36313 }
36314
36315 for (var key in obj) {
36316 if (!accessor$4.hasOwnProperty(key)) {
36317 continue;
36318 }
36319
36320 if (kindOf(obj[key]) === accessor$4[key]) {
36321 continue;
36322 }
36323
36324 if (typeof obj[key] !== 'undefined') {
36325 return false;
36326 }
36327 }
36328 return true;
36329}
36330
36331function has$7(obj, key) {
36332 return {}.hasOwnProperty.call(obj, key);
36333}
36334
36335/**
36336 * Expose `isAccessorDescriptor`
36337 */
36338
36339var isAccessorDescriptor_1$4 = isAccessorDescriptor$4;
36340
36341var isDataDescriptor$4 = function isDataDescriptor(obj, prop) {
36342 // data descriptor properties
36343 var data = {
36344 configurable: 'boolean',
36345 enumerable: 'boolean',
36346 writable: 'boolean'
36347 };
36348
36349 if (kindOf(obj) !== 'object') {
36350 return false;
36351 }
36352
36353 if (typeof prop === 'string') {
36354 var val = Object.getOwnPropertyDescriptor(obj, prop);
36355 return typeof val !== 'undefined';
36356 }
36357
36358 if (!('value' in obj) && !('writable' in obj)) {
36359 return false;
36360 }
36361
36362 for (var key in obj) {
36363 if (key === 'value') continue;
36364
36365 if (!data.hasOwnProperty(key)) {
36366 continue;
36367 }
36368
36369 if (kindOf(obj[key]) === data[key]) {
36370 continue;
36371 }
36372
36373 if (typeof obj[key] !== 'undefined') {
36374 return false;
36375 }
36376 }
36377 return true;
36378};
36379
36380var isDescriptor$4 = function isDescriptor(obj, key) {
36381 if (kindOf(obj) !== 'object') {
36382 return false;
36383 }
36384 if ('get' in obj) {
36385 return isAccessorDescriptor_1$4(obj, key);
36386 }
36387 return isDataDescriptor$4(obj, key);
36388};
36389
36390var defineProperty$8 = function defineProperty(obj, prop, val) {
36391 if (typeof obj !== 'object' && typeof obj !== 'function') {
36392 throw new TypeError('expected an object or function.');
36393 }
36394
36395 if (typeof prop !== 'string') {
36396 throw new TypeError('expected `prop` to be a string.');
36397 }
36398
36399 if (isDescriptor$4(val) && ('set' in val || 'get' in val)) {
36400 return Object.defineProperty(obj, prop, val);
36401 }
36402
36403 return Object.defineProperty(obj, prop, {
36404 configurable: true,
36405 enumerable: false,
36406 writable: true,
36407 value: val
36408 });
36409};
36410
36411var utils_1$2 = createCommonjsModule(function (module) {
36412
36413
36414
36415
36416/**
36417 * Utils
36418 */
36419
36420var utils = module.exports;
36421var cache = utils.cache = new fragmentCache();
36422
36423/**
36424 * Cast `val` to an array
36425 * @return {Array}
36426 */
36427
36428utils.arrayify = function(val) {
36429 if (!Array.isArray(val)) {
36430 return [val];
36431 }
36432 return val;
36433};
36434
36435/**
36436 * Memoize a generated regex or function
36437 */
36438
36439utils.memoize = function(type, pattern, options, fn) {
36440 var key = utils.createKey(type + pattern, options);
36441
36442 if (cache.has(type, key)) {
36443 return cache.get(type, key);
36444 }
36445
36446 var val = fn(pattern, options);
36447 if (options && options.cache === false) {
36448 return val;
36449 }
36450
36451 cache.set(type, key, val);
36452 return val;
36453};
36454
36455/**
36456 * Create the key to use for memoization. The key is generated
36457 * by iterating over the options and concatenating key-value pairs
36458 * to the pattern string.
36459 */
36460
36461utils.createKey = function(pattern, options) {
36462 var key = pattern;
36463 if (typeof options === 'undefined') {
36464 return key;
36465 }
36466 for (var prop in options) {
36467 key += ';' + prop + '=' + String(options[prop]);
36468 }
36469 return key;
36470};
36471
36472/**
36473 * Create the regex to use for matching text
36474 */
36475
36476utils.createRegex = function(str) {
36477 var opts = {contains: true, strictClose: false};
36478 return regexNot(str, opts);
36479};
36480});
36481
36482/**
36483 * Characters to use in text regex (we want to "not" match
36484 * characters that are matched by other parsers)
36485 */
36486
36487var TEXT_REGEX$1 = '([!@*?+]?\\(|\\)|[*?.+\\\\]|\\[:?(?=.*\\])|:?\\])+';
36488var not$3 = utils_1$2.createRegex(TEXT_REGEX$1);
36489
36490/**
36491 * Extglob parsers
36492 */
36493
36494function parsers$3(extglob) {
36495 extglob.state = extglob.state || {};
36496
36497 /**
36498 * Use `expand-brackets` parsers
36499 */
36500
36501 extglob.use(expandBrackets.parsers);
36502 extglob.parser.sets.paren = extglob.parser.sets.paren || [];
36503 extglob.parser
36504
36505 /**
36506 * Extglob open: "*("
36507 */
36508
36509 .capture('paren.open', function() {
36510 var parsed = this.parsed;
36511 var pos = this.position();
36512 var m = this.match(/^([!@*?+])?\(/);
36513 if (!m) return;
36514
36515 var prev = this.prev();
36516 var prefix = m[1];
36517 var val = m[0];
36518
36519 var open = pos({
36520 type: 'paren.open',
36521 parsed: parsed,
36522 val: val
36523 });
36524
36525 var node = pos({
36526 type: 'paren',
36527 prefix: prefix,
36528 nodes: [open]
36529 });
36530
36531 // if nested negation extglobs, just cancel them out to simplify
36532 if (prefix === '!' && prev.type === 'paren' && prev.prefix === '!') {
36533 prev.prefix = '@';
36534 node.prefix = '@';
36535 }
36536
36537 defineProperty$8(node, 'rest', this.input);
36538 defineProperty$8(node, 'parsed', parsed);
36539 defineProperty$8(node, 'parent', prev);
36540 defineProperty$8(open, 'parent', node);
36541
36542 this.push('paren', node);
36543 prev.nodes.push(node);
36544 })
36545
36546 /**
36547 * Extglob close: ")"
36548 */
36549
36550 .capture('paren.close', function() {
36551 var parsed = this.parsed;
36552 var pos = this.position();
36553 var m = this.match(/^\)/);
36554 if (!m) return;
36555
36556 var parent = this.pop('paren');
36557 var node = pos({
36558 type: 'paren.close',
36559 rest: this.input,
36560 parsed: parsed,
36561 val: m[0]
36562 });
36563
36564 if (!this.isType(parent, 'paren')) {
36565 if (this.options.strict) {
36566 throw new Error('missing opening paren: "("');
36567 }
36568 node.escaped = true;
36569 return node;
36570 }
36571
36572 node.prefix = parent.prefix;
36573 parent.nodes.push(node);
36574 defineProperty$8(node, 'parent', parent);
36575 })
36576
36577 /**
36578 * Escape: "\\."
36579 */
36580
36581 .capture('escape', function() {
36582 var pos = this.position();
36583 var m = this.match(/^\\(.)/);
36584 if (!m) return;
36585
36586 return pos({
36587 type: 'escape',
36588 val: m[0],
36589 ch: m[1]
36590 });
36591 })
36592
36593 /**
36594 * Question marks: "?"
36595 */
36596
36597 .capture('qmark', function() {
36598 var parsed = this.parsed;
36599 var pos = this.position();
36600 var m = this.match(/^\?+(?!\()/);
36601 if (!m) return;
36602 extglob.state.metachar = true;
36603 return pos({
36604 type: 'qmark',
36605 rest: this.input,
36606 parsed: parsed,
36607 val: m[0]
36608 });
36609 })
36610
36611 /**
36612 * Character parsers
36613 */
36614
36615 .capture('star', /^\*(?!\()/)
36616 .capture('plus', /^\+(?!\()/)
36617 .capture('dot', /^\./)
36618 .capture('text', not$3);
36619}
36620/**
36621 * Expose text regex string
36622 */
36623
36624var TEXT_REGEX_1$1 = TEXT_REGEX$1;
36625
36626/**
36627 * Extglob parsers
36628 */
36629
36630var parsers_1$1 = parsers$3;
36631parsers_1$1.TEXT_REGEX = TEXT_REGEX_1$1;
36632
36633/**
36634 * Module dependencies
36635 */
36636
36637
36638
36639
36640
36641/**
36642 * Local dependencies
36643 */
36644
36645
36646
36647
36648/**
36649 * Customize Snapdragon parser and renderer
36650 */
36651
36652function Extglob(options) {
36653 this.options = extendShallow$6({source: 'extglob'}, options);
36654 this.snapdragon = this.options.snapdragon || new snapdragon(this.options);
36655 this.snapdragon.patterns = this.snapdragon.patterns || {};
36656 this.compiler = this.snapdragon.compiler;
36657 this.parser = this.snapdragon.parser;
36658
36659 compilers$3(this.snapdragon);
36660 parsers_1$1(this.snapdragon);
36661
36662 /**
36663 * Override Snapdragon `.parse` method
36664 */
36665
36666 defineProperty$8(this.snapdragon, 'parse', function(str, options) {
36667 var parsed = snapdragon.prototype.parse.apply(this, arguments);
36668 parsed.input = str;
36669
36670 // escape unmatched brace/bracket/parens
36671 var last = this.parser.stack.pop();
36672 if (last && this.options.strict !== true) {
36673 var node = last.nodes[0];
36674 node.val = '\\' + node.val;
36675 var sibling = node.parent.nodes[1];
36676 if (sibling.type === 'star') {
36677 sibling.loose = true;
36678 }
36679 }
36680
36681 // add non-enumerable parser reference
36682 defineProperty$8(parsed, 'parser', this.parser);
36683 return parsed;
36684 });
36685
36686 /**
36687 * Decorate `.parse` method
36688 */
36689
36690 defineProperty$8(this, 'parse', function(ast, options) {
36691 return this.snapdragon.parse.apply(this.snapdragon, arguments);
36692 });
36693
36694 /**
36695 * Decorate `.compile` method
36696 */
36697
36698 defineProperty$8(this, 'compile', function(ast, options) {
36699 return this.snapdragon.compile.apply(this.snapdragon, arguments);
36700 });
36701
36702}
36703
36704/**
36705 * Expose `Extglob`
36706 */
36707
36708var extglob = Extglob;
36709
36710/**
36711 * Module dependencies
36712 */
36713
36714
36715
36716
36717
36718/**
36719 * Local dependencies
36720 */
36721
36722
36723
36724
36725
36726var MAX_LENGTH$3 = 1024 * 64;
36727
36728/**
36729 * Convert the given `extglob` pattern into a regex-compatible string. Returns
36730 * an object with the compiled result and the parsed AST.
36731 *
36732 * ```js
36733 * var extglob = require('extglob');
36734 * console.log(extglob('*.!(*a)'));
36735 * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?'
36736 * ```
36737 * @param {String} `pattern`
36738 * @param {Object} `options`
36739 * @return {String}
36740 * @api public
36741 */
36742
36743function extglob$1(pattern, options) {
36744 return extglob$1.create(pattern, options).output;
36745}
36746
36747/**
36748 * Takes an array of strings and an extglob pattern and returns a new
36749 * array that contains only the strings that match the pattern.
36750 *
36751 * ```js
36752 * var extglob = require('extglob');
36753 * console.log(extglob.match(['a.a', 'a.b', 'a.c'], '*.!(*a)'));
36754 * //=> ['a.b', 'a.c']
36755 * ```
36756 * @param {Array} `list` Array of strings to match
36757 * @param {String} `pattern` Extglob pattern
36758 * @param {Object} `options`
36759 * @return {Array} Returns an array of matches
36760 * @api public
36761 */
36762
36763extglob$1.match = function(list, pattern, options) {
36764 if (typeof pattern !== 'string') {
36765 throw new TypeError('expected pattern to be a string');
36766 }
36767
36768 list = utils_1$2.arrayify(list);
36769 var isMatch = extglob$1.matcher(pattern, options);
36770 var len = list.length;
36771 var idx = -1;
36772 var matches = [];
36773
36774 while (++idx < len) {
36775 var ele = list[idx];
36776
36777 if (isMatch(ele)) {
36778 matches.push(ele);
36779 }
36780 }
36781
36782 // if no options were passed, uniquify results and return
36783 if (typeof options === 'undefined') {
36784 return arrayUnique(matches);
36785 }
36786
36787 if (matches.length === 0) {
36788 if (options.failglob === true) {
36789 throw new Error('no matches found for "' + pattern + '"');
36790 }
36791 if (options.nonull === true || options.nullglob === true) {
36792 return [pattern.split('\\').join('')];
36793 }
36794 }
36795
36796 return options.nodupes !== false ? arrayUnique(matches) : matches;
36797};
36798
36799/**
36800 * Returns true if the specified `string` matches the given
36801 * extglob `pattern`.
36802 *
36803 * ```js
36804 * var extglob = require('extglob');
36805 *
36806 * console.log(extglob.isMatch('a.a', '*.!(*a)'));
36807 * //=> false
36808 * console.log(extglob.isMatch('a.b', '*.!(*a)'));
36809 * //=> true
36810 * ```
36811 * @param {String} `string` String to match
36812 * @param {String} `pattern` Extglob pattern
36813 * @param {String} `options`
36814 * @return {Boolean}
36815 * @api public
36816 */
36817
36818extglob$1.isMatch = function(str, pattern, options) {
36819 if (typeof pattern !== 'string') {
36820 throw new TypeError('expected pattern to be a string');
36821 }
36822
36823 if (typeof str !== 'string') {
36824 throw new TypeError('expected a string');
36825 }
36826
36827 if (pattern === str) {
36828 return true;
36829 }
36830
36831 if (pattern === '' || pattern === ' ' || pattern === '.') {
36832 return pattern === str;
36833 }
36834
36835 var isMatch = utils_1$2.memoize('isMatch', pattern, options, extglob$1.matcher);
36836 return isMatch(str);
36837};
36838
36839/**
36840 * Returns true if the given `string` contains the given pattern. Similar to `.isMatch` but
36841 * the pattern can match any part of the string.
36842 *
36843 * ```js
36844 * var extglob = require('extglob');
36845 * console.log(extglob.contains('aa/bb/cc', '*b'));
36846 * //=> true
36847 * console.log(extglob.contains('aa/bb/cc', '*d'));
36848 * //=> false
36849 * ```
36850 * @param {String} `str` The string to match.
36851 * @param {String} `pattern` Glob pattern to use for matching.
36852 * @param {Object} `options`
36853 * @return {Boolean} Returns true if the patter matches any part of `str`.
36854 * @api public
36855 */
36856
36857extglob$1.contains = function(str, pattern, options) {
36858 if (typeof str !== 'string') {
36859 throw new TypeError('expected a string');
36860 }
36861
36862 if (pattern === '' || pattern === ' ' || pattern === '.') {
36863 return pattern === str;
36864 }
36865
36866 var opts = extendShallow$6({}, options, {contains: true});
36867 opts.strictClose = false;
36868 opts.strictOpen = false;
36869 return extglob$1.isMatch(str, pattern, opts);
36870};
36871
36872/**
36873 * Takes an extglob pattern and returns a matcher function. The returned
36874 * function takes the string to match as its only argument.
36875 *
36876 * ```js
36877 * var extglob = require('extglob');
36878 * var isMatch = extglob.matcher('*.!(*a)');
36879 *
36880 * console.log(isMatch('a.a'));
36881 * //=> false
36882 * console.log(isMatch('a.b'));
36883 * //=> true
36884 * ```
36885 * @param {String} `pattern` Extglob pattern
36886 * @param {String} `options`
36887 * @return {Boolean}
36888 * @api public
36889 */
36890
36891extglob$1.matcher = function(pattern, options) {
36892 if (typeof pattern !== 'string') {
36893 throw new TypeError('expected pattern to be a string');
36894 }
36895
36896 function matcher() {
36897 var re = extglob$1.makeRe(pattern, options);
36898 return function(str) {
36899 return re.test(str);
36900 };
36901 }
36902
36903 return utils_1$2.memoize('matcher', pattern, options, matcher);
36904};
36905
36906/**
36907 * Convert the given `extglob` pattern into a regex-compatible string. Returns
36908 * an object with the compiled result and the parsed AST.
36909 *
36910 * ```js
36911 * var extglob = require('extglob');
36912 * console.log(extglob.create('*.!(*a)').output);
36913 * //=> '(?!\\.)[^/]*?\\.(?!(?!\\.)[^/]*?a\\b).*?'
36914 * ```
36915 * @param {String} `str`
36916 * @param {Object} `options`
36917 * @return {String}
36918 * @api public
36919 */
36920
36921extglob$1.create = function(pattern, options) {
36922 if (typeof pattern !== 'string') {
36923 throw new TypeError('expected pattern to be a string');
36924 }
36925
36926 function create() {
36927 var ext = new extglob(options);
36928 var ast = ext.parse(pattern, options);
36929 return ext.compile(ast, options);
36930 }
36931
36932 return utils_1$2.memoize('create', pattern, options, create);
36933};
36934
36935/**
36936 * Returns an array of matches captured by `pattern` in `string`, or `null`
36937 * if the pattern did not match.
36938 *
36939 * ```js
36940 * var extglob = require('extglob');
36941 * extglob.capture(pattern, string[, options]);
36942 *
36943 * console.log(extglob.capture('test/*.js', 'test/foo.js'));
36944 * //=> ['foo']
36945 * console.log(extglob.capture('test/*.js', 'foo/bar.css'));
36946 * //=> null
36947 * ```
36948 * @param {String} `pattern` Glob pattern to use for matching.
36949 * @param {String} `string` String to match
36950 * @param {Object} `options` See available [options](#options) for changing how matches are performed
36951 * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
36952 * @api public
36953 */
36954
36955extglob$1.capture = function(pattern, str, options) {
36956 var re = extglob$1.makeRe(pattern, extendShallow$6({capture: true}, options));
36957
36958 function match() {
36959 return function(string) {
36960 var match = re.exec(string);
36961 if (!match) {
36962 return null;
36963 }
36964
36965 return match.slice(1);
36966 };
36967 }
36968
36969 var capture = utils_1$2.memoize('capture', pattern, options, match);
36970 return capture(str);
36971};
36972
36973/**
36974 * Create a regular expression from the given `pattern` and `options`.
36975 *
36976 * ```js
36977 * var extglob = require('extglob');
36978 * var re = extglob.makeRe('*.!(*a)');
36979 * console.log(re);
36980 * //=> /^[^\/]*?\.(?![^\/]*?a)[^\/]*?$/
36981 * ```
36982 * @param {String} `pattern` The pattern to convert to regex.
36983 * @param {Object} `options`
36984 * @return {RegExp}
36985 * @api public
36986 */
36987
36988extglob$1.makeRe = function(pattern, options) {
36989 if (pattern instanceof RegExp) {
36990 return pattern;
36991 }
36992
36993 if (typeof pattern !== 'string') {
36994 throw new TypeError('expected pattern to be a string');
36995 }
36996
36997 if (pattern.length > MAX_LENGTH$3) {
36998 throw new Error('expected pattern to be less than ' + MAX_LENGTH$3 + ' characters');
36999 }
37000
37001 function makeRe() {
37002 var opts = extendShallow$6({strictErrors: false}, options);
37003 if (opts.strictErrors === true) opts.strict = true;
37004 var res = extglob$1.create(pattern, opts);
37005 return toRegex$1(res.output, opts);
37006 }
37007
37008 var regex = utils_1$2.memoize('makeRe', pattern, options, makeRe);
37009 if (regex.source.length > MAX_LENGTH$3) {
37010 throw new SyntaxError('potentially malicious regex detected');
37011 }
37012
37013 return regex;
37014};
37015
37016/**
37017 * Cache
37018 */
37019
37020extglob$1.cache = utils_1$2.cache;
37021extglob$1.clearCache = function() {
37022 extglob$1.cache.__data__ = {};
37023};
37024
37025/**
37026 * Expose `Extglob` constructor, parsers and compilers
37027 */
37028
37029extglob$1.Extglob = extglob;
37030extglob$1.compilers = compilers$3;
37031extglob$1.parsers = parsers_1$1;
37032
37033/**
37034 * Expose `extglob`
37035 * @type {Function}
37036 */
37037
37038var extglob_1 = extglob$1;
37039
37040var compilers$4 = function(snapdragon) {
37041 var compilers = snapdragon.compiler.compilers;
37042 var opts = snapdragon.options;
37043
37044 // register nanomatch compilers
37045 snapdragon.use(nanomatch_1.compilers);
37046
37047 // get references to some specific nanomatch compilers before they
37048 // are overridden by the extglob and/or custom compilers
37049 var escape = compilers.escape;
37050 var qmark = compilers.qmark;
37051 var slash = compilers.slash;
37052 var star = compilers.star;
37053 var text = compilers.text;
37054 var plus = compilers.plus;
37055 var dot = compilers.dot;
37056
37057 // register extglob compilers or escape exglobs if disabled
37058 if (opts.extglob === false || opts.noext === true) {
37059 snapdragon.compiler.use(escapeExtglobs);
37060 } else {
37061 snapdragon.use(extglob_1.compilers);
37062 }
37063
37064 snapdragon.use(function() {
37065 this.options.star = this.options.star || function(/*node*/) {
37066 return '[^\\\\/]*?';
37067 };
37068 });
37069
37070 // custom micromatch compilers
37071 snapdragon.compiler
37072
37073 // reset referenced compiler
37074 .set('dot', dot)
37075 .set('escape', escape)
37076 .set('plus', plus)
37077 .set('slash', slash)
37078 .set('qmark', qmark)
37079 .set('star', star)
37080 .set('text', text);
37081};
37082
37083function escapeExtglobs(compiler) {
37084 compiler.set('paren', function(node) {
37085 var val = '';
37086 visit(node, function(tok) {
37087 if (tok.val) val += (/^\W/.test(tok.val) ? '\\' : '') + tok.val;
37088 });
37089 return this.emit(val, node);
37090 });
37091
37092 /**
37093 * Visit `node` with the given `fn`
37094 */
37095
37096 function visit(node, fn) {
37097 return node.nodes ? mapVisit(node.nodes, fn) : fn(node);
37098 }
37099
37100 /**
37101 * Map visit over array of `nodes`.
37102 */
37103
37104 function mapVisit(nodes, fn) {
37105 var len = nodes.length;
37106 var idx = -1;
37107 while (++idx < len) {
37108 visit(nodes[idx], fn);
37109 }
37110 }
37111}
37112
37113var not$4;
37114
37115/**
37116 * Characters to use in negation regex (we want to "not" match
37117 * characters that are matched by other parsers)
37118 */
37119
37120var TEXT = '([!@*?+]?\\(|\\)|\\[:?(?=.*?:?\\])|:?\\]|[*+?!^$.\\\\/])+';
37121var createNotRegex = function(opts) {
37122 return not$4 || (not$4 = textRegex(TEXT));
37123};
37124
37125/**
37126 * Parsers
37127 */
37128
37129var parsers$4 = function(snapdragon) {
37130 var parsers = snapdragon.parser.parsers;
37131
37132 // register nanomatch parsers
37133 snapdragon.use(nanomatch_1.parsers);
37134
37135 // get references to some specific nanomatch parsers before they
37136 // are overridden by the extglob and/or parsers
37137 var escape = parsers.escape;
37138 var slash = parsers.slash;
37139 var qmark = parsers.qmark;
37140 var plus = parsers.plus;
37141 var star = parsers.star;
37142 var dot = parsers.dot;
37143
37144 // register extglob parsers
37145 snapdragon.use(extglob_1.parsers);
37146
37147 // custom micromatch parsers
37148 snapdragon.parser
37149 .use(function() {
37150 // override "notRegex" created in nanomatch parser
37151 this.notRegex = /^\!+(?!\()/;
37152 })
37153 // reset the referenced parsers
37154 .capture('escape', escape)
37155 .capture('slash', slash)
37156 .capture('qmark', qmark)
37157 .capture('star', star)
37158 .capture('plus', plus)
37159 .capture('dot', dot)
37160
37161 /**
37162 * Override `text` parser
37163 */
37164
37165 .capture('text', function() {
37166 if (this.isInside('bracket')) return;
37167 var pos = this.position();
37168 var m = this.match(createNotRegex(this.options));
37169 if (!m || !m[0]) return;
37170
37171 // escape regex boundary characters and simple brackets
37172 var val = m[0].replace(/([[\]^$])/g, '\\$1');
37173
37174 return pos({
37175 type: 'text',
37176 val: val
37177 });
37178 });
37179};
37180
37181/**
37182 * Create text regex
37183 */
37184
37185function textRegex(pattern) {
37186 var notStr = regexNot.create(pattern, {contains: true, strictClose: false});
37187 var prefix = '(?:[\\^]|\\\\|';
37188 return toRegex$1(prefix + notStr + ')', {strictClose: false});
37189}
37190
37191var cache$5 = new (fragmentCache)();
37192
37193var utils_1$3 = createCommonjsModule(function (module) {
37194
37195var utils = module.exports;
37196
37197
37198/**
37199 * Module dependencies
37200 */
37201
37202
37203utils.define = defineProperty;
37204utils.diff = arrDiff;
37205utils.extend = extendShallow;
37206utils.pick = object_pick;
37207utils.typeOf = kindOf;
37208utils.unique = arrayUnique;
37209
37210/**
37211 * Returns true if the platform is windows, or `path.sep` is `\\`.
37212 * This is defined as a function to allow `path.sep` to be set in unit tests,
37213 * or by the user, if there is a reason to do so.
37214 * @return {Boolean}
37215 */
37216
37217utils.isWindows = function() {
37218 return path.sep === '\\' || process.platform === 'win32';
37219};
37220
37221/**
37222 * Get the `Snapdragon` instance to use
37223 */
37224
37225utils.instantiate = function(ast, options) {
37226 var snapdragon$1;
37227 // if an instance was created by `.parse`, use that instance
37228 if (utils.typeOf(ast) === 'object' && ast.snapdragon) {
37229 snapdragon$1 = ast.snapdragon;
37230 // if the user supplies an instance on options, use that instance
37231 } else if (utils.typeOf(options) === 'object' && options.snapdragon) {
37232 snapdragon$1 = options.snapdragon;
37233 // create a new instance
37234 } else {
37235 snapdragon$1 = new snapdragon(options);
37236 }
37237
37238 utils.define(snapdragon$1, 'parse', function(str, options) {
37239 var parsed = snapdragon.prototype.parse.apply(this, arguments);
37240 parsed.input = str;
37241
37242 // escape unmatched brace/bracket/parens
37243 var last = this.parser.stack.pop();
37244 if (last && this.options.strictErrors !== true) {
37245 var open = last.nodes[0];
37246 var inner = last.nodes[1];
37247 if (last.type === 'bracket') {
37248 if (inner.val.charAt(0) === '[') {
37249 inner.val = '\\' + inner.val;
37250 }
37251
37252 } else {
37253 open.val = '\\' + open.val;
37254 var sibling = open.parent.nodes[1];
37255 if (sibling.type === 'star') {
37256 sibling.loose = true;
37257 }
37258 }
37259 }
37260
37261 // add non-enumerable parser reference
37262 utils.define(parsed, 'parser', this.parser);
37263 return parsed;
37264 });
37265
37266 return snapdragon$1;
37267};
37268
37269/**
37270 * Create the key to use for memoization. The key is generated
37271 * by iterating over the options and concatenating key-value pairs
37272 * to the pattern string.
37273 */
37274
37275utils.createKey = function(pattern, options) {
37276 if (utils.typeOf(options) !== 'object') {
37277 return pattern;
37278 }
37279 var val = pattern;
37280 var keys = Object.keys(options);
37281 for (var i = 0; i < keys.length; i++) {
37282 var key = keys[i];
37283 val += ';' + key + '=' + String(options[key]);
37284 }
37285 return val;
37286};
37287
37288/**
37289 * Cast `val` to an array
37290 * @return {Array}
37291 */
37292
37293utils.arrayify = function(val) {
37294 if (typeof val === 'string') return [val];
37295 return val ? (Array.isArray(val) ? val : [val]) : [];
37296};
37297
37298/**
37299 * Return true if `val` is a non-empty string
37300 */
37301
37302utils.isString = function(val) {
37303 return typeof val === 'string';
37304};
37305
37306/**
37307 * Return true if `val` is a non-empty string
37308 */
37309
37310utils.isObject = function(val) {
37311 return utils.typeOf(val) === 'object';
37312};
37313
37314/**
37315 * Returns true if the given `str` has special characters
37316 */
37317
37318utils.hasSpecialChars = function(str) {
37319 return /(?:(?:(^|\/)[!.])|[*?+()|\[\]{}]|[+@]\()/.test(str);
37320};
37321
37322/**
37323 * Escape regex characters in the given string
37324 */
37325
37326utils.escapeRegex = function(str) {
37327 return str.replace(/[-[\]{}()^$|*+?.\\\/\s]/g, '\\$&');
37328};
37329
37330/**
37331 * Normalize slashes in the given filepath.
37332 *
37333 * @param {String} `filepath`
37334 * @return {String}
37335 */
37336
37337utils.toPosixPath = function(str) {
37338 return str.replace(/\\+/g, '/');
37339};
37340
37341/**
37342 * Strip backslashes before special characters in a string.
37343 *
37344 * @param {String} `str`
37345 * @return {String}
37346 */
37347
37348utils.unescape = function(str) {
37349 return utils.toPosixPath(str.replace(/\\(?=[*+?!.])/g, ''));
37350};
37351
37352/**
37353 * Strip the prefix from a filepath
37354 * @param {String} `fp`
37355 * @return {String}
37356 */
37357
37358utils.stripPrefix = function(str) {
37359 if (str.charAt(0) !== '.') {
37360 return str;
37361 }
37362 var ch = str.charAt(1);
37363 if (utils.isSlash(ch)) {
37364 return str.slice(2);
37365 }
37366 return str;
37367};
37368
37369/**
37370 * Returns true if the given str is an escaped or
37371 * unescaped path character
37372 */
37373
37374utils.isSlash = function(str) {
37375 return str === '/' || str === '\\/' || str === '\\' || str === '\\\\';
37376};
37377
37378/**
37379 * Returns a function that returns true if the given
37380 * pattern matches or contains a `filepath`
37381 *
37382 * @param {String} `pattern`
37383 * @return {Function}
37384 */
37385
37386utils.matchPath = function(pattern, options) {
37387 return (options && options.contains)
37388 ? utils.containsPattern(pattern, options)
37389 : utils.equalsPattern(pattern, options);
37390};
37391
37392/**
37393 * Returns true if the given (original) filepath or unixified path are equal
37394 * to the given pattern.
37395 */
37396
37397utils._equals = function(filepath, unixPath, pattern) {
37398 return pattern === filepath || pattern === unixPath;
37399};
37400
37401/**
37402 * Returns true if the given (original) filepath or unixified path contain
37403 * the given pattern.
37404 */
37405
37406utils._contains = function(filepath, unixPath, pattern) {
37407 return filepath.indexOf(pattern) !== -1 || unixPath.indexOf(pattern) !== -1;
37408};
37409
37410/**
37411 * Returns a function that returns true if the given
37412 * pattern is the same as a given `filepath`
37413 *
37414 * @param {String} `pattern`
37415 * @return {Function}
37416 */
37417
37418utils.equalsPattern = function(pattern, options) {
37419 var unixify = utils.unixify(options);
37420 options = options || {};
37421
37422 return function fn(filepath) {
37423 var equal = utils._equals(filepath, unixify(filepath), pattern);
37424 if (equal === true || options.nocase !== true) {
37425 return equal;
37426 }
37427 var lower = filepath.toLowerCase();
37428 return utils._equals(lower, unixify(lower), pattern);
37429 };
37430};
37431
37432/**
37433 * Returns a function that returns true if the given
37434 * pattern contains a `filepath`
37435 *
37436 * @param {String} `pattern`
37437 * @return {Function}
37438 */
37439
37440utils.containsPattern = function(pattern, options) {
37441 var unixify = utils.unixify(options);
37442 options = options || {};
37443
37444 return function(filepath) {
37445 var contains = utils._contains(filepath, unixify(filepath), pattern);
37446 if (contains === true || options.nocase !== true) {
37447 return contains;
37448 }
37449 var lower = filepath.toLowerCase();
37450 return utils._contains(lower, unixify(lower), pattern);
37451 };
37452};
37453
37454/**
37455 * Returns a function that returns true if the given
37456 * regex matches the `filename` of a file path.
37457 *
37458 * @param {RegExp} `re` Matching regex
37459 * @return {Function}
37460 */
37461
37462utils.matchBasename = function(re) {
37463 return function(filepath) {
37464 return re.test(path.basename(filepath));
37465 };
37466};
37467
37468/**
37469 * Determines the filepath to return based on the provided options.
37470 * @return {any}
37471 */
37472
37473utils.value = function(str, unixify, options) {
37474 if (options && options.unixify === false) {
37475 return str;
37476 }
37477 return unixify(str);
37478};
37479
37480/**
37481 * Returns a function that normalizes slashes in a string to forward
37482 * slashes, strips `./` from beginning of paths, and optionally unescapes
37483 * special characters.
37484 * @return {Function}
37485 */
37486
37487utils.unixify = function(options) {
37488 options = options || {};
37489 return function(filepath) {
37490 if (utils.isWindows() || options.unixify === true) {
37491 filepath = utils.toPosixPath(filepath);
37492 }
37493 if (options.stripPrefix !== false) {
37494 filepath = utils.stripPrefix(filepath);
37495 }
37496 if (options.unescape === true) {
37497 filepath = utils.unescape(filepath);
37498 }
37499 return filepath;
37500 };
37501};
37502});
37503
37504/**
37505 * Module dependencies
37506 */
37507
37508
37509
37510
37511
37512
37513/**
37514 * Local dependencies
37515 */
37516
37517
37518
37519
37520
37521var MAX_LENGTH$4 = 1024 * 64;
37522
37523/**
37524 * The main function takes a list of strings and one or more
37525 * glob patterns to use for matching.
37526 *
37527 * ```js
37528 * var mm = require('micromatch');
37529 * mm(list, patterns[, options]);
37530 *
37531 * console.log(mm(['a.js', 'a.txt'], ['*.js']));
37532 * //=> [ 'a.js' ]
37533 * ```
37534 * @param {Array} `list` A list of strings to match
37535 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37536 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37537 * @return {Array} Returns an array of matches
37538 * @summary false
37539 * @api public
37540 */
37541
37542function micromatch(list, patterns, options) {
37543 patterns = utils_1$3.arrayify(patterns);
37544 list = utils_1$3.arrayify(list);
37545
37546 var len = patterns.length;
37547 if (list.length === 0 || len === 0) {
37548 return [];
37549 }
37550
37551 if (len === 1) {
37552 return micromatch.match(list, patterns[0], options);
37553 }
37554
37555 var omit = [];
37556 var keep = [];
37557 var idx = -1;
37558
37559 while (++idx < len) {
37560 var pattern = patterns[idx];
37561
37562 if (typeof pattern === 'string' && pattern.charCodeAt(0) === 33 /* ! */) {
37563 omit.push.apply(omit, micromatch.match(list, pattern.slice(1), options));
37564 } else {
37565 keep.push.apply(keep, micromatch.match(list, pattern, options));
37566 }
37567 }
37568
37569 var matches = utils_1$3.diff(keep, omit);
37570 if (!options || options.nodupes !== false) {
37571 return utils_1$3.unique(matches);
37572 }
37573
37574 return matches;
37575}
37576
37577/**
37578 * Similar to the main function, but `pattern` must be a string.
37579 *
37580 * ```js
37581 * var mm = require('micromatch');
37582 * mm.match(list, pattern[, options]);
37583 *
37584 * console.log(mm.match(['a.a', 'a.aa', 'a.b', 'a.c'], '*.a'));
37585 * //=> ['a.a', 'a.aa']
37586 * ```
37587 * @param {Array} `list` Array of strings to match
37588 * @param {String} `pattern` Glob pattern to use for matching.
37589 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37590 * @return {Array} Returns an array of matches
37591 * @api public
37592 */
37593
37594micromatch.match = function(list, pattern, options) {
37595 if (Array.isArray(pattern)) {
37596 throw new TypeError('expected pattern to be a string');
37597 }
37598
37599 var unixify = utils_1$3.unixify(options);
37600 var isMatch = memoize$3('match', pattern, options, micromatch.matcher);
37601 var matches = [];
37602
37603 list = utils_1$3.arrayify(list);
37604 var len = list.length;
37605 var idx = -1;
37606
37607 while (++idx < len) {
37608 var ele = list[idx];
37609 if (ele === pattern || isMatch(ele)) {
37610 matches.push(utils_1$3.value(ele, unixify, options));
37611 }
37612 }
37613
37614 // if no options were passed, uniquify results and return
37615 if (typeof options === 'undefined') {
37616 return utils_1$3.unique(matches);
37617 }
37618
37619 if (matches.length === 0) {
37620 if (options.failglob === true) {
37621 throw new Error('no matches found for "' + pattern + '"');
37622 }
37623 if (options.nonull === true || options.nullglob === true) {
37624 return [options.unescape ? utils_1$3.unescape(pattern) : pattern];
37625 }
37626 }
37627
37628 // if `opts.ignore` was defined, diff ignored list
37629 if (options.ignore) {
37630 matches = micromatch.not(matches, options.ignore, options);
37631 }
37632
37633 return options.nodupes !== false ? utils_1$3.unique(matches) : matches;
37634};
37635
37636/**
37637 * Returns true if the specified `string` matches the given glob `pattern`.
37638 *
37639 * ```js
37640 * var mm = require('micromatch');
37641 * mm.isMatch(string, pattern[, options]);
37642 *
37643 * console.log(mm.isMatch('a.a', '*.a'));
37644 * //=> true
37645 * console.log(mm.isMatch('a.b', '*.a'));
37646 * //=> false
37647 * ```
37648 * @param {String} `string` String to match
37649 * @param {String} `pattern` Glob pattern to use for matching.
37650 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37651 * @return {Boolean} Returns true if the string matches the glob pattern.
37652 * @api public
37653 */
37654
37655micromatch.isMatch = function(str, pattern, options) {
37656 if (typeof str !== 'string') {
37657 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
37658 }
37659
37660 if (isEmptyString(str) || isEmptyString(pattern)) {
37661 return false;
37662 }
37663
37664 var equals = utils_1$3.equalsPattern(options);
37665 if (equals(str)) {
37666 return true;
37667 }
37668
37669 var isMatch = memoize$3('isMatch', pattern, options, micromatch.matcher);
37670 return isMatch(str);
37671};
37672
37673/**
37674 * Returns true if some of the strings in the given `list` match any of the
37675 * given glob `patterns`.
37676 *
37677 * ```js
37678 * var mm = require('micromatch');
37679 * mm.some(list, patterns[, options]);
37680 *
37681 * console.log(mm.some(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
37682 * // true
37683 * console.log(mm.some(['foo.js'], ['*.js', '!foo.js']));
37684 * // false
37685 * ```
37686 * @param {String|Array} `list` The string or array of strings to test. Returns as soon as the first match is found.
37687 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37688 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37689 * @return {Boolean} Returns true if any patterns match `str`
37690 * @api public
37691 */
37692
37693micromatch.some = function(list, patterns, options) {
37694 if (typeof list === 'string') {
37695 list = [list];
37696 }
37697 for (var i = 0; i < list.length; i++) {
37698 if (micromatch(list[i], patterns, options).length === 1) {
37699 return true;
37700 }
37701 }
37702 return false;
37703};
37704
37705/**
37706 * Returns true if every string in the given `list` matches
37707 * any of the given glob `patterns`.
37708 *
37709 * ```js
37710 * var mm = require('micromatch');
37711 * mm.every(list, patterns[, options]);
37712 *
37713 * console.log(mm.every('foo.js', ['foo.js']));
37714 * // true
37715 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js']));
37716 * // true
37717 * console.log(mm.every(['foo.js', 'bar.js'], ['*.js', '!foo.js']));
37718 * // false
37719 * console.log(mm.every(['foo.js'], ['*.js', '!foo.js']));
37720 * // false
37721 * ```
37722 * @param {String|Array} `list` The string or array of strings to test.
37723 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37724 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37725 * @return {Boolean} Returns true if any patterns match `str`
37726 * @api public
37727 */
37728
37729micromatch.every = function(list, patterns, options) {
37730 if (typeof list === 'string') {
37731 list = [list];
37732 }
37733 for (var i = 0; i < list.length; i++) {
37734 if (micromatch(list[i], patterns, options).length !== 1) {
37735 return false;
37736 }
37737 }
37738 return true;
37739};
37740
37741/**
37742 * Returns true if **any** of the given glob `patterns`
37743 * match the specified `string`.
37744 *
37745 * ```js
37746 * var mm = require('micromatch');
37747 * mm.any(string, patterns[, options]);
37748 *
37749 * console.log(mm.any('a.a', ['b.*', '*.a']));
37750 * //=> true
37751 * console.log(mm.any('a.a', 'b.*'));
37752 * //=> false
37753 * ```
37754 * @param {String|Array} `str` The string to test.
37755 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37756 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37757 * @return {Boolean} Returns true if any patterns match `str`
37758 * @api public
37759 */
37760
37761micromatch.any = function(str, patterns, options) {
37762 if (typeof str !== 'string') {
37763 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
37764 }
37765
37766 if (isEmptyString(str) || isEmptyString(patterns)) {
37767 return false;
37768 }
37769
37770 if (typeof patterns === 'string') {
37771 patterns = [patterns];
37772 }
37773
37774 for (var i = 0; i < patterns.length; i++) {
37775 if (micromatch.isMatch(str, patterns[i], options)) {
37776 return true;
37777 }
37778 }
37779 return false;
37780};
37781
37782/**
37783 * Returns true if **all** of the given `patterns` match
37784 * the specified string.
37785 *
37786 * ```js
37787 * var mm = require('micromatch');
37788 * mm.all(string, patterns[, options]);
37789 *
37790 * console.log(mm.all('foo.js', ['foo.js']));
37791 * // true
37792 *
37793 * console.log(mm.all('foo.js', ['*.js', '!foo.js']));
37794 * // false
37795 *
37796 * console.log(mm.all('foo.js', ['*.js', 'foo.js']));
37797 * // true
37798 *
37799 * console.log(mm.all('foo.js', ['*.js', 'f*', '*o*', '*o.js']));
37800 * // true
37801 * ```
37802 * @param {String|Array} `str` The string to test.
37803 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37804 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37805 * @return {Boolean} Returns true if any patterns match `str`
37806 * @api public
37807 */
37808
37809micromatch.all = function(str, patterns, options) {
37810 if (typeof str !== 'string') {
37811 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
37812 }
37813 if (typeof patterns === 'string') {
37814 patterns = [patterns];
37815 }
37816 for (var i = 0; i < patterns.length; i++) {
37817 if (!micromatch.isMatch(str, patterns[i], options)) {
37818 return false;
37819 }
37820 }
37821 return true;
37822};
37823
37824/**
37825 * Returns a list of strings that _**do not match any**_ of the given `patterns`.
37826 *
37827 * ```js
37828 * var mm = require('micromatch');
37829 * mm.not(list, patterns[, options]);
37830 *
37831 * console.log(mm.not(['a.a', 'b.b', 'c.c'], '*.a'));
37832 * //=> ['b.b', 'c.c']
37833 * ```
37834 * @param {Array} `list` Array of strings to match.
37835 * @param {String|Array} `patterns` One or more glob pattern to use for matching.
37836 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37837 * @return {Array} Returns an array of strings that **do not match** the given patterns.
37838 * @api public
37839 */
37840
37841micromatch.not = function(list, patterns, options) {
37842 var opts = extendShallow({}, options);
37843 var ignore = opts.ignore;
37844 delete opts.ignore;
37845
37846 var unixify = utils_1$3.unixify(opts);
37847 list = utils_1$3.arrayify(list).map(unixify);
37848
37849 var matches = utils_1$3.diff(list, micromatch(list, patterns, opts));
37850 if (ignore) {
37851 matches = utils_1$3.diff(matches, micromatch(list, ignore));
37852 }
37853
37854 return opts.nodupes !== false ? utils_1$3.unique(matches) : matches;
37855};
37856
37857/**
37858 * Returns true if the given `string` contains the given pattern. Similar
37859 * to [.isMatch](#isMatch) but the pattern can match any part of the string.
37860 *
37861 * ```js
37862 * var mm = require('micromatch');
37863 * mm.contains(string, pattern[, options]);
37864 *
37865 * console.log(mm.contains('aa/bb/cc', '*b'));
37866 * //=> true
37867 * console.log(mm.contains('aa/bb/cc', '*d'));
37868 * //=> false
37869 * ```
37870 * @param {String} `str` The string to match.
37871 * @param {String|Array} `patterns` Glob pattern to use for matching.
37872 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37873 * @return {Boolean} Returns true if the patter matches any part of `str`.
37874 * @api public
37875 */
37876
37877micromatch.contains = function(str, patterns, options) {
37878 if (typeof str !== 'string') {
37879 throw new TypeError('expected a string: "' + util$2.inspect(str) + '"');
37880 }
37881
37882 if (typeof patterns === 'string') {
37883 if (isEmptyString(str) || isEmptyString(patterns)) {
37884 return false;
37885 }
37886
37887 var equals = utils_1$3.equalsPattern(patterns, options);
37888 if (equals(str)) {
37889 return true;
37890 }
37891 var contains = utils_1$3.containsPattern(patterns, options);
37892 if (contains(str)) {
37893 return true;
37894 }
37895 }
37896
37897 var opts = extendShallow({}, options, {contains: true});
37898 return micromatch.any(str, patterns, opts);
37899};
37900
37901/**
37902 * Returns true if the given pattern and options should enable
37903 * the `matchBase` option.
37904 * @return {Boolean}
37905 * @api private
37906 */
37907
37908micromatch.matchBase = function(pattern, options) {
37909 if (pattern && pattern.indexOf('/') !== -1 || !options) return false;
37910 return options.basename === true || options.matchBase === true;
37911};
37912
37913/**
37914 * Filter the keys of the given object with the given `glob` pattern
37915 * and `options`. Does not attempt to match nested keys. If you need this feature,
37916 * use [glob-object][] instead.
37917 *
37918 * ```js
37919 * var mm = require('micromatch');
37920 * mm.matchKeys(object, patterns[, options]);
37921 *
37922 * var obj = { aa: 'a', ab: 'b', ac: 'c' };
37923 * console.log(mm.matchKeys(obj, '*b'));
37924 * //=> { ab: 'b' }
37925 * ```
37926 * @param {Object} `object` The object with keys to filter.
37927 * @param {String|Array} `patterns` One or more glob patterns to use for matching.
37928 * @param {Object} `options` See available [options](#options) for changing how matches are performed
37929 * @return {Object} Returns an object with only keys that match the given patterns.
37930 * @api public
37931 */
37932
37933micromatch.matchKeys = function(obj, patterns, options) {
37934 if (!utils_1$3.isObject(obj)) {
37935 throw new TypeError('expected the first argument to be an object');
37936 }
37937 var keys = micromatch(Object.keys(obj), patterns, options);
37938 return utils_1$3.pick(obj, keys);
37939};
37940
37941/**
37942 * Returns a memoized matcher function from the given glob `pattern` and `options`.
37943 * The returned function takes a string to match as its only argument and returns
37944 * true if the string is a match.
37945 *
37946 * ```js
37947 * var mm = require('micromatch');
37948 * mm.matcher(pattern[, options]);
37949 *
37950 * var isMatch = mm.matcher('*.!(*a)');
37951 * console.log(isMatch('a.a'));
37952 * //=> false
37953 * console.log(isMatch('a.b'));
37954 * //=> true
37955 * ```
37956 * @param {String} `pattern` Glob pattern
37957 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
37958 * @return {Function} Returns a matcher function.
37959 * @api public
37960 */
37961
37962micromatch.matcher = function matcher(pattern, options) {
37963 if (Array.isArray(pattern)) {
37964 return compose$1(pattern, options, matcher);
37965 }
37966
37967 // if pattern is a regex
37968 if (pattern instanceof RegExp) {
37969 return test(pattern);
37970 }
37971
37972 // if pattern is invalid
37973 if (!utils_1$3.isString(pattern)) {
37974 throw new TypeError('expected pattern to be an array, string or regex');
37975 }
37976
37977 // if pattern is a non-glob string
37978 if (!utils_1$3.hasSpecialChars(pattern)) {
37979 if (options && options.nocase === true) {
37980 pattern = pattern.toLowerCase();
37981 }
37982 return utils_1$3.matchPath(pattern, options);
37983 }
37984
37985 // if pattern is a glob string
37986 var re = micromatch.makeRe(pattern, options);
37987
37988 // if `options.matchBase` or `options.basename` is defined
37989 if (micromatch.matchBase(pattern, options)) {
37990 return utils_1$3.matchBasename(re, options);
37991 }
37992
37993 function test(regex) {
37994 var equals = utils_1$3.equalsPattern(options);
37995 var unixify = utils_1$3.unixify(options);
37996
37997 return function(str) {
37998 if (equals(str)) {
37999 return true;
38000 }
38001
38002 if (regex.test(unixify(str))) {
38003 return true;
38004 }
38005 return false;
38006 };
38007 }
38008
38009 var fn = test(re);
38010 Object.defineProperty(fn, 'result', {
38011 configurable: true,
38012 enumerable: false,
38013 value: re.result
38014 });
38015 return fn;
38016};
38017
38018/**
38019 * Returns an array of matches captured by `pattern` in `string, or `null` if the pattern did not match.
38020 *
38021 * ```js
38022 * var mm = require('micromatch');
38023 * mm.capture(pattern, string[, options]);
38024 *
38025 * console.log(mm.capture('test/*.js', 'test/foo.js'));
38026 * //=> ['foo']
38027 * console.log(mm.capture('test/*.js', 'foo/bar.css'));
38028 * //=> null
38029 * ```
38030 * @param {String} `pattern` Glob pattern to use for matching.
38031 * @param {String} `string` String to match
38032 * @param {Object} `options` See available [options](#options) for changing how matches are performed
38033 * @return {Boolean} Returns an array of captures if the string matches the glob pattern, otherwise `null`.
38034 * @api public
38035 */
38036
38037micromatch.capture = function(pattern, str, options) {
38038 var re = micromatch.makeRe(pattern, extendShallow({capture: true}, options));
38039 var unixify = utils_1$3.unixify(options);
38040
38041 function match() {
38042 return function(string) {
38043 var match = re.exec(unixify(string));
38044 if (!match) {
38045 return null;
38046 }
38047
38048 return match.slice(1);
38049 };
38050 }
38051
38052 var capture = memoize$3('capture', pattern, options, match);
38053 return capture(str);
38054};
38055
38056/**
38057 * Create a regular expression from the given glob `pattern`.
38058 *
38059 * ```js
38060 * var mm = require('micromatch');
38061 * mm.makeRe(pattern[, options]);
38062 *
38063 * console.log(mm.makeRe('*.js'));
38064 * //=> /^(?:(\.[\\\/])?(?!\.)(?=.)[^\/]*?\.js)$/
38065 * ```
38066 * @param {String} `pattern` A glob pattern to convert to regex.
38067 * @param {Object} `options` See available [options](#options) for changing how matches are performed.
38068 * @return {RegExp} Returns a regex created from the given pattern.
38069 * @api public
38070 */
38071
38072micromatch.makeRe = function(pattern, options) {
38073 if (typeof pattern !== 'string') {
38074 throw new TypeError('expected pattern to be a string');
38075 }
38076
38077 if (pattern.length > MAX_LENGTH$4) {
38078 throw new Error('expected pattern to be less than ' + MAX_LENGTH$4 + ' characters');
38079 }
38080
38081 function makeRe() {
38082 var result = micromatch.create(pattern, options);
38083 var ast_array = [];
38084 var output = result.map(function(obj) {
38085 obj.ast.state = obj.state;
38086 ast_array.push(obj.ast);
38087 return obj.output;
38088 });
38089
38090 var regex = toRegex$1(output.join('|'), options);
38091 Object.defineProperty(regex, 'result', {
38092 configurable: true,
38093 enumerable: false,
38094 value: ast_array
38095 });
38096 return regex;
38097 }
38098
38099 return memoize$3('makeRe', pattern, options, makeRe);
38100};
38101
38102/**
38103 * Expand the given brace `pattern`.
38104 *
38105 * ```js
38106 * var mm = require('micromatch');
38107 * console.log(mm.braces('foo/{a,b}/bar'));
38108 * //=> ['foo/(a|b)/bar']
38109 *
38110 * console.log(mm.braces('foo/{a,b}/bar', {expand: true}));
38111 * //=> ['foo/(a|b)/bar']
38112 * ```
38113 * @param {String} `pattern` String with brace pattern to expand.
38114 * @param {Object} `options` Any [options](#options) to change how expansion is performed. See the [braces][] library for all available options.
38115 * @return {Array}
38116 * @api public
38117 */
38118
38119micromatch.braces = function(pattern, options) {
38120 if (typeof pattern !== 'string' && !Array.isArray(pattern)) {
38121 throw new TypeError('expected pattern to be an array or string');
38122 }
38123
38124 function expand() {
38125 if (options && options.nobrace === true || !/\{.*\}/.test(pattern)) {
38126 return utils_1$3.arrayify(pattern);
38127 }
38128 return braces_1(pattern, options);
38129 }
38130
38131 return memoize$3('braces', pattern, options, expand);
38132};
38133
38134/**
38135 * Proxy to the [micromatch.braces](#method), for parity with
38136 * minimatch.
38137 */
38138
38139micromatch.braceExpand = function(pattern, options) {
38140 var opts = extendShallow({}, options, {expand: true});
38141 return micromatch.braces(pattern, opts);
38142};
38143
38144/**
38145 * Parses the given glob `pattern` and returns an array of abstract syntax
38146 * trees (ASTs), with the compiled `output` and optional source `map` on
38147 * each AST.
38148 *
38149 * ```js
38150 * var mm = require('micromatch');
38151 * mm.create(pattern[, options]);
38152 *
38153 * console.log(mm.create('abc/*.js'));
38154 * // [{ options: { source: 'string', sourcemap: true },
38155 * // state: {},
38156 * // compilers:
38157 * // { ... },
38158 * // output: '(\\.[\\\\\\/])?abc\\/(?!\\.)(?=.)[^\\/]*?\\.js',
38159 * // ast:
38160 * // { type: 'root',
38161 * // errors: [],
38162 * // nodes:
38163 * // [ ... ],
38164 * // dot: false,
38165 * // input: 'abc/*.js' },
38166 * // parsingErrors: [],
38167 * // map:
38168 * // { version: 3,
38169 * // sources: [ 'string' ],
38170 * // names: [],
38171 * // mappings: 'AAAA,GAAG,EAAC,kBAAC,EAAC,EAAE',
38172 * // sourcesContent: [ 'abc/*.js' ] },
38173 * // position: { line: 1, column: 28 },
38174 * // content: {},
38175 * // files: {},
38176 * // idx: 6 }]
38177 * ```
38178 * @param {String} `pattern` Glob pattern to parse and compile.
38179 * @param {Object} `options` Any [options](#options) to change how parsing and compiling is performed.
38180 * @return {Object} Returns an object with the parsed AST, compiled string and optional source map.
38181 * @api public
38182 */
38183
38184micromatch.create = function(pattern, options) {
38185 return memoize$3('create', pattern, options, function() {
38186 function create(str, opts) {
38187 return micromatch.compile(micromatch.parse(str, opts), opts);
38188 }
38189
38190 pattern = micromatch.braces(pattern, options);
38191 var len = pattern.length;
38192 var idx = -1;
38193 var res = [];
38194
38195 while (++idx < len) {
38196 res.push(create(pattern[idx], options));
38197 }
38198 return res;
38199 });
38200};
38201
38202/**
38203 * Parse the given `str` with the given `options`.
38204 *
38205 * ```js
38206 * var mm = require('micromatch');
38207 * mm.parse(pattern[, options]);
38208 *
38209 * var ast = mm.parse('a/{b,c}/d');
38210 * console.log(ast);
38211 * // { type: 'root',
38212 * // errors: [],
38213 * // input: 'a/{b,c}/d',
38214 * // nodes:
38215 * // [ { type: 'bos', val: '' },
38216 * // { type: 'text', val: 'a/' },
38217 * // { type: 'brace',
38218 * // nodes:
38219 * // [ { type: 'brace.open', val: '{' },
38220 * // { type: 'text', val: 'b,c' },
38221 * // { type: 'brace.close', val: '}' } ] },
38222 * // { type: 'text', val: '/d' },
38223 * // { type: 'eos', val: '' } ] }
38224 * ```
38225 * @param {String} `str`
38226 * @param {Object} `options`
38227 * @return {Object} Returns an AST
38228 * @api public
38229 */
38230
38231micromatch.parse = function(pattern, options) {
38232 if (typeof pattern !== 'string') {
38233 throw new TypeError('expected a string');
38234 }
38235
38236 function parse() {
38237 var snapdragon = utils_1$3.instantiate(null, options);
38238 parsers$4(snapdragon, options);
38239
38240 var ast = snapdragon.parse(pattern, options);
38241 utils_1$3.define(ast, 'snapdragon', snapdragon);
38242 ast.input = pattern;
38243 return ast;
38244 }
38245
38246 return memoize$3('parse', pattern, options, parse);
38247};
38248
38249/**
38250 * Compile the given `ast` or string with the given `options`.
38251 *
38252 * ```js
38253 * var mm = require('micromatch');
38254 * mm.compile(ast[, options]);
38255 *
38256 * var ast = mm.parse('a/{b,c}/d');
38257 * console.log(mm.compile(ast));
38258 * // { options: { source: 'string' },
38259 * // state: {},
38260 * // compilers:
38261 * // { eos: [Function],
38262 * // noop: [Function],
38263 * // bos: [Function],
38264 * // brace: [Function],
38265 * // 'brace.open': [Function],
38266 * // text: [Function],
38267 * // 'brace.close': [Function] },
38268 * // output: [ 'a/(b|c)/d' ],
38269 * // ast:
38270 * // { ... },
38271 * // parsingErrors: [] }
38272 * ```
38273 * @param {Object|String} `ast`
38274 * @param {Object} `options`
38275 * @return {Object} Returns an object that has an `output` property with the compiled string.
38276 * @api public
38277 */
38278
38279micromatch.compile = function(ast, options) {
38280 if (typeof ast === 'string') {
38281 ast = micromatch.parse(ast, options);
38282 }
38283
38284 return memoize$3('compile', ast.input, options, function() {
38285 var snapdragon = utils_1$3.instantiate(ast, options);
38286 compilers$4(snapdragon, options);
38287 return snapdragon.compile(ast, options);
38288 });
38289};
38290
38291/**
38292 * Clear the regex cache.
38293 *
38294 * ```js
38295 * mm.clearCache();
38296 * ```
38297 * @api public
38298 */
38299
38300micromatch.clearCache = function() {
38301 micromatch.cache.caches = {};
38302};
38303
38304/**
38305 * Returns true if the given value is effectively an empty string
38306 */
38307
38308function isEmptyString(val) {
38309 return String(val) === '' || String(val) === './';
38310}
38311
38312/**
38313 * Compose a matcher function with the given patterns.
38314 * This allows matcher functions to be compiled once and
38315 * called multiple times.
38316 */
38317
38318function compose$1(patterns, options, matcher) {
38319 var matchers;
38320
38321 return memoize$3('compose', String(patterns), options, function() {
38322 return function(file) {
38323 // delay composition until it's invoked the first time,
38324 // after that it won't be called again
38325 if (!matchers) {
38326 matchers = [];
38327 for (var i = 0; i < patterns.length; i++) {
38328 matchers.push(matcher(patterns[i], options));
38329 }
38330 }
38331
38332 var len = matchers.length;
38333 while (len--) {
38334 if (matchers[len](file) === true) {
38335 return true;
38336 }
38337 }
38338 return false;
38339 };
38340 });
38341}
38342
38343/**
38344 * Memoize a generated regex or function. A unique key is generated
38345 * from the `type` (usually method name), the `pattern`, and
38346 * user-defined options.
38347 */
38348
38349function memoize$3(type, pattern, options, fn) {
38350 var key = utils_1$3.createKey(type + '=' + pattern, options);
38351
38352 if (options && options.cache === false) {
38353 return fn(pattern, options);
38354 }
38355
38356 if (cache$5.has(type, key)) {
38357 return cache$5.get(type, key);
38358 }
38359
38360 var val = fn(pattern, options);
38361 cache$5.set(type, key, val);
38362 return val;
38363}
38364
38365/**
38366 * Expose compiler, parser and cache on `micromatch`
38367 */
38368
38369micromatch.compilers = compilers$4;
38370micromatch.parsers = parsers$4;
38371micromatch.caches = cache$5.caches;
38372
38373/**
38374 * Expose `micromatch`
38375 * @type {Function}
38376 */
38377
38378var micromatch_1 = micromatch;
38379var micromatch_2 = micromatch_1.matcher;
38380
38381function ensureArray(thing) {
38382 if (Array.isArray(thing))
38383 return thing;
38384 if (thing == undefined)
38385 return [];
38386 return [thing];
38387}
38388
38389var createFilter = function createFilter(include, exclude) {
38390 var getMatcher = function (id) {
38391 return id instanceof RegExp
38392 ? id
38393 : {
38394 test: micromatch_2(resolve$1(id)
38395 .split(sep)
38396 .join('/'))
38397 };
38398 };
38399 var includeMatchers = ensureArray(include).map(getMatcher);
38400 var excludeMatchers = ensureArray(exclude).map(getMatcher);
38401 return function (id) {
38402 if (typeof id !== 'string')
38403 return false;
38404 if (/\0/.test(id))
38405 return false;
38406 id = id.split(sep).join('/');
38407 for (var i = 0; i < excludeMatchers.length; ++i) {
38408 var matcher = excludeMatchers[i];
38409 if (matcher.test(id))
38410 return false;
38411 }
38412 for (var i = 0; i < includeMatchers.length; ++i) {
38413 var matcher = includeMatchers[i];
38414 if (matcher.test(id))
38415 return true;
38416 }
38417 return !includeMatchers.length;
38418 };
38419};
38420
38421var modules = {};
38422
38423var getModule = function(dir) {
38424 var rootPath = dir ? path.resolve(dir) : process.cwd();
38425 var rootName = path.join(rootPath, '@root');
38426 var root = modules[rootName];
38427 if (!root) {
38428 root = new module$1(rootName);
38429 root.filename = rootName;
38430 root.paths = module$1._nodeModulePaths(rootPath);
38431 modules[rootName] = root;
38432 }
38433 return root;
38434};
38435
38436var requireRelative = function(requested, relativeTo) {
38437 var root = getModule(relativeTo);
38438 return root.require(requested);
38439};
38440
38441requireRelative.resolve = function(requested, relativeTo) {
38442 var root = getModule(relativeTo);
38443 return module$1._resolveFilename(requested, root);
38444};
38445
38446var requireRelative_1 = requireRelative;
38447
38448var chokidar;
38449try {
38450 chokidar = requireRelative_1('chokidar', process.cwd());
38451}
38452catch (err) {
38453 chokidar = null;
38454}
38455var chokidar$1 = chokidar;
38456
38457var opts = { encoding: 'utf-8', persistent: true };
38458var watchers = new Map();
38459function addTask(id, task, chokidarOptions, chokidarOptionsHash, isTransformDependency) {
38460 if (!watchers.has(chokidarOptionsHash))
38461 watchers.set(chokidarOptionsHash, new Map());
38462 var group = watchers.get(chokidarOptionsHash);
38463 var watcher = group.get(id) || new FileWatcher(id, chokidarOptions, group);
38464 if (!watcher.fileExists) {
38465 if (isTransformDependency)
38466 throw new Error("Transform dependency " + id + " does not exist.");
38467 }
38468 else {
38469 watcher.addTask(task, isTransformDependency);
38470 }
38471}
38472function deleteTask(id, target, chokidarOptionsHash) {
38473 var group = watchers.get(chokidarOptionsHash);
38474 var watcher = group.get(id);
38475 if (watcher)
38476 watcher.deleteTask(target, group);
38477}
38478var FileWatcher = /** @class */ (function () {
38479 function FileWatcher(id, chokidarOptions, group) {
38480 var _this = this;
38481 this.id = id;
38482 this.tasks = new Set();
38483 this.transformDependencyTasks = new Set();
38484 var modifiedTime;
38485 try {
38486 var stats = statSync(id);
38487 modifiedTime = +stats.mtime;
38488 this.fileExists = true;
38489 }
38490 catch (err) {
38491 if (err.code === 'ENOENT') {
38492 // can't watch files that don't exist (e.g. injected
38493 // by plugins somehow)
38494 this.fileExists = false;
38495 return;
38496 }
38497 else {
38498 throw err;
38499 }
38500 }
38501 var handleWatchEvent = function (event) {
38502 if (event === 'rename' || event === 'unlink') {
38503 _this.close();
38504 group.delete(id);
38505 _this.trigger(id);
38506 }
38507 else {
38508 var stats = void 0;
38509 try {
38510 stats = statSync(id);
38511 }
38512 catch (err) {
38513 if (err.code === 'ENOENT') {
38514 modifiedTime = -1;
38515 _this.trigger(id);
38516 return;
38517 }
38518 throw err;
38519 }
38520 // debounce
38521 if (+stats.mtime - modifiedTime > 15)
38522 _this.trigger(id);
38523 }
38524 };
38525 if (chokidarOptions) {
38526 this.fsWatcher = chokidar$1.watch(id, chokidarOptions).on('all', handleWatchEvent);
38527 }
38528 else {
38529 this.fsWatcher = watch$1(id, opts, handleWatchEvent);
38530 }
38531 group.set(id, this);
38532 }
38533 FileWatcher.prototype.addTask = function (task, isTransformDependency) {
38534 if (isTransformDependency === void 0) { isTransformDependency = false; }
38535 if (isTransformDependency)
38536 this.transformDependencyTasks.add(task);
38537 else
38538 this.tasks.add(task);
38539 };
38540 FileWatcher.prototype.close = function () {
38541 this.fsWatcher.close();
38542 };
38543 FileWatcher.prototype.deleteTask = function (task, group) {
38544 var deleted = this.tasks.delete(task);
38545 deleted = this.transformDependencyTasks.delete(task) || deleted;
38546 if (deleted && this.tasks.size === 0 && this.transformDependencyTasks.size === 0) {
38547 group.delete(this.id);
38548 this.close();
38549 }
38550 };
38551 FileWatcher.prototype.trigger = function (id) {
38552 this.tasks.forEach(function (task) {
38553 task.invalidate(id, false);
38554 });
38555 this.transformDependencyTasks.forEach(function (task) {
38556 task.invalidate(id, true);
38557 });
38558 };
38559 return FileWatcher;
38560}());
38561
38562var DELAY = 200;
38563var Watcher = /** @class */ (function () {
38564 function Watcher(configs) {
38565 var _this = this;
38566 this.invalidatedIds = new Set();
38567 this.rerun = false;
38568 this.succeeded = false;
38569 this.emitter = new (/** @class */ (function (_super) {
38570 __extends(class_1, _super);
38571 function class_1(close) {
38572 var _this = _super.call(this) || this;
38573 _this.close = close;
38574 // Allows more than 10 bundles to be watched without
38575 // showing the `MaxListenersExceededWarning` to the user.
38576 _this.setMaxListeners(Infinity);
38577 return _this;
38578 }
38579 return class_1;
38580 }(EventEmitter)))(this.close.bind(this));
38581 this.tasks = (Array.isArray(configs) ? configs : configs ? [configs] : []).map(function (config) { return new Task(_this, config); });
38582 this.running = true;
38583 process.nextTick(function () { return _this.run(); });
38584 }
38585 Watcher.prototype.close = function () {
38586 if (this.buildTimeout)
38587 clearTimeout(this.buildTimeout);
38588 this.tasks.forEach(function (task) {
38589 task.close();
38590 });
38591 this.emitter.removeAllListeners();
38592 };
38593 Watcher.prototype.emit = function (event, value) {
38594 this.emitter.emit(event, value);
38595 };
38596 Watcher.prototype.invalidate = function (id) {
38597 var _this = this;
38598 if (id) {
38599 this.invalidatedIds.add(id);
38600 }
38601 if (this.running) {
38602 this.rerun = true;
38603 return;
38604 }
38605 if (this.buildTimeout)
38606 clearTimeout(this.buildTimeout);
38607 this.buildTimeout = setTimeout(function () {
38608 _this.buildTimeout = undefined;
38609 _this.invalidatedIds.forEach(function (id) { return _this.emit('change', id); });
38610 _this.invalidatedIds.clear();
38611 _this.emit('restart');
38612 _this.run();
38613 }, DELAY);
38614 };
38615 Watcher.prototype.run = function () {
38616 var _this = this;
38617 this.running = true;
38618 this.emit('event', {
38619 code: 'START'
38620 });
38621 var taskPromise = Promise.resolve();
38622 var _loop_1 = function (task) {
38623 taskPromise = taskPromise.then(function () { return task.run(); });
38624 };
38625 for (var _i = 0, _a = this.tasks; _i < _a.length; _i++) {
38626 var task = _a[_i];
38627 _loop_1(task);
38628 }
38629 return taskPromise
38630 .then(function () {
38631 _this.succeeded = true;
38632 _this.running = false;
38633 _this.emit('event', {
38634 code: 'END'
38635 });
38636 })
38637 .catch(function (error) {
38638 _this.running = false;
38639 _this.emit('event', {
38640 code: _this.succeeded ? 'ERROR' : 'FATAL',
38641 error: error
38642 });
38643 })
38644 .then(function () {
38645 if (_this.rerun) {
38646 _this.rerun = false;
38647 _this.invalidate();
38648 }
38649 });
38650 };
38651 return Watcher;
38652}());
38653var Task = /** @class */ (function () {
38654 function Task(watcher, config) {
38655 this.invalidated = true;
38656 this.cache = null;
38657 this.watcher = watcher;
38658 this.closed = false;
38659 this.watched = new Set();
38660 var _a = mergeOptions({
38661 config: config
38662 }), inputOptions = _a.inputOptions, outputOptions = _a.outputOptions;
38663 this.inputOptions = inputOptions;
38664 this.outputs = outputOptions;
38665 this.outputFiles = this.outputs.map(function (output) {
38666 if (output.file || output.dir)
38667 return path.resolve(output.file || output.dir);
38668 });
38669 var watchOptions = inputOptions.watch || {};
38670 if ('useChokidar' in watchOptions)
38671 watchOptions.chokidar = watchOptions.useChokidar;
38672 var chokidarOptions = 'chokidar' in watchOptions ? watchOptions.chokidar : !!chokidar$1;
38673 if (chokidarOptions) {
38674 chokidarOptions = __assign({}, (chokidarOptions === true ? {} : chokidarOptions), { disableGlobbing: true, ignoreInitial: true });
38675 }
38676 if (chokidarOptions && !chokidar$1) {
38677 throw new Error("watch.chokidar was provided, but chokidar could not be found. Have you installed it?");
38678 }
38679 this.chokidarOptions = chokidarOptions;
38680 this.chokidarOptionsHash = JSON.stringify(chokidarOptions);
38681 this.filter = createFilter(watchOptions.include, watchOptions.exclude);
38682 }
38683 Task.prototype.close = function () {
38684 var _this = this;
38685 this.closed = true;
38686 this.watched.forEach(function (id) {
38687 deleteTask(id, _this, _this.chokidarOptionsHash);
38688 });
38689 };
38690 Task.prototype.invalidate = function (id, isTransformDependency) {
38691 this.invalidated = true;
38692 if (isTransformDependency) {
38693 this.cache.modules.forEach(function (module) {
38694 if (!module.transformDependencies || module.transformDependencies.indexOf(id) === -1)
38695 return;
38696 // effective invalidation
38697 module.originalCode = null;
38698 });
38699 }
38700 this.watcher.invalidate(id);
38701 };
38702 Task.prototype.run = function () {
38703 var _this = this;
38704 if (!this.invalidated)
38705 return;
38706 this.invalidated = false;
38707 var options = __assign({}, this.inputOptions, { cache: this.cache });
38708 var start = Date.now();
38709 this.watcher.emit('event', {
38710 code: 'BUNDLE_START',
38711 input: this.inputOptions.input,
38712 output: this.outputFiles
38713 });
38714 setWatcher(this.watcher.emitter);
38715 return rollup(options)
38716 .then(function (result) {
38717 if (_this.closed)
38718 return;
38719 var watched = (_this.watched = new Set());
38720 _this.cache = result.cache;
38721 _this.watchFiles = result.watchFiles;
38722 _this.cache.modules.forEach(function (module) {
38723 if (module.transformDependencies) {
38724 module.transformDependencies.forEach(function (depId) {
38725 watched.add(depId);
38726 _this.watchFile(depId, true);
38727 });
38728 }
38729 });
38730 _this.watchFiles.forEach(function (id) {
38731 watched.add(id);
38732 _this.watchFile(id);
38733 });
38734 _this.watched.forEach(function (id) {
38735 if (!watched.has(id))
38736 deleteTask(id, _this, _this.chokidarOptionsHash);
38737 });
38738 return Promise.all(_this.outputs.map(function (output) { return result.write(output); })).then(function () { return result; });
38739 })
38740 .then(function (result) {
38741 _this.watcher.emit('event', {
38742 code: 'BUNDLE_END',
38743 duration: Date.now() - start,
38744 input: _this.inputOptions.input,
38745 output: _this.outputFiles,
38746 result: result
38747 });
38748 })
38749 .catch(function (error) {
38750 if (_this.closed)
38751 return;
38752 if (_this.cache) {
38753 // this is necessary to ensure that any 'renamed' files
38754 // continue to be watched following an error
38755 if (_this.cache.modules) {
38756 _this.cache.modules.forEach(function (module) {
38757 if (module.transformDependencies) {
38758 module.transformDependencies.forEach(function (depId) {
38759 _this.watchFile(depId, true);
38760 });
38761 }
38762 });
38763 }
38764 _this.watchFiles.forEach(function (id) {
38765 _this.watchFile(id);
38766 });
38767 }
38768 throw error;
38769 });
38770 };
38771 Task.prototype.watchFile = function (id, isTransformDependency) {
38772 if (isTransformDependency === void 0) { isTransformDependency = false; }
38773 if (!this.filter(id))
38774 return;
38775 if (this.outputFiles.some(function (file) { return file === id; })) {
38776 throw new Error('Cannot import the generated bundle');
38777 }
38778 // this is necessary to ensure that any 'renamed' files
38779 // continue to be watched following an error
38780 addTask(id, this, this.chokidarOptions, this.chokidarOptionsHash, isTransformDependency);
38781 };
38782 return Task;
38783}());
38784function watch(configs) {
38785 return new Watcher(configs).emitter;
38786}
38787
38788export { version as VERSION, rollup, watch };